Compare commits

..

521 Commits

Author SHA1 Message Date
Maurice 99465d04de fix(mobile): the add-place button of the stay sheet takes the caption size
It uses the planner's add-place label, which no view named before, so the
unused-key baseline of planner.ts drops by one.
2026-11-19 21:41:54 +01:00
Maurice 73a7c4843b fix(mobile): a stay can be added to a trip that has no place yet
A stay belongs to one of the trip's places, so on a new trip the
accommodation sheet only said "Add places to your trip first", and the
booking could not be saved without leaving the sheet (TestFlight feedback,
5.1.3). The hint now carries the "Add place/activity" button for anyone
allowed to add places: the place form opens over the sheet, and the place
is listed to pick once it is saved.
2026-11-19 21:31:46 +01:00
Maurice 6e919696bb fix(native): a tap beside a field closes the keyboard
The app hides the keyboard's bar with its "done" button, and a textarea
keeps its return key for new lines, so after typing a note in the place
editor nothing closed the keyboard and it covered the rest of the sheet,
times and Save included (TestFlight feedback, 5.1.3). A tap away from the
focused field now lets go of the focus. A scroll keeps the keyboard open,
and a tap on another field moves the focus there.
2026-11-19 21:27:54 +01:00
Maurice d32cfb3635 fix(native): give the Apple Watch app icon a light background
watchOS crops the icon to a circle on a black face, so the black icon did
not read as a circle at all (App Review, guideline 4). The mark now sits
dark on a light grey ground, drawn from the same master silhouette.
2026-11-19 21:26:38 +01:00
Maurice 31c9f40550 fix(native): App Review builds can buy TREK Cloud while orders are closed
While TREK Cloud's orders are closed, the plan picker on iOS offers the
subscriptions only to builds that buy in the App Store sandbox (TestFlight,
App Review, Xcode). That was read from the receipt's file name alone, which
App Review's build did not carry: the reviewer saw "TREK Cloud opens soon"
and no way to buy, and the app was rejected under 2.1(b) because its
in-app purchases could not be found.

The environment now comes from the signed app transaction (StoreKit 2, iOS
16 and later), with the receipt's file name as the fallback on iOS 15 or
when the app transaction cannot be read. A production build still sees the
plans without a buy button until orders open, and the cloud refuses a
production purchase before the opening as before.
2026-11-19 21:26:38 +01:00
Maurice 7ae4dcba51 fix(db): sort the Postgres move's names with an explicit code-unit compare
Five sorts in the Postgres bootstrap and the move from SQLite relied on the
default sort, which SonarCloud reports as a bug because it compares by code
unit implicitly. They order migration names, table names and JSON keys for a
checksum, where locale-aware ordering would change the result, so each now
names the code-unit compare the default already used. Nothing changes.
2026-11-18 23:58:20 +01:00
Maurice daa4e1dfcf test(planner): an older place lookup that answers last does not replace the newer results 2026-11-18 23:30:37 +01:00
Raz Erlich 9a7bce6fd8 fix(planner): scope transit picks by day and rank other stays by date 2026-11-18 23:30:36 +01:00
Maurice 0834d4f8fe docs(airtrail): name the API key scopes AirTrail 3.13 checks 2026-11-18 23:17:47 +01:00
Maurice d8c28c9998 fix(airtrail): read the v1 answers at the boundary and refuse an arrival before the departure
The v1 bodies were cast to their types unchecked, so a flight page whose data
was not a list, or a passenger list of another shape, failed deeper down as a
TypeError instead of an AirTrail request error. Each v1 answer (a flight, a
page of flights, a created flight, a reference lookup, the key owner) is now
read through a small schema that keeps the fields TREK does not need lenient.

The legacy save refuses an arrival before the departure; the v1 body passed
it on, so an overnight arrival time without its date would have been stored
before the departure. The v1 write-back now refuses it with the same message.
2026-11-18 23:17:27 +01:00
aaronspruit 76ff6e15b1 feat(airtrail): use the AirTrail /api/v1 routes, and keep the legacy routes
AirTrail 3.13 adds /api/v1 and marks the /api/flight/* routes as
deprecated. TREK now asks the public discovery document GET /api/v1
and uses v1 when the instance has it. It uses the legacy routes for
an older instance. The client methods keep their signatures, and the
sync hash stays the same, so a linked flight does not sync again
when an instance changes to v1.

The probe cache holds only a clear answer: 200 with the discovery
document gives v1, and 404 gives legacy. The cache is per AirTrail
URL, for 10 minutes. A timeout, a 5xx or a network error fails that
call only. A 401, a 403 or a page that is not the discovery document
uses legacy for that call only. A 404 for one flight makes the client
ask the probe again before it reports the flight as deleted.

A missing scope gives AirtrailScopeError, which names the scope. It
does not unlink a flight. The API key hint and the help step list
the scopes for read and for write-back, in all languages.

Each new request goes through safeFetch, with the SSRF guard, the
timeout and the size cap. The flight list reads pages of 100 and
fails above 50 pages. A failed list unlinks nothing.

airtrail-v1.ts translates between the v1 shapes and the legacy
shapes. A write-back looks up the airport, airline and aircraft ids,
and changes each local time to a UTC instant in the zone of its own
airport. It writes each instant in the +00:00 form of the legacy
save, because AirTrail stores the string as it gets it and the sync
hash reads that string.

The tests cover both APIs over HTTP, the probe cache rules, the sync
hash on a switch and on a save, the page limit, the scope error, and
the UTC conversion across midnight, the date line and daylight-saving
changes.
2026-11-18 23:07:35 +01:00
Maurice 3e0a2ef8ed fix(native): widgets turn to the next trip day by themselves
TestFlight feedback: during a trip the widgets stayed on day 1 until the app
was opened again. The app wrote only today's day into the widget snapshot,
and only while it ran, so every timeline entry after midnight still showed
the day it last ran, with its stops all ahead again.

The snapshot now also carries the trip's days from today on (a month at
most, sixteen stops a day), each with its date. On iOS every timeline entry
takes the day of its own date, so the quarter-hour entry at midnight turns
the widget to the next day, and the bookings list drops the days behind; the
Android widgets do the same on each update. A snapshot from an app without
the days reads as it was written, and an older app binary ignores them.
2026-11-18 22:21:26 +01:00
Maurice fd35f79c36 fix(mobile): keep every screen clear of an iPhone Duo's status capsule
TestFlight feedback: on an iPhone Duo the status capsule in the top right
corner covered the trip's controls, its day chips, the map's category bar and
the first cards of every trip tab, upright and on its side. The app has
measured the capsule since 0f42b8b8a, but only the shell's own bars and page
used it, and the trip, its map and the sheets place their own controls.

- Upright, a control row in the capsule's height stands beside it and the
  content starts below it: the trip's top row and day chips, the map's
  category bar, the road trip's stage bar, every trip tab's first row, the
  places browser, the plan timeline, docked and card sheets, the assistant,
  the account menu, the image viewer's close button, the atlas search,
  vacay's header and a journey's content and map controls.
- On a wide window the page gives up the capsule's side over the whole
  height instead, as an iPhone on its side does for its camera: lifting each
  page below the capsule cost a quarter of the height of an unfolded Duo.
  The list tabs, the assistant panel and the form sheets end before it too.
- Screens whose first row is part of the page (settings, administration,
  collections) are lifted until that row is below the capsule; screens that
  keep clear of it by themselves (atlas, vacay, a journey) are not lifted.
- Right to left the rail stands on the capsule's side and takes it.

All of it reads the corner variables the app publishes, which are 0 on every
other device and before iOS 26, so nothing else moves. The rules for the
screens that place their own controls live in mobile/corner.css.
2026-11-18 21:23:14 +01:00
Maurice 294a386d23 fix(planner): take a ?tab=, ?day= or ?assistant= link once per URL
React Router lands the URL without the link as a transition. Until it does,
every render still read the link, and the tab link took it again on each of
them: selectTab is a new function per render and onLinked sets state, so a
notification's ?tab= link rendered the planner into React's update limit and
the route's error page replaced the trip on an iPad or an unfolded foldable.
Both link hooks now take a link once per URL and wait for the cleaned one;
the same link in a new URL is taken again.
2026-11-18 21:23:03 +01:00
Maurice ee79413653 fix(mobile): keep the navigation rail's list ref stable
The rail's list ref was an inline function that set state. React 19 detaches
and re-attaches a ref whose function changed, so every commit set the list to
null and back and asked for one more render of the rail. The ref is one
function for the rail's lifetime now.
2026-11-18 21:23:03 +01:00
Maurice ec08915a16 fix(trips): a day added before the start leaves the plan on its dates
Adding a day before a trip's start with "Keep bookings on their dates"
moved almost everything a day earlier and emptied the last day. The day
grid was always rebuilt by position: the n-th day row took the n-th date
of the new range. With bookings kept on their dates, only timed bookings
and stays were re-anchored afterwards. Places, day notes, bookings with no
time and a booking's place in a day's order stayed on their re-dated rows
and slid to the day before. Days added at both ends had the same problem.

planDayGrid now takes keepDates. When the new range still holds every
dated day, each of them keeps its date and the new days go around them.
The server passes it unless the traveller chose to shift everything, and
the trip dialog's warning check uses the same rule. A moved or shorter
range still follows the positional rule the dialog describes, and "Shift
everything" still moves the whole plan with the new start.

Two things keyed outside the day rows followed the old rule. Road trip day
boundaries are keyed by day number, so a new first day left each one on
the day before its own. They now follow their days to their new numbers
and go out to every screen. The owner's leave days moved by the change of
start even when days were only added. They now move by as far as the
trip's first day moved, which is nothing when days are only added. The
help text of the option and the MCP description say what happens when
days are added.

Closes #3119
2026-11-18 17:14:38 +01:00
Maurice 40f9c020bb fix(bookings): show the calendar date beside transport times
Tapping a transport in the compact Transports or Bookings list on the phone
opens the transport sheet, and its time boxes showed only the clock time. The
sheet named a date only in its subline, and only for a booking with no route
and no airline or number, so a flight or ferry could not be placed on a day
without unfolding the whole list. A transport holding only times (its date
lives on the linked trip day) had no date at all, and the desktop transport
detail dialog had the same gap: it read the date off reservation_time alone
and never named the arrival day of an overnight trip.

The dates now come from one helper, bookingDates(), which reads the booking's
own date, then the stop's local date, then the linked day's date, the rule
bookingFacts already used and now shares. The phone sheet prints the date
above each time (a leg opened from its row uses its own days); when no time
box carries a date, because no time is entered yet or the live flight card
stands in their place, the subline names the day instead. The desktop dialog
names the day, or both days of an overnight trip in reading order, in the
user's locale.

Closes #3122
2026-11-18 16:52:18 +01:00
Maurice 684a3bf5f5 fix(roadtrip): draw the drive between connected days in the arrival day's colour
With "Connect the days" and "A colour per day" on, the drive from one day's
last stop to the next day's first stop was coloured as the day it left. A stop
reached after midnight was handled the same way: the line into it kept the
colour of the day it came from. The road trip panel counts both drives toward
the arriving day (its distance includes them, and the setting's hint says
connecting drives count toward the arrival day). So the map showed the drive
under one day while the panel counted it under the other. This also happened
with daily travel times set to end the day at the last place, whenever the
schedule could not be kept (a drive longer than the window) and the days were
drawn as stored.

assembleRoadtrip now puts every line drawn into a day under that day's
number, the day whose figures count it, and still marks it as a join, so the
one-day stage view still leaves it off. Every map takes its day colours
from this list: desktop Leaflet and Mapbox GL, the phone map and its stage
view. The client tests that pinned the old colouring and the old join order
now expect the new ones.

Closes #3123
2026-11-18 16:52:17 +01:00
Maurice 26122a4208 ci(test): mirror the dev push run on the release pull request
Every push to dev started test.yml twice for the same commit: the push
run on dev and the pull_request run of the open release PR into main.
Together about 72 long jobs exceeded the 60 organisation slots, so jobs
queued and ci-ok landed minutes later.

On a pull request from dev into main (head in this repository) the
changes job now sets mirror and turns every area off
(scripts/ci/changed-areas.mjs), so no gate, test, coverage or scan job
runs. ci-ok keeps its needs verdict and then runs
scripts/ci/mirror-push-run.mjs, which waits for the ci-ok of the push
run of test.yml on dev for exactly the PR head commit and passes or
fails with it. A missing push run, one that ended without a verdict,
an API that keeps failing or a wait past 17 minutes fails with a
re-run hint. ci-ok reads with actions, checks and contents only, and
its timeout rises to 20 minutes.

A push to dev now lists its changes against the merge base with main
instead of the previous push, so the run the mirror copies covers
every area the release pull request brings in, also when an earlier
push's run was cancelled or red.

The release workflows keep reading the newest ci-ok on a commit. A
green mirror implies a green push ci-ok before it; a mirror that fails
on its own blocks a release until it is re-run.
2026-11-18 16:18:46 +01:00
Maurice 9dc80760f7 feat(server): name the database in the start banner
The move guide tells the operator to check that the log reports the Postgres engine, but the start banner never said which database the process runs on. It now carries a Database line with the engine's own description: the SQLite file, or the Postgres URL with its password masked. The guide's check and the manual checklist point at that line.
2026-11-18 15:43:26 +01:00
Maurice 090db8519d docs(postgres): document the volume path per major and what the move carries over
The compose pages name postgres:18, list the volume path for 18 and for 14
to 17, and say that changing a database's major needs pg_upgrade or a
backup and restore. The move steps say to carry the install's own
environment variables, container name and port over, and to append the
passwords and COMPOSE_FILE to the existing .env instead of replacing it,
so later plain docker compose commands, the ones in Updating included, keep
using the Postgres file instead of starting TREK on the old travel.db. The
pages also say which data is lost to an anonymous volume, which compose
service waits for the database, what tables that differ from the Postgres
schema mean, and how to recover from a first start without a password.
2026-11-18 15:22:52 +01:00
Maurice efc55ac700 fix(deploy): run the Postgres compose on postgres:18 without the Swarm-only config mode
The postgres image refuses a volume at /var/lib/postgresql/data from 18 on,
so the db service now mounts /var/lib/postgresql, and the file says that 14
to 17 need the old path and that an existing database keeps its image tag
and path. Compose ignores a config's mode outside Swarm and warned about it
on every command, while the image sourced the init script anyway. The mode
is gone and the script runs its work in a subshell, so set -eu and exit stay
inside it and a failure still fails the first start whether the script is
sourced or executed.
2026-11-18 15:22:52 +01:00
Maurice 85b773420c fix(db): say what a schema difference means when the move to Postgres refuses it
The refusal listed the differences and nothing else. A table or column
only one side has now comes with what that means: the file is at this
version's level, the start that brought it there added every column it
could, the start log names the rest, and the operator keeps running on
SQLite and reports it. A column of TREK's own schema the move cannot copy
is listed apart and named a bug in TREK, since the file is not at fault.
The server guide describes the gap, the repair, the check and the refusal.
2026-11-18 15:22:51 +01:00
Maurice 771dab7c35 feat(db): name the tables and columns the database lacks on every start
After the migrations, both engines compare the declared entities with the
live schema in one catalog statement and log a warning naming each table or
column that is missing, what fails because of it, and that it should be
reported. It never refuses a start, not even when the check itself fails,
and says nothing on a database the migrations built; a Postgres lane suite
holds that on a real server.
2026-11-18 15:22:38 +01:00
Maurice ca7cdcebcc fix(db): add every column an upgraded pre-ORM install can lack
The legacy baseline records the positional runner's steps up to
schema_version as executed without running them, so a column that runner
never added stays missing for good. Two things in its history left such
gaps: a step inserted below a version a build had already shipped (step 53,
users.mfa_backup_codes, so turning on MFA failed there) and a column added
to createTables() with no step (users.immich_access_token).

Migration20200101046460 adds, where missing, every column the schema held
at legacy step 258 that head still holds and ALTER TABLE ADD COLUMN can
add, declared as head declares it; on Postgres every one of them is in the
baseline, so nothing is added there. The list is derived again from the
migrations in tests/unit/db/legacy-column-repair.test.ts, which also adds
all of them to a database lacking them and upgrades a v244 install shaped
like the one whose move to Postgres was refused.
2026-11-18 15:22:38 +01:00
Maurice 6bc27a259b ci(test): give the e2e container a compiler on a node_modules cache miss
better-sqlite3 compiles on install, and the Playwright container has no make or g++, so the first e2e run of a lockfile failed in npm ci. The setup action now installs both when they are missing, before npm ci; a cache hit skips the step.
2026-11-18 14:52:59 +01:00
Maurice a2d9c2416d ci(native): drop the watch-bridge job and the lockfile trigger
watch-bridge repeated the client typecheck and three client test files
that test.yml already runs on every change under client/, inside ci-ok.
The shells link only @capacitor/* packages, all declared in
client/package.json, which stays a trigger, so a native dependency bump
still builds iOS and Android while lockfile-only bumps no longer queue a
Mac build.
2026-11-18 14:48:44 +01:00
Maurice fd1942afab ci(test): restructure test.yml for a ten-minute ci-ok
Rename the workflow to CI and name every job "<Area> <what>[ i/n]" with
ids in kebab-case, in area order. Fold i18n parity, shared coverage and
the plugin SDK into Shared tests, split the client gates into Client
types and Client checks (with the bundle), and merge the image and chart
jobs into Docker and Helm with per-area step conditions. Server and
client tests run in ten slices, the Postgres lane in three per major,
and e2e in two slices inside the digest-pinned Playwright container.

A local setup action restores node_modules and shared/dist from exact
cache keys and falls back to npm ci and the shared build. The
node_modules key covers the lockfile and every workspace package.json,
so npm ci still refuses a package.json out of step with the lockfile.
Only pushes to dev and main save, the npm download cache included, and
only a full install saves that one. The plugin SDK installs and runs
before the root install so it resolves only its own dependencies.
Timeouts drop to 15/10/5 minutes. The workflow tests now check the name
form, the Playwright tag against the lockfile, scan's needs, timeouts,
the cache keys and saves, and that installs go through the setup action;
.github/actions/ counts like test.yml in changed-areas.
2026-11-18 14:48:43 +01:00
Maurice 23eabe1499 style(server): format the doc-sync controller test 2026-11-18 13:44:54 +01:00
Maurice bcc82db7bd test(server): pass numeric row ids to controllers and seed addons with booleans
Controllers read their path ids through the rowId pipe now, so unit tests that call a handler directly pass the number the pipe hands it. The e2e suites enable addons with true, the type of the entity's field. The realtime gateway test builds its book sockets through one helper instead of a second hand-built TripAccessService.
2026-11-18 13:36:37 +01:00
Maurice 26b220470a fix(shared): parse an id param's digits with Number before the integer check
The union of an integer and a digit string fed z.coerce.number() through pipe(), which Zod 4 types with an unknown input and tsc refuses. The digits are now turned into a number with Number and checked by z.number().int().positive(), the same rule as before.
2026-11-18 13:24:09 +01:00
Maurice cdc31967b2 docs(db): describe the final Postgres, plugin data and deployment behaviour
wiki/Database-Postgres.md, server/CLAUDE.md and the plugin SDK docs now
describe what plugin SQL may name on Postgres, the pinned output
settings, the shared contract (NUL and transaction control refused on
every engine), the move's refusals, the Postgres lane in two slices per
major on 14 and 18, and that TREK runs as one instance on either engine.
server/.env.example names the version 18 client tools the image ships,
and the troubleshooting entry and the Helm values name the full set of
roles a restore refuses. A doc-paths baseline entry that no longer
applies is removed.
2026-11-18 13:20:10 +01:00
Maurice 4a435df6e4 fix(plugin-sdk): apply TREK's plugin data contract under trek-plugin dev and the mock host
trek-plugin dev and createMockHost copied the db:own checks by hand and
let through what TREK refuses (NUL, transaction control outside tx()), so
a plugin worked locally and failed in TREK. Both now read the contract
from src/plugin-data-contract.ts, a byte-identical copy of the server's
file that the parity test compares, and check in the server's order.
Tests compare every refusal of the dev database and the mock host with
the contract's text.
2026-11-18 13:20:09 +01:00
Maurice 21f4f7d5de docs(server): plain wording in the comments and test titles this change added
Comments and test titles added on this branch cited review labels and
planning documents that do not exist in the repository, and some used
dashes as separators. They now say what the code does and why in plain
sentences, and the Postgres lane's suites share one header format. Test
ids stay as they were.
2026-11-18 13:20:09 +01:00
Maurice e3d195896c ci(postgres): run the lane in two slices per major with fsync off
Before Postgres 15, every CREATE DATABASE ... TEMPLATE the lane runs per
file is two checkpoints waiting for fsync, and the lane took 20 to 23
minutes on 14 against about 12 on 18. The service now runs with fsync
off, set through ALTER SYSTEM and a reload and checked afterwards. A test
database has nothing to keep through a crash.

Two slices per major replace three, so four long jobs replace six. The
job-count note in test.yml now states the real count: up to 30 jobs, 24
of them long, for 20 organisation-wide slots. At least four long jobs
start only after another has ended. A run with six slices started nine
long jobs four to five minutes late and ended its client coverage eight
minutes after the on-time shards. The job comment says what was measured
on CI and what only locally. The lane docs say two slices, and the root
guide describes the slice gate.
2026-11-18 13:20:09 +01:00
Maurice 911bd825c1 test(ci): fail every sliced job whose slice count the gate cannot hold to one
A sliced job states its slice count three times: the matrix shard axis,
the i/n in its name and the --shard=i/n it hands vitest. Changing one and
not the others still passes and leaves part of the suite in no slice or
reports the wrong count. workflow-jobs.test.mjs now treats every job that
names matrix.shard or runs --shard as sliced and fails, naming the exact
fix, until the three agree. A job whose axis is not the one-line
"shard: [1, ..., n]" form fails too, instead of going unchecked, and so
does a fixed --shard. Tests on small inline workflows hold the reader
itself to these cases.
2026-11-18 13:20:08 +01:00
Maurice 81628d78ee fix(db): name the Postgres compose file in the move command hint
The boot refusal beside a SQLite install told the operator to run the move
with plain `docker compose run`, which uses the SQLite compose file. It now
gives the command the wiki gives, and PGBOOT-037 holds both to the page.
2026-11-18 13:20:08 +01:00
Maurice 69e791206e fix(db): trace a broken key in the move without blaming the wrong row
The move read unique indexes by joining indkey to pg_attribute. An expression key such as lower(email) has attnum 0 there, so idx_users_email_lower was missing from the plan. The catalog query now reads each index's key as Postgres prints it, whether any part of it is an expression, and the columns it reads: the plain key columns and the Var nodes of indexprs, without INCLUDE columns or the predicate.

A broken unique key no longer names --drop-nul as its cause. The refusal names the key and the shared value from Postgres's detail. It explains that the SQLite file held the two rows apart, and the hint about SQLite's lower() appears only for an expression key. Values --drop-nul changed in the key's columns are listed as rows to check first, and only when the duplicate value holds their text. An unrelated value that lost a NUL is no longer named. A plain key over a quoted column is named by its column, not as an expression.

A row that breaks a constraint (SQLSTATE class 23) is now a MoveRefusal that says what to correct, in the SQLite file or in a plugin's plugin.db. Before, it was a bare error with a stack. A value Postgres refuses by its type (class 22) stays a failure: it names no row, and values.ts should have refused it first, so the message asks for a bug report. MoveRefusal and the remedy text move to refusal.ts so copy.ts can use them without an import cycle. The usage text of --drop-nul and the wiki's move section describe NUL in JSON, the key listing and these refusals.
2026-11-18 13:20:08 +01:00
Maurice e66330e226 fix(db): treat a raw NUL in JSON like any NUL in the move
A raw U+0000 in TREK's JSON text, which an old or hand-edited travel.db can hold, was refused as "not valid JSON" without naming the NUL or the remedy. It is now refused with the NUL reason, so the refusal names --drop-nul. With --drop-nul, raw and escaped NULs are removed and nothing else, the way TREK's own writes drop them, and each change is listed. Text that is not valid JSON even without its NULs is refused as that, and the checksum's source side follows the same rule.

A \u escape of half a surrogate pair parses in JavaScript but jsonb refuses it. Before, that failed the insert without naming a row. It is now refused by table, row and column.
2026-11-18 13:20:07 +01:00
Maurice c970245e0d fix(plugins): hold plugin data on Postgres to its own schema and to one contract on both engines
The plugin SQL guard now refuses what still reached outside a plugin's
schema or depended on the server:
- reads of the system columns (xmin, xmax, cmin, cmax, ctid, tableoid),
  which show transaction ids and storage layout and do not exist on
  SQLite; a value of the plugin's own may still be named xmin with AS
- the xid and xid8 types wherever the word stands for the type, since
  age() of an xid is the cluster's transaction counter
- the text search functions that coerce a text argument to regconfig, a
  catalog lookup by name, which leave the allowlist
- collations and access methods outside the set every server has, which
  could tell whether a locale or an extension exists

Every plugin transaction pins, with SET LOCAL, the settings that decide
how values print and parse (TimeZone UTC, DateStyle, the C locales, float,
bytea and xml output, the text search configuration), so a plugin's output
neither depends on nor reveals the server's configuration.

Both stores now keep one contract. Its texts and caps live once, in
plugin-data-contract.ts, and both stores throw only those: NUL in SQL,
an argument or a migration id is refused on SQLite as on Postgres,
transaction control is refused in every call on both engines (tx() is
how a batch becomes atomic), a closed store refuses every call, and the
Postgres store answers the cases better-sqlite3 names with its words.
The SQLite store moves beside the Postgres one as SqlitePluginDataStore
in db/engine/sqlite, takes its file from the backend so src/db never
imports src/nest, and no longer needs the driver exemption. A contract
test runs every violation on both stores and fails when they answer
differently. The Postgres lane holds the allowlist, the pinned settings
and the SQL plugins commonly write against a real database.
2026-11-18 13:20:07 +01:00
Maurice cc0fe6ce2b test(api): hold every request row id to toRowId on paths, bodies, queries, MCP URIs and plugin RPC
ROUTEID walks every route the app registers.
- ROUTEID-001 sends 'abc' and the non-canonical spellings of a seeded row's id to each path param named like an id, and requires no 5xx and the answer 'abc' gets. It then sends the spellings of an id no row has and records what the database drivers are handed (tests/helpers/sql-capture.ts, below MikroORM and Kysely). It fails when a spelling, or the number Number() makes of it, reaches SQL, so a route over a table the suite seeds nothing in is held too. Stale NOT_ROW_IDS entries fail, and the walk runs on one listening keep-alive server.
- ROUTEID-002 walks every @trek/shared request, body and query schema and every route's body and query DTO, and fails on a field named like a row id that accepts such a spelling. String ids are listed with their reason; open fields name the handler test that holds them.

Three more suites cover the other entry points:
- MCPROWID does the same for every MCP resource template.
- RPCROWID refuses a plugin RPC id param read past rowIdParam.
- BODYID, JRNID and QUERYID cover the open accommodation update body, the collab reply, the journey fields a handler parses itself and the notifications limit and offset.

All suites that boot the app run in the SQLite suite and in the Postgres lane on 14 and 18. server/CLAUDE.md states the rule and the four gates.
2026-11-18 13:20:07 +01:00
Maurice 39346ceca7 fix(mcp,rpc): parse resource URI, websocket and plugin RPC ids with toRowId
Eleven MCP tool files carried their own parseId, which used Number() and so took '0x1' and '1e20'; they now share uriRowId. The websocket join and book:join read the id with toRowId instead of Number().

Plugin RPC ids go through rowIdParam instead of num(), and a param that may be left out goes through the new optionalRowIdParam. num() let '0x5', 1.5 and 1e20 through, which Postgres refuses or reads its own way while SQLite matches nothing.

accommodations.create read its refs with Math.trunc(Number()), and accommodations.update bound its open input's refs as sent. collab.createMessage took replyTo only when typeof was 'number', which let 1.5 and 1e20 through. All three now read their ids as row ids. A canonical numeric string still passes, as the published contract says, and the refusal keeps num()'s message.
2026-11-18 13:20:06 +01:00
Maurice 6dfba51f21 fix(api): read body, query and handler-parsed ids with toRowId instead of Number() and parseInt
The services and controllers that took an id from a request with Number(), parseInt() or not at all now use toRowId. That covers admin users, notifications (and their limit and offset), trip members and guests, day notes, assignments, memories (photo owner, album link, body photo_id), photos, mail-ingest, the assistant id parsers, dawarich, registration invites, the plugin contribution routes and the collab reply.

The accommodation update body is open, so AccommodationsService reads the place and day refs of every stay write with toRowId and answers a refused one with the create schema's 400.

AdminService.deleteUser checked the caller with parseInt and deleted with Number(), so an admin could delete their own account by spelling its id in hex; both now use one parse.

The OAuth session revoke called Number(id) first and so revoked session 5 for '0x5'; the service now reads the id as sent.
2026-11-18 13:20:06 +01:00
Maurice 3973741509 fix(shared): refuse a malformed row id in every request schema
Request fields that hold a row id took z.union([z.number(), z.string()]), a bare z.string() or z.array(z.number()), so '0x5', '5e0', 1.5 and 1e20 reached the handler and from there SQL, where SQLite matches nothing, Postgres 14 and 15 refuse the cast and 16 and later read hex and underscores as a number. Two primitives join idParamSchema: rowIdInputSchema takes a safe integer or its digits and keeps the value as sent, so field types do not change; rowIdStringSchema takes digits only, for multipart fields. Both refuse with 'Invalid id'. The accommodation, assignment, reservation position, admin invite, collab reply, vacay, file and memories photo ids now use them, and every list of ids is z.array(z.number().int()). idParamSchema takes only the decimal spelling or a whole number, and the trip-journal-link and tour library ids use it. A body id spelled '0x5' is now a 400 on SQLite too.
2026-11-18 13:20:05 +01:00
Maurice 3eac508baf fix(api): parse path ids with a rowId pipe that answers like an unknown id
RowIdPipe (src/nest/common/row-id.pipe.ts) parses a path param with toRowId. It answers a refused spelling with the route's own not-found answer, so '0x5', '5e0' and 'abc' get what an id that names no row gets. ParseRowIdPipe replaces Nest's ParseIntPipe with the same 400 and message: ParseIntPipe let '-1' and numbers past 2^53 through, and Postgres refuses the latter as out of range. Journey, journey recordings, day import, book design, map, public photo, collections, doc-sync, vacay, atlas and the plugin user-data export declare their ids through it. The upload routes parse in the handler with withRowId, so a refused id takes the existing cleanup path, or carry SpoolCleanupInterceptor (collections).
2026-11-18 13:20:05 +01:00
Maurice 7f6f2eb97c fix(db): read every request row id through toRowId, at the trip guards and the repository lookups
toRowId moves to src/db/row-id.ts so repositories can use it (src/db sits below src/nest), together with a new withRowId helper; src/nest/common/row-id.ts re-exports both. Its docstring is rewritten to state the rule plainly. TripsRepository read its number | string trip ids raw: SQLite matched '0x1' against nothing, Postgres 14 and 15 refused the cast with a 500, and 16 and later read it as trip 1. Its access reads, DaysRepository.existsInTrip and the packing template lookups now parse the id first, so an id toRowId refuses is no row on every engine. TripAccessGuard, TripOwnerGuard and JourneyAssistantGuard used Number(), which read '0x1' and '1e0' as row 1; they now use toRowId.
2026-11-18 13:20:05 +01:00
Maurice f2cfbc4041 fix(db): close the move's remaining silent changes
An attack on the move to Postgres with real SQLite files found five values
that changed without a refusal or a listing, or a valid file that failed:

- Negative zero in a plugin column became 0: pg sends the number -0 as "0",
  and the checksum printed both as "0". It is sent as text and kept apart in
  the checksum on both sides.
- Text whose bytes are not valid UTF-8 was read with each bad sequence
  replaced by U+FFFD, and the checksum was built from the replaced text.
  Text is now read as its bytes and decoded strictly in the file's encoding
  (UTF-8, or UTF-16 for a file created so); such a value is refused in
  TREK's and in plugin data, with --drop-nul too, and listed with its bytes.
- --drop-nul serialized a JSON value again, so a large number lost digits
  and 1.0 became 1. Only the \u0000 escapes are removed now.
- A plugin default Postgres refuses for the column (DEFAULT 0 on a BLOB
  column) failed the move, and DEFAULT 1.5 on an integer column would have
  been rounded. Such a default is left off and listed as not carried over.
- A plugin index or primary key SQLite compared with COLLATE NOCASE or RTRIM
  became one that compares exactly. It is still created, and the summary
  lists the collation it lost.

Each case has a regression test that fails without its fix, on SQLite and
on the Postgres lane.
2026-11-17 23:30:35 +00:00
Maurice 636fc7d0a6 fix(db): refuse the column notation without parentheses and aclitem in plugin SQL
Postgres reads x.f as the call f(x) when x has no column f. The guard counted
that spelling only after ")." or "].", so over a function in FROM that
returns a single value, or a parameter, the allowlist was bypassed:
"select g.obj_description from generate_series(...) g" returned the comments
on every object of the database, and g.current_schemas, g.txid_status and
$1.ts_token_type passed as well. A refused catalog function after a dot is
now refused too, except the names in COLUMN_NAMES (money, name, oid, version,
xid, xml), which take no argument or only convert it to their type, so t.name
keeps working. PGPLUG-021 holds that list to pg_proc on the lane's server.

The type aclitem names roles: '=r'::aclitem printed the cluster's first
superuser and 'x=r/x'::aclitem told whether a role exists. It is refused in
every spelling like the reg* types.

The allowlist itself moves to assets/postgres/plugin-functions.txt, beside
the catalog list it is checked against. As TypeScript it spelled 'like' and
'json_each', names of Postgres functions that the SQLite dialect gate reads
as SQLite SQL.
2026-11-17 23:30:29 +00:00
Maurice adcda60f7d ci(postgres): run the Postgres lane in three slices per major
Since the lane runs every suite that boots the app it takes about ten
minutes on Postgres 18 and about 25 on 14, past the job's 20 minute timeout.
Each major now runs it in three slices (--shard=i/3), each on its own runner
and service with its own template; the probe and its artifact stay once per
major, in the first slice. ci-ok still needs server-postgres, whose result is
failure when any slice fails or is cancelled, so every slice is required.
2026-11-17 22:50:02 +00:00
Maurice e8f808b67f fix(reservations): parse every referenced id in a booking body with toRowId
The booking body is not schema-checked, so day_id, end_day_id, place_id,
assignment_id, accommodation_id and the create_accommodation ids can arrive
as any string. The reference guards passed them to SQL as they came. SQLite
compares '0x5', '5e0' or 'abc' against an integer id and matches nothing
(or, for '5e0', the row), so the guard answered "Unknown reference". Postgres
refuses the cast on 14 and 15 and reads hex as a number from 16 on, so the
same body answered a 500 on one major and reached a real row on another;
the Postgres 14 lane caught it in L2.

Both guards now read each id through toRowId, the rule every other untrusted
row id follows: an id it refuses resolves to nothing, so referencesOutsideTrip
does not name it and unresolvedReferences does, and the answer is the same
400 on every engine. create() reads the payload's accommodation_id through
toRowId as update() already did, instead of storing '0x5.0', which the
reads' join could not cast back on Postgres.

ReservationRow and ReservationTraveler move to reservation-rows.ts, the way
reservation-inputs.ts holds the input shapes, so the service stays within
its size baseline; the service exports them on and it is lowered to 1166.
2026-11-17 22:49:55 +00:00
Maurice 70108e5694 test(memories): type the Synology fakes' request init as RequestInit
The fakes that answer safeFetch by API took their init as any; safeFetch
declares it as RequestInit, which is what they read (the body as
URLSearchParams or text). The SSRF album case had gained one more of them,
which put the tests' no-explicit-any count one over its baseline. All five
are typed now, and the baseline is lowered to the 1545 the tests hold.
2026-11-17 22:49:55 +00:00
Maurice c75fb22289 docs(db): describe the move's refusals and --drop-nul
The wiki's move section, the server guide and the nul-free header said
the move drops NUL as every write does. They now say what it does: a
plugin's data moves unchanged or the move is refused with the values
listed, TREK's own NUL is refused unless --drop-nul is given, which lists
every value it changed, and the checksum comes from the SQLite values.
2026-11-17 23:28:42 +01:00
Maurice 621b2f17df test(db): run the move's NUL and plugin type rules on a real Postgres
The plugin in the move suite gains a BLOB column holding text and an
untyped column holding numbers, and the plugin store must read both back
as they were stored. A new suite moves a file whose plugin and own rows
hold NUL: the plugin's refuses before anything is written, TREK's
refuses until --drop-nul, a username that dropping the NUL makes
duplicate is named with users_username_unique, and a move without a
collision lists the value it changed and stores it without the NUL.
2026-11-17 23:28:41 +01:00
Maurice bc6728678b fix(db): let the move to Postgres change nothing silently
The move stripped NUL from a plugin's own text, merging keys that were
distinct, and turned a plugin's values into another type (text in a BLOB
column into bytea, numbers in an untyped column into text). Its checksum
was built from the converted values, so both passed as verified.

A plugin's data now moves exactly as the Postgres plugin store would
hand it back, or not at all: a NUL, a value of another storage class
than its column, or an integer past 2^53 refuses the move before
anything is written, listing plugin, table, row and column. A column
left open by SQLite's affinity takes the kind its values need, so text
in a BLOB column stays text.

TREK's own text holding a NUL from an older install is refused by
default too. --drop-nul drops it, lists every changed value in the
summary, and names a unique key that dropping a NUL broke.

Every table's checksum is now built from the values read from SQLite,
so a conversion that changes a value fails the verification.
2026-11-17 23:28:41 +01:00
Maurice 6040b60e86 fix(db): keep NUL only in the password fields TREK hashes, not every key naming a password
nulFreeInput left a string as sent under any key containing "password".
That covered the admin settings password_login and password_registration,
which are flags: 'true\u0000' failed the lockout check as a disabled
password login while the database stored 'true'. It also tested the raw
key, so 'pass\u0000word' lost the NUL of the password it carried.

The exemption is now HASHED_PASSWORD_KEYS, the fields TREK only ever hashes
with bcrypt (password, current_password, new_password), matched exactly on
the key without its NUL. A unit test reads every field of the shared
schemas and the instance settings named like a password, passphrase or
secret and fails until each is either in that list or decided against with
its reason.
2026-11-17 23:22:59 +01:00
Maurice 2edf5f807a fix(db): let a plugin call only an allowlist of Postgres's catalog functions
The plugin SQL guard refused functions by name, so every function that reads
the catalogs or the server and was not listed passed: obj_description,
col_description and shobj_description returned the comments on TREK's
tables, columns, database and roles by OID, format_type named a type by its
OID, and version(), current_database(), inet_server_addr() and the session
keywords described the server.

A call to a pg_catalog function is now refused unless the function is on
PLUGIN_FUNCTIONS (string, number, date and time, JSON, array, aggregate,
window, UUID, range, geometry, network and text search functions), in
either spelling of a call, f(...) and the column notation (x).f. The
catalog's function names of Postgres 14 to 18 are kept in
assets/postgres/catalog-functions.txt, and PGPLUG-021 fails on the lane
when the server has a function that list does not name, so a new major
cannot widen what a plugin may call. The session keywords current_user,
session_user, current_role, user, system_user, current_catalog and
current_schema are refused unquoted.
2026-11-17 23:22:59 +01:00
Maurice fd864cc441 chore(lint): read the rule test's parser from typescript-eslint and drop a stale knip entry 2026-11-17 23:04:13 +01:00
Maurice b004d3b88e test(journey): a NUL inside a share token is dropped before the lookup 2026-11-17 23:04:13 +01:00
Maurice 9b1bd6e435 test(memories): answer the SSRF album case by API, not by call order 2026-11-17 23:04:12 +01:00
Maurice 73f3aa8309 test(db): give the stand-in migration storage the master transaction calls 2026-11-17 23:04:12 +01:00
Maurice 82195c7418 fix(db): type the cleaned cookies for the strict compiler 2026-11-17 23:04:12 +01:00
Maurice 9fd77b04fa docs(db): describe the layers that hold plugin SQL on Postgres and the NUL rule for plugin data
The plugin-sdk README, the Postgres wiki page and server/CLAUDE.md now name
the layers as the code enforces them: the refusal on a privileged role and
the boot log line, the guard (the reg* types, INTO after the statement's
own INSERT or MERGE only, TEMP only where it makes a temporary object), the
targets Postgres resolves before an ALTER, DROP, REFRESH, TRUNCATE or
CREATE INDEX, one statement per round trip, pg_temp last, and the quota over
every relation with the object cap. They also say that a plugin argument
holding NUL is refused on Postgres and bound exactly on SQLite.
2026-11-17 23:04:12 +01:00
Maurice f1ea716305 fix(db): hold plugin SQL on Postgres in layers the database enforces
The token guard kept leaking: on a superuser connection an unqualified
`alter type int4 rename to int4x` renamed pg_catalog's type for the whole
server, sequences and catalog-only objects grew the database past the quota,
regtype/regconfig/regdictionary looked TREK's objects up by name, and a
column alias named insert or merge in front of INTO made a table. Instead
of a longer word list, the store now asks the database:

- No plugin SQL while TREK's role is privileged in the sense of the restore
  check (PRIVILEGED_ROLE_SQL, imported from server-checks.ts): every db:own
  call fails with PRIVILEGED_ROLE_PLUGIN_REFUSAL, read once per pool
  connection, and the boot log says why.
- The objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX ... ON
  changes, and the tables a CREATE or ALTER TABLE ties to its own, are
  resolved with to_regclass/to_regtype in the transaction right before the
  statement, and it is refused unless each one found lies in the plugin's
  schema. An unqualified int4, text or box is pg_catalog's and refused even
  with the role check off.
- The quota counts every relation of the schema with its TOAST table, and a
  schema holds at most PLUGIN_SCHEMA_MAX_OBJECTS catalog objects (relations,
  types, constraints, enum labels).
- The guard refuses every reg* type and its array in every spelling, the
  has_*_privilege functions, currtid2 and the BRIN/GIN maintenance
  functions; INTO only after the INSERT or MERGE that is the statement's
  verb or a WITH body's; TEMP only where it makes a temporary object
  (CREATE TEMP/TEMPORARY, SELECT ... INTO TEMP), so a column named temp
  works again; a base type; and a NUL anywhere in the SQL text.
- A bound value or a migration id holding NUL is refused with the reason
  instead of being stripped, so the plugin's keys never change meaning.

Every bypass from the re-review is a test on the real database, on the
role the plugin data is meant to run as and on a superuser connection with
the role check off.
2026-11-17 23:04:12 +01:00
Maurice da1a02e7a8 fix(plugins): bind a plugin's own SQLite arguments exactly again, NUL included
5ff5e7660 stripped U+0000 from every argument a plugin bound to its own
SQLite file, but left the rows it had stored alone. A key written with a
NUL (through a bound arg or char(0) in the plugin's SQL) could no longer be
found by the same key, upserts added duplicates, and keys that differ only
in where a NUL sits ('a\0bc', 'ab\0c') collapsed into one and collided.

A plugin's data is the plugin's, so its file binds the arguments exactly as
sent again, as before that commit. TREK's own data still holds no NUL; the
Postgres store, whose text cannot hold the character, refuses it instead.
2026-11-17 23:04:11 +01:00
Maurice 9808e113e4 fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants
The privileged-role check missed three ways a role can reach the database
host from SQL. Before PostgreSQL 16 a member of a CREATEROLE role sets its
role to it and grants itself pg_execute_server_program, since role
attributes are not inherited but the grant checks the role in effect. A role
granted EXECUTE on lo_export, lo_import, pg_read_file, pg_ls_dir and their
siblings reads or writes server files, and lo_export keeps the file after the
transaction rolls back. From PostgreSQL 15 on a role can be granted ALTER
SYSTEM on a setting or SET on a superuser-only one.

PRIVILEGED_ROLE_SQL now counts all three. The parameter grants are read
through query_to_xml inside a CASE taken only on 15 or later, because a
statement naming pg_parameter_acl does not parse on 14. A SET grant on a
setting every role may change anyway, and pg_monitor, stay ordinary. The
lane test creates each kind of role and shows the escalation the check is
for on the server it runs against.
2026-11-17 23:04:11 +01:00
Maurice 13e81c04ab fix(db): drop NUL from every request value before any logic runs
The database stores no NUL on either engine, but the application still held
the value a client sent. A key or a check made from it was then a different
value from the one the database compared: `victim@x.test` followed by NUL
was a fresh key for the per-email password-reset throttle while the lookup
found the victim's row, so every spelling mailed a new link and voided the
last one.

Every input now loses its NUL where it enters TREK: the nulFreeRequest
middleware after the body parsers (path, query string, body, cookies), the
first global pipe for what a route parses itself (a multipart body), the
websocket adapter for every frame, and the MCP registry through a new
host-supplied input mapper, since /mcp keeps its raw body. Headers need
nothing: Node refuses a NUL in one with a 400. A string under a key naming a
password stays as sent: it is only ever hashed, and stripping it would lock
out an account whose password was set with one. The stripping in the
database layer stays as the backstop for what does not come from a request.
2026-11-17 23:04:11 +01:00
Maurice fd42d06d55 docs(db): drop the pg_restore rollback that fails and name the client tool directories the code searches
Updating offered a second way to roll back a Postgres update: drop the
database, create it again and pg_restore the pre-migrate copy into it. TREK's
copy is a dump of its schema by name, so pg_restore creates public again,
stops at "schema public already exists" and rolls the load back, leaving an
empty database in the middle of a rollback. The page now says so and keeps the
steps that clear the schema instead.

Environment-Variables listed /usr/lib/postgresql/17 to 14 as the default
search path for the client tools; the code and the image start at 18.
2026-11-17 23:04:11 +01:00
Maurice e6f4f7a5f3 fix(db): leave nothing behind when a first Postgres boot fails, so RESTORE_FROM_BACKUP still runs
createFromBaseline created the migration history's table through MikroORM's
storage before, and outside, the transaction that runs the baseline. Without a
master transaction MikroORM commits that table on its own, so a first boot that
failed in the baseline (a server without ICU, a timeout, a dropped connection)
left an empty mikro_orm_migrations behind. The next start with
RESTORE_FROM_BACKUP took that for a database in use, skipped the restore with a
warning and brought up an empty instance, after which the restore never ran.

The table is now created on the baseline's own transaction, so a failed first
boot leaves the database empty. The boot restore also treats a lone migration
history that records nothing as no database, which a restore clears anyway; any
other answer keeps it, so the check fails closed. Database-Postgres says both.
2026-11-17 23:04:11 +01:00
Maurice 9497b586b7 test(db): read the raw-SQL exemptions without awaiting in a loop
The two checks over every file under src/ awaited ESLint's config file by
file, which lint:warnings counts as no-await-in-loop. They read the configs
with Promise.all instead.
2026-11-17 23:04:10 +01:00
Maurice 77d90be4f8 docs(db): describe plugin SQL on its own pool client instead of the marker hook
The guard's header, server/CLAUDE.md and the Postgres wiki page named
extended-query.ts and a hook on every pool connection. They now say that the
store sends each plugin statement over the extended protocol on a client it
checks out per call, and drops that client's temporary tables and session
state before handing it back.
2026-11-17 23:04:10 +01:00
Maurice a884539a2b fix(db): run plugin SQL on a pool client of its own instead of patching the pool
Plugin statements on Postgres went over the extended query protocol through a
marker parameter and a hook that replaced query() on every client of TREK's
pool. That kept a plugin to one statement per round trip, but it changed
TREK's own hot path for a concern only plugin data has.

The plugin data store now checks a pg client out of the ORM's pool for each
transaction, through MikroORM's getNativeClient, and runs the transaction on
it directly. Every plugin write goes as a query with queryMode 'extended' and
every read through a pg-cursor on that client, so Postgres parses exactly one
statement either way. The settings the transaction makes are local, and
before the client goes back to the pool the store drops temporary tables,
cursors, listeners, session advisory locks and sequence state, or closes a
client it cannot bring back to that state. The row cap, quota, time budget,
untimed migrate, per-plugin queue, pool share and script commits are as
before, and plugin args are still sent without NUL.

The marker, the hook and its install in the Postgres driver are gone.
2026-11-17 23:04:10 +01:00
Maurice 633df91bd6 fix(db): refuse raw SQL everywhere under src/, not only in the repositories
The ESLint walls against raw(), the sql tag and SQL text handed to
execute/run/all/get applied to src/db/repositories and src/db/seeders only. A
service, job, guard or MCP tool could send its own SQLite-only SQL through
em.getConnection().execute(...), which the Postgres probe never runs, since it
only calls the repositories. The walls now cover all of src/. The dialect layer,
the engines and the migrations stay the homes of raw SQL, and the four boot-time
lifecycle files that hold SQL text today are named and pinned to their count.
2026-11-17 23:04:10 +01:00
Maurice dd98469a02 fix(db): pass the chunk size and the abort options through the NUL-free connection
The wrapper took the chunk size of a stream as optional, which lint:strict refuses, and dropped the abort options Kysely hands executeQuery and streamQuery, so a cancelled query kept running.
2026-11-17 23:04:10 +01:00
Maurice 223a7605ed test: import vi in the trip members suite and type the move's SQLite ORM options 2026-11-17 23:04:10 +01:00
Maurice 0e04eeaf9a test: send the reset and seeding steps one by one or together, not awaited in a loop
resetDatabase empties tables and puts back the default categories one after another through the repo's oneByOne helper, where the order can matter, and the default addons and photo providers together; the MCP suites switch their addons on together and create ordered stops through oneByOne. The warnings this brings below the baseline, and the no-explicit-any and no-unused-vars counts earlier commits lowered, are lowered in scripts/eslint-baseline.json.
2026-11-17 23:04:09 +01:00
Maurice aa77e21d4b fix(db): refuse to regenerate a frozen Postgres baseline and check its trigger ports once frozen
gen:pg-baseline rewrote the baseline with its cut at the newest migration on
disk, so after a migration landed after the cut, running it moved the cut over
that migration while Postgres installs created from the old baseline would
still run it through the migrator. It now refuses while a migration follows the
committed cut, names those migrations and the routine, and moves the cut only
with --move-cut (lint:dialect keeps such a migration under the post-cut rules
either way).

check:pg-baseline stopped comparing SQLite triggers with POSTGRES_TRIGGERS once
the baseline was frozen, so a trigger a later migration created on SQLite went
unnoticed. The comparison now runs in both states, with advice that points at
the migration when the baseline is frozen.
2026-11-17 23:04:09 +01:00
Maurice 8c8cfb5d5d fix(db): hold SQLite-only functions, LIKE and the sqlite member of a post-cut migration in lint:dialect
lint:dialect missed several classes of SQL that SQLite reads and Postgres does
not, or reads differently:

- group_concat, ifnull, instr, iif, printf, typeof, total(), changes() and
  json_object/json_array/json_valid/json_type/json_quote, as calls in SQL text
  and as the bare name handed to eb.fn.
- LIKE in SQL text, Kysely's 'like' operator and MikroORM's $like, which ignore
  case on SQLite only. A LIKE that is exact on purpose now says so in a
  like-exact comment; the six existing ones (setting keys, storage paths, the
  lowercased reference search, sqlite_master) carry it.
- The sqlite member of engineDdl was not read at all, so a trigger or a data
  backfill put there never reached Postgres. It may now hold only the schema
  change and a rebuild's copy and sqlite_sequence bookkeeping, and SQLite
  statements with an empty postgres member need a sqlite-only reason.
- execBestEffort, bestEffort and execUnlessTableMissing in a post-cut
  migration: on Postgres a swallowed failure aborts the migration transaction.
- The post-cut rules follow POSTGRES_FIRST_CUT as well as the manifest, so
  regenerating the baseline over a new migration no longer releases it.

src/db/engine/sqlite/ is SQLite's own code and is no longer scanned.
2026-11-17 23:04:09 +01:00
Maurice 9eeb59997e fix(db): count every spelling of an engine check in lint:engine-dispatch
The gate matched only isSqlite(/isPostgres(, instanceof on a platform class
and a comparison on a property named engine or id. A destructured engine name,
the literal on the left, a switch over the engine, instanceof on a driver class
and a comparison with a driver class all passed with an empty baseline, and
standalone-orm.ts already held one such check. The regex now matches every one
of them, the guard in standalone-orm.ts moves into the engine port as
assertSqliteOrmConfig, and the advice names where a check belongs.
2026-11-17 23:04:09 +01:00
Maurice 8179d7d707 test(db): list the carry-over migration among the ones without a legacy step 2026-11-17 23:04:09 +01:00
Maurice f211a1c614 docs(db): describe the NUL, whole-number and calendar-date rules
server/CLAUDE.md names where NUL is dropped, INTCOL and the .int() rule
for integer columns, and the calendar-date check for a bound date, and no
longer lists the places NUL suite as SQLite-only. The Postgres wiki says
the move drops a NUL instead of refusing it.
2026-11-17 23:04:09 +01:00
Maurice f42ef5246c fix(db): store no NUL character on either engine
Postgres text cannot hold U+0000, so any write or filter carrying one (a
request body, a query string, an import, a feed, a forwarded mail, a
plugin's own SQL) answered a 500 on Postgres while SQLite stored it. Both
engines now drop the character where every value leaves for the database
(src/db/nul-free.ts): the MikroORM platforms when they inline a string or
serialize a JSON value, the Kysely dialects for every parameter, a
plugin's own SQLite file for its arguments, and the move from SQLite,
which used to refuse such text. The same request now answers the same
status and leaves the same row on both engines, so the places NUL suite
runs on Postgres as well and leaves SQLITE_ONLY.
2026-11-17 23:04:08 +01:00
Maurice e1a5864406 fix(storage): find a stored reference in any case on Postgres too
The release queue narrows each owner's rows with LIKE '%run%' before it
parses them, and relied on SQLite's LIKE ignoring ASCII case. On Postgres
LIKE is exact, so a row naming an object in uppercase was not found and
the release deleted an object that row still names. likeAny now matches
LOWER(column) against the lowercase run, which reads alike on both
engines. RELI-010 fails on Postgres without it.
2026-11-17 23:04:08 +01:00
Maurice 62c03d71bf fix(db): find no nearest day for a date the calendar does not have
The nearest-day fallback of a booking's time cast the bound date to a
timestamp on Postgres, which refuses 2024-02-30 with a 500, while SQLite's
JULIANDAY rolled it over into March and placed the booking there.
dayDistance now refuses anything but a calendar date on both engines
(isCalendarDate), so a caller that forgets the check fails on SQLite too,
and findNearestDayId answers no day for such a date. The size baseline of
Reservations.repository.ts drops by one line.
2026-11-17 23:04:08 +01:00
Maurice f4ce2c2bd0 fix(db): keep a carried-over half day as a half on both engines
A vacation day can be taken as a half day, so what a year carries into
the next can end in a half. vacay_user_years.carried_over was an INTEGER
column: SQLite stored 29.5 as a REAL, Postgres (bigint) rounded it to 30,
and the move refused such a SQLite value. The column becomes REAL on
SQLite (a table rebuild that keeps every id and the AUTOINCREMENT counter)
and double precision on Postgres, through the first migration after the
Postgres baseline's cut. VACAY-046 books a half day and reads the
carry-over on both engines.
2026-11-17 23:04:08 +01:00
Maurice d643f8c329 test(memories): answer the session retry cases by API, not by call order
The album list asks three sources at once; which call reaches the fake first
depends on how database reads interleave, which differs between the engines.
The fake now answers by API and category and the cases assert the retry with
a fresh session itself.
2026-11-17 23:04:08 +01:00
Maurice 1b270806a1 test(share): write the place photo cache through the app's own ORM
The suite built the cache over a second SQLite ORM, so on Postgres its rows
went to a database the app never reads.
2026-11-17 23:04:07 +01:00
Maurice 2d7392c4c0 fix(db): refuse a fraction for an integer column at the request boundary
Every integer column is bigint on Postgres. SQLite stored a fraction sent
to one (a packing quantity of 1.5, a budget item for 2.5 days, an id of
3.5) as a REAL, while Postgres rounded it in a statement MikroORM renders
and refused it with a 500 in a Kysely statement, so the engines held
different data for the same request.

The request schemas of those fields now take whole numbers only, and
INTCOL (tests/unit/contracts/integer-columns.test.ts) holds the class: it
reads the integer columns from the entities and fails on any DTO field or
inline MCP tool field of that name that takes any number.
2026-11-17 23:04:07 +01:00
Maurice a9cdb2f91c docs(db): describe the plugin SQL layers and the refused restore roles
The Postgres wiki page and the plugin author guide list what the plugin
SQL guard now refuses and the two layers behind it, and the wiki and
server/CLAUDE.md name every kind of role a restore refuses, including
CREATEROLE on PostgreSQL 14 and 15, which the managed postgres role on
such a server holds.
2026-11-17 23:04:07 +01:00
Maurice 2983971c8b fix(db): refuse restores for every role that can reach the database host
The privileged-role check looked only at the role's own rolsuper and at
pg_execute_server_program and pg_write_server_files. A role that is no
superuser itself but a member of one passed it and could SET ROLE to the
superuser from a crafted archive; on PostgreSQL 14 and 15 a role with
CREATEROLE could grant itself pg_execute_server_program; and
pg_read_server_files let COPY read the server's files into TREK's tables.

The check now counts membership in any superuser role, the three
predefined server roles, and CREATEROLE before 16. The boot warning and
the restore refusal describe the same list from one constant. A Postgres
lane suite creates each kind of role and evaluates the check as it, and
shows on the server it runs against whether CREATEROLE can grant itself
pg_execute_server_program.
2026-11-17 23:04:07 +01:00
Maurice e6a0a39a51 fix(db): read plugin SQL the way the Postgres lexer does and refuse INTO and TEMP anywhere
The guard ended a -- comment at LF only, while Postgres ends it at CR as
well, so "select 1 --\rfrom public.users" hid a qualified name from the
guard that Postgres then read, and with no args a second statement after
the CR ran as TREK's role. It also only looked for INTO at the top level
of a SELECT, so "(select ... into temp users)" made a temporary table that
shadowed TREK's own users table on the pooled connection.

The tokenizer now skips exactly what Postgres skips as whitespace, ends a
line comment at CR or LF, and refuses any character the two read
differently (other control characters, non-ASCII whitespace such as
U+00A0, U+FEFF and U+2028, and the non-decimal and underscored numbers
Postgres before 16 reads another way) instead of guessing. INTO is refused
anywhere but after INSERT or MERGE, at any depth, and the words TEMP and
TEMPORARY anywhere outside a string or quoted name.

The guard tests carry both payloads and their variants; the Postgres lane
runs them against the real database, proves a second statement in one
text is refused by Postgres over the extended protocol, and that a
temporary table never shadows TREK's or a plugin's tables.
2026-11-17 23:04:07 +01:00
Maurice 87612c0c79 fix(db): run plugin SQL one statement at a time and search pg_temp last
The plugin SQL guard was the only thing between a plugin and TREK's tables
on Postgres, and two gaps in it were enough to leave the plugin schema.
Two layers now hold even when the guard is fooled.

A plugin write with no bound args went over the simple query protocol,
which runs every statement in its text. Plugin statements now go through
extendedQuery, which pg sends over the extended protocol whatever the
args, so a second statement is a syntax error instead of a statement that
runs. A marker parameter carries the request to the pool's clients, and a
client without the hook binds one value too many, so it fails closed.

pg_temp is searched before the search_path unless the path names it, and
a temporary table lives as long as its pooled connection, so one left
behind would stand in for users, sessions and every other table for the
next caller. Every connection of TREK's pool now puts pg_temp last on the
search_path the role configured, and a plugin transaction sets its schema
with pg_temp last.
2026-11-17 23:04:07 +01:00
Maurice ff57883e3d test(db): run the notifications and advanced packing MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The tag notification case waits for the fire-and-forget row with
vi.waitFor instead of one turn of the event loop: on SQLite the insert
lands within that turn, on Postgres it needs a few round trips more.
2026-11-17 23:04:06 +01:00
Maurice cd1a3fd433 test(realtime): run the websocket wire envelope suite on the real database module
It takes the ORM from the app buildApp boots, seeds through the factories
and resets through resetDatabase instead of the SQLite snapshot mock, so
it runs in the Postgres lane as well.
2026-11-17 23:04:06 +01:00
Maurice 377f22972b test(db): run the trips and vacay MCP suites and the route inventory on the real database module
The MCP suites seed through the booted container's ORM instead of the
SQLite snapshot mock and reset through resetDatabase. The route inventory
never touched the database and only mocked it; without the mock it
compiles AppModule over the real module, so it runs in the Postgres lane
as well.
2026-11-17 23:04:06 +01:00
Maurice fff7d123f6 test(db): run the transports, trip members and trip warnings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The trip warnings suite seeded through the factories but only closed
the snapshot handle; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:06 +01:00
Maurice bedb70c479 test(db): run the share, tags, maps and weather, and transit MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The transit suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:06 +01:00
Maurice 3b8270edc3 test(db): run the reservations, road trip and settings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The road trip suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice 6137aaf716 test(db): run the packing, places and plugin MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The plugin search suite seeded nothing through the snapshot handle
and only closed it; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:05 +01:00
Maurice 97a3389409 test(db): run the feeds and invite, journey, leg transport mode, memories and notes MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well.
2026-11-17 23:04:05 +01:00
Maurice 95ade9cbb2 test(db): run the days, accommodations, files and help MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The collab sub-feature case in the help suite toggles through the
container's AddonsService in a request context instead of one built by
hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice c4c278d2f3 test(db): run the budget and collections MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The settlement parity cases call the
container's BudgetController in a request context instead of one built by
hand over the SQLite handle, and the collections suite drops its raw
per-table DELETE for the same reset.
2026-11-17 23:04:05 +01:00
Maurice 2cb1964863 test(db): run the AirTrail, atlas expanded, collab and categories MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The PermissionsService the AirTrail cases save
through and the CategoriesMcp and DemoService the categories write
harness attaches are the container's own, called in a request context,
instead of instances built by hand over the SQLite handle.

include_coords compares the coordinates as a set: getTravelStats reads
them through a SELECT DISTINCT without an order, and Postgres returns
them in hash order.
2026-11-17 23:04:05 +01:00
Maurice 876cc5e0f0 test(db): run the demo tool gate, addon gating, atlas and assignments MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The tour the assignment cases put on a day is
made with makeTour instead of a raw insert.
2026-11-17 23:04:04 +01:00
Maurice caae538056 test(db): merge the factory imports of the newly ported integration suites
One import per module, and the resetTestDb import that no longer has a
caller dropped.
2026-11-17 23:04:04 +01:00
Maurice 1cebddac0e test(db): run the trips and vacay suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 78bfa8183a test(db): run the share, system notices and trip access primitives suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 43af349391 test(db): run the security, settings, tags and todo suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 9c35343d9d test(db): run the scheduler gate, storage health context and uploads suites on the real database module
They drop the SQLite snapshot mock and, where they seed, reset through
resetDatabase and seed through the ORM factories, so they run in the
Postgres lane as well.
2026-11-17 23:04:03 +01:00
Maurice b0b1986377 test(db): keep the legacy upgrade suites on SQLite by name
They boot on a SQLite file the retired positional runner built, which no
Postgres database ever came from, so they belong in SQLITE_ONLY rather
than in the snapshot baseline. The lane scan now tells such a suite apart
from the snapshot mock: it mocks src/db/database onto a database of its
own, never names createSnapshotTestDb, and is named in SQLITE_ONLY with
its reason. A snapshot suite added to SQLITE_ONLY stays in the baseline.
2026-11-17 23:04:03 +01:00
Maurice f11f021e15 test(db): run the Immich, Synology and unified memories suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

IMMICH-057 and SYNO-035 need a shared photo row whose trip is gone, which
the foreign key's cascade rules out on a database that enforces it; they
write it with SQLite's foreign keys off as before and are skipped on
Postgres, which has no such switch.
2026-11-17 23:04:03 +01:00
Maurice 6e7336b8d7 test(db): run the MCP and OAuth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well. The OAuth service they drove by hand over a second ORM on the
SQLite handle is now the container's own, called in a request context.

The MCP audit cases wait for the mcp.tool_call row: the transport writes
it without awaiting it, so on Postgres it can land after the response.
2026-11-17 23:04:03 +01:00
Maurice 927fcab67f test(db): run the places and incoming leg mode suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

The two cases about a NUL byte in a place name move to
places-nul-sqlite.test.ts, listed in SQLITE_ONLY: they pin SQLite's value
quoting, and Postgres text cannot hold U+0000. The control characters
0x01 to 0x1F stay in places.test.ts and run on both engines.
2026-11-17 23:04:03 +01:00
Maurice c51f4f78bb test(db): run the packing, reservations and journey suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 12f4a40d7c test(db): run the OIDC, passkey, profile, notifications and ORM request context seam suites on the real database module
They reset through resetDatabase (the seam suite needs no reset) and seed
through the ORM factories instead of the SQLite snapshot mock, so they run
in the Postgres lane as well.
2026-11-17 23:04:02 +01:00
Maurice 3a6e91e26b test(db): run the journey place order, maps, misc and local OIDC provider suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 680ce7324a test(db): run the admin and auth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well, the user erasure cases included.
2026-11-17 23:04:02 +01:00
Maurice f5fbd60b5e test(db): run the files and collab suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 8c1395c8f1 test(db): run the atlas and backup suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 19bfa77ace test(db): run the assignments, day notes and async closure guard suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice 2fb041a428 test(db): run the feeds, atlas geocode, collections and Immich suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice be1983c9a4 test(db): run the boot, boot sweep, demo seed, AirTrail and doc sync context suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. The demo seed suite spies on the real runDemoSeed
export instead of replacing the database module to wrap it.
2026-11-17 23:04:01 +01:00
Maurice 2288487fe1 fix(oauth): narrow the refused registration for the strict compiler 2026-11-17 23:04:01 +01:00
Maurice b2384892a8 test(db): run the session revocation, api docs, app config and help suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. sessionRowsOf reads a user's session rows through
a booted app's ORM, next to sessionRows for the suites that still hand in
a better-sqlite3 handle.
2026-11-17 23:04:01 +01:00
Maurice 43e30ca28e test(realtime): run the websocket connection suite on the real database module
Seeds through the ORM factories, resets through resetDatabase and mints
ws-tokens through the container's TokenService instead of one built by hand
over the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:01 +01:00
Maurice 42f0705f07 test(todo): run the todo MCP tool suite on the real database module
Seeds through the booted container's ORM instead of a second ORM over the
SQLite snapshot mock, and resets through resetDatabase, so it runs in the
Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e97dbc89c9 fix(db): keep the stay filter inside src/db and cover the flag type's missing read
src/db may not import src/nest, so the '<id>.0' shape is spelled where the
filter is. The flag type's undefined read had no test, which left the types
folder below its branch threshold.
2026-11-17 23:04:00 +01:00
Maurice 76dfbe0a00 test(days): run the days suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 424fa538e0 test(budget): run the budget suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 863ff62b6c test(categories): run the categories suite on the real database module
It resets through resetDatabase instead of the SQLite snapshot mock, so it
runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e2b0910e28 test(db): reset a suite's database between tests on either engine
resetTestDb needs the SQLite snapshot mock's better-sqlite3 handle, so a
suite resetting with it can only run on SQLite. resetDatabase takes the
booted app's ORM and leaves the same state on SQLite and Postgres: every
table but the kept ones emptied (read from the live schema), sequences left
counting, seedDefaults' rows back through the ORM, and on the first call the
users sequence restarted as the snapshot mock normalises it.
2026-11-17 23:03:59 +01:00
Maurice cf9172f9e7 fix(db): type the move's value conversion and client for the server's compiler
Formats the two files the format gate listed.
2026-11-17 23:03:59 +01:00
Maurice 0e911608af fix(db): match a stay's bookings by the stored '<id>.0' text, as SQLite did
Reading the TEXT column as an integer also matched '14', ' 14' and '14abc',
which the legacy REAL-bound compare never did (AC37/AC40). Comparing with the
'<id>.0' text the services store keeps that contract on both engines.
2026-11-17 23:03:59 +01:00
Maurice 95d067ad6d test(auth): a plugin table missing from the schema fails the user erasure
The erasure no longer skips a missing plugin table in a savepoint of its own (61ea6b648); USER-CLEANUP-005 still expected the skip.
2026-11-17 23:03:59 +01:00
Maurice ba043cb1c0 style(plugins): keep the runtime and the SDK within their size baselines
The plugin data engine added three lines to each; six comments that wrapped past 120 columns now fit in one.
2026-11-17 23:03:59 +01:00
Maurice 3a4c523509 test(db): the move command's own output and target ORM 2026-11-17 23:03:58 +01:00
Maurice 057748c47a fix(db): set no deferred references once the move refused a value
Nothing is inserted after the first refused value, so the self-references held back had no rows to land on, and the move failed on them instead of listing the values (MOVE-006).
2026-11-17 23:03:58 +01:00
Maurice e4457ed9eb style(db): format postgresTarget as Prettier does 2026-11-17 23:03:58 +01:00
Maurice f430cbe59e chore(lint): lower the server's no-console baseline to 231
AuthService no longer warns through console when an invite's last use was taken: the registration now refuses it inside its transaction.
2026-11-17 23:03:58 +01:00
Maurice 5316362e9e fix(db): open the move's SQLite source through openDatabase, keep the drop failure as the cause
ESLint refused both: better-sqlite3 is imported only in src/db/connection.ts and its named neighbours, and an error thrown in a catch carries what that catch caught.
2026-11-17 23:03:58 +01:00
Maurice 900f2bfc30 test(realtime): read each parity case after its notification sends have settled
On Postgres a fire-and-forget notification still ran when the case read its recording, so it landed in the next case. The harness now waits for NotificationsService.settled() after each write and each exemption; a late send of any other kind still fails the next case.
2026-11-17 23:03:58 +01:00
Maurice b7c8f0629c feat(notifications): know when the sends a write left running have finished
Most writes start their notification without waiting for it. NotificationsService now tracks each send until it settles, and settled() resolves once every send started before it has finished. The channel check moves to channel-gate.ts, which keeps the service under the size limit.
2026-11-17 23:03:57 +01:00
Maurice 45fef1077a test(demo): read the baseline refusal from the logger 2026-11-17 23:03:57 +01:00
Maurice ddb42ecf0a test(db): name the restore's plugin schemas as plugin ids allow 2026-11-17 23:03:57 +01:00
Maurice 09295781f4 test(integrations): give the AirTrail suites' UnitOfWork its engine 2026-11-17 23:03:57 +01:00
Maurice 5938609f69 test(db): no await inside a loop in the Postgres tests 2026-11-17 23:03:57 +01:00
Maurice d3cd484519 test(db): stand-in pg tools write --file=- to their own stdout
The CI runner gives a child process a socket for stdout, which /dev/stdout cannot open, so every case whose pg_restore streams its script failed there. The COPY terminators in PGTOOLS-020 are spelled as a dump spells them.
2026-11-17 23:03:56 +01:00
Maurice 410d2393e0 fix(db): log the demo baseline refusal through the logger, read the tool versions at once 2026-11-17 23:03:56 +01:00
Maurice 44b6340be5 docs(db): every transaction goes through UnitOfWork, checks read inside it 2026-11-17 23:03:56 +01:00
Maurice 2f3dc4ea79 feat(lint): refuse a transaction outside UnitOfWork under src/
trek/transactions-through-unit-of-work reads the receiver's type and reports
transactional() on anything but a UnitOfWork (an untyped receiver
included), and begin() or transaction() on an EntityManager, a connection
or Kysely. src/db/engine/ and the two boot-time schema files are left out.
It runs with the rest of the server's ESLint, so lint:warnings fails on a
new one, and its message names UnitOfWork, writeTransaction and the rule in
server/CLAUDE.md.
2026-11-17 23:03:56 +01:00
Maurice af861e5816 fix(db): read the checks a write relies on in the transaction that writes
On Postgres a check read before a transaction, or outside one, no longer
holds at the write that follows: the pool runs other requests' writes in
between. Moved into the unit of work that writes:

- the last-admin guard of an admin's role edit and of an account deletion
  (deleteUserCompletely takes a precondition run in its transaction)
- the login lockout guards of the auth settings save and the SSO settings
  save
- the first-account check of an SSO sign-up, which starts over as an
  ordinary sign-up when another account won
- the OAuth client caps, the token cap and the mail intake limits
- the year check before a vacay year is opened, and the label name check of
  a rename

A password sign-up that loses the last use of an invite is now refused, as
the SSO sign-up already was, and a reset link is burned by one conditional
update, so two resets with one link cannot both change the password.
2026-11-17 23:03:56 +01:00
Maurice c1bbe27ac6 fix(db): take the write lock in every transaction that writes
UnitOfWork took the engine's write lock, but four repositories opened
transactions of their own: the demo addon set, the plugin user erasure's
savepoints, and the plugin metadata and scheduler cap checks. On Postgres
those ran beside the others on the pool.

writeTransaction (src/db/engine/write-transaction.ts) is now the one
transaction that writes: UnitOfWork wraps it, and the demo seed and reset,
which run outside the container, call it with the engine the environment
names. The capped plugin writes run in their caller's unit of work instead
of a transaction of their own, and the plugin erasure runs in the erasure's
transaction without savepoints, since its three tables come with the
migrations on both engines. lint:tx counts writeTransaction as a
transaction.
2026-11-17 23:03:56 +01:00
Maurice 11f4373076 docs(db): rotating the encryption key on Postgres 2026-11-17 23:03:55 +01:00
Maurice f57fb7f9de test(db): the key rotation on Postgres, and its refusals before a key is asked 2026-11-17 23:03:55 +01:00
Maurice 96f2427518 fix(db): rotate the encryption key on Postgres through the server's engine
The rotation ran on the SQLite file only and refused when TREK_DB_URL was
set. Its statements now go through a small store per engine: better-sqlite3
for the file, unchanged, and on Postgres the server's own MikroORM
connection, in one transaction that takes the engine's write lock first. The
Postgres path checks that it reaches a database holding TREK's tables and
that the data directory is writable before it asks for a key, writes a
pg_dump copy before it changes anything, refuses DB_PATH or TREK_DB_FILE
beside the URL, and reads the jsonb addon config the driver hands back
parsed. The SQLite transaction is now BEGIN IMMEDIATE, since better-sqlite3
takes no async function.
2026-11-17 23:03:55 +01:00
Maurice 3f51153dcc docs(db): moving an existing install to Postgres, and the refusal of an empty database beside one 2026-11-17 23:03:55 +01:00
Maurice fc37eb95d1 test(db): move a factory-seeded SQLite install into Postgres and read it back through the app 2026-11-17 23:03:55 +01:00
Maurice 55607ff2f9 feat(db): move a SQLite install into an empty Postgres database
npm run db:move-to-postgres (dist/move-to-postgres.js in the image) copies
a SQLite file at this build's migration level into an empty Postgres
database. It refuses a file at another level, rows whose references point
at nothing and a target holding any table or plugin schema, creates the
schema with the engine's own bootstrap, then in one transaction copies every
table in foreign key order (setting a self-reference once its rows are in),
converts each value to its column's type and refuses one Postgres cannot
hold exactly, copies each plugin's plugin.db into its schema, moves the
sequences past the copied ids and compares every table's row count and an
order-free checksum over all rows before it commits. A failure drops the
schema again. The SQLite files and the uploads are never written.
2026-11-17 23:03:54 +01:00
Maurice 1ea08dcf0a fix(db): refuse a Postgres boot that would leave a SQLite install behind
Setting TREK_DB_URL on an existing SQLite install booted a new, empty
instance beside its data. The Postgres bootstrap now refuses an empty
database, or a migrated one without a single account, while the data
directory's travel.db holds accounts, and names the move command. A file
that cannot be read counts as holding them. TREK_DB_IGNORE_SQLITE_FILE=true
starts anyway, with a warning; the file is opened read-only and only when
the database holds no TREK data.
2026-11-17 23:03:54 +01:00
Maurice c6f6dd2d57 fix(db): find a stay's bookings on Postgres
reservations.accommodation_id is TEXT and holds '14.0'. Compared with a bare
number, Postgres binds the number as the text '14' and finds nothing, so
deleting a stay, a day or a place left its bookings behind with no error. The
three filters read the column as an integer, as the joins already do.
2026-11-17 23:03:54 +01:00
Maurice 579df97bba fix(db): type the integer flag and the owner literal for the server's compiler
The server compiles without strictNullChecks, where a narrowed value returned
as is keeps its full type, and two literal arms of one UNION column must share
a type.
2026-11-17 23:03:54 +01:00
Maurice aa2f7ca8b4 test(db): the Postgres plugin data store against a stand-in client
Covers what every call sets up, the schema check before plugin SQL runs, the
row cap, the time budget between chunks and at statement_timeout, the quota,
a script committed statement by statement, the tx and migrate shapes and one
call at a time per plugin, without a database. The Postgres lane runs the
same store on a real one.
2026-11-17 23:03:54 +01:00
Maurice 17c9c0758f docs(db): plugin data on Postgres, its SQL rules and one TREK per database
The plugin-sdk README says what dialect a plugin writes when TREK runs on
Postgres, what the guard refuses and how the limits hold there. The wiki's
Postgres page describes the plugin schemas, their backup and restore and
the one-instance-per-database limit, and its key rotation path now names
the file where it is.
2026-11-17 23:03:54 +01:00
Maurice 7340087353 fix(db): carry the plugin data schemas in Postgres backups and restores
pg_dump now names the trek_plugin_ schemas TREK's role owns beside its own
schema. A restore reads the dump's plugin schemas from its table of
contents, drops the plugin schemas the role owns, creates the dump's and
loads them with TREK's schema, all in the one psql transaction. Schemas of
another role and every other schema of the database are never read or
dropped.

The dump's migration history is read from TREK's mikro_orm_migrations only,
so a plugin table of that name cannot pass for it.
2026-11-17 23:03:53 +01:00
Maurice 910c98b971 feat(plugins): store plugin data on the engine TREK runs on
PLUGIN_DATA binds the plugin data backend to the engine (the same
{ sqlite, postgres }[engine.id] binding the backup port uses): the SQLite
file per plugin, unchanged, or the Postgres schema per plugin. The host
opens a plugin's store through it and an uninstall that deletes data erases
through it, which drops the schema on Postgres. Nothing outside db/engine
asks which engine runs.

A plugin's SQL is passed through as written, so a plugin needs to know the
dialect: db.engine (db:own) answers 'sqlite' or 'postgres', and the SDK
exposes it as ctx.db.engine(), in the mock host (dbEngine option) and in
dev. The plugin facts are regenerated and the SDK goes to 1.10.0.

The Postgres lane's PGPLUG suite installs, uses and erases plugin data on
Postgres and shows that a plugin reaches neither TREK's users table nor
another plugin's schema.
2026-11-17 23:03:53 +01:00
Maurice b144781e9f feat(db): keep a plugin's own data in a Postgres schema of its own
A plugin with db:own got a SQLite WAL file in the data volume whatever the
engine, so a Postgres install still needed a local disk (discussion #386).
This adds the plugin data port (db/engine/plugin-data.ts) and its Postgres
side: one schema per plugin, trek_plugin_<id>, reached through TREK's pool.

Every call runs in a transaction that creates the schema if missing, puts
only it on the search_path and sets statement_timeout to the call's budget.
Reads stream through a cursor and stop at the row cap, a write that grows
the schema past the quota rolls back, and the calls of one plugin run one at
a time on at most half of the pool.

TREK's role may read every table, and a role per plugin would need
CREATEROLE, so plugin-sql-guard.ts checks each statement first: it lexes the
SQL as Postgres does and refuses another schema as a qualifier, the pg_
catalogs and functions, functions that run SQL from a string or reach an
object by a name in one, temporary tables, and every statement but DML and
DDL on tables, indexes, views, sequences and types.
2026-11-17 23:03:53 +01:00
Maurice a26db47cb6 refactor(db): keep the touched files within their size baselines
The users identity guard moves to repositories/_shared/user-identity.ts
(Users.repository.ts re-exports UserIdentityTakenError), the flag text pass
of the entity generator to scripts/generate-entities-flags.ts, and the
Wallet pass query takes the repository's EntityManager. The size baseline
of Users.repository.ts is lowered to what it holds now (1445 to 1421); a
few exports only their own file used are no longer exported.
2026-11-17 23:03:53 +01:00
Maurice 9e5379d092 fix(demo): keep a demo baseline per engine and check it before every reset
The baseline was travel-baseline.db on both engines and went straight into
the swap, so a SQLite baseline left in the data directory made every hourly
reset of a Postgres demo fail inside pg_restore, and never got replaced. It
is now named after the engine's archive entry (travel-baseline.db on
SQLite, travel-baseline.pgdump on Postgres), and the backup port's new
checkCopy refuses one the engine cannot restore before the swap; the reset
then saves a fresh baseline and logs the reason instead of failing hourly.
2026-11-17 23:03:53 +01:00
Maurice 693acd5580 fix(db): reset the admin on Postgres and keep the key rotation off it
reset-admin.js opened data/travel.db with better-sqlite3 whatever the
engine, so on a Postgres install it created a stray SQLite file or reset
the admin in a leftover one. With TREK_DB_URL set it now resets the account
in Postgres through the built server's engine (its pool, SSL and write
lock, in one transaction), and refuses a TREK_DB_FILE beside the URL; the
SQLite branch is unchanged. migrate-encryption.ts cannot re-encrypt the
secrets in Postgres yet, so it now stops before it opens or writes any file
when TREK_DB_URL is set. The wiki says what each does on Postgres.
2026-11-17 23:03:52 +01:00
Maurice c3f6177be1 fix(db): sort NULLs where SQLite sorts them on Postgres
SQLite takes NULL as the smallest value and Postgres as the largest, so any
list ordered by a nullable column (bookings without a time, trips without
dates) came back in another order on Postgres. Instead of every ORDER BY
spelling its NULL position, the Postgres engine renders SQLite's wherever a
statement names none: a Kysely query compiler for this.kysely() statements
and a MikroORM platform for find() and the query builder. An explicit
position is kept.

A new Postgres-lane suite checks the answers the probe cannot see: the NULL
order, a stay linked as '14.0' in the public reads, the traveller owner
flag, the identity errors for a lost race, and the plugin caps under a race
on the pool.
2026-11-17 23:03:52 +01:00
Maurice 60642cc18b fix(plugins): hold the write lock for the plugin cap checks on Postgres
meta.set and scheduler.set checked their caps in a transaction of the
repository's own, which keeps check and write together on SQLite's single
writer but not on Postgres, where two pool connections both read the same
count. Both RPCs now run the capped write inside UnitOfWork.transactional,
which takes the engine's write lock; the repository's transaction becomes a
savepoint of it.
2026-11-17 23:03:52 +01:00
Maurice 54b843ae29 fix(db): store addons.enabled as the integer flag on Postgres too
addons.enabled was the one flag MikroORM's boolean type declared as a
Postgres boolean, while SQLite and every other flag hold 0/1, so an addon
migration's usual SET enabled = 1 would fail there and a Kysely read would
answer true instead of 1. The column now uses IntegerFlagType: the entity
still reads a boolean, both engines store 0/1, and the regenerated Postgres
baseline declares it bigint default 0. The entity generator renders the
type for the columns in BOOLEAN_COLUMNS.
2026-11-17 23:03:52 +01:00
Maurice 633e9bcdc1 docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback
- Database-Postgres: supported versions, the version 18 client and the tool
  search order, sslrootcert with a client before 16, how to create a role
  that is not a superuser and move an older compose install to one, a
  current schema other than public, and the space a restore needs.
- Updating: the manual rollback clears the whole schema and loads the copy
  in one transaction, as TREK's restore does; dropping only the tables left
  the collation, the trigger functions and the sequences behind. A unit
  test keeps the printed statement equal to CLEAR_SCHEMA_SQL, and the boot's
  rollback hint points at that section.
- Troubleshooting, Install-Docker-Compose, Environment-Variables, README
  and server/CLAUDE.md follow.
2026-11-17 23:03:52 +01:00
Maurice eab501925f fix(deploy): run TREK as a role that is not a superuser in the Postgres compose file
The compose file let the postgres image create TREK's role as the
superuser, so a crafted backup restored by TREK could run commands in the
database container. The superuser is now postgres, with a password of its
own, and an init script creates the role trek that owns TREK's database and
nothing more. The Helm values say the same about the role in the URL.
2026-11-17 23:03:51 +01:00
Maurice 2630d7e8ec build(docker): ship the PostgreSQL 18 client tools from the PGDG repository
A client handles every server up to its own major and refuses a newer one,
so the image needs the newest supported major, 18, which Debian 13 does not
ship. The PGDG repository is added with its signing key kept in the
repository and its component pinned to 18.
2026-11-17 23:03:51 +01:00
Maurice 116ba52fbb fix(db): check the Postgres server and tools before a dump or a restore
- The client tools are looked for newest first, from 18 down: a client
  handles every server up to its own major and refuses a newer one. A dump
  or a restore now refuses a client older than the server up front, naming
  both versions, and the boot refuses a server outside PostgreSQL 14 to 18.
- sslrootcert=system is used only by a client from libpq 16 on; an older
  client is refused with a message that names sslrootcert and the bin dir.
- The restore's CVE-2025-8714 table covers 18.
- A restore refuses a role that is a superuser or may run programs or write
  files on the database host, since the archive's SQL runs as that role;
  the boot warns about such a role.
- pg_restore's script is streamed to its work file and stopped once it
  passes BACKUP_MAX_DECOMPRESSED_MB, so a small dump can no longer expand
  without limit on the data volume.
- A failed tool's error keeps only the summarized stderr; its cause names
  the exit code and signal instead of carrying the process error, whose
  message and stderr quoted row data into the log.
- The migration history is looked for in the current schema, where the
  tables and the backups are, so a role whose search_path is not public
  boots a second time.
2026-11-17 23:03:51 +01:00
Maurice e5fb6d9107 fix(db): read unique violations and missing tables the same way on both engines
guardIdentity matched only SQLite's message text, so on Postgres a lost
race for an email or a username escaped as a 500 instead of a 409. The new
dialect module driver-errors.ts reads a unique violation by Postgres's
SQLSTATE 23505 and constraint name, or by SQLite's message, and the users
repository maps the key names of both engines. isMissingTableError moves
there too and also knows Postgres's 42P01 for an unconverted error.
2026-11-17 23:03:51 +01:00
Maurice 98529bc84c fix(db): return the traveller owner flag as a number on Postgres
The owner and member branches of listTravellerUsernames selected bound
values, which Postgres resolves to text in a UNION column, so the public
API reported every traveller as owner: false. The literals are written into
the statement as integers now.
2026-11-17 23:03:51 +01:00
Maurice 4a3ad562a7 fix(db): match a stay-linked booking on Postgres in the public stay check
publicStayExists cast reservations.accommodation_id straight to integer,
which Postgres refuses for the stored '14.0', so the calendar feed and the
share links failed for every trip once any booking was linked to a stay.
The correlation now goes through accommodationIdMatches, which compares
through the new dialect helper integerTextEqualsKysely, and the Wallet pass
context uses the same helper instead of its own numeric cast.
2026-11-17 23:03:50 +01:00
Maurice 518287ff12 docs(db): describe the discovered Postgres lane and the 14/18 job 2026-11-17 23:03:50 +01:00
Maurice 0cdfb9eb42 ci(db): run the Postgres probe and lane on Postgres 14 and 18
TREK supports Postgres 14 to 18, and CI tested 17 only. One server-postgres
job per major now runs the probe and then the lane against the same service,
so the change keeps the job count of the two jobs it replaces. The lane's
global setup refuses a service whose major is not TREK_TEST_PG_MAJOR, and
the image's Postgres boot moves to 18, the major its client tools target.

scripts/ci/workflow-jobs.test.mjs fails when a job other than the scan is
missing from ci-ok's needs, and changed-areas pins that migrations,
repositories, the engine and the lane's files always run the job.
2026-11-17 23:03:50 +01:00
Maurice 4d0067a455 test(db): find the Postgres lane's suites instead of listing them
The lane ran a hand-kept list of 26 suites that had already missed
trip-tags-mcp and the broadcast-parity suites, and listed two that never
touch a database. tests/postgres/lane.ts now takes every test file that
reaches src/bootstrap.ts or src/nest/app.module.ts through its imports and
does not vi.mock src/db/database, minus a named SQLITE_ONLY map with the
reason for each.

tests/unit/postgres-lane.test.ts (PGLANE, in the SQLite lane) fails on a
suite that names a boot entry point the discovery does not see, on a stale
exclusion, and on a new suite that boots the app over the SQLite snapshot
mock; the 105 that still do are held in snapshot-suites-baseline.json,
which only shrinks.
2026-11-17 23:03:50 +01:00
Maurice 66d4431d26 docs(db): the routine for a migration after the Postgres cut 2026-11-17 23:03:50 +01:00
Maurice 293a48c26a fix(db): keep check:pg-baseline speaking once the baseline is frozen
A frozen baseline still has its manifest verified, and the check now lists the
migrations that run on Postgres after the cut and what holds them. Every
problem it reports says what to do about it.
2026-11-17 23:03:50 +01:00
Maurice 80fca10784 feat(db): hold migrations after the Postgres cut to engineDdl in lint:dialect
A migration newer than the baseline's through (read from
assets/postgres/baseline.json) fails on a schema statement outside engineDdl,
a plain string column for addColumnIfMissing or a SQLite-only helper, and on a
SQLite spelling in an engineDdl postgres member. The advice names the two
steps, and the baseline cannot hold an allowance for these rules.
2026-11-17 23:03:49 +01:00
Maurice 830cd6e3b5 feat(db): print the Postgres side of a new migration with gen:pg-migration
The script builds a scratch database the way a boot does (the baseline, then
the migrations after its cut) up to the target migration, compares it with the
entities by PARITY-PG's rules and prints the remaining statements as the
postgres member of engineDdl. The scratch database is always dropped.
2026-11-17 23:03:49 +01:00
Maurice 0f338d5484 refactor(db): move PARITY-PG's schema comparison into the Postgres engine
Which comparator statements change nothing (drop not null on a live primary
key, spelling-only defaults and checks proven by a rolled-back fingerprint, the
hand-ported triggers) is now one module the parity test and the migration
generator share, with unit tests for the sorting and the rollback.
2026-11-17 23:03:49 +01:00
Maurice a99cd40f4d feat(db): write a migration's schema change once per engine
A migration after the Postgres baseline's cut runs on both engines, but its DDL
is not one language. engineDdl(this, { sqlite, postgres }) queues the statements
of the engine the migration runs on, like addSql, and addColumnIfMissing takes a
column definition per engine, both picked in the dialect layer so a migration
never branches on the engine itself.
2026-11-17 23:03:49 +01:00
Maurice f3ea50b17b fix(db): cut the Postgres baseline at the newest migration again
The merge with dev brought eight migrations written for SQLite (DATETIME,
INTEGER PRIMARY KEY without identity); run verbatim on Postgres they stop the
first boot. No Postgres install has been released, so the baseline moves to
the newest migration and those tables come from the entities.
2026-11-17 23:03:49 +01:00
Isaias Tavares 2e3762afe1 feat(db): run TREK on PostgreSQL
TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
2026-11-17 23:03:33 +01:00
Maurice 17b47b38b9 test(places): wait for the new tag's tick, not only the tag
The tag reaches the trip's list before the form ticks it, so the button
could be found in the moment between and read as not pressed.
2026-11-17 10:12:33 +01:00
Maurice 494c848ec9 chore(i18n): drop the place form's old text placeholders
The texts card explains each text in a line of its own and the phone sheet
follows it, so the description, notes and day note placeholders are no
longer read anywhere.
2026-11-17 09:41:30 +01:00
Maurice c203b0a597 test(places): look for the hidden tab's formatting buttons too 2026-11-17 09:27:49 +01:00
Maurice b36fefdf5d test(places): keep the place form's test file at its size
The tab changes had grown it past its line budget; the labels of the texts
are covered by PlaceFormTexts' own tests.
2026-11-17 09:20:46 +01:00
Maurice 8611359f7c chore(lint): lower the tests' non-null count to what they hold 2026-11-17 09:18:50 +01:00
Maurice c8e48460b6 fix(places): settle the gates for the place form rework
The text tabs name their field type for the switch, so it type-checks. The
colour field's sliders run left to right in every language and say so with
dir=ltr and a logical inset. The new phone fields take their sizes from the
type tiers or fs() instead of rem literals, the category field builds its
icon as an element, and the ESLint and theme baselines come down to what the
tree now holds. The tests follow the tabs (only the open tab's field and
formatting bar are shown), the category list and the files row, whose link
button keeps its place before attach.
2026-11-17 09:08:41 +01:00
Maurice 5ecf3001af fix(places): keep the hooks' helper types to their files
knip counts an exported type nothing imports; the tabs' row type and the
hours' field type are only used where they are declared.
2026-11-17 08:57:18 +01:00
Maurice 2c5beee849 fix(deps): hold jsdom at 29 and isomorphic-dompurify at 3, and settle the gates
jsdom 31 failed 56 client test files: it simplifies calc() and reads an
unset border as none in computed styles, and its File no longer carries
what the upload tests hand it. It moves back to 29 with isomorphic-dompurify
3, which needs it; the lockfile is resolved from the one before the bump, so
both sit at the root as they did. jsdom stays a root devDependency, so npm
keeps the copy vitest resolves at the root.

knip 6.45 reports tsconfig-paths, which test.yml loads from the server, as
unlisted rather than unresolved; it is the server's dependency. The removed
RTL text plugin took one swallowed catch with it, so that ESLint count is
lowered to what the tree holds.
2026-11-17 08:49:37 +01:00
Maurice a3f6635633 feat(places): colour tags, tabs for the texts and opening hours on the phone
Tags on the place form are pills in their own colour, with a palette under
the dot that recolours a tag for the whole trip (PUT /trips/:id/tags/:id was
there already, the client now reaches it through repo and store) and a
custom colour field of its own instead of the system picker. A new tag is
made in a colour picked the same way.

Description, notes and the note for one day's visit sit in one card under a
switch, each with a line on where the text shows up; the day tab is named
after its day and is only there with one visit in context. Nothing about the
three fields changes underneath.

Opening hours get a switch for open around the clock next to closed. Google
writes a place open all week as one period on Sunday that never closes; it
read as Sunday open and every other day closed, and now opens every day.

The phone form follows the desktop: category as one field with a list, tags
in one field, the texts switch, and phone, e-mail and opening hours, which it
did not have. The hours and the text tabs are shared hooks (usePlaceHours,
usePlaceTextTabs). Files and costs on the phone sheets are drawn as fields
like the rest, and the paste hint, a keyboard shortcut a phone has no use
for, is gone with its key.
2026-11-17 08:44:46 +01:00
Mariano 33d074c786 feat(places): tags on places, owned by the trip
A place keeps its one category, which decides its marker, and can now carry
any number of tags as extra labels to filter by.

- Tags belong to the trip (tags.trip_id): every member sees the same list and
  whoever may edit the trip's places adds, renames and deletes. Personal tags
  stay what they were.
- The place form picks them on desktop and mobile through one shared hook,
  usePlaceTags, and can add a new tag to the trip on the spot.
- The existing category filter of the places list lists the tags as well.
- Tags show on the place (inspector pills, phone place sheet); the marker is
  untouched.
- MCP: create_place, create_and_assign_place and update_place take `tags`,
  and list/create/update/delete_trip_tag manage a trip's tags.
- /api/trips/:tripId/tags and the tripTags:changed event keep every client
  of the trip in step.
2026-11-17 08:44:10 +01:00
Maurice e952586f60 chore(deps): keep the rollup musl pins on the installed rollup
The minor and patch group raised the Alpine pins to 4.68.3 while rollup
itself stayed on 4.62.0, so npm nested a second 4.62.0 copy under rollup
and the hoisted pins went unused. The pins follow rollup again.
2026-11-17 07:56:26 +01:00
Maurice 35c0cd35ef ci(dependabot): leave TypeScript majors to be moved by hand
TypeScript 7 is the native compiler without a JavaScript API, which
typescript-eslint, the coverage instrumenter and the Postgres probe need.
2026-11-16 21:20:33 +01:00
Maurice a1d753a975 style(i18n): format Arabic and Thai locales for Prettier 3.10
Prettier 3.10 measures the width of Arabic and Thai text differently, so
strings that fit the line now stay on it.
2026-11-16 21:20:33 +01:00
Maurice 35dbcc2103 chore(deps): bump npm dependencies, jsdom 31, isomorphic-dompurify 4 and dotenv 18
The minor and patch group of #3108 without MikroORM: 7.2.9 refuses to set
the OAuth client reference from its client_id (the Postgres probe fails on
OauthTokens.insertToken and OauthConsents.upsertGrant), so MikroORM stays on
7.2.8 and with it better-sqlite3 and kysely, which it pins exactly.

mapbox-gl 3.33 shapes right-to-left text itself and removed setRTLTextPlugin,
so the engine registers nothing any more and @mapbox/mapbox-gl-rtl-text, its
Vite alias and the registration guard go. The WebAssembly module it loads
instead comes from api.mapbox.com, which the CSP already allows.

jsdom 31 and isomorphic-dompurify 4 move together, since the sanitizer needs
jsdom 31. jsdom is also a root devDependency now: listed only in the client,
npm nests it under client/ where vitest's built-in jsdom environment does not
find it.

dotenv 18 is loaded through `import 'dotenv/config'` only, which stays quiet.

Closes #3108, closes #3109, closes #3110, closes #3112
2026-11-16 21:20:33 +01:00
Maurice 3c054fffa0 chore(plugin-sdk): bump @clack/prompts from 1.8.1 to 1.9.0
Closes #3106
2026-11-16 21:20:32 +01:00
Maurice c1bad1204c ci: bump SonarSource/sonarqube-scan-action from 8.4.1 to 8.5.0
Closes #3107
2026-11-16 21:20:32 +01:00
Maurice 9890f31d10 chore(dawarich): keep the stay naming helpers module-private 2026-11-16 16:57:03 +01:00
Maurice 04e0dc26e1 fix(dawarich): name a stay from its geocoded points when Dawarich sends a placeholder
Since 1.22 Dawarich sends a visit's display name, which is "Unknown Location"
for a visit without a place. TREK showed that as the name, although the points
recorded during the stay are reverse geocoded. A stay without a real name now
takes its place's name or address, and otherwise the city most of its points
fall in. A visit without a place also takes the middle of its points as its
coordinate.

Closes #3105
2026-11-16 16:34:47 +01:00
Maurice eb56e77600 fix(studio): hold photos back only in the export's sheets
The print-mode photos held their source back for the print view, but the
assistant also draws pages in print mode and needs its photos loaded. Only
the export's sheets now ask for it, the loader reads a minimal print
document like whenReady, and the new test helpers stay within the client's
TypeScript target and lint baseline.
2026-11-16 10:47:50 +01:00
Maurice 1a50e7f0ac fix(costs): settle up only in the currency the debts were read in
After switching the display currency the flows stayed in the old one until
the new read landed, or for good when it failed offline, and a settle-up
booked those amounts in the new currency. The ledger now remembers the
currency it read, drops answers to older reads and only settles flows read
in the one shown.
2026-11-16 10:45:24 +01:00
Maurice 2a134babbc fix(trips): keep a visit's own stay when a trip is copied
insertAssignmentCopy took stay_minutes but never wrote it, so a copied trip
fell back to the place's duration for every visit.
2026-11-16 10:45:24 +01:00
Maurice 2180175040 fix(mail-ingest): refuse an undo when the booking was moved in between
A move keeps the entry's resolution and changes only its trip and created
ids, so an undo that read them before a move landed still claimed the entry,
removed nothing and left the moved booking behind. The claim is now bound to
the trip and ids it was read with.
2026-11-16 10:45:23 +01:00
Maurice 856d1e5ea5 fix(flight-live): keep a past flight's times in its booking view
The booking dialog and the phone sheet hid their departure and arrival tiles
as soon as the store held any leg of the flight, but a leg long over or never
seen by the feed draws no live card, so such a flight showed no times at
all. Both views now hide the tiles only for legs that get a card.
2026-11-16 10:45:23 +01:00
Maurice ea5542f8eb fix(plugins): require budget_edit for a plugin switching a trip's costs mode
trips.update checked trip_edit and the archive and cover permissions, but
let costs_mode through without the budget_edit check REST and MCP apply.
2026-11-16 10:45:23 +01:00
Maurice 40dea84085 fix(flight-live): leave a through flight's first sector aircraft to that sector
With two booked sectors under one flight number, the second is in its watch
window for the whole first one, and the aircraft flying the first sector was
read as the second having departed, with its departure notice hours early.
An aircraft that fits a sibling sector better is now left to it.
2026-11-16 10:45:22 +01:00
Maurice 89f7908359 fix(mail-ingest): let the pause notice job keep its cursor row
The CHECK on mail_ingest_cursor.transport did not allow 'notice', so the
hourly job that tells address holders the import is paused failed on its
lease insert every run. A new migration rebuilds the table with 'notice'
allowed, keeping every reader's position and lease.
2026-11-16 10:45:22 +01:00
Maurice f02c4c57c3 fix(android): keep the offline copy to its own server and whole across a refresh
The offline flag lived in the process, so after picking another server the
recreated activity still answered with the previous server's start page. The
copy now stands in only for the server it was activated for, and an online
start clears it.

A refresh stored the new start page before the build files it names, so one
cut off halfway left a page whose scripts were missing. The page now goes in
last, once every file is stored.
2026-11-16 10:45:21 +01:00
Maurice 5b0412bc2c fix(mail-ingest): read a mail of bare sender lines in one pass
isBareHeaderBlock rescanned the header run below every sender line, so a
plain-text mail of nothing but "From:" lines without a subject took
quadratic time and held the event loop for seconds before the address was
even checked. The block starts are now worked out for all lines in one pass
from the bottom up, with the same rule.
2026-11-16 10:45:21 +01:00
Maurice aa8d041a33 fix(studio): load a large book's photos a few at a time for the PDF export
Every printed photo got its src at once, off screen in the editor and again
in the print frame, so a journey with a few hundred photos asked for every
original in parallel and the browser failed with insufficient resources.

The print markup now holds the source back, and the print view hands it over
four at a time, retries a failed photo once, gives up on one that never
answers and shows the progress on the Save button.

Closes #3102
2026-11-16 10:30:32 +01:00
Maurice 24bc132476 fix(planner): keep an untimed stop between the bookings it was dropped between
The desktop day list hides the stop a lodging booking puts on the day, but
the places are stored across the full day. Bookings and notes were positioned
by counting only the visible places, so every hidden row ahead of a stop
pushed it one slot behind the booking it was dropped above, and it fell
below the evening flight on every drag or arrow move.

Position bookings and notes in the same full-day count the places are
stored in, and share that count with the page's reorder.

Closes #3100
2026-11-16 10:29:47 +01:00
Maurice f728b568ed test(plugins): avoid a non-null assertion in the new frame visibility tests
The added test used querySelector('iframe')! which pushes the tests
no-non-null-assertion count one over its frozen baseline; cast instead.
2026-11-15 20:39:19 +01:00
Maurice c4a2a91578 fix(plugins): pause and suspend plugin frames when they leave the screen
A tester reported that their own plugin, fine on the web, slowed the app down
badly on a phone. A sandboxed plugin iframe keeps running its timers, polling and
animation even off screen, and on a phone it shares the WebView's main thread with
the whole app, so a heavy one janks everything.

The frame now watches whether it is on screen and the app in the foreground
(IntersectionObserver + page visibility) and forwards it as trek:visibility, so a
plugin can pause its work while hidden; the design kit exposes trek.onVisibility /
trek.isVisible and pauses its own CSS animations via data-hidden. On a phone a
dashboard-widget plugin scrolled well out of view is suspended outright: its iframe
is unmounted and a placeholder holds the widget's height, so an offscreen widget
costs nothing and remounts when it scrolls back.
2026-11-15 20:33:27 +01:00
Maurice a58d0117c6 fix(packing): a lighter visibility switch and bringers side by side in the item window
The picked visibility is a raised light segment on the grey track, like the
other pills in the window, instead of a black block, and the +N of further
bringers sits beside the first picture rather than over its initial.
2026-11-15 15:08:26 +01:00
Maurice 439736e904 fix(packing): stack the item window and the Lists menu on the app's layers
The item window sits on the layer of the other floating menus and the Lists
menu just above the bars, through the z-index tokens instead of numbers, and
the theme baseline follows the files the redesign left with fewer literals.
2026-11-15 12:51:20 +01:00
Maurice 71510a62f3 fix(packing): take a bringer off in one transaction, and settle the last baselines
Clearing a common item's owner and dropping the bringer row now happen inside
one unit of work, so a failure cannot leave one without the other. The lint
and RTL baselines follow the rows that lost their last physical sides.
2026-11-15 12:40:01 +01:00
Maurice a65342574a test: bring the packing, todo and dashboard changes in line with the CI gates
Lower the lint and strict baselines the redesign made smaller, keep the
detail window and the todo tab under the complexity limit by moving their
choices into helpers, read the toast in the detail test through its module
rather than a window global, keep the new dialog focus case in the module's
existing test file, show the panel's progress once in the standalone header,
and point the planner wiring tests at the Lists menu.
2026-11-15 12:30:14 +01:00
Maurice 783a697d95 fix(dashboard): a long trip name in an upcoming booking ends in an ellipsis
The badge holds its text in an element of its own, which the ellipsis needs
inside a flex badge, and the row's middle column may shrink below its content.
2026-11-15 12:23:27 +01:00
Maurice b8966330e0 test: keep the bringer and panel width changes within the lint and RTL ratchets
The bringer tests read their items through a small type instead of any, the
panel hook names its two ceilings after the panels rather than the sides, and
the stored-width test runs on a window wide enough for the map's share.
2026-11-15 12:22:12 +01:00
Maurice cb1b5dd88c fix(dashboard): upcoming bookings read cleanly, pending as a letter on the icon
The PENDING pill beside a title broke long names over several lines; a small
dot on the type icon's corner now carries the status's first letter (A for
Ausstehend, P for Pending), with the word as its tooltip and accessible name.
The time and the trip or place below the name are soft badges instead of a
line strung together with dots. Desktop and phone alike.
2026-11-15 12:22:05 +01:00
Maurice a1f063c703 fix(collections): the add-place search reads as one field and takes the focus
The search runs from a small button inside the field, dark once there is
something to look for, instead of a greyed-out button beside it, and the row
keeps its distance from the address box below. A dialog can now mark the field
it starts in, so this one opens in the search rather than in the name above it.
2026-11-15 12:11:43 +01:00
Maurice b65a1bb65c feat(collections): the map's padlock, and a picked place on the full map keeps the map
The collections map gets the trip map's padlock (#2010): locked, a click on a
place leaves the camera where it is, so places can be clicked through without
the map zooming in and out. One setting for both maps. On the full map a
picked place no longer brings the list back: its details dock on the map's
edge, or open as a sheet on a narrow screen.
2026-11-15 12:11:42 +01:00
Maurice d1cb0a418a feat(todo): the phone's task list takes the look of the packing list
The progress card says how many tasks are done with a slim bar, a round "+"
for a new task and a "..." for the order and the lists; the filters sit in
one tinted track, with "Mine" kept short there; and the tasks are rows of one
card, with priority and due date under the name and the assignee's face.
2026-11-15 12:11:40 +01:00
Maurice 5536d29cbf feat(packing): a calmer packing list, with every item's choices in one window
A row now shows its box, its name and only what is set: the amount from two
up, the pieces packed while packing, and who brings it. A click on the name
opens a small window at the row with the list, amount, pieces packed, weight,
bag, who brings it and who sees it, each as one pill, plus copy and delete,
instead of fields, a bin and menus in menus on every row. Above the lists the
Lists bar keeps Add list and gathers templates, import, export, the order,
hiding packed items, the bags on a narrow screen and the clean-up in one menu;
the progress moves next to the Shared/My list switch. The bag overview stays.

The phone follows the same shape: one "..." sheet for the list's actions, a
sheet per list for its own, a slim row and an item sheet that saves as you go.
Who may change what about an item lives in one module both views read.
2026-11-15 12:11:15 +01:00
Maurice 7bbb5a9f71 fix(packing): anyone on the trip can be put down as the bringer of a shared item, and taken off again (#3098)
A common item only let you pledge yourself. Nobody else could be named,
and a bringer could never be removed, so an item that went personal and back
kept its owner's avatar for good. The item menu now lists every member to
tick on or off, a click on the avatar opens it there, and the add route takes
an optional user_id limited to the trip's members. Taking the owner off
clears the owner. The remove route now checks visibility for the caller, not
for the user named in the path.
2026-11-15 11:00:21 +01:00
Maurice a1bf57b71a feat(planner): planner panels widen as far as the window allows and follow the drag without lag
The side panels stopped at a fixed 520 px, which left a wide screen with a
narrow day plan. Each panel may now take whatever the window leaves once the
map keeps at least 35% of it (never under 360 px), the day plan keeping its
width first when the window shrinks. While a handle is held the width
transition is off, so the panel no longer trails behind the map and its
buttons.
2026-11-15 11:00:11 +01:00
Maurice 87bcb5a519 fix(native): an entry field pushed under the open keyboard by a new row comes back above it
The packing list keeps its entry field open after Enter, and each added item
lands above it. With the keyboard already up no keyboard event fires, so the
field slid under the keyboard after the first entry. While the keyboard is up,
a change to the page now checks the focused field again, once a frame at most.
2026-11-14 23:29:33 +01:00
Maurice c72c8dcaf7 fix(plugins): hand a visit's stay_minutes to plugins in the assignment output contract (#3092) 2026-11-14 18:03:20 +01:00
Maurice bac4599d64 fix(roadtrip): keep the stay on each visit, not on the place (#3092)
A nullable day_assignments.stay_minutes holds the stay of one visit; a visit without one keeps reading the place's duration, so existing trips drive as before. REST PUT /trips/:tripId/assignments/:id/stay and the MCP tool set_assignment_stay write it with day_edit.
2026-11-14 17:48:57 +01:00
Maurice 535761dbd5 fix(journey): draw lines across the antimeridian the short way on the Journey map (#3080) 2026-11-14 17:48:57 +01:00
Maurice 5be521199f fix(share): wrap a note's detail line and long words on a shared trip link (#3082) 2026-11-14 17:48:56 +01:00
Maurice f71acb08bd fix(assistant): send the earlier answer back to the provider in the shape it saw it (#3094)
Follow-up messages failed with HTTP 400: a whitespace-only text block, two model messages in a row where the turn had pushed for an answer, or a tool call renamed after its provider state was recorded. The rebuilt history now matches what the provider saw during the first answer.
2026-11-14 17:48:56 +01:00
Maurice d6905435ae refactor(mobile): move the trip shell's tab switch into a hook of its own, under the size limit 2026-11-14 17:48:56 +01:00
Luffy ba562c9047 fix(tests): ensure email channel is registered before sending notifications 2026-11-14 16:49:32 +01:00
Luffy 6bcc49fc6f fix(notifications): link admin emails to admin notification settings 2026-11-14 16:49:32 +01:00
Maurice 64847e906e fix(vacay): keep the last weekend day selected and restore the weekend days label 2026-11-14 16:49:31 +01:00
Luffy 75d458b06b fix(vacay): correct weekend toggling and remove redundant labels 2026-11-14 16:49:31 +01:00
Maurice a76a96ccca fix(notifications): drop a tab the planner lacks from the URL, link booking mails to the reservations tab, open the chat on the phone 2026-11-14 16:49:20 +01:00
Maurice bfdbf4d811 fix(notifications): format the tests, move the open-planner tab test into its own file, lower the exhaustive-deps baseline 2026-11-14 16:49:20 +01:00
Luffy b068e593fc fix(notifications): update navigation targets for trip and vacay events 2026-11-14 16:49:19 +01:00
Maurice d3ec833ab7 refactor(client): keep the login page's language corner class in a module of its own 2026-11-14 16:45:02 +01:00
Maurice 5e97123bdf chore(deps): raise the hono floor to 4.13.18 for its validator and routing security fixes 2026-11-14 16:37:28 +01:00
Maurice 2bcef51664 fix(native): the login page's language menu stands beside a Duo's status capsule 2026-11-14 16:33:05 +01:00
Maurice 0f42b8b8ae fix(mobile): put the top bar beside a Duo's status capsule and the page below it, full width
Keeping the whole right inset clear gave up a strip of the full height for a
capsule that only sits in the corner. The iOS app now measures an element in
a top corner (iOS 26 safe area with corner adaptation, vertical against
horizontal) and hands its reach and width to the page: the floating bars
stand beside it, the page keeps the full width and starts below it. Without
such an element, on every other device and before iOS 26, nothing changes.
2026-11-14 16:30:58 +01:00
Maurice c67c95201b style(test): format the safe-area chrome tests 2026-11-14 16:25:43 +01:00
Maurice e6f35158c5 fix(mobile): keep the page clear of a Duo's status capsule and leave a scrolled column's pull to it
TestFlight feedback from an iPhone Duo:

- Folded, the status capsule stands in the right inset and ran over the hero
  card's actions; the page now keeps clear of the side insets as iOS asks
  (.m-page), and a floating bar keeps a little air next to an inset.
- Unfolded, the top bar ignored the trailing inset and the capsule sat on the
  avatar; on a wide window the bars now end before it, by their box, so a
  bar that centres itself still does.
- Dragging the dashboard's second column back up refreshed the page: a pull
  that starts inside a box scrolled on its own now belongs to that box.
2026-11-14 16:19:44 +01:00
Maurice d541bfa838 test(mobile): the passkey confirm now closes with the user sheet it belongs to 2026-11-14 12:00:41 +01:00
Maurice ef5deada83 fix(android): write the session cookie down when the app leaves the screen
The web view flushes new cookies about half a minute after a sign-in; an
app Android ended in that time lost the sign-in it just had.
2026-11-14 11:50:51 +01:00
Maurice e1090d5427 chore(client): lower the complexity and function-length baselines the settings refactor shrank 2026-11-14 11:48:03 +01:00
Maurice 335dd9c788 fix(android): reach Capacitor's package-private injector by reflection for the offline copy 2026-11-14 11:36:47 +01:00
Maurice c23518dae0 fix(native): start without the server on Android and keep the offline start on iOS
A tester with a server on his home network could not open the Android app
away from it: after closing the app and turning Wi-Fi off it stayed on the
address screen ("No server answered at this address").

- Android keeps the server's UI itself (TrekOfflineShell): the start page
  and every file of the build, listed by native/offlineShell.ts from the
  server's manifest and downloaded natively. A web view runs no service
  worker on a plain-http server, the usual address of a server at home, so
  the old "Android has the service worker" assumption did not hold.
- Without a network, or once the server failed to load twice, the web view
  serves the copy under the server's origin with Capacitor's bridge; the UI
  runs on its own offline data and the API answers again once the server
  is back. The address screen opens the copy too (openOfflineCopy).
- The check an update asks for no longer locks the app out offline: on both
  platforms a server out of reach is put back on its copy and checked on
  the next launch that reaches it. iOS no longer throws its copy away when
  the update check runs.
2026-11-14 11:34:28 +01:00
Maurice 91f8deb3f3 refactor(mobile): keep the settings views under the size and complexity limits
The user sheet's actions on another account (passkeys, two-factor, SSO
link, delete) are MUserDangerActions with their own confirms, the place
names picker is MPlaceLanguage, and useApiKeys takes its copied flag from
a small useCopiedFlag.
2026-11-14 11:34:28 +01:00
Maurice a40ae60abb feat(mobile): API keys in the phone's settings
- MApiKeysSection: the keys with what each may read, creating one in a sheet
  (name, the areas as chips, the key shown once with a copy button), deleting
  behind a confirm sheet, and the endpoint to copy.
- The list and every action move from ApiKeysSection into useApiKeys, shared
  by both views; the calls go through a small online-only apiKeysRepo, so no
  view reaches the API (offline baseline loses ApiKeysSection and
  AdminSettingsTab).
- The phone's Integrations tab is always there now, as on the desktop: the
  keys in it need no addon.
- A test title no longer breaks on its apostrophe.
2026-11-14 11:19:06 +01:00
Maurice 5caa890523 feat(mobile): notification defaults, SSO unlink, wanderer and place names on the phone
- Admin notifications: the defaults every user's cells start as, one row per
  event with a pill per channel cycling On, Off and Blocked
  (MAdminNotificationDefaults); the grid's constants are shared with the
  desktop panel in notificationDefaultsModel.
- Editing a user offers "Remove SSO link" behind a confirm sheet, as on the
  desktop, once SSO is set up and never for yourself.
- Settings: the wanderer connection (MWandererConnectionSection, on
  useWandererConnection) and the language of place names under General.
- MSetCard takes a brand mark as its icon, not only a lucide icon.
2026-11-14 11:14:09 +01:00
Maurice a3620f9e05 feat(mobile): the admin services section gets what the desktop tab has
- Place search and routing as one card, as on the desktop: TREK's own
  services, today's allowance with a new identity behind a confirm sheet
  (MAdminServiceQuota), sharing place details (MAdminPlaceContrib), the transit
  backend and the place search provider as TREK selects, and the search log.
- The key card holds Google (with its options and the daily request cap,
  MAdminGoogleDailyLimit), Unsplash and Amap, in the desktop order.
- The logic both views need moves into one place: the transit switch into
  useAdminSettingsActions, the allowance figures into serviceIdentityModel,
  and the share-place-details panel into usePlaceContribPanel.
- MAdminSettingsSection renders each section in a function of its own.
- Tests follow the split admin sections (Save order, 2FA label, field marker).
2026-11-14 11:09:22 +01:00
Maurice dbda2d7d7c chore(client): lower the size, theme and knip baselines the mobile settings pass shrank 2026-11-14 10:59:10 +01:00
Maurice b6a296ffea style(i18n): format the help strings the Mapbox change shortened 2026-11-14 10:52:36 +01:00
Maurice ae3dfa2eb7 feat(mobile): admin and settings sections ordered and trimmed like the desktop
- The phone's admin sections follow the desktop sidebar: the same groups
  (Users, Configuration, Maintenance) in its dropdown, Security and Services
  instead of one Settings section, and live flights and booking mails beside
  the addons they configure. An old ?tab=settings link still opens Security.
- Passkey login and the 2FA rule sit with the other ways in; the passkey card
  keeps the domain, and a managed install no longer shows the danger zone.
- MAdminSelect replaces every native select on the admin screens: TREK's own
  field or row pill that opens the picker sheet (permissions, backup schedule,
  invite trip, plugin settings).
- Explanations wait behind an info mark (MHintLabel), as on the desktop: admin
  rows and fields, the settings rows' new `hint`, addon and provider rows.
- Permissions are one line each with the level as a pill; addon rows lose the
  type badge their heading already names; settings buttons no longer wrap.
- "Require 2FA" in every language; admin.tabs.settings is unused and gone.
2026-11-14 10:49:09 +01:00
Maurice bab1ca9dca feat(settings): drop the experimental badge from Mapbox GL 2026-11-14 10:29:49 +01:00
Maurice e1e8c4c63d fix(flight-live): sort attribution sources with an explicit compare 2026-11-14 10:18:03 +01:00
Maurice 5f49c87f4a fix(admin): map the retired integration group for managed tabs
The settings redesign folded the integration sidebar group into config,
but ManagedAdminTab still accepts group 'integration'. Indexing the label
map with it was an implicit any under the strict check and would have put
such a tab under an empty heading. It now lands under config.
2026-11-13 23:30:35 +00:00
Maurice 01653f81e3 test(settings): follow the redesigned settings and admin pages
The tests now look for what the pages show after the redesign: the admin
Settings tab is Security and Services, MCP Access and User Defaults are MCP
and Defaults, notification channels and the 2FA rule are rows with a named
switch, hints sit behind the info mark, each addon type card counts its own
addons, OAuth scopes and the AI sharing note are shown in full, and the 2FA
disable password is the field beside the code. The phone's MCP admin header
keeps its own title, MCP Access. The mail pill test renders with
translations, so it finds From mail rather than the key.
2026-11-13 23:10:05 +00:00
Maurice a0764b9c96 fix(settings): the checks the settings redesign left red
The phone's MCP card still read the config fold state that the shared hook
no longer holds, so the client failed to typecheck. The phone keeps its
folded config, so it now holds that state itself.

SettingsColumns takes start and end instead of left and right: the prop
types counted as two physical sides for lint:rtl, and in a right-to-left
language the first column is the right one anyway.

Also: an unused icon import, seven files outside the format baseline run
through Prettier, Routing (de) and Services (fr) confirmed as the same word
as in English, and the size and warning baselines lowered to what the
redesign left (AdminPluginsPanel one wrapped line shorter, two promise
warnings, one long function and two non-null assertions in tests fewer).
2026-11-13 23:10:05 +00:00
Maurice 94ac7673a5 feat(settings): one look for every user and admin settings page
The settings pages had grown into a mix of styles: folds, dialogs behind
rows, full-width rows next to boxed ones, pills for every figure and buttons
in four sizes. Every page now uses the same kit.

- Cards keep their tinted head band; every part of a card is a rounded block
  with its own small head (SettingsBlock), and rows sit in rounded boxes.
- Nothing folds and nothing hides behind a dialog: the MCP config, OAuth
  scopes, mail how-to, AI privacy note and addon sub-options are all shown.
- Each page is split into two columns balanced by length (SettingsColumns).
- Long explanations moved into an info mark next to the label (HintMark).
- One button size everywhere (text-control); tab names are one word.
- Admin: the old Settings tab is split into Security and Services
  (?tab=settings still opens Security, and the phone keeps its single
  Settings section for both); the Integration group is gone, live flights
  and mail import sit next to the addons they configure.
- Addons: one card per type with rows, no search, filter or fold.
- Quota, TREK API facts, mail import status and Google's daily limit are
  compact lines and strips instead of tiles and pills.
- Language is a select; routing has its own card under the defaults;
  storage saves from the foot of its categories card.
- Unused keys, FoldSummary and the page-width wrapper are removed.
2026-11-13 23:18:28 +01:00
Maurice 5fe3dea4cc feat(settings): collapsible settings cards, first on the integrations tab
The settings pages list everything at once, so they read as a wall of
forms. SettingsCard and Section take 'collapsible': the card starts shut
and its badge says its state ('Connected', 'Not set up'); its title is the
button, stretched over the head, the head's action stays its own button.
The body stays mounted while shut. A link to #id opens the card and
scrolls to it; the browser remembers a card left open.

Every integrations card is collapsible now; AI parsing shows its saved
model and MCP the apps signed in. The assistant's settings link opens the
AI connection card. Tests that read into a card open it first
(tests/helpers/settingsCards.ts).
2026-11-13 21:57:20 +01:00
Maurice 608f76f32c feat(settings): two columns for the integrations tab
From xl up, as on the admin settings: what connects your trips with other
services (booking mails, photo servers, AirTrail, Dawarich, Wanderer) on
the left, AI and developer access (AI connection, AI parsing, API keys,
MCP) on the right. A column with nothing to show drops out and the other
takes the whole width.
2026-11-13 21:35:04 +01:00
Maurice a2cc7af695 fix(bookings): keep 'From mail' out of the card and list head
Behind the title stood the review mark, the 'From mail' pill and the two
actions, and the title was cut short. Where a booking came from is looked
up in its detail dialog, so the pill stays there only. The AirTrail note
sat above the mail pill; it is back above AirTrailPill.
2026-11-13 21:21:49 +01:00
Maurice dfbe23e5b8 fix: one status tile list for both admin cards; clear the copied timer on unmount
- The mail import's status tiles (which, labels, tones) were written out
  in the desktop and the mobile card alike; statTiles in the shared model
  holds them, each card keeps its own look.
- The journey share link set 'copied' back two seconds after a copy even
  when the dialog had closed, which also broke a client test run (window
  gone at teardown). useCopied, the trip share's hook, moves to hooks/ and
  serves both; it clears its timer on unmount.
- PlanLlmConfig is not exported: only the union is used outside.
2026-11-13 21:17:28 +01:00
Maurice 6ac7bd2d96 fix(mail-ingest): read a mail as soon as a transport takes it in
Only an upload started a processing run; a forwarded mail waited for the
next two-minute tick, and one that came in right after a run waited for two.
The IMAP and relay runs start one run once they took anything in, the
webhook once per mail it accepted.
2026-11-13 21:05:54 +01:00
Maurice a67361c6bd fix(mail-ingest): read on to To when a delivery header names no address
Stalwart writes Delivered-To as the mailbox itself, its sub-address dropped,
so a forwarded mail to trek+<token>@ was refused as unknown_address: the
first delivery header won even though it carried no token. The headers are
now read in their order of trust, and the first that names a live address
decides.
2026-11-13 20:57:55 +01:00
Maurice 7a40225852 feat(llm-parse): read bookings on a ChatGPT plan
A ChatGPT sign-in only ever ran the assistant: parsing's clients call an
endpoint with a key, and a plan has none. AI connections now lends the plan
as a reader. Each document is one Responses call with the schema as the one
tool the model has to call (tool_choice required). The token is read and
refreshed per call by ChatgptAuthService, and a sign-in that has to be
renewed lends nothing.

- ResolvedLlmConfig is a union: ApiLlmConfig (what an admin configures) or
  PlanLlmConfig (provider chatgpt, a read function, never stored).
- ConnectionReadClient sends the text plus photo or scanned pages, and reads
  the filled shape, or the shape written as text; prose is unreadable.
- AiChatClientService.chatgptPlan is the one place that builds the plan's
  client, for the assistant and for parsing.
- Wiki: a ChatGPT sign-in reads bookings on its plan.
2026-11-13 20:49:08 +01:00
Maurice 29816f81a9 fix(mail-ingest): send an uploaded .eml as multipart; publish the booking origin as a contract
- The upload posted its FormData through the client's JSON default, so the
  form went as JSON and the server saw no file (400). It goes through
  postMultipart now, like every other upload.
- reservation-origin.ts becomes reservation-origin.contract.ts: the booking
  import sets an origin, and a contract is what another domain may import.
- CI: the client's strict type check holds the whole program with strict
  checks and outgrew the default ~4 GB heap; it gets 8 GB like the server's.
2026-11-13 20:49:08 +01:00
Maurice 4337969c2c fix(mail-ingest): the settings card makes the person's own address on first look
The own address was made only when asked for, and the card had no way to ask
before one existed, so it showed none. Once a template is set and the
person's import is on, the first look provisions it (idempotent; read after).
2026-11-13 20:32:31 +01:00
Maurice 6789ee1cb6 refactor(server): keep the grown files at their size baselines; centre the inbox dialog
- auth.service: how an admin form value is stored (validated, encrypted, a
  masked echo kept) moves to the app settings registry as storedAdminValue
  and isMaskEcho.
- reservations.service: a booking's origin (withoutOrigin, originColumns)
  moves to reservation-origin.ts, its input shapes to reservation-inputs.ts,
  exported on from the service so importers stay as they were.
- Reservations.repository: the joined projection, the origin lookup and the
  origin columns move to _shared/, like the Wallet pass context before.
- test-sql: MailIngestApplyService.prepare is marked as no SQL statement.
- The pending bookings dialog opens centred, and says 'nothing waiting' once.
2026-11-13 20:28:17 +01:00
Maurice 7ed15a77b4 style(mail-ingest): a more compact admin status 2026-11-13 19:55:13 +01:00
Maurice 4806c62976 feat(mail-ingest): the admin status as tiles with a health dot
The last read sits in the head line with a green dot, amber while the last
run failed; the day's numbers are tiles with their icon in a soft tone
(mails, added on their own, waiting, failed turning red above zero); the
last error is its own amber note. Desktop and phone.
2026-11-13 19:53:30 +01:00
Maurice 3957b292be feat(mail-ingest): a blue note under each way of taking mail in
Upload only, IMAP and webhook each explain themselves in the admin card,
desktop and phone: what the way means, what it needs (a mailbox of its own
taking plus addresses, a signing secret), with its icon centred beside the
title and the sentence. All 28 locales.
2026-11-13 19:50:47 +01:00
Maurice 783f679124 chore(server): lower the eslint baseline to what the code holds now 2026-11-13 19:38:57 +01:00
Maurice 7e1de86f0b test: no non-null assertions or awaits in a loop in the new mail import tests 2026-11-13 19:31:14 +01:00
Maurice c13c288f00 test(broadcast-parity): cases for the mail import's write tools
add, move, file, discard and undo of a mail booking and the import
settings each get a case with their REST twin. A trip expectation may
name its own room, for the move that announces in two trips.
2026-11-13 19:31:14 +01:00
Maurice 89b67a791f fix(mail-ingest): Outlook HTML forwards, the default AI limit, secret env vars, and the pipeline tests
- mime-walker: trim each line of a stripped HTML body, so the space a tag
  leaves is not read as a folded header line that swallows the booking
  under an Outlook forward's header block.
- settings: an unset daily AI limit is the default of ten, not zero
  (Number(null) is 0), which kept the AI from ever reading a mail.
- env: MAIL_INGEST_IMAP_PASS and MAIL_INGEST_WEBHOOK_SECRET are secrets
  and never printed in the boot report.
- pipeline test: the subject is kept without its forward prefixes, the
  demo move adds its booking before the second trip exists, the typed
  notification mock, and AI reading stays offered while the person
  switched it off.
- e2e: the pipeline tick runs in a request context of its own, as the
  cron registrar runs it, and the 401 checks run without awaiting in a loop.
2026-11-13 19:31:13 +01:00
Maurice 2ee413368b fix(mail-ingest): AI reading can be switched back on, and its hint names the addon
ai_available folded the person's own switch in, so switching AI reading off
greyed the switch out and it never came back. It now says only whether AI
reading works on the instance (the AI Parsing addon and a connection). When
it does not, the settings card says it needs the AI Parsing addon, by its
localized name, in all 28 locales; the wiki says the same.
2026-11-13 19:29:48 +01:00
Maurice 1aa586d829 test: type fixes the CI typecheck found, and the lowered test-new-service baseline
- mailInboxModel.test: actionsOf takes the entry alone since the AI reread left.
- booking-origin.test: its endpoint helper gives the sequence an endpoint has.
- test-new-service baseline follows booking-import's single service factory.
2026-11-13 19:20:09 +01:00
Maurice 53833fd212 fix(mail-ingest): server gates after joining dev, and smaller admin buttons
- lint:tx: the mail transports and the intake document why their writes stand
  alone (@txIndependent, network I/O between them, one copy per address); the
  JSDoc of NotificationsService.respond is back above it after the response
  actions were registered in between.
- lint:boundaries: booking-import asks McpToolGuardsService whether the person
  may edit the trip's bookings instead of reading the Users table; its unit
  test builds the service through one named factory.
- lint:query-api: findIdByExternal reads through Kysely.
- lint:test-mocks: the mail e2e hands its own snapshot db to the ORM instead
  of mocking the database module.
- Entities regenerated (index order only).
- Client: the review row reads the live booking, the shells share
  useMailInboxShell, and the admin card's buttons are one size down.
2026-11-13 18:58:55 +01:00
Maurice a7adef5353 feat(mail-ingest): admin card, review mark, inbox events and links, translations
- Admin settings (desktop and phone, self-hosted only): the instance switch,
  how mail arrives (IMAP or a signed webhook) with its fields, the address
  template, the AI allowance per person and day, a connection test and the
  status in counts. Changed fields only are saved; secrets stay masked.
- The review mark of an imported booking takes its mark off: the pill in the
  desktop dialog and a row in the phone's transport sheet ('Looks right'),
  through the ordinary booking update. Its hint no longer speaks of airports.
- The inbox follows mailInbox:changed and mailInbox:settings, and
  ?inbox=mail (the 'bookings waiting' notification) opens it.
- mailIngestRepo: the online-only path the views take, answers parsed
  against the shared contracts.
- Dropped 'read with AI' and the unused mail-review contract: the server
  reads a passing AI failure again on its own.
- mailInbox, mailAdmin and the new reservation, settings and notification
  strings in all 28 locales; the pending notice is a plural group.
- The live flight line on the booking cards is one of the card's fields,
  full width on the phone; the phone's live card keeps its map to the middle.
- Admin flight and mail cards sit in the left column.
2026-11-13 18:31:07 +01:00
Maurice bd11cd347d fix(mail-ingest): type errors and formatting after joining the flight work
The cron callbacks hand back nothing; the cursor's lookup is findCursor so it
no longer shadows the base repository's find(); the draft's suggested trip
uses the shared contract's type; endpoints spell out their optional columns;
the relay page's running count is typed. Prettier over every new file outside
the generated entities.
2026-11-13 18:03:14 +01:00
Maurice b19bd8e709 build: lock imapflow for the mail import's IMAP transport 2026-11-13 17:49:07 +01:00
Maurice 8dedab0375 feat(mail-ingest): inbox, settings and trip address UI on desktop and phone (wip) 2026-11-13 17:46:19 +01:00
Maurice cbd1800976 test(mail-ingest): name the control plane's fixture file the relay page is copied from
The fixture moved out of the control plane's sources so its tests read it
from disk; the comment now names where it lives.
2026-11-13 17:44:57 +01:00
Maurice 44f669cd0e feat(mail-ingest): tell every address holder once when the import stops
A plan without the import switches it off from outside the server, and an
admin can switch it off too; the plan promises a "mail import paused" note.
An hourly job sends mail_ingest_paused to each holder of a live address with
their own import on, notes the pause first, and forgets it once it is back.
2026-11-13 17:44:55 +01:00
Maurice 1d052f725f fix(mail-ingest): send mailInbox:settings, and give both events their client place
The settings event was registered with no sender; renewing or revoking an
address and changing the switches now send it. The client lists both events
as not yet shown, which keeps the registry-parity test green until the mail
screens move them to their listener.
2026-11-13 17:43:55 +01:00
Maurice f7bad3c5b3 docs(wiki): the mail import's deferred folder, recipients, limits and sender hint
Describes TREK/deferred, which header names the address, the webhook's 401
and 429 answers and where the sender hint can show at all. The variables
table leaves an empty default blank instead of a dash.
2026-11-13 17:43:54 +01:00
Maurice 264f352502 fix(mail-ingest): guard the public webhook and the settings that open it
The webhook refuses headers that cannot be signed right before reading a
byte, limits each address to 120 requests a minute and reads four bodies at
once. The admin save refuses a webhook secret under 32 characters, and the
MCP settings tool registers its input strict like every other tool.
2026-11-13 17:43:54 +01:00
Maurice 32291ce8b4 fix(mail-ingest): trust a sender verdict only from the IMAP box's own server
Anyone could add an Authentication-Results header with dmarc=pass. The hint
now needs a DKIM pass signed by the From domain or a DMARC pass naming it,
and reads it only for IMAP, where the receiving server's header is topmost;
the Cloud relay, the webhook and uploads never show a sender as verified.
2026-11-13 17:43:53 +01:00
Maurice c35f39add1 fix(mail-ingest): only the forwarder moves a booking, and filing claims the entry first
A co-member could move the forwarder's booking into a private trip, carrying
their mail along; undo stays open to editors. Move and filing refuse demo
accounts, and filing claims the entry before writing documents, putting it
back into the inbox when nothing could be filed.
2026-11-13 17:43:52 +01:00
Maurice 993ed4b472 fix(mail-ingest): refuse an upload while the person's import is off, and start no run in tests
An upload made an address and stored a mail the pipeline then put aside;
it now answers 409 instead. The run an upload asks for at once starts only
where the crons run, so it can no longer outlive a test's database.
2026-11-13 17:43:51 +01:00
Maurice e7db110417 fix(mail-ingest): read the Cloud inbox as it is sent, and keep mail refused for now
The relay job reads the control plane's { messages, more, next } page, checks
each mail on its own, pages on while more wait and is idle on a 404. A mail
for several addresses is stored for each, and a passing refusal (inbox full,
daily share taken) leaves it with the relay or in IMAP's TREK/deferred.
2026-11-13 17:43:51 +01:00
Maurice 011cc9f11f fix(mail-ingest): an empty IMAP folder is not asked for a uid range
Some servers refuse a FETCH range on a folder with no mails, which would turn
every quiet run into a failure on the status card.
2026-11-13 17:43:50 +01:00
Maurice 844d03a9cd feat(mail-ingest): REST routes and MCP tools for the settings card, the inbox and trip addresses
/api/mail-ingest serves the settings card, the inbox, the mail preview, the
.eml upload and every action on an entry; trip addresses and the admin status
and connection test have routes of their own. The MCP tools act through the
same services and never hand out an address, and the trip assistant is not offered them.
2026-11-13 17:43:50 +01:00
Maurice 1bfaf4ea98 feat(mail-ingest): read forwarded mails from an IMAP box, a signed webhook and the TREK Cloud relay
The IMAP job reads the box every two minutes through the SSRF guard, keeps a
uid cursor and moves read mails to TREK/processed. The webhook takes raw MIME
signed with HMAC-SHA256 over a timestamp, the recipient and the mail, and is a
404 unless it is the transport. The relay job collects a managed install's mails.
2026-11-13 17:43:49 +01:00
Maurice 6309064f40 feat(mail-ingest): the inbox a person reads, and moving an added booking to another trip
The inbox pages a person's entries with the mail each came from and the trip
it suggests (named only when the reader can see it), shows a mail as plain
text, and takes an uploaded .eml, reading it at once. Move writes the booking
anew in the other trip and removes it from the first in one transaction.
2026-11-13 17:43:49 +01:00
Maurice 7d3ed21a03 feat(mail-ingest): the transport settings in the admin form, each overridable from the environment
The IMAP box, the webhook secret and the address template join the admin
settings form (masked, encrypted, held by the operator on a managed install),
and MAIL_INGEST_* variables override them through the mailIngestConfig token.
The audit row masks every masked key, and key rotation covers the new secrets.
2026-11-13 17:43:48 +01:00
Maurice f319b3610a feat(mail-ingest): tell open clients when the inbox changes
Every new waiting entry and every decision sends mailInbox:changed with the count, so a badge follows without a reload.
2026-11-13 17:43:27 +01:00
Maurice 81d27d8e8d refactor(mail-ingest): keep the types nothing else imports private to their file
Exported types without a reader outside their file only add to the unused-export count.
2026-11-13 17:43:26 +01:00
Maurice de7de4b8de feat(mail-ingest): read forwarded booking mails and add what passes the checks to its trip
Addresses per person and per trip (random base32 token, stored hashed and
encrypted), an intake every transport shares, and a job that reads each
mail once under a lease: filters without AI, machine-readable data always,
one AI request with the person's trips, the server's checks G1 to G9, then
one transaction per mail that adds what passed, keeps the rest in the inbox
with a reason, and notifies the forwarder and co-travellers. Undo within
7 days, manual apply, filing as documents, a prefilled form and a nightly
retention complete it; on a managed install the operator's switch decides.
2026-11-13 17:43:26 +01:00
Maurice 340454cfc7 feat(notifications): events for bookings added from mail, and actions a domain registers
mail_booking_added tells the forwarder (with keep or undo) and co-travellers
of a shared trip; mail_booking_pending points at the inbox. Both are listed
only while the mail import is on, with texts in all 28 locales.
registerResponseAction lets a domain name what a yes/no tap does without
this module importing it.
2026-11-13 17:43:25 +01:00
Maurice 5f600cf263 style(mail-ingest): wrap the repository lines the way prettier does
The new repositories and their tests held a few lines past the 120-column print width.
2026-11-13 17:42:44 +01:00
Maurice aa84d71302 feat(llm-parse): read a forwarded booking mail and name its trip in one request
MailReadService sends one mail as one document: its subject, body and up to
three attachments inside data tags the prompt calls untrusted, with the
person's trips under references made up for the call. Answers keep only
offered trip references and known field names. BookingImportService reads
a mail's machine-readable parts and maps an AI reading to booking items.
2026-11-13 17:42:44 +01:00
Maurice baa906fb6b feat(mail-ingest): tables for forwarded booking mails and their bookings
Five tables carry the mail import: forwarding addresses (token hash plus the
encrypted token), a person's switches, the readers' cursor and lease, every
mail as it arrived, and each booking read from it with its checks and fate.
Repositories read the trips a booking may go to by column, so the import
weighs a booking without reaching into five other domains.
2026-11-13 17:42:43 +01:00
Maurice 53ebc9d632 fix(llm-parse): the local router reports how its reading ended
The Ollama router catches a failed model call and answered an empty list, which
the outcome read as a document without bookings. It now returns the outcome with
the list; failureOutcome and foundOutcome move to llm-outcome.ts so the router and
the service share them without importing each other.
2026-11-13 17:40:53 +01:00
Maurice 332206089b build(server): add imapflow for the mail import's IMAP transport
The self-hosted import reads its catch-all mailbox over IMAP; imapflow is the
client the transport is written against. The lockfile follows with the install.
2026-11-13 17:40:53 +01:00
Maurice 57d0b42726 feat(llm-parse): a MIME walker that keeps a booking mail's body and attachments
walkMail() reads a forwarded mail for the import: the envelope apart, a body
without From, To, Cc or forwarding header blocks, message/rfc822 and quoted
forwards unwrapped up to depth 10, and the PDF, pkpass, ics, JPEG, PNG and WebP
attachments whose bytes match their type. Nothing is rendered or fetched.
2026-11-13 17:40:52 +01:00
Maurice d01f973e62 feat(mail-ingest): shared contracts for the booking mail import
Zod contracts for the forwarding address, the person's switches, messages,
the bookings read from them, the inbox and every action on an entry, the upload,
the webhook and the admin status card. One reason enum names why a mail or booking
waits, mapped from every AI outcome; mailInbox:changed and mailInbox:settings are
registered as user-scoped events.
2026-11-13 17:40:51 +01:00
Maurice d557f08e28 feat(llm-parse): a typed outcome for every AI reading instead of warning text
LlmParseService.parse() now says how a reading ended (ok, empty, no_text,
quota_exhausted, ai_disabled, user_cap, provider_error, too_large). The clients throw
LlmRequestError with status and body code, so the TREK Cloud gate's 429 QUOTA_SPENT
and HARD_CAP read as a spent allowance. The preview reports the outcome per file and
the assistant reads its empty reason from it rather than matching warning strings.
2026-11-13 17:40:29 +01:00
Maurice 5dc1de0e5b feat(booking-import): report each unconfirmed item and check the right in confirm()
confirm() now answers { created, failed: [{ index, reason }] } instead of logging
and dropping the items it could not write, and checks the trip and reservation_edit
itself so the import route and the assistant get one answer. An item with a booking
reference records it as its origin (sync off) and a repeat import is a duplicate.
2026-11-13 17:40:27 +01:00
Maurice d2b12cd3dd feat(reservations): record an import's origin and scope the joined read to its trip
CreateReservationData and insertReservation take an optional external_source,
external_id and sync_enabled, so an importer can record where a booking came from;
without them every write keeps the column defaults. Client bodies on REST and the
plugin RPC have the origin stripped, so no caller can pose as an import or a link.
getReservationWithJoins now takes the trip and reads nothing outside it.
2026-11-13 17:40:27 +01:00
Maurice 64418489e2 fix(map): guard the GL bridge's resize frame on the layer it attaches
Reading the bridge's MaplibreGL export threw under the test mocks, which
define only the factory, so every mocked basemap counted as an unloaded
chunk. The guard now patches the class of the layer being attached, and
only a class that has _transitionEnd itself, so stand-in layers are left
alone.
2026-11-13 17:20:15 +01:00
Maurice 7238f8ae25 fix(flight-live): reuse the basemap's label hiding and keep the GL guard optional
The resize guard reached for the bridge's MaplibreGL class, which the test
mocks of the bridge do not provide, so every mocked basemap counted as an
unloaded chunk. The guard now only applies where the class exists. The
mini map hides place names through VectorBasemap's own hideLabelLayers
(a hideLabels prop) instead of a second copy of that logic, and the route
test no longer uses Array.prototype.at, which the client's lib target lacks.
2026-11-13 17:02:39 +01:00
Maurice e525e0b838 feat(flight-live): route mini map and a calmer live card; fix the CI gates
The live flight card shows a small real map behind the pass: the great
circle between the airports, solid where flown and dotted ahead, the
aircraft on the line turned along the route. The route is framed in the
free middle, the map fades out under the airports and times laid over it,
and its place names are hidden. Data and map credits sit on the map as its
hover text instead of a footer line.

The card head now follows the booking dialog: a tinted band with pills for
the state, what comes next and the delay; the numbers of the moment use the
dialog's fields on the desktop and the sheet's stat boxes on the phone; both
times sit on equal tiles in one line. Without live data the card, the strips
and the plan line show nothing, and the pulsing dots are gone.

Also fixes the failed dev run: unit symbols and the leg position are listed
as NOT_PLURAL, the aircraft label uses logical sides, the flight store is in
the test reset registry, the sync loop stops once no flight lies ahead (no
endless timers under fake timers), and timeCell and widgetFlight drop below
the max-params and complexity limits. Guards the GL bridge's resize frame
against a layer removed before it runs, and keeps the booking code pill as
tall as its neighbours.
2026-11-13 16:39:46 +01:00
Maurice 2d95bf6744 docs(wiki): live flight status and FLIGHT_LIVE_ENABLED
The transport page explains what TREK follows, where it shows and what open
data cannot give; the environment page documents the switch and what leaves
the server.
2026-11-13 15:36:43 +01:00
Maurice 41134cc455 fix(native): read the flight widget's direction from the locale
Android lint refuses a composition reading the Configuration through
LocalContext. The arc's mirroring now follows the locale's layout direction,
which is what the widget's language decides anyway.
2026-11-13 15:36:43 +01:00
Maurice 27f12c2245 feat(native): a flight widget and a boarding-pass Live Activity
A new Flight widget on iOS (small to large and the lock screen) and Android
shows the trip's next flight or the one in the air: both airports, the arc
with the aircraft, a countdown the system keeps running, and the delay. It
follows the feed's phase, so a late departure is not flown along the arc.
Around a flight the travel day's Live Activity becomes a boarding pass with
a running bar and countdown, in the Dynamic Island too.
2026-11-13 15:29:21 +01:00
Maurice 4796615439 feat(flight-live): a live boarding pass on the web, desktop and phone
The booking dialog and the phone's transport sheet show a flight's moment,
both airports with planned and expected times, the route as an arc with the
aircraft on it and the numbers of the flight; booking cards and day plan
rows get a one-line state with a progress bar. The trip map draws the
aircraft in the air on Leaflet and GL, and the admin settings carry the
switch. Translated into every language.
2026-11-13 15:29:10 +01:00
Maurice 154563f34d feat(flight-live): follow booked flights live from keyless ADS-B feeds
A new flight-live domain polls the open feeds adsb.lol and adsb.fi (no key,
no cost; adsb.fi only on self-hosted installs, its terms are non-commercial)
for every booked flight leg in its watch window, derives phase, take-off,
landing, delay and an arrival estimate, and pushes changes as flight:live.
GET /api/trips/:tripId/flights/live, the MCP tool get_trip_flight_status,
notifications for take-off, landing and delays, and the admin switch
flight_live_enabled (FLIGHT_LIVE_ENABLED wins) come with it.
2026-11-13 15:29:03 +01:00
Maurice 3365511b10 fix(bookings): the file buttons of a booking never wrap their label
"Vorhandene verknüpfen" broke onto two lines in the narrow half of the
booking dialog. The labels now truncate instead of wrapping, and the German
label is the shorter "Datei verknüpfen", matching "Datei anhängen".
2026-11-13 15:28:55 +01:00
Maurice c2c0535d52 fix(ci): list the packing share pair, and read a stored costs mode through its enum
The whole-list sharing runs on usePackingCategorySharing in the packing panel
and the phone tab, its sheet is markup fed by the tab. The trips service reads
a stored costs_mode as one of TripsCostsMode, which the export check wants used.
2026-11-13 13:30:37 +01:00
Maurice d6799d1205 fix(ci): the calendar query DTO as the contract it publishes, and two typed tests
feeds and trips import the calendar query DTO, so it lives in
calendar.contract.ts rather than as calendar's internal dto file. The places
controller tests pass the KML service in every call, and the revisit pill
test builds a whole list.
2026-11-13 13:13:13 +01:00
Maurice 9cbf31da27 fix(client): the trip form's review and the slow-open splash, and the tests that followed
Inside the trip settings, Escape and the backdrop no longer close the dialog
while the date question is up, and the embedded form does not load the
members it does not show. Every trip open is timed afresh for the splash.
The tests follow the cover image card, the danger button, the delayed splash
and the open and download mocks.
2026-11-13 12:57:57 +01:00
Maurice 71cc97822a fix(ci): the second round of the quick-win checks on the server
oidc_auto_redirect is managed-locked in the registry too, costs_mode is read
as the mode it is, the days of a dated trip are read through the factories,
and the dashboard's country order moves out of the atlas service into a
module of its own, so the service keeps its size.
2026-11-13 12:57:56 +01:00
Maurice c2ba78253d fix(client): lint, theme and size ratchets of the quick-win round, and the tests that followed the features
New warnings fixed at their source (refs written in effects, typed tile
options, no stray imports, smaller functions and components), the payer and
split heads hold their switch instead of letting it overhang, the baselines
lowered where the round removed warnings, and the tests updated to the
solo trip, the shares view and the revisit status.
2026-11-13 12:40:17 +01:00
Maurice 75aeba29ed feat(mobile): calmer trip settings, list editing, selecting places and the journey map switch
The trip settings sheet opens on a list of its areas, each a page of its own
with a way back, and the journal there is drawn in the phone's own cards. A
new packing list is typed into a card with its add and cancel, selecting
places keeps its way out in view with the actions as icons below, and the
journey's satellite switch sits in its bar beside the menu.
2026-11-13 12:40:16 +01:00
Maurice bd58f17ec0 feat(trip-settings): edit the trip inside its settings, in one look across the areas and the trip form
Edit trip is an area of the settings dialog, beside People, Sharing and
Journal, instead of a second dialog. The side column names the areas only, the
dialog keeps one height, and every area uses the same cards, fields and
buttons; the trip form on its own takes the same head, cards and buttons. A
trip that loads quickly opens without the splash on the desktop too.
2026-11-13 12:40:16 +01:00
Maurice 721a610a70 fix(ci): green the quick-win round on the server, the shared contracts and the plugin facts
The trips entity takes costs_mode as the generator writes it, the plugin
output contract publishes it, and the hand-built test schemas carry it. The
new MCP fields come from @trek/shared, the link tool tests join the collab
file that already mocks the database, oidc_auto_redirect is the operator's
on a managed install, and the tests follow the KML service, the dated trip
days and the zod pipe.
2026-11-13 12:40:15 +01:00
Maurice eda27f1e59 fix(costs): the receipt link is an icon, so the receipts title keeps one line (#2839) 2026-11-13 11:06:48 +01:00
Maurice a08d4b944e feat(mobile): icon-only action rows in the transport and booking sheets (#2585)
The transport sheet's row wrapped once a ticket and the wallet were there.
Its actions are icons now, named by their labels, and the attachments sit in
their own rows with a download, like the transports list. The wallet is a
black circle, beside the close button in the booking editor. A failed
download on the phone now says so.
2026-11-13 10:49:30 +01:00
Maurice 5137bcb86a docs(wiki): no dashes in the collab sub-feature sentence (#3076) 2026-11-13 10:49:30 +01:00
Maurice 7861006bf5 fix(journey): theme tokens for the album date range (#2859) 2026-11-13 10:49:29 +01:00
Maurice 5f6594f697 fix(tours): Google Maps follows a tour on foot or by bike, CoMaps only gets a route it can follow (#2812)
The Google link carried no mode, so a hike opened as a drive, and a stop on
the equator or the prime meridian was dropped. CoMaps routes a start and an
end only; a tour with stops between would reach it as unrouted pins.
2026-11-13 10:49:28 +01:00
Maurice fcbb538c24 fix(costs): the count beside the total adds up what it does, and its left-out chip counts all again (#2819, #2839)
With a category left out the total card still counted every expense, and in
the table view the only way back was to switch views; the chip now brings
everything back. The phone says what is left out once, under the total.
Linking a receipt offers pictures and PDFs only, like the upload.
2026-11-13 10:49:28 +01:00
Maurice 43a8984e4c feat(planner): a calmer place inspector footer, and a folded place opens in full again
The footer wrapped once a place had a day, a website and a collection. Now
only adding to the day, navigation and edit carry words, website and
collection are icons, and removing from the day and delete sit behind one
"…". The words drop out when the panel is narrow (a tablet) instead of the
row wrapping. Folding is kept for the place on show only (#3039).
2026-11-13 10:49:17 +01:00
Maurice e958a9a2bb feat(ui): icon footer button, and a button menu at the foot opens above its button
DialogIconButton is the square footer button DeleteButton already was, for
any action named by its tooltip. A "…" menu near the bottom of the window
used to be pushed up over its own button; it now opens above it.
2026-11-13 10:49:17 +01:00
Maurice 986dabf11f fix(categories): the new bus, station and airport icons count as transport (#2706) 2026-11-13 10:48:58 +01:00
Maurice 318e71aa0c fix(pdf): shrink place photos without AbortSignal.timeout and decode them near thumbnail size (#1501)
Safari before 16 has no AbortSignal.timeout, which cost the whole export; a
controller and a timer replace it. Photos decode at twice the thumbnail
height and three at a time, so a long trip no longer ends the web view.
2026-11-13 10:48:58 +01:00
Maurice 308daec14e feat(packing): change the sharing of a whole list at once (#2961)
The list menu on desktop and phone gets "Sharing for Whole List": pick
Shared, Personal or Shared with people once and every item of yours in
that list moves there through the existing per-item sharing write. Items
other people added stay as they are, and the dialog says so up front.
2026-11-13 10:17:35 +01:00
Maurice 3f68c8a50e feat(bookings): download button on booking and transport attachments (#2585)
Each attached file row now has a download icon next to its name, on the
desktop booking cards and detail dialog and on the phone's bookings and
transports cards. On the phone the file rows move out of the card body
button so open and download are two real sibling buttons.
2026-11-13 10:17:35 +01:00
Maurice 74af74fb5e feat(atlas): show the most recently visited countries first on the dashboard (#2648)
The place and endpoint reads behind the passport tile now carry the last day
of each started trip, and getTravelStats orders the countries by their latest
visit, with countries only marked by hand after them. The country set is
unchanged; repository, parity and service tests pin the order.
2026-11-13 10:17:26 +01:00
Maurice 924b4e0787 feat(auth): let admins keep the login page on OIDC-only instances (#2925)
A new app setting oidc_auto_redirect (default on) is part of the admin form
and the public app config. Off, an instance without password login no longer
sends visitors straight to the IdP: the login page shows its SSO button,
also while the cached config is read. Admin toggle on desktop and phone.
2026-11-13 10:17:26 +01:00
Maurice d5d9428cf2 feat(calendar): let a feed leave out the per-day summary events (#2602)
Both feed routes and the one-off export.ics take ?days=0, validated by a
shared query contract, and then skip the all-day "Day N" event per day; the
default is unchanged. The subscribe dialog gets a Day overview events switch
that adds the parameter to its links, export_trip_ics takes dayEvents and the
feed tools explain the parameter.
2026-11-13 10:17:25 +01:00
Maurice b9231ffb53 feat(mcp): manage the trip's shared links over MCP (#3076)
list_collab_links, create_collab_link, update_collab_link and
delete_collab_link run the Links panel's REST routes as tools: the shared
body contracts, trip access, collab_edit on writes and the collab🔗*
broadcasts, behind the links sub-feature flag. Unit, e2e and broadcast
parity cases cover them; the wiki lists the tools.
2026-11-13 10:17:15 +01:00
Maurice 489ba93c0c feat(mcp): let update_display_settings set the dashboard world clocks (#3044)
dashboard_timezones joins the display-preference allow-list as a list of
IANA zone ids, each checked with Intl like the widget does, without repeats
and capped at 24. The write goes through saveMany, so open tabs refresh, and
both tool descriptions name the widget's fallback zones.
2026-11-13 10:17:15 +01:00
Maurice 2a448722c6 feat(helm): make the PVC access modes configurable (#3061)
persistence.data.accessModes and persistence.uploads.accessModes default to
ReadWriteOnce, so existing installs render the same claims. ReadWriteMany lets a
backup pod mount the volumes; values.yaml and the docs warn that SQLite allows
only one writer of travel.db. CI renders the override too.
2026-11-13 10:17:14 +01:00
Maurice cd53d0a895 feat(tours): open a tour's route in Google Maps, Apple Maps or CoMaps (#2812)
The tour detail gets a Maps button beside Navigation that hands the whole route
to the apps that follow one, in the tour's own mode (walking or cycling). The
stops are spread evenly along the line and capped at ten, the most a Google
Maps directions link opens. Ski, paddle and horse tours are not offered, since
a map app would route them by road; the GPX export stays the way for those.
2026-11-13 10:17:14 +01:00
Maurice db6bb911c2 feat(roadtrip): show the place photo on the stop sheet and the stop dialog (#2629)
On the road a stop's picture is often what decides whether it is worth the
detour. The phone's stop sheet shows the place's picture full width under its
name and the desktop stop dialog shows it in place of the kind tile; both open
the place's photos on tap. The picture is the place's own image, else the
provider photo for its Google or OSM id through the shared photo cache.
2026-11-13 10:17:14 +01:00
Maurice 69552ffeef feat(journey): satellite base layer on every journey map, the shared page included (#2594)
The journey map gets the planner's round satellite switch in its top corner,
on the desktop aside, the phone views and the public page. Leaflet takes the
vector basemap off while the imagery shows and reattaches it on the way back;
the GL renderer slides the imagery under the journey's own layers. The choice
is per view and opens on the map, so no setting is read or written.
2026-11-13 10:17:13 +01:00
Maurice 1f710bd217 feat(journey): narrow an open photo album to a date range (#2859)
A shared Immich or Synology album can hold hundreds of photos from other
trips. Once an album is open the picker now offers a from/to range that
filters the already loaded assets by the day the grid files them under, so
Select all only takes the photos in range. No server change.
2026-11-13 10:17:13 +01:00
Maurice 11e4fe6ae3 feat(dawarich): preselect the stay's day in the accept dialog (#3068)
The accept dialog opened on "not on a day yet" although the stay carries its
local date. It now picks the trip day whose date matches, on open and when the
trip is switched, and falls back to no day when the trip has none that matches.
2026-11-13 10:17:13 +01:00
Maurice 3e98938c95 feat(export): places as KML for Google My Maps (#1866)
Google Maps takes no list from outside, but My Maps imports a KML layer.
The trip export dialog and the phone export sheet get "Places for Google
My Maps" (GET places/export.kml, MCP export_trip_kml), and a list's export
menu gets KML next to GPX. The KML codec gains a pin writer; the list file
mapping moves to collections.helpers to keep the service within its size.
2026-11-13 10:17:12 +01:00
Maurice 7283b75cac feat(mcp): list_collection_places pages a long list compactly (#2647)
A read tool that answers one list a page at a time (100 by default, up to
500) as compact one-line JSON rows, filtered by status, label or "no label",
with the list's labels, the matching total and a cursor. The cursor is the
last place's position (sort_order, created_at, id), so labelling a page
while paging through unlabelled places skips none. getCollection orders by
the same keys, id last, so both tools agree on ties.
2026-11-13 10:17:11 +01:00
Maurice cae04e83dd feat(collections): edit a saved place's provider ids, website, phone and price (#2646)
The update contract takes google_place_id, google_ftid, osm_id, website,
phone, price and currency like saving does, website with the same
normalisation and refusal. REST and update_collection_place share it, so an
agent can correct a place instead of re-saving it and losing its labels,
ratings, position and id. The assistant's change card names the new fields.
2026-11-13 10:17:11 +01:00
Maurice 72e8b1f8d9 feat(collections): "want to revisit" status for saved places (#2567)
A fourth status after visited, for a place already seen that the user wants
to go back to. It joins the one-tap cycle, the filters, the pickers, the
assistant cards and the MCP status tool, and counts as visited wherever
visits are counted (isVisitedCollectionStatus), so "visited everywhere"
keeps it. The status pickers go two by two where four would not fit.
2026-11-13 10:17:11 +01:00
Maurice 73ac4b29ad feat(collections): filter by category on the phone (#2618)
The phone toolbar gets a category chip beside the status and label chips,
fed by the same categoryOptions the desktop dropdown uses, and no longer
clears a category picked on desktop. Managing labels moves into the label
panel so the row keeps four chips at phone width.
2026-11-13 10:17:10 +01:00
Maurice 208af03212 feat(dialogs): save a dialog with Ctrl/Cmd+Enter (#1303)
Ctrl/Cmd+Enter in any field of a DialogShell presses its one primary footer
button, focusing it first so blur-committed fields keep their value. Dialogs
with no or several primaries leave the keys to the field, as does the journal
story editor, which opts out with data-keeps-ctrl-enter.
2026-11-13 10:17:07 +01:00
Maurice 8401428ca7 feat(pdf): bake place photos into the trip PDF at thumbnail size (#1501)
The print engine embedded every place photo at full resolution, so a trip of a
few hundred stops saved to a PDF of tens of megabytes. Same-origin photos are now
fetched six at a time, scaled to a 156 px short side and inlined as JPEG data
URLs; photos from other origins, failures and an aborted export keep the URL.
2026-11-13 10:17:06 +01:00
Maurice 12406bbbf4 feat(pdf): large text switch in the trip PDF preview (#2817)
A third switch next to the page break and transport notes switches scales the
day content's type by 1.35 and darkens its greys, for readers who print the
plan. Off by default and remembered per browser like the other two; the day
content's sizes and greys now come from three CSS variables on <body>.
2026-11-13 10:17:06 +01:00
Maurice 12ae32b69e feat(map): setting to hide the Mapbox basemap points of interest (#1761)
Mapbox Standard labels shops, restaurants and sights of its own; they look like trip
places but cannot be picked. A Hide Points of Interest switch next to the other Mapbox
options, on the desktop and the phone, turns them off on the trip map and the preview
without a rebuild. The Standard config handling moves into useStandardBasemapConfig.
2026-11-13 10:17:06 +01:00
Maurice 5176dc29d6 feat(places): say when a place has an address but no coordinates (#2837)
A place saved with a typed address and no search pick, link or map point gets no
coordinates, so it never shows on the map, and nothing said why. The place form warns
under the address while that is so, and the inspector, the phone's place sheet and
both place lists mark such a place. No geocoding on save; the form stays unchanged
for a service stop, which explains a missing position itself.
2026-11-13 10:17:05 +01:00
Maurice 0eac3a9f49 feat(planner): fold the place inspector to its head and keep the place selected (#3039)
On a landscape phone or a small tablet the inspector covered most of the map, and the
only way to clear it was closing it, which deselected the place. A chevron in the head
now folds the card to the avatar and name; the next place opens in full. The head band
moves to PlaceInspectorHead so the inspector stays inside its size budget.
2026-11-13 10:17:05 +01:00
Maurice 64b86c2403 feat(planner): edit the trip from its settings in the planner (#2811)
The trip form was mounted in the planner but nothing opened it, so title, dates,
cover and currency could only be changed from My Trips. Trip settings now lists
Edit Trip at the foot of its areas for anyone with trip_edit; it swaps the dialog
for the trip form. The phone already has Edit Trip in the More sheet.
2026-11-13 10:17:04 +01:00
Maurice 66d85729ff feat(categories): icons for parking, bus stops, stations, airports and fuel (#2706)
The category picker had no icon to tell a car park or a terminal apart from the
places a trip visits. Five transport icons join the shared table, which the admin
pickers, map pins and the PDF all read; the ship's tooltip now also says ferry.
2026-11-13 10:17:04 +01:00
Maurice e7bff6681e fix(roadtrip): a hire car picked up after a night sets off from the stay (#2993)
With hotel bookends on, a day whose first stop was a hire car pick-up got no morning
bookend, so the drive from the stay to the desk was missing. Only a landing means the
traveller was not at the hotel; the pick-up is the first drive of the day.
2026-11-13 10:17:04 +01:00
Maurice c7cfa5a64f feat(costs): read a trip in another currency from the Costs tab (#1683)
Costs always converted to the display currency from Settings, so a trip
that moves on to another country could not be read in its new local
currency. A picker in the Costs bar (beside the Expenses heading on the
phone) now reads one trip in any currency; the server already settles in
any base. The pick is per trip and kept in this browser, nothing stored.
2026-11-13 10:17:03 +01:00
Maurice 72fc61a016 feat(costs): leave a category out of the totals for a look (#2819)
Seeing what a trip cost without, say, food meant adding it up by hand. A
click (or tap) on a category in the breakdown now leaves it out of the
total, your share and what you paid, dimmed in place with a line naming it
and Count all to undo. View only: nothing is saved, and what is owed, open
or settled stays whole. The desktop breakdown moves into its own component.
2026-11-13 10:17:03 +01:00
Maurice a70eea5bf2 feat(costs): let a trip keep its costs as totals only (#1714)
Travellers who track what a trip costs but never split it saw an
Unfinished warning on every expense and a settle-up they had no use for.
A trip now has a costs mode (appended migration, trips.costs_mode, split
by default); totals leaves payers, shares and settling up out of Costs on
desktop and phone through the same gate as a trip of one, and saves new
expenses without a payer. PUT /api/trips/:id and update_trip take it on
budget_edit. The split chips move into their own component.
2026-11-13 10:17:03 +01:00
Maurice c9c419b4ad feat(costs): leave out owing and settling on a trip of one (#2689)
With one traveler every share is the whole amount, yet Costs showed owe,
owed, outstanding, settle-up, balances and the final budget. A shared gate
(showsSplitting) now hides that side on desktop and phone, unless the ledger
still names someone else; the expense editor drops who paid and the split
while the expense holds nothing more. The payment dialog moves into its own
file to keep the panel under the size ratchet.
2026-11-13 10:17:03 +01:00
Maurice 6759277c3b feat(costs): link a trip file as an expense receipt (#2839)
A booking confirmation that is also the invoice had to be uploaded a second
time to sit on the expense. The expense editor (desktop and phone) now lists
the trip's files to link, the booking's own first; the save sends the id in
receipt_file_ids, which the server already links. The desktop receipts block
moves into its own component.
2026-11-13 10:17:02 +01:00
Maurice 10d5f3ed46 feat(costs): split a custom expense by shares (#1165)
A stay shared by people who slept a different number of nights had to be
worked out by hand. The custom split now takes shares next to amounts and
percent: five nights against four split the total 5/9 to 4/9, cent-exact by
largest remainder. Only the amounts are saved, so server and MCP are
unchanged; the phone sheet gains the same unit switch, percent included.
2026-11-13 10:17:02 +01:00
Maurice 2934319722 feat(costs): start a new expense in the trip currency (#2807)
A new expense opened in the display currency, so every bill on the road
needed the trip currency picked from the full list. It now starts in the
trip's own currency (a scanned receipt keeps the one it read), and the
trip and display currencies lead the picker on desktop and phone.
2026-11-13 10:17:02 +01:00
Maurice d4c81bc5f2 chore(lint): lower the warning baseline for the two promise rules the dock change cleared 2026-11-13 08:42:01 +01:00
Maurice 35e0613986 test(native): read the listener names as strings, so the appLinks case typechecks 2026-11-13 08:34:05 +01:00
Maurice ccfa92f650 feat(mobile): the assistant is an entry of the dock, sorted like the pages
The home assistant sat behind the More button on every page outside a
trip, so a dock with free slots showed "..." for a single entry. It is now
an entry of the dock list while its addon is on and it can run for the
user: an account that never sorted its dock gets it in a slot the addons
leave free, and Settings > Appearance > Mobile can move it between the bar
and More like any page.
2026-11-13 08:27:31 +01:00
Maurice fdb2095ced fix(native): a widget tap opens its page every time, also after iOS ended the page
A widget or Live Activity tap reached the UI as Capacitor's appUrlOpen, or
as the launch URL. When iOS had ended the web view's process in the
background, the event went to the old page's listeners and was lost, and
the reloaded page found the same link in getLaunchUrl that it had already
followed once and skipped it: the second tap on the packing widget opened
the start page.

The binary now takes com.liketrek.trek://navigate links itself and hands
them over like a quick action, held until the UI takes it and kept for a
page that is still loading. It reports the feature appLinks, and the UI
only follows the link through Capacitor for binaries without it.
2026-11-13 08:27:23 +01:00
Maurice d6a6b49b6b test(planner): the #3074 case in a file of its own, and the category pick inside guessedCategory, so both files stay within their size 2026-11-12 23:18:51 +01:00
Maurice 0855bafca7 fix(search): place searches find a name typed without its accents (#3075)
"Obidos" did not find "Óbidos", nor "Sao Bras" "São Brás". The search of the
places list, a collection, the saved-place picker, the import from a trip
and the location picker now compare without case and Latin accents, with
letters such as ß, ø or ł folded to their plain spelling. Marks outside Latin
script stay, since there they change the word.
2026-11-12 23:06:36 +01:00
Maurice a39f3fe40c fix(planner): a place added from a collection keeps its category (#3074)
The place form guessed the category of a picked place from its kind, so a
place taken from a collection inside a trip lost the category it was saved
under, while adding it from the collection kept it. A picked place that
carries a category this server has now brings it along; a category chosen
in the form by hand still wins.
2026-11-12 23:06:35 +01:00
Maurice f13a0aa6ee fix(collections): pins on the map show their place's category (#3073)
The server nests a saved place's category, while the markers and the hover
card read the flat fields a trip place carries, so every pin on a
collection's map was the grey default. The map now hands its places on with
the category's colour, icon and name where the markers look for them.
2026-11-12 22:02:05 +01:00
Maurice 10d1a61614 fix(ios): a running TREK Cloud subscription is found on a fresh install too
The check before a purchase read only the entitlements on the device. Those
can be empty while the subscription runs, so the app offered the plans and
the purchase changed the running subscription's plan in the App Store. The
status of the subscription group now decides when the device has none. A
renewal the device has not finished yet no longer counts as a purchase
waiting for its instance either, which also let the check through.
2026-11-12 21:21:51 +01:00
github-actions[bot] 2bcfc1bfcb chore: bump version to 5.1.4 [skip ci] 2026-11-12 19:51:06 +00:00
Maurice b6e3c9bf39 feat(native): the app needs TREK 5.1.4 on the server
nativeApi goes to 3 with 5.1.4, whose UI follows a widget or Live Activity
tap that starts the app. The apps refuse an older server with the hint to
update, and check a server they remember once more.
2026-11-12 20:21:16 +01:00
Maurice 736dc5dda9 chore(lint): lower the non-null assertion baseline the AirTrail test change freed 2026-11-12 17:47:05 +01:00
Maurice ae26a6c61c refactor(airtrail): save the settings in one transaction
The address and the key it may no longer carry now change together, as
they do for Dawarich, so the transaction ratchet drops the AirTrail entry.
The tests that pinned the old no-transaction shape now pin the new one.
2026-11-12 17:31:56 +01:00
Maurice 8979bd1fcd test(airtrail): one case per key field instead of a loop of awaits 2026-11-12 17:14:54 +01:00
Maurice 74d243d8e0 fix(airtrail): a new host does not inherit the stored API key
Saving the AirTrail settings with a different URL and the key field left
masked or blank kept the stored key, so the next sync sent the old
instance's key to the new host. The key now goes with the host, as it
already did for the connection test and for Dawarich: a new origin without
a new key clears it, a path edit on the same origin keeps it. The key is
cleared before the new address is written.
2026-11-12 16:58:24 +01:00
Maurice 56b9bac031 fix(native): a widget tap that starts the app opens what it points at
A tap on a widget or a Live Activity hands the app
com.liketrek.trek://navigate/<path>. A running app gets it as appUrlOpen;
an app started by the tap gets it as its launch URL, which nothing read, so
the path was lost and the app opened its start page (the packing widget
landed on the trip's plan instead of its lists). The launch link is now
followed once per launch.
2026-11-12 16:53:04 +01:00
Maurice 4983b3407c fix(planner): a flight without airports keeps its day and times on save
A flight created with a day and times but no endpoints (over MCP) showed
them in the form, but buildTransportPayload took a flight's span only from
rows with an airport, so a save sent day, end day and both times as null.
Like a train without stations, such a flight now takes its day, times,
airline, flight number and seat from the raw rows. Endpoints and legs still
come only from rows with an airport.

Fixes #3070
2026-11-12 16:49:29 +01:00
Maurice ed1728feec refactor(admin): the SSO unlink section is a component of its own
The edit dialog's component crossed the complexity limit with the section's
conditions; the section and its confirm step now live in SsoUnlinkSection,
which decides itself when it shows.
2026-11-12 16:14:34 +01:00
Maurice 11472c05ff fix(native): a failed SSO round trip from the app still hands back on the retry
A sign-in the app starts runs through the server's handoff page in the
system browser. When the SSO callback failed (an expired or overwritten
state), the login page dropped the way back to that page, so the retry from
there was a plain web login and ended in the web app inside the app's
browser sheet instead of signing in the app. The login page now keeps a way
back that points at the handoff page, and only that, and renews its
fallback copy for a slow retry. State, nonce, PKCE and the handoff verifier
are unchanged; the handoff page still asks for a tap before it passes
anything on.
2026-11-12 16:10:14 +01:00
Maurice f2ac12ca4f fix: hold the ratchets after the SSO unlink and the day pager window
- The SSO unlink answers with a response contract (adminSsoUnlinkResponseSchema).
- It reuses linkOidcIdentity with nulls instead of a new repository method,
  so UsersRepository keeps its method count and size.
- The client calls the route through apiClient, so api/client.ts does not
  grow, and its confirm dialog takes no async callback.
- The pager's preview step and pagesFor keep their complexity.
2026-11-12 15:56:59 +01:00
Maurice b53130ca0d feat(admin): remove the SSO link of an account whose provider changed its subject
A sign-in with another subject of the same provider is refused, so an
account whose provider re-issued the subject (a migrated or rebuilt IdP, a
changed sub format) was locked out: editing the email, as the wiki advised,
never touched the stored link. The edit dialog now offers "Remove SSO link"
for other accounts while SSO is set up (DELETE /api/admin/users/:id/sso,
audit admin.user_sso_unlink). The next SSO sign-in links again under the
rules of a first one, so it still needs a verified, not self-set email.
The log line names the remedy, and the wiki tells the two refusals apart.

Fixes #3065
2026-11-12 15:39:21 +01:00
Maurice a3a4f7cf79 fix(mobile): days drawn ahead of a fast swipe through the day pager
Only the selected day and two on either side were drawn, and the selection
moves only once the strip comes to rest, which iOS takes a while for. A run
of fast swipes ran past the drawn pages into blank ones until it settled.
The drawn window now also follows the day the swipe is heading for, so the
next days are there before they slide in. At most two windows of five pages
are mounted, however long the trip.

Fixes #3067
2026-11-12 15:39:20 +01:00
Maurice ac7094df05 fix(planner): a refresh of the trip no longer wipes an open transport or booking form
The transport form re-seeded itself whenever the trip's costs arrived as a
new array, and the booking form whenever days, places or stays did. A
socket reconnect re-reads the whole trip, so behind a proxy that drops idle
sockets every 15 to 30 seconds everything typed so far was wiped. Both forms
now re-seed only for what opens a different form; the data is read when the
form is seeded, as before.

Fixes #3069
2026-11-12 15:39:20 +01:00
Maurice 80130f7946 fix: the provisioning line reads as a key reference, the safe-area test follows margin-inline
lint:i18n-keys took the spread in front of t() for a member call and did not
see native.provisioning.sub; the sentence is its own constant now. The
shell chrome test asks for the logical margins and their right-to-left swap.
2026-11-12 14:52:42 +01:00
Maurice fc648bc7e4 fix: green checks after the first-screen redesign and the safe-area floor
- native-shell/amount.ts: the no-break spaces in the price pattern were
  written out as characters; \s already matches them.
- widgets.ts: the Live Activity's lead time stays inside the module.
- i18n: the count strings of the new plan tiles replace the removed ones
  on NOT_PLURAL, and the address placeholders of the non-Latin locales
  are their own instead of English copies.
- mobile.css: the side safe-area margins of the floating bars use
  margin-inline, swapped for right to left, instead of physical sides.
2026-11-12 14:36:13 +01:00
Maurice 9005d6b333 fix(native): name TREK without an article in the first screens
TREK is the application, not a thing one has a copy of: "I already have
TREK", not "a TREK". The same for the not-TREK messages in German and
Dutch and the agreement title in French, Spanish, Italian and Catalan.
2026-11-12 14:18:42 +01:00
Maurice 52f0fb882f feat(native): redesign the app's first screens around a living landscape
The screens the app ships itself (welcome, plans, address, own server and
the states between) move from the dark card layout to a light design on an
animated aerial landscape drawn by a WebGL shader (native-shell/scenery.ts):
an island, a coastal town, farmland and mountains in one world.

- Welcome: the landscape with the TREK wordmark, three perks in one card,
  "Explore cloud plans" and "I already have a TREK" as two buttons.
- Plans: one tab per plan; choosing one flies the camera to its place,
  further inland with every plan. Each plan reads as a kind of trip, the
  price sits in a card with a monthly/yearly switch and counts to its new
  amount in the store's own format (native-shell/amount.ts), and a yearly
  price shows what it makes a month. Restore purchases, the renewal terms
  and the links stay as the store rules require.
- Address: the address writes itself on a glass card over the landscape;
  free, the password rules and the agreement sit on white cards.
- Own server: the server address on the glass card; a failed check turns
  the card red with what went wrong, proxy sign-in and client certificate
  panels in the same style.
- States: server not reachable, certificate needed, already subscribed,
  setting up (with its steps, then "Arrived") and the slow setup.
- iPad, an unfolded phone and a phone on its side get two columns, the
  landscape beside the content; on a dual-screen device each half takes
  one screen. Arabic and Hebrew mirror through logical sides only.
- The shader caps the pixel ratio at 2, drops to a lower resolution on a
  slow device, stops in the background and is one still frame with
  reduced motion.
- The sign-in and error page bars over a proxy's page (iOS and Android)
  take the same look: a white card and a dark button.
- Plus Jakarta Sans is bundled for the text, with Montserrat standing in
  for Cyrillic; the wordmark fonts and the old preview images are gone.
- New strings in all 28 languages; the keys of the old screens removed.
- The dev sample plans follow the cloud's plans (start, basis, plus, pro).
2026-11-12 14:18:42 +01:00
Maurice b8ec428ad1 fix(native): show the travel day's Live Activity from three hours before its first stop
The Live Activity started with the first sync of a travel day and stayed on
the lock screen all day, so a day whose first stop is an evening flight held
it from the early morning on. It now appears three hours before the day's
first timed stop and stays until the day is done; liveDayDue() decides.
2026-11-12 14:00:47 +01:00
Maurice a1d3ffc2ce feat(native): the 'server not reachable' screen names the cause, small, for a report
A load that failed sent the app to the address screen with a general message only, and a tester's screenshot told nothing. The web view's own error (net::ERR_..., an HTTP status, NSURLErrorDomain and its code, a client certificate the proxy asked for) is kept natively and shown under the message once.
2026-11-12 10:11:01 +01:00
Maurice 46b9df54bf feat(native): the TREK Cloud screens show the app and make the choice of a plan easy
The cloud screen shows real screens of the app. The plans are a choice now: one tap marks a plan, the recommended one is marked, what every plan has is said once above them, storage says how many photos it holds, and the yearly switch shows what a year saves; one button at the foot carries the chosen plan on. The claim screen names the plan with a way to change it, shows the address as it will be once it is free, ticks off the password rules while typing, says in three words where the servers are, that it can be cancelled and that there are no ads, and puts the photo behind the form away.
2026-11-12 10:04:31 +01:00
Maurice 3c0c3b3f6e fix(native): a store account with a running TREK Cloud subscription buys no second one
One subscription per Apple ID or Google account. Choosing another plan in the app changed the running subscription on the App Store, and the redeem then failed with 'We could not set up your TREK'. The app now asks the store first and shows a screen of its own: the account already has TREK Cloud, a new one can be taken out once it has ended, with Open my TREK and the store's page to manage it. The native purchase refuses as well; a paid one that was never set up is still redeemed. On the address screens the link 'What is a TREK server?' is gone, and the small print under a purchase is set in the system text face at regular weight.
2026-11-12 09:28:56 +01:00
Maurice 5395d53332 fix(native): the top bar keeps clear of a camera in the corner of the screen
The iOS app hands the page the safe area it measures, a floor under env() where WebKit reports none, and on a phone the floating bars keep clear of the side insets as well.
2026-11-12 08:42:17 +01:00
Maurice ec08032e98 fix(native): SSO in the Android app survives Android ending the app while the browser is open
A Samsung phone may end the app while the sign-in runs in the browser. The browser's return then started the app anew without the call that waited for it, the first page load failed while the network was still held back, and the user came back to 'server not reachable' and then to the sign-in page, in a loop. The return is now kept natively and redeemed by the sign-in page with the verifier kept until then, and a page that failed on the network is loaded once more before the app gives up.
2026-11-12 08:42:17 +01:00
Maurice cc5eca5553 feat(native): a client certificate can be added on the address screen before connecting
The import was only offered once the check saw the proxy ask for a certificate during the handshake. A proxy that refuses without asking left no way in. The wiki also points to the certificate's new place in Settings and explains why a certificate from an iOS configuration profile cannot be used by the app.
2026-11-12 08:42:16 +01:00
Maurice 1323183cce fix(assistant): Claude Sonnet 5.5 no longer ends a turn with 'came back without an answer'
Sonnet 5.5 hands back the words written before a tool call as a hidden thinking block. After the ask for the answer, an empty step got the general push with tools open again; the model answered, offered follow-ups once more, and the answer was lost a second time. That push now asks for the answer as text and stays text-only.
2026-11-12 08:42:16 +01:00
Maurice 009be05d22 fix(mobile): a sheet no longer shows the page through it while it opens
The dim faded in on the sheet's own parent, and opacity multiplies down the tree, so for its first frames even the opaque sheet let the list behind read through as ghost text (Android tester, expense editor). The dim now fades on a layer of its own beside the sheet, and the card is opaque halfway through its pop.
2026-11-12 08:42:16 +01:00
Maurice 860ffc1dee fix(planner): the drag state setters are stable, so the sidebar's dragend listener lists them and is still set up once 2026-11-12 08:42:15 +01:00
Maurice c515f95d17 fix(ci): the drag hook lists its dependencies, closeOnDone stays module-private, and the weight test waits for its save 2026-11-12 07:10:18 +00:00
Maurice 855bf8610a refactor(planner): the day plan's drag state lives in a hook of its own; the holiday provider cases get a suite of their own
DayPlanSidebar grew past its size baseline with the Firefox drag fix. Its drag state (what is dragged, the drop line, the day under the drag, whether a drag happened) and the effect that ends a lost drag move into useDayPlanDragState, typed, which also lowers the file's strict-mode count; size and strict baselines are lowered with it.

vacay.service.test.ts went past the 2000-line limit once the Nager v4 cases were back in it. They move into vacay.holiday-provider.test.ts, which takes VacayService from a Nest testing module over a snapshot db, so neither the db mock nor a hand-built service is needed.
2026-11-11 22:38:59 +00:00
Maurice 742edc4a79 fix(ci): today's changes pass the release gates
- iOS: the navigation proxy reports an error page through a callback the controller sets; it called the controller's method on itself and did not build.
- keyboard: the done key reads the field's text in the capture phase, before the field's own handler, so a list that adds an item on Enter and clears itself keeps the keyboard; the tests wire it as the app does.
- Ireland migration: the queued writes use addSql instead of awaiting inside loops; only table constants and integer ids reach the SQL.
- tests: the Dawarich GL test types its two layer specs once (strict baseline lowered), the collab test reads the id off the listed message, the reasoning test runs its four servers in parallel, and a wasm copy covers the precompressed branch without a charset.
- en wording: the deviations agreement no longer calls TREK self-hosted.
2026-11-11 22:06:50 +00:00
Maurice 1975a23aab fix(mobile): the settings group headings follow the text size setting
They used a fixed 10px size, which theme:lint refuses; they take the caption tier now.
2026-11-11 21:32:05 +00:00
Maurice 80c8d9c602 feat(mobile): settings group their sections by what they reach: your account or this device
A tester could not tell which settings follow the account to every device and which stay on the phone, and looked for offline mode for a while. The section list and dropdown now stand under two headings, "Your account" and "This device". The server the app opens, the app lock and a client certificate move out of Account into a section of their own, "App", shown only in the app, next to Offline; About stands under TREK. Labels in all locales. TestFlight feedback, 5.1.3.
2026-11-11 21:31:14 +00:00
Maurice 948c9ef57b fix(atlas): show Ireland's 26 counties instead of its four provinces
geoBoundaries has no county layer for Ireland: its ADM1 is the four
provinces and its ADM2 the 166 local electoral areas, so the Atlas showed
Ireland as four provinces next to a UK of counties.

The Atlas builder can now take a country's regions from another source.
Ireland's come from Tailte Éireann's 26 counties (CC BY 4.0), with Dublin,
Cork, Galway and Limerick each one county, under their ISO 3166-2:IE
codes. Those outlines come at full detail, so the builder simplifies them
itself and keeps the borders two counties share identical on both sides,
so no point between them falls into neither. ATLAS_ONLY rebuilds just the
named countries without downloading the whole world.

A migration clears Ireland's cached place regions so they are worked out
again as counties, moves visited rows that name a county onto its code,
and hides each county of a province a user had hidden. Provinces a user
marked as visited are kept as they are.

Fixes #2922
2026-11-11 21:26:31 +00:00
Maurice bac968c0bf fix(ai): retry chat requests with reasoning_effort none when a server refuses tools with reasoning
Azure AI Foundry reasoning deployments behind an "Own server" connection
reject function tools on /v1/chat/completions at their default reasoning
effort and answer HTTP 400 naming reasoning_effort. The Responses API
switch from #2792 only covers direct OpenAI keys, so the assistant could
not run on these deployments at all.

The chat client still never sends reasoning_effort, so servers that do not
know the field (Ollama, LM Studio, vLLM, OpenRouter) see unchanged
requests. When a request with tools is refused over reasoning_effort, it
goes out once more with reasoning_effort "none", and the rest of the turn
keeps sending it. The refused field is now carried on AiProviderError
instead of only being logged.

Fixes #3043
2026-11-11 21:26:20 +00:00
Maurice 520562ef86 fix(planner): keep day plan drags alive in Firefox
Firefox fires dragstart while it handles the mouse move that starts the
drag and delivers that move to the page afterwards, button still held.
The listener that clears a drag whose dragend never arrived took that
move as the end of the drag and dropped the drag data at pick-up, so a
stop could only be reordered with its arrows. The same held-button moves
come from the touch polyfill on hybrid laptops throughout a drag. Only a
move with no button held now counts as the drag being over.

The day list also switched its stagger animation back on whenever a drag
ended, which replayed the entrance of every day card ("weird reload").
It now plays once on mount and stays off after the first drag.

Fixes #3041
2026-11-11 21:26:15 +00:00
Maurice 001253c39b fix(ios): the strip above the page carries the page colour on releases that lay the web view out below the status bar
On iOS 27.0.x the web view started below the status bar, and the strip above it showed the view controller's black instead of the screen background. The colour behind the web view now follows the theme the UI reports through StatusBar.setStyle (the top colour of --m-scr), so the strip reads as part of the page on every release. TestFlight feedback, 5.1.3.
2026-11-11 21:24:35 +00:00
Maurice 5345b50d17 test(vacay): the holiday provider cases live in the existing suites again
The two new test files mocked the db module and built VacayService by hand,
which the test-mocks and new-service ratchets refuse for files without a
baseline entry. The cases move back into vacay.service.test.ts and
vacay.test.ts unchanged; VACAY-037 asks for a year no other case caches. The
unrelated admin addon test change is reverted and two comments name the new
provider.
2026-11-11 21:06:29 +00:00
Luffy a3622e91b6 feat(vacay): implement Nager.Holidays v4 integration and adapt holiday data structure 2026-11-11 21:04:07 +00:00
Luffy be305c3daf fix(vacay): move holiday lookups to Nager.Holidays v4 2026-11-11 21:04:07 +00:00
Sebastian Fischer ec78cfbdd0 feat(tours): find bakeries and groceries on the map and along a hike
A multi-day hike restocks on the way: bread in the morning, food for
lunch and supper every day or two. Neither could be searched for.

- Explore pill: new `bakery` and `supermarket` chips. `supermarket`
  already existed on the server (shop=supermarket|convenience) but no
  pill offered it; `bakery` is new (shop=bakery).
- Along the tour: `bakery` and `supermarket` are offered to a hike,
  after its existing kinds so a new hike still starts on the same three.
- TREK places index: `bakery` maps to food_and_drink>casual_eatery>bakery;
  `supermarket` is narrowed to grocery and convenience stores, since the
  whole food_and_beverage_store branch also brought tobacconists and
  wine shops. Both paths checked against a live answer of the index.
  As the more specific term, a bakery is no longer listed as a place to
  eat when only `food` is asked along a tour.
- Category guess: a bakery or grocer picked from the map was preselected
  as Bar/Cafe or Shopping even where the admin had made a Bakery or
  Groceries category. The guess now looks for such a category first, by
  name in the usual languages or by icon, and keeps the broad one when
  there is none. The category icon picker offers Croissant and
  ShoppingBasket, the icons the map chips use.
- Labels in every locale; MCP tool description names the new kinds.
2026-11-11 20:59:59 +00:00
Ibrahim Roshdy 8023be452a fix(atlas): give a point no polygon contains to the nearest border
A point just off a simplified coastline lies in no admin0 polygon, and the
fallback then took the candidate with the smallest bounding box. Nice and
Menton sit ~80 m outside France's coast and 20+ km from Italy, but Italy's
box is the smaller one, so they resolved to IT. The fallback now ranks the
candidates by distance to their border. A deferred loose box (PS/XK) keeps
its priority. The parity test's reference lookup mirrors the new rule.

Closes #3048
2026-11-11 20:59:53 +00:00
John Jahn 5112c96c05 perf(places): the country lookup skips polygons whose box misses the point and remembers its answers
The places list and the trip bundle resolve the country of every place
without a cached region on each read, and that lookup was about 90% of
their CPU time: it ray-cast every polygon of each candidate country, which
is thousands of rings for a country that is mostly islands.

A polygon whose outer ring's box does not hold the point is now skipped
without walking it, and an answer is kept by coordinate pair (20,000 pairs,
oldest out first), since the borders never change while the process runs.
The answers are the ones the ray-cast alone gives; ATLAS-SVC-051 and
ATLAS-SVC-055 compare every country against the reference lookup.

Measured on a production build with a 360-place trip: GET places
22.7 ms -> 3.5 ms, GET bundle 27.5 ms -> 6.2 ms. A first lookup of a
pair is about 1.8 times faster (90 us -> 50 us over 20 cities).
2026-11-11 20:59:47 +00:00
John Jahn 04b1fb72bb perf(static): serve the hashed assets from Brotli copies written at build time
Every file under assets/ was compressed again on each download, at the low
level a request path can afford. They carry their content hash in the name
and never change, so the client build now writes a Brotli copy beside each
compressible one (postbuild, scripts/precompress.mjs) and production points
a browser that accepts Brotli at that copy before express.static serves it.

Measured on a production build of 5.1.2, fetching the 652 precached files
the way a service worker install does: 16.3 MB -> 13.9 MB on the wire and
about 1.0 s -> 0.2 s of server CPU per install. A client without Brotli, a
range request and a build without copies are served exactly as before.
2026-11-11 20:59:40 +00:00
John Jahn a9d11ccb2e fix(plugins): grant plugin children the network on Node 25 and newer
From Node 25 the permission model covers the network, so a plugin child
forked with --permission and no --allow-net gets ERR_ACCESS_DENIED on every
lookup and connect, and no plugin can reach a host it was granted. Node 24
is unaffected and rejects the flag as a bad option, so it is passed only
where process.allowedNodeEnvironmentFlags knows it.

Which hosts a plugin may reach is still decided by the egress guard inside
the child.

Fixes #3045
2026-11-11 20:59:34 +00:00
John Jahn 848e3f90e1 perf(client): the icons the first load needs ship as one chunk instead of 187
Every lucide icon is its own module, and the plugin icon lookup reaches all
of them by name from the navigation. The bundler therefore put each icon
another chunk also uses into a chunk of its own: 187 files of a few hundred
bytes, each one a request on a first visit and an entry in the precache.

A `vendor-icons` group collects them. The first load asks for 32 script
files instead of 224 (the bytes stay the same, 3.9 MB before compression),
and the service worker installs 460 files instead of 652. With 50 ms added
to every response the login page reaches DOMContentLoaded in 0.5 s
instead of 3.8 s.
2026-11-11 20:59:27 +00:00
Botond Rakoczi e83b6741ad docs: add TrueNAS SCALE installation guide 2026-11-11 20:57:42 +00:00
Maurice 0a3d93b59b fix(collab): a deleted chat message keeps no text
Deleting a message set the flag and kept the text in the row and in every backup; only the client hid it. The delete now blanks the text with the flag, and a migration clears what earlier deletes left. The row stays for the placeholder.
2026-11-11 20:41:25 +00:00
Maurice 102e2141ec fix(mobile): screens with pull-to-refresh bounce like every other iOS list
The dashboard, journeys and notifications switched the iOS bounce off entirely so it would not race the pull. The pull now holds only a clearly downward move from the very top, from its first pixel, and the page bounces everywhere else, its end included. TestFlight feedback, 5.1.3.
2026-11-11 20:41:25 +00:00
Maurice 768fd6f439 fix(mobile): a plugin's page in the phone shell sits below the status bar and above the dock
The page took 100vh with no top inset inside the touch shell, so the plugin's header ran under the status bar and the frame reached past the screen and under the dock. It now takes the visible height (100dvh) less the dock, after the safe area and the rail, and the plugin's own document scrolls. TestFlight feedback, 5.1.3 (Trip Importer).
2026-11-11 20:41:24 +00:00
Maurice 231a610466 fix(map): the recorded Dawarich route reads on a busy street map
A thin, translucent dash over a nearly opaque white casing read as a pale trace and was barely visible on past trips. Full colour, a wider line and longer dashes, shared by the Leaflet and GL layers. TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice 7db5ec0721 fix(native): the keyboard's done key closes the keyboard
A field outside a form gets enterkeyhint="done", but a web view only sends Enter and nothing listened, so the key did nothing. When no handler took the Enter (same text, still focused a moment later) the field lets go of the focus; a field that acts on Enter and clears itself keeps it. TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice a2b9d96e86 fix(ios): the system sign-in prompt names the app TREK, not "App"
ASWebAuthenticationSession's prompt reads CFBundleName, which was $(PRODUCT_NAME), the Xcode target "App". TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice e0022c12c4 fix(native): an error page in place of the server's keeps a way back to the address screen
A proxy's block page or a refused client certificate (Cloudflare's "Sorry, you have been blocked") left the app on a page without TREK's UI and no way to change the server. Any 4xx main-frame page that the client-certificate path does not handle now shows the sign-in bar with its own hint and "Change server", on iOS and Android. TestFlight feedback, 5.1.2.
2026-11-11 20:41:24 +00:00
Maurice 66b8f2c906 feat(native): ask for the separate TREK Cloud deviations agreement before an in-app purchase
The claim screen loads the agreement text and its version from /api/iap/consent, shows it with its own checkbox and buys nothing until it is ticked. The redeem sends consent { acceptedDeviations, version }; a refusal for an outdated text reloads it and asks again without a second purchase.
2026-11-11 20:41:23 +00:00
github-actions[bot] 6fbe10fe63 chore: bump version to 5.1.3 [skip ci] 2026-11-10 09:56:54 +00:00
Maurice 278871a31e chore(theme): the login's fixed light colours move with its code step into MfaCodeStep
The login card is a fixed light surface whose text colours are written out,
not tokens. Four of them moved with the two-factor step, so the baseline moves
them too: 58 to 54 for the page, 4 for the new component, the same total.
2026-11-10 10:23:53 +01:00
Maurice bdcef33a3e test(bookings): two test names no longer break their string on an apostrophe 2026-11-10 10:10:24 +01:00
John Jahn 8e8cff8105 fix(reservations): keep day_id on partial updates of time-only bookings
A partial update that left day_id out (a notes-only PUT, an MCP
update_reservation or update_transport call) re-derived the day from the
stored reservation_time whenever one was set. A time-only value such as
"12:00" resolves to no day, so the booking's day_id was written as null and
it vanished from its day in the planner. The end_day_id branch did the same
when a time-only reservation_end_time was sent.

The day is now derived only when the time carries a date that resolves to a
trip day; otherwise an omitted day_id or end_day_id keeps the stored value.
A dated time still re-pins the day, an explicit day_id null still clears it,
and a cleared end time still clears end_day_id. REST and both MCP update
tools share updateInTx, so the fix covers all three.

Tests: service unit cases (RESV-SVC-044..048), an e2e case per behaviour
on PUT /api/trips/:tripId/reservations/:id, and an update_reservation MCP
case, all seeded with the ORM factories.

Fixes #3025
2026-11-10 10:05:22 +01:00
Maurice 6b086eaed5 refactor: the login's code step and the reservation row shapes get modules of their own
Both files had grown past their size limit with this round's fixes. The
two-factor step moves to pages/login/MfaCodeStep.tsx and the reservation row
types to reservation-rows.ts, re-exported from the repository, and both size
baselines come down to match.
2026-11-10 09:55:36 +01:00
Maurice 0ac06555cb test(native): reset the file preview mock between the file opening tests
The second test asserted the preview was not called while the first one's call
was still counted, so it failed whenever both ran in order.
2026-11-10 09:55:36 +01:00
Maurice 1b87c62847 chore: keep the API client within its size and the native API minimum module-private 2026-11-10 09:55:36 +01:00
Maurice 98eae61b90 chore(plugin-sdk): regenerate the host facts for the stay times on reservations 2026-11-10 09:50:30 +01:00
Maurice 19956f2742 fix(native): a leg without an arrival day lands on the day it leaves in the Live Activity 2026-11-10 09:50:30 +01:00
Maurice 7506eaa4aa fix(native): the sign-in bar's room for the keyboard holds, and Android 7 to 10 see the keyboard
On iOS the keyboard plugin sizes the body and zeroes the scroll inset in a
frame update that runs after the keyboard is up, so the room made for it was
taken back. The inset is now kept while a sign-in page shows, the body gets its
height back after that update, and with the keyboard down the page can scroll
past the bar. On Android before 11 the keyboard went unseen in the insets
Capacitor passes on, so the bar stayed over the form; it is read off the
window's own insets now.
2026-11-10 09:50:29 +01:00
Maurice 57c9c9d5f2 style: format the Japanese and Korean app strings and two tests as Prettier wants them 2026-11-10 09:43:01 +01:00
Maurice 0b3d2873c2 feat(native): a proxy's sign-in page in the app has a way out and says what cannot work there
Behind Pangolin or authentik the app shows the proxy's sign-in page itself, and
nothing on it led back to the address screen: a failed passkey left users stuck
on every launch. A bar over that page now offers to change the server and says
that passkeys and security keys do not work there, as a web view cannot use them
for a domain the app is not tied to. It steps aside while the keyboard is up.
On iOS the page also gets the room the keyboard takes, so a button under it can
be scrolled into view. The address screen hands the bar its words in the user's
language when it connects.
2026-11-10 09:36:50 +01:00
Maurice 1454b58ea1 fix(mobile): quick swipes through the days no longer stop after two
The pager held the selected day and two either side, and moved that window
only once the strip had come to rest. Swiping on before the snap settled ran
into the end of the strip after two days and sprang back until the animation
was over. Every day now has its page, only the selection and two either side
draw their content, so a run of swipes goes as far as the trip does.
2026-11-10 09:30:29 +01:00
Maurice 2ab4459bc3 fix(native): the Live Activity keeps a day with flights ahead open instead of calling it done
A booking with stopovers was one stop at its first departure, and a stop
counted as done the moment it began. With a car at one and a connecting flight
at two, the Live Activity said all done for today mid-afternoon. Each leg is
now a stop of its own, as the planner shows it, and a flight or anything else
with an end time counts as under way until it lands or ends.
2026-11-10 09:29:40 +01:00
Maurice 6ebb92af6c fix(bookings): a hotel booking's card shows check-in and check-out when only the stay has them
The edit form fell back to the linked stay's times, the cards read only the
booking's metadata, so a hotel showed 15:00 and 11:00 when edited and no times
in the list. The reservation list now carries the stay's check-in window and
check-out, and the desktop facts and the phone card fall back to them. On the
phone they come first, so a price or a seat cannot push them off the card.
2026-11-10 09:28:43 +01:00
Maurice 3ab4927cb7 fix(native): the app asks for notifications on iOS too, and again if the question went unanswered
The prompt looked at the app's features once, when the user counted as signed
in. After the sign-in the page loads with the session already there, and on
iOS the bridge had not named its features yet, so the prompt gave up for good.
It now waits for them. It also counted as asked the moment it opened, so a
sheet that went under another one never came back; it counts once answered.
2026-11-10 09:26:59 +01:00
Maurice 6a0ae482d7 fix(login): the two-factor code field is set up for one-time codes and a password manager
The code step drops the email field, so a password manager had no login to
match a one-time code to; the step now keeps the address in a hidden username
field. The code field names itself and sets its keyboard hints directly
(characters, no autocorrect), as autoFocus gave it focus before anything could
prepare it, and its placeholder is translated.
2026-11-10 09:23:16 +01:00
Maurice 20eeaeb61f fix(native): the iOS app builds again, with Quick Look in an extension of its own
The file preview kept its data source in a stored property inside an
extension, which Swift does not allow, so every iOS build since failed. It is
a static now, in its own extension, and the Wallet comment it had split is
whole again.
2026-11-10 09:18:20 +01:00
Maurice 5cbe4e2fa3 feat(native): the app needs TREK 5.1.3 on the server and checks a remembered one once after the update
The fixes that keep the app's sign-in in the app live in the server's UI,
so an updated app on a 5.1.2 server still ended in the browser. The server now
reports nativeApi 2 and the app refuses anything below it, naming 5.1.3.

A server the app remembers from before is not loaded unchecked: the first
launch after the update shows the address screen filled in with it, says why
and checks it right away. A server that is new enough loads again with its
session; an older one gets the update hint.
2026-11-10 09:17:26 +01:00
Maurice b124e1bc9c fix(mobile): a day tapped in the day rail moves the pager on short trips too
The strip re-centred only when its window of pages changed. On a trip of up
to five days a tap can keep the same pages, so the rail showed the new day
while the card below stayed on the old one.
2026-11-10 09:17:26 +01:00
Maurice 08034c4402 fix(map): the iOS app's tile store is allowed by the CSP, so its maps draw tiles again
The iOS app rewrites raster tiles to trek-tile:// and answers them from its
store. WebKit checks that scheme against img-src, which had only https:, so
every tile was refused and the app showed routes and markers on a blank map.
2026-11-10 09:17:25 +01:00
Maurice 0577a9ccb9 fix(native): the hand-off page goes straight to SSO instead of TREK's login first
The app's browser sign-in opens /native-handoff, which sends the user on to
the identity provider by itself. The page was not on the list of public auth
pages, so the 401 from loading the user sent the browser to /login with the
hand-off as its return path first. On a server that also offers passwords the
user then had to pick SSO a second time before getting back to the app.
2026-11-10 09:17:22 +01:00
Maurice 2f03554a60 feat(native): files open in the system viewer instead of the share sheet
A PDF, image or document opened in the app went straight to the share sheet.
It now opens in Quick Look on iOS, to page through and zoom with its own share
button, and in the app that views its type on Android. An app without the
viewer (feature filePreview), or a type nothing on the device shows, gets the
share sheet as before.
2026-11-10 00:21:28 +01:00
Maurice 28079197e7 fix(assistant): an answer that hands the talk on to a trip or journey chat ends the turn
The home assistant wrote its answer and offered the trip's own chat in the
same step. The loop asked the model once more after the card, and it wrote
the same answer a second time below it. A step that has its answer and only
hands the conversation on now finishes the turn; a hand-on without an answer,
or beside a read, still asks the model again.
2026-11-10 00:14:44 +01:00
Maurice 0b46b89b62 fix(mobile): swipe actions are rounded tiles beside the row, icon only; expenses keep their own buttons
The actions under a swiped row were square blocks to the row's edge, unlike
the rounded cards around them. They are now tiles of their own with the
card's radius and a gap, inset within a grouped card such as the packing
list, and show only their icon (the label names them for a screen reader).
An expense already shows edit and delete beside its card, so it no longer
swipes to a second, larger pair of the same buttons.
2026-11-10 00:11:50 +01:00
Maurice 05caf67bc4 chore(notices): the release popup comes back for 5.1.3 2026-11-09 23:43:24 +01:00
Maurice 6d3c400e4a ci(native): build the iOS app with Xcode 27.1 on the xcode-27 image
An app linked against an SDK older than iOS 27.1 runs letterboxed on the inner
display of an iPhone Duo. The iOS build and the release now run on GitHub's
xcode-27 image and select Xcode 27.1; the previews stay on Xcode 26.
2026-11-09 23:33:23 +01:00
Maurice 9932288b04 chore(deps): bump the npm minor and patch group, with React's override and one MikroORM
From #3032, adjusted where it broke:
- react and react-dom are pinned in the root overrides; the group raised the
  workspaces to 19.3.1 and left the override at 19.3.0, so two react-dom
  versions met in every client test. The override moves along.
- @mikro-orm/nestjs kept the old @mikro-orm/core at the root while the server
  got 7.2.8 of its own, two copies whose types do not match; the lockfile now
  holds one 7.2.8.
- mapbox-gl stays at 3.31: 3.34 drops setRTLTextPlugin from its types, which
  the map engine uses.
- the musl pins of rollup stay at 4.62, the rollup version the lockfile holds.
2026-11-09 23:31:38 +01:00
Maurice 56b13541bd chore(native): keep the handoff start path inside browserSignIn, nothing else reads it 2026-11-09 23:29:38 +01:00
Maurice d568e20f02 chore(plugin-sdk): bump vitest and @vitest/coverage-v8 to 5 together
The two only resolve as a pair; one at a time (#3028, #3029) npm refuses the
peer range.
2026-11-09 23:28:26 +01:00
Maurice f03d59bc22 chore(deps): bump @capacitor/cli to 8.6, vite-plugin-pwa to 2 and @nestjs/schedule to 12
@capacitor/cli 8.6 drops the old uuid 7 through its xcode dependency (#3012).
vite-plugin-pwa 2 keeps the registerSW.js in public/ in place of its own, as
1.x did (#3033). @nestjs/schedule 12 still runs on Nest 11 (#3035).
2026-11-09 23:27:18 +01:00
dependabot[bot] 0833ca28c2 chore(plugin-sdk): bump semver
Bumps the plugin-sdk-minor-and-patch group in /plugin-sdk with 1 update: [semver](https://github.com/npm/node-semver).


Updates `semver` from 7.8.5 to 7.8.6
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.8.5...v7.8.6)

---
updated-dependencies:
- dependency-name: semver
  dependency-version: 7.8.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: plugin-sdk-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 23:26:18 +01:00
dependabot[bot] 3ed5f21a48 ci: bump actions/setup-java from 5 to 6
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5 to 6.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 23:26:18 +01:00
dependabot[bot] 2eb6b79bea ci: bump the actions-minor-and-patch group with 2 updates
Bumps the actions-minor-and-patch group with 2 updates: [docker/login-action](https://github.com/docker/login-action) and [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action).


Updates `docker/login-action` from 4.7.0 to 4.8.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/81c6f93d4bc991e510b342a00b419b3bb4efc5c6...8aa5831fb8d48d8f76594c7ddde61ae58019f550)

Updates `SonarSource/sonarqube-scan-action` from 8.4.0 to 8.4.1
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/4d1dc0c91ee400dcf8a6dddf2f705ac36542e304...e805d875275f728fac1885b413934be6d7c63f65)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions-minor-and-patch
- dependency-name: SonarSource/sonarqube-scan-action
  dependency-version: 8.4.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 23:26:17 +01:00
Maurice 8dd2e9716d test(native): fix the sign-in handoff tests' quoting and formatting 2026-11-09 23:15:09 +01:00
Maurice 1cdde6e9a4 fix(native): a field on a page as tall as the screen comes up above the keyboard on iOS
The login on an iPhone scrolls in no pane of its own, and the keyboard plugin
holds the body's height, so the page had nothing to scroll by and the password
field stayed under the keyboard, most of all with an error shown above it. Such
a page now gets room as tall as the keyboard at its end and scrolls the field
above it; the room goes with the keyboard.
2026-11-09 23:12:27 +01:00
Maurice 034cfb539a fix(native): the app's browser sign-in no longer lands on the dashboard when the browser still holds an older TREK
A browser that ran TREK before 5.1.1 keeps that version's app in its service
worker. When the app opened /native-handoff, the worker answered it from its
cache with an app that has no such page, which sent the user to /, and the
sign-in ended on the dashboard in the browser instead of in the app.

The app now opens /api/auth/native/start, which every TREK service worker
passes to the server. That page takes the workers off the browser and
forwards to the handoff page. Until the sign-in is handed back, the web app
registers no service worker and does not reload for a new version: a tab
still open on the older TREK keeps its worker alive, and a registration or a
reload in the middle of the sign-in brought it back to answer the next page.
2026-11-09 23:02:33 +01:00
Maurice 5420077b98 fix(native): a proxy sign-in the address check never met loads in the app instead of the browser
A proxy that lets /api through (an Authelia or Authentik bypass for the app)
still sends the page itself to its sign-in. The app took that redirect for a
foreign link and handed it to the browser, so the sign-in happened there and
the app stayed black on every launch. A redirect away from the server while
its first page loads is now kept as the proxy's sign-in host, on Android and
iOS, and the iOS bridge guard is always in place for hosts learned that way.
2026-11-09 20:17:37 +01:00
github-actions[bot] 5cfc7a602a chore: bump version to 5.1.2 [skip ci] 2026-11-09 12:58:07 +00:00
Maurice b48e344749 test(planner): the booking dialog's map button reads Map 2026-11-09 13:17:22 +01:00
Maurice e58a880f34 fix(mobile): the detail sheet reads its edit permission off the live booking, not the held one 2026-11-09 13:07:50 +01:00
Maurice 17ff7f6bd8 fix(i18n): the short wallet label in the non-Latin locales is their own word for it
A Latin word in those scripts counts as English whatever it is, so
same-as-en is not honoured there.
2026-11-09 13:00:09 +01:00
Maurice f03bb97d50 fix(mobile): a booking opens its detail sheet first, as a transport and the desktop do; Wallet and Map buttons read short
Bookings in the Bookings tab, the day sheet, a place's sheet and the road trip
opened their editor straight away, while a transport showed its details with
a pencil to edit. Every booking now opens the same detail sheet; its edit and
delete follow the booking's own permission (reservation_edit for a stay, a
table or a ticket, day_edit for a transport). Notes keep opening for editing,
as on the desktop.

The wallet button reads "Wallet" (its accessible name still says which one),
and "On map" reads "Map" in every language.
2026-11-09 12:56:50 +01:00
Maurice ed0142be7d chore(client): list the client certificate card as a phone-only screen 2026-11-09 12:38:52 +01:00
Maurice 6e9f89a25f fix(map): a GL map follows its box, not only the window, so closing the plan pane on a tablet leaves no black band (#3023)
Mapbox GL measures its container on window resizes only. In the app on a
tablet the trip's plan pane closes beside the map without one: the box grew
to the full width while the canvas kept its old size, and the rest stayed
black. Every GL map built through buildGlMap now watches its container and
resizes once per frame while it changes; the observer goes with the map.

Closes #3023
2026-11-09 12:29:37 +01:00
Maurice a3c7c3d76a fix(memories): mark the Synology lookups and repair as independent writes for the transaction gate
Each photo's write follows its own network lookup, the repair's marker only
records that the pass ran, and a lookup may renew the Synology session on
its own; none of these can share one transaction.
2026-11-09 12:25:40 +01:00
Maurice c043ca4bba chore(notices): the release popup comes back for 5.1.2 2026-11-09 12:18:17 +01:00
Maurice 004c6212c0 fix(i18n): mark the client certificate strings that stay English on purpose
"Server" and Italian "Password" are the words those languages use; the
untranslated-strings ratchet counts them unless they carry same-as-en.
2026-11-09 12:14:38 +01:00
Maurice 07448e662c feat(native): client certificates for servers behind mutual TLS
A proxy in front of TREK (Cloudflare, nginx, Caddy, Traefik, HAProxy) can
let in only devices that show a client certificate. The apps could not, so
such a server was unusable from them.

- Address screen: the server check runs natively and notices when the
  server asks for a certificate. Instead of "no server answered" it says so
  and offers to add a .p12/.pfx file; a wrong password asks again, an
  expired, not yet valid or keyless file is named as such.
- The certificate is shown only to the host and port it was added for.
  iOS keeps it in the keychain (this device only), Android seals the key
  with an Android Keystore key. The file's password is never stored.
- The web view answers the server's certificate request on both platforms;
  WebSocket, service worker and API requests go through with it. The
  offline copy, watch requests and the check use it too.
- When the server stops letting the app in (certificate removed, expired
  or no longer trusted) while the page still comes from the service worker
  or the offline copy, a native check sends the app to the address screen,
  which offers to add another. A server that only asks and lets everyone
  in is left alone.
- Cloudflare-style 403 and nginx-style 400 refusals without a certificate
  lead to the same screen instead of staying up as an error page.
- Settings, Account: a Client certificate card (only with one stored)
  shows subject, issuer, server and expiry, with Replace and Remove.
- Wiki: Native-Apps "Client certificates (mTLS)" with Cloudflare, nginx,
  Caddy and Traefik setup and how to make a certificate for the app.
- The app icon on the unreachable screen is black on the light surface.
2026-11-09 12:03:31 +01:00
Maurice d3bdc6de62 fix(memories): keep the Synology repair's progress through the settings domain
The repair job wrote its marker rows through the AppSettings repository,
which the settings domain owns. It now registers both keys and goes through
SettingsService, as the import boundary check asks.
2026-11-09 12:03:27 +01:00
Maurice a9bfcd0fd5 fix(memories): log capture reconfirm failures through the Nest logger
Keeps the no-console and test-new-service ratchets at their baselines: the
reconfirm tests build the service through the suite's existing helper.
2026-11-09 11:32:27 +01:00
Maurice 12caa7fbde fix(synology): an unreachable library is reported, not asked a second time for the next id 2026-11-09 11:08:54 +01:00
Maurice 1cbd4acf01 feat(synology): photos attached before the fix get their own capture time and place once
Until #3019 a Synology photo's capture time and GPS came from the item after
it, which on many libraries is the next photo, and no one can edit a photo's
capture time to put it right. On the first start after this, every Synology
photo is asked again through its owner's library, held to the backfill's few
lookups per NAS, and what Synology confirms for that very photo replaces what
was stored; a photo it cannot confirm keeps its values. While a library could
not answer, the pass runs again on the next start, at most three times.
2026-11-09 10:59:43 +01:00
Maurice 687e477ca5 fix(synology): the asset lookup asks its two candidates without an await in a loop 2026-11-09 10:59:41 +01:00
Maurice 3a66f2a8da fix(native): the keyboard on the claim screen closes again
On "Almost there" nothing put the keyboard away: the web view keeps it open on
a tap beside the fields, and "Next" sent the half-filled form, whose check
focused a field again. A tap beside the fields or a drag of the screen now
closes it, as in an iOS app, on every first screen. "Next" walks from the
address to the email to the password, "Go" buys, and the keyboard goes as the
purchase starts.
2026-11-09 10:51:20 +01:00
Maurice 7f52e424e8 fix(native): a double tap on the app's first screens no longer zooms them on iOS 2026-11-09 10:49:57 +01:00
Maurice 2479e5661b fix(mobile): swiping days ticks as the swipe is decided, and a quick second swipe reaches the day after
The detent came only once the strip had settled, which on iOS is a good while
after the finger lifts, so it felt late. It now ticks as soon as another day
becomes the nearer page, and no second time as the snap lands.

The strip held the selected day and one on either side. A second swipe made
while the first still snapped ran into the end of the strip and sprang back,
so paging several days took a pause after each. It now holds two on either
side, and the second swipe carries on to the day after.
2026-11-09 10:49:55 +01:00
Maurice bc2fb1ce2d fix(synology): journey photos keep their own capture date and place, not the next photo's
getSynologyAssetInfo asked Browse.Item for the unit id plus one, a fixed
offset that holds on some libraries and on others names the next photo, whose
date and GPS were then stored for the attached one. It now asks for the unit
id, then for the one after, and takes only an item whose own thumbnail belongs
to the requested unit; when neither does, it answers not found instead of a
neighbour's metadata.

Closes #3019
2026-11-09 10:47:22 +01:00
Maurice ffa07b3d05 chore(i18n): two task keys are in use again, the unused baseline goes down 2026-11-09 10:25:47 +01:00
Maurice 306753d6a1 fix(native): placeholders pass the tests and the theme, the swipe actions use tokens, the task card stays simple 2026-11-09 10:02:02 +01:00
Maurice 80c04df4fc feat(native): swipe rows, long-press menus, placeholders while loading, fading pictures, iOS bounce and app icon quick actions
Packing items, tasks and expenses swipe sideways to their actions, as in
Mail or Reminders: done or open one way, delete and edit the other, the
first one run by a full swipe. They are second ways to what each row
already offers; an expense still asks before it goes.

A long press on a trip card lifts it and opens its menu with the card's own
actions. Plain confirmations in MConfirmSheet now also ask through the
system where the app can.

Lists, the atlas and a journey show grey placeholders in their shape while
loading instead of a spinner in an empty screen (MSkeleton); buttons keep
theirs. A picture still loading fades in once it is there; one from the
cache shows at once. In the iOS app the page bounces at its ends again,
except on screens with pull-to-refresh, whose pull it would race; Android
keeps its stretch off.

On iOS a long press on the app icon offers "New trip" and the trip coming
up by its name, set by the UI in its language (TrekShell.setQuickActions,
feature quickActions), and a tap opens it, also from a cold start.

The app's own CSS moves out of index.css into native/nativeApp.css, which
had outgrown its size budget.
2026-11-09 09:37:36 +01:00
Maurice c9a91bbdad fix(native): the native question reads no ref while rendering, and its tests type and lint clean 2026-11-09 09:16:58 +01:00
Maurice d06168d94a feat(native): the app answers a finger like a native app, not like a web page
After a tap, WebKit and Chrome keep :hover on what was tapped and send a
made-up mouseover, so buttons and rows stayed tinted until the next tap.
While a finger drives the app <html> carries data-touch-input: a PostCSS
step guards every :hover rule with it (no specificity change), and the
made-up mouseover and mouseout stop before any handler. A trackpad or mouse
clears the mark and gets hover back; a browser never sets it.

A control without a press of its own dims the moment a finger lands on it,
after a 60 ms wait so a scroll does not flash rows, and only the innermost
pressed control. A focus: ring no longer stays round a tapped button.

Fields get a fitting return key ("done", "go" in a form, "search" on the
search fields), and addresses, codes and numbers are no longer capitalised
or corrected. Ticking off packing items and tasks, a picker chip, a select
option, a picked date and dragging a plan row now give the haptics a native
list gives.

Confirmations ask through the system where the binary has the new
@capacitor/action-sheet and @capacitor/dialog plugins: a sheet with the
action in red when it destroys something, an alert otherwise, also for
"discard changes" in a sheet. An older app, a browser and a question with a
list under it keep the HTML dialog, as does a system that could not ask.

iOS no longer lifts a page preview on a long press on a link.
2026-11-09 08:54:51 +01:00
Maurice d9baaa8957 fix(native): a long press in the app selects no text and opens no callout
In the iOS and Android app a long press on a label, card or image started a text
selection, the magnifier or a "save image" menu, the clearest sign of a web page
in a frame. startNativeApp marks <html> with data-native-app, and index.css then
turns selection and the callout off for the UI. Inputs, textareas, selects and
editors stay selectable so typing, pasting and the caret work; text worth copying
opts in with .trek-selectable. A browser keeps its default.
2026-11-09 08:32:24 +01:00
Maurice fede671f3b fix(managed): bootstrap hands the managed routes to the boot gate, so the shared kernel imports no domain 2026-11-09 00:09:27 +00:00
Maurice b3113e66b9 feat(native): buying TREK Cloud in the app asks for the password of the new TREK and opens it signed in
The claim screen takes the password (TREK's policy, checked before anything is
bought) and sends it with the purchase; the control plane answers with a
one-time welcome code, which the app hands to setServer. iOS and Android open
the instance's welcome page with it once after the first page, which signs the
buyer in. Without the code (a restore, an older control plane) the app opens
the instance as before.
2026-11-08 23:43:15 +00:00
Maurice 286b0b09ec feat(managed): the managed attachment point declares the routes it serves without a session, and the boot gate allows exactly those
Empty in this repository, as the module itself. An install that replaces the
module adds its anonymous routes in the same file, and the gate still fails on a
route missing there or an entry that went stale.
2026-11-08 23:33:52 +00:00
Maurice c0b39abe18 style(i18n): the German native strings formatted as Prettier asks 2026-11-08 23:19:39 +00:00
Maurice 6e3a6386b8 fix(i18n): German setup screens speak of "dein TREK", as everywhere else, and the proxy note reads naturally 2026-11-08 22:24:29 +01:00
Maurice 5e7d778740 fix(assistant): the step after the ask for the answer may only write text, so Claude Sonnet 5.5 can no longer offer its follow-ups a second time instead (#3016) 2026-11-08 21:16:09 +01:00
Maurice 3be87343b8 fix: the gate texts formatted as the locales are, gate detection as a table of rules, and no non-null assertions in its tests 2026-11-08 20:58:49 +01:00
Maurice 517efabbca feat(native): the address screen recognises a sign-in proxy in front of TREK and signs in to it inside the app, so its session works as in a browser 2026-11-08 20:44:26 +01:00
2760 changed files with 133848 additions and 30454 deletions
+156
View File
@@ -0,0 +1,156 @@
name: Set up Node and the workspaces
description: >-
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
and optionally shared/dist from a cache or a build. Runs after checkout.
# A local action, so it is versioned with the workflow that calls it and needs
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
# test.yml: a change here runs everything.
#
# node_modules is restored only on an exact key: the runner image, the scope,
# the Node ABI, the lockfile and every workspace package.json. There are no
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
# npm ci. The package.json files are in the key because npm ci is also the
# check that they agree with the lockfile: an edited range without a fresh
# lockfile misses the cache and fails the install, as it did when every job
# ran npm ci. Only pushes to dev and main save, the npm download cache
# included, so pull requests read what their base left and cannot evict it or
# fill the repository's cache quota with entries of their own.
inputs:
scope:
description: >-
Which workspaces to install: full (npm ci), client (shared and client)
or shared (shared alone).
required: true
build-shared:
description: "'true' to restore shared/dist, or build it on a miss."
required: false
default: 'false'
runs:
using: composite
steps:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
# ImageOS and ImageVersion name the runner image, whose system libraries
# the native modules were built against. They live in the runner's
# environment, not in the env context, so the key is put together here. A
# job in a container has neither; the container's OS release stands in,
# and that job's tree is kept apart from the runner's.
- name: Work out the cache keys
id: keys
shell: bash
env:
SCOPE: ${{ inputs.scope }}
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
run: |
set -euo pipefail
case "$SCOPE" in
full | client | shared) ;;
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
esac
if [ -n "${ImageOS:-}" ]; then
image="$ImageOS-${ImageVersion:-unknown}"
else
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
fi
abi="$(node -p process.versions.modules)"
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
- name: Restore node_modules
id: nm
uses: actions/cache/restore@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# The npm download cache only matters when npm ci runs, so it is restored
# only then. It may fall back to an older lockfile's cache: npm ci checks
# every tarball against the lockfile's integrity hash and fetches what is
# missing, so a stale entry only costs downloads.
- name: Restore the npm download cache
id: npm
if: steps.nm.outputs.cache-hit != 'true'
uses: actions/cache/restore@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install dependencies
if: steps.nm.outputs.cache-hit != 'true'
shell: bash
env:
SCOPE: ${{ inputs.scope }}
run: |
set -euo pipefail
# better-sqlite3 ships no prebuilt binary and compiles on install. The
# hosted runners carry a compiler; the Playwright container of the e2e
# jobs does not, so on a cache miss there it gets one first. A hit,
# the usual case once a push to dev has saved the container's key,
# never reaches this step.
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
export DEBIAN_FRONTEND=noninteractive
timeout 300 apt-get update -qq
timeout 300 apt-get install -y -qq --no-install-recommends make g++
fi
case "$SCOPE" in
full) npm ci ;;
# The scoped install keeps @testing-library/dom (a peer of
# @testing-library/react) in the tree.
client) npm ci --workspace shared --workspace client ;;
shared) npm ci --workspace shared ;;
esac
- name: Save node_modules
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# Only a full install saves the download cache, so the entry holds every
# tarball; a scoped job that finished first would otherwise claim the key
# with part of the tree and no later run would fill it.
- name: Save the npm download cache
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
uses: actions/cache/save@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
# The key holds every input of the build: the sources, the package and
# build configs, and the lockfile that pins tsdown and zod.
- name: Restore shared/dist
id: sd
if: inputs.build-shared == 'true'
uses: actions/cache/restore@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
- name: Build shared
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
shell: bash
run: npm run build --workspace=shared
- name: Save shared/dist
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
+11 -1
View File
@@ -7,8 +7,11 @@
# enforce-target-branch.yml moves those onto dev.
#
# Every PR runs test.yml like any other, so ci-ok decides whether it can
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
# A bump of @playwright/test also needs the Playwright container tag and
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
# fails the PR until they match.
version: 2
updates:
# The root lockfile covers the client, server and shared workspaces.
@@ -25,6 +28,13 @@ updates:
groups:
npm-minor-and-patch:
update-types: [minor, patch]
ignore:
# TypeScript 7 is the native compiler and has no JavaScript API yet:
# typescript-eslint, the coverage instrumenter and the Postgres probe all
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
# tooling supports it.
- dependency-name: typescript
update-types: [version-update:semver-major]
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm
+2 -2
View File
@@ -175,7 +175,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -236,7 +236,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+2 -2
View File
@@ -344,7 +344,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -403,7 +403,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+8 -1
View File
@@ -18,9 +18,16 @@ jobs:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: package-lock.json
# shared's ESLint and Prettier plugins are its own devDependencies, and
# the format ratchet in scripts/lib/ resolves prettier from the root, so
# shared plus the root is the whole tree these checks read. npm ci
# installs exactly what the lockfile says, where npm install could
# resolve anew.
- name: Install dependencies
run: npm install
run: npm ci --workspace shared --include-workspace-root
- name: Run lint & format check
# Both are check-only: lint used to run eslint --fix, which rewrote the
+8 -6
View File
@@ -49,7 +49,7 @@ jobs:
node-version-file: .nvmrc
cache: npm
- uses: actions/setup-java@v5
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 21
@@ -111,19 +111,21 @@ jobs:
ios:
if: github.repository == 'liketrek/TREK'
runs-on: macos-15
runs-on: xcode-27
timeout-minutes: 60
environment: store
steps:
- uses: actions/checkout@v6
# App Store uploads must be built with Xcode 26; the image's default is older.
- name: Select Xcode 26
# The iOS 27.1 SDK, on the xcode-27 image: an app built against an older SDK
# runs letterboxed on the inner display of an iPhone Duo.
- name: Select Xcode 27.1
run: |
XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1)
test -n "$XCODE"
XCODE=/Applications/Xcode_27.1.app
test -d "$XCODE"
sudo xcode-select -s "$XCODE"
xcodebuild -version
xcodebuild -showsdks | grep iphoneos27.1
- uses: actions/setup-node@v6
with:
+15 -35
View File
@@ -10,6 +10,13 @@ permissions:
#
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
# not get, and belong in a release workflow of their own.
#
# package-lock.json is not a trigger: every dependency bump touches it, and a
# Mac build per bump only held the queue. The shells link nothing but the
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
# bump of one of them raises the range there too, so it still runs. The client
# typecheck and the watch and widget snapshot tests run in test.yml on every
# change under client/.
on:
pull_request:
paths:
@@ -24,7 +31,6 @@ on:
- 'client/scripts/check-store-metadata.mjs'
- 'client/fastlane/**'
- 'client/package.json'
- 'package-lock.json'
- 'shared/src/i18n/*/native.ts'
- '.github/workflows/native.yml'
workflow_dispatch:
@@ -60,7 +66,7 @@ jobs:
node-version-file: .nvmrc
cache: npm
- uses: actions/setup-java@v5
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 21
@@ -90,18 +96,20 @@ jobs:
retention-days: 14
ios:
runs-on: macos-15
runs-on: xcode-27
timeout-minutes: 40
steps:
- uses: actions/checkout@v6
# App Store uploads must be built with Xcode 26; the image's default is older.
- name: Select Xcode 26
# The iOS 27.1 SDK, on the xcode-27 image: an app built against an older SDK
# runs letterboxed on the inner display of an iPhone Duo.
- name: Select Xcode 27.1
run: |
XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1)
test -n "$XCODE"
XCODE=/Applications/Xcode_27.1.app
test -d "$XCODE"
sudo xcode-select -s "$XCODE"
xcodebuild -version
xcodebuild -showsdks | grep iphoneos27.1
- name: Check the property lists
run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements client/ios/App/TREKWidgets/Info.plist client/ios/App/TREKWidgets/TREKWidgets.entitlements client/ios/App/TREKWidgets/*.lproj/Localizable.strings client/ios/App/ShareExtension/Info.plist client/ios/App/ShareExtension/ShareExtension.entitlements client/ios/App/ShareExtension/*.lproj/Localizable.strings client/ios/App/TREKWatch/Info.plist client/ios/App/TREKWatch/TREKWatch.entitlements client/ios/App/TREKWatch/*.lproj/Localizable.strings client/ios/App/TREKWatchWidgets/Info.plist client/ios/App/TREKWatchWidgets/TREKWatchWidgets.entitlements
@@ -180,34 +188,6 @@ jobs:
path: client/ios/WidgetPreviews/out
retention-days: 14
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
# builds and the ticks it takes back, typechecked and tested here as well,
# so a change to the bridge is checked next to the Swift that reads it.
watch-bridge:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci --workspace=shared --workspace=client
- name: Build shared
run: npm run build --workspace=shared
- name: Typecheck the client
working-directory: client
run: npm run typecheck
- name: Test the widget and watch snapshots
working-directory: client
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
# every screen on the largest and the smallest watch, the main ones in every
# language, and the complications, as PNGs to look at without a watch.
+2 -2
View File
@@ -13,7 +13,7 @@ name: Security Scan
# - scout scans the built image, base image packages included. It needs
# the Docker Hub login, so it runs on PRs and pushes into main only and
# skips fork PRs. Whether the image builds at all is test.yml's
# docker-image job, which a red scan cannot hide.
# docker job, which a red scan cannot hide.
on:
pull_request:
branches: [main, dev]
@@ -74,7 +74,7 @@ jobs:
load: true
tags: trek:scan
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+929 -745
View File
File diff suppressed because it is too large Load Diff
+13 -5
View File
@@ -31,6 +31,7 @@ Tests:
npm run test # all workspaces
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
cd client && npm run test # client vitest run
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
@@ -134,13 +137,18 @@ 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: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-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), 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 (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `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 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.
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
- **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.
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
+20 -6
View File
@@ -72,10 +72,23 @@ COPY server/package.json ./server/
# package, and a telemetry ping.
# 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).
RUN apt-get update && \
#
# 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
# (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).
# 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.
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' \
> /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 && \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
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 && \
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
# database starts from). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
COPY --chown=node:node server/tsconfig.json ./server/
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
# raw .ts source — it never enters dist, so it must be copied in explicitly or
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
+17 -1
View File
@@ -20,7 +20,23 @@ geoBoundaries is licensed under **CC BY 4.0**
The bundled files are simplified (coordinate-quantized) and re-tagged with the
property names TREK consumes. Country borders (`admin0`) derive from the geoBoundaries
CGAZ composite; sub-national regions (`admin1`) derive from the per-country open
(gbOpen) release.
(gbOpen) release, except for Ireland (below).
## Tailte Éireann — counties of Ireland
Ireland's regions in the same files (`admin1/IE.geojson.gz`, and its features in
`admin1.geojson.gz`) are the 26 counties from Tailte Éireann's *Counties - National
Statutory Boundaries - 2019 - Generalised 20m*, because geoBoundaries has no county
layer for Ireland.
Contains Tailte Éireann data, © Tailte Éireann, licensed under **CC BY 4.0**
(https://creativecommons.org/licenses/by/4.0/). Source:
https://data-osi.opendata.arcgis.com/
The outlines are simplified, coordinate-quantized and re-tagged with ISO 3166-2:IE
codes by `server/scripts/build-atlas-geo.mjs`. Tailte Éireann publishes the
generalised boundaries for reference only; they may not match the statutory
boundaries exactly.
## OpenStreetMap — geocoding, place details & descriptions
+12 -4
View File
@@ -146,7 +146,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
#### 🗺️ Atlas, Vacay and Collections
- **Atlas**: countries and regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, a bucket list, travel stats, and a tour activities tab with planned against recorded totals
- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
- **Vacay**: leave calendar with half days, public holidays from [nagerholidays.com](https://nagerholidays.com), school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
- **Collections** (off by default): a place library outside any trip with lists, labels, ratings, a status per place, cover images, GPX and file export, copy into a trip, and sharing by invite
- **Dawarich** (off by default): link a Dawarich instance for recorded tracks, suggested stays and countries for the Atlas
@@ -276,6 +276,8 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
**TrueNAS SCALE:** Install TREK directly from the Community catalog. See the [TrueNAS SCALE installation guide](https://github.com/liketrek/TREK/wiki/Install-TrueNAS-SCALE).
> [!TIP]
> **No server yet?** TREK's own public services run on [**dataforest cloud**](https://cloud.dataforest.net/en?mtm_campaign=trek), our infrastructure sponsor. A small seed is plenty for a TREK instance and is ready within a minute.
@@ -319,6 +321,11 @@ 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
[`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.
<br />
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
@@ -348,7 +355,7 @@ TREK then launches fullscreen with its own icon, just like a native app.
## Updating
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
Docker run, Helm, Portainer, Unraid and Proxmox, plus the encryption-key note.
Docker run, Helm, Portainer, Unraid, TrueNAS SCALE and Proxmox, plus the encryption-key note.
<br />
@@ -437,8 +444,9 @@ Every variable, its default and what it does: see
The Atlas map's country and sub-national (province/county) boundaries come from
[**geoBoundaries**](https://www.geoboundaries.org/) (Runfola et al., 2020), licensed
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See [NOTICE.md](NOTICE.md)
for full third-party attributions.
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); Ireland's counties come from
[**Tailte Éireann**](https://data-osi.opendata.arcgis.com/), also CC BY 4.0. See
[NOTICE.md](NOTICE.md) for full third-party attributions.
<br />
+3 -1
View File
@@ -43,8 +43,10 @@ See `values.yaml` for more options.
## Notes
- Ingress is off by default. Enable and configure hosts for your domain.
- PVCs use the cluster's default StorageClass. Set `persistence.data.storageClassName` and/or `persistence.uploads.storageClassName` to bind a specific class.
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, annotations) are then ignored.
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2
name: trek
version: 5.1.1
version: 5.1.4
description: Minimal Helm chart for TREK app
appVersion: "5.1.1"
appVersion: "5.1.4"
+17 -4
View File
@@ -1,3 +1,6 @@
{{- if and .Values.database.url (not .Values.database.existingSecret) .Values.existingSecret }}
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -5,11 +8,13 @@ metadata:
labels:
app: {{ include "trek.name" . }}
spec:
# One replica. Its rate limits, pending codes, permission cache and WebSocket
# connections live in the process's memory, so a second pod would not share them. That
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
replicas: 1
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
# RollingUpdate would start a second pod holding the same volume before the old one
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
# the old pod down first. Keep it, see updateStrategy in values.yaml.
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
strategy:
type: {{ .Values.updateStrategy | default "Recreate" }}
selector:
@@ -61,6 +66,14 @@ spec:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
optional: true
{{- if or .Values.database.url .Values.database.existingSecret }}
# Required when set: a missing key stops the pod rather than starting it on SQLite.
- name: TREK_DB_URL
valueFrom:
secretKeyRef:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.database.existingSecret }}
key: {{ if .Values.database.existingSecret }}{{ .Values.database.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
{{- end }}
- name: ADMIN_EMAIL
valueFrom:
secretKeyRef:
+2 -2
View File
@@ -11,7 +11,7 @@ metadata:
{{- end }}
spec:
accessModes:
- ReadWriteOnce
{{- toYaml (.Values.persistence.data.accessModes | default (list "ReadWriteOnce")) | nindent 4 }}
{{- with .Values.persistence.data.storageClassName }}
storageClassName: {{ . | quote }}
{{- end }}
@@ -33,7 +33,7 @@ metadata:
{{- end }}
spec:
accessModes:
- ReadWriteOnce
{{- toYaml (.Values.persistence.uploads.accessModes | default (list "ReadWriteOnce")) | nindent 4 }}
{{- with .Values.persistence.uploads.storageClassName }}
storageClassName: {{ . | quote }}
{{- end }}
+6
View File
@@ -8,6 +8,9 @@ metadata:
type: Opaque
data:
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
{{- if .Values.database.url }}
TREK_DB_URL: {{ .Values.database.url | b64enc | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
{{- end }}
@@ -65,6 +68,9 @@ stringData:
{{- else }}
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
{{- end }}
{{- if .Values.database.url }}
TREK_DB_URL: {{ .Values.database.url | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
{{- end }}
+33 -5
View File
@@ -4,10 +4,13 @@ image:
# tag: latest
pullPolicy: IfNotPresent
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
# during a RollingUpdate the new pod migrates the database while the old one still
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
# processes on one host, which network filesystems do not provide.
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
# starts, and during a RollingUpdate it would do that while the old pod still writes to
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
updateStrategy: Recreate
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
@@ -178,6 +181,22 @@ env:
# address is sent unless you set one here.
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
# carries the password, so it is never a plain env value: with url, the chart writes it into
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
# variable is required when either is set: a missing Secret key stops the pod instead of
# 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.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
url: ""
existingSecret: ""
existingSecretKey: TREK_DB_URL
# Secret environment variables stored in a Kubernetes Secret.
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
# rotatable via the admin panel) — it is not configured here.
@@ -247,12 +266,21 @@ persistence:
size: 1Gi
# Leave empty to use the cluster's default StorageClass; set to bind a specific class.
storageClassName: ""
# Bind an existing PVC. The other values (size, storageClassName, annotations) are then ignored.
# Access modes of the claim. ReadWriteMany lets another pod mount the volume, for
# example a backup sidecar, but only for reading: SQLite needs every writer on one
# host, so two pods writing travel.db over a network filesystem corrupt it.
accessModes:
- ReadWriteOnce
# Bind an existing PVC. The other values (size, storageClassName, accessModes,
# annotations) are then ignored.
existingClaim: ""
annotations: {}
uploads:
size: 1Gi
storageClassName: ""
# Access modes of the claim; ReadWriteMany lets other pods read or add uploads.
accessModes:
- ReadWriteOnce
# Specify an existing PVC to bind. The other values are then ignored.
existingClaim: ""
annotations: {}
+1 -1
View File
@@ -6,7 +6,7 @@ Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PW
```bash
npm run dev # Vite dev server; proxies the API/ws/uploads/MCP/OAuth paths → http://localhost:3001
npm run build # prebuild generates PWA icons, then vite build
npm run build # prebuild generates PWA icons, then vite build; postbuild writes a Brotli copy beside each hashed asset for the server to hand out
npm run typecheck # tsc --noEmit (CI)
npm run lint:strict # tsc over tsconfig.strict.json (strictNullChecks + noImplicitAny): errors per file may only shrink against scripts/strict-baseline.json, a new file starts at zero (CI gate; --list shows them, --update lowers it)
npm run lint # eslint . (CI runs lint:warnings instead, which fails on the same errors)
@@ -9,7 +9,9 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-action-sheet')
implementation project(':capacitor-app')
implementation project(':capacitor-dialog')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-haptics')
implementation project(':capacitor-keyboard')
+9
View File
@@ -36,3 +36,12 @@
@android.webkit.JavascriptInterface <methods>;
}
-keep public class * extends com.getcapacitor.Plugin
# The stored copy of the server's UI gets Capacitor's bridge the way the
# server's own page does (TrekOfflineShell.withBridge reads it by reflection).
-keepclassmembers class com.getcapacitor.Bridge {
private com.getcapacitor.JSInjector getJSInjector();
}
-keep class com.getcapacitor.JSInjector {
public java.io.InputStream getInjectedStream(java.io.InputStream);
}
@@ -15,6 +15,7 @@ import androidx.glance.appwidget.GlanceRemoteViews
import com.liketrek.trek.tripday.TripDayNotification
import com.liketrek.trek.widget.AtlasWidget
import com.liketrek.trek.widget.BookingsWidget
import com.liketrek.trek.widget.FlightWidget
import com.liketrek.trek.widget.CollabWidget
import com.liketrek.trek.widget.PackingWidget
import com.liketrek.trek.widget.TodayWidget
@@ -74,6 +75,7 @@ class WidgetGalleryActivity : Activity() {
"trip" to TripWidget(),
"today" to TodayWidget(),
"bookings" to BookingsWidget(),
"flight" to FlightWidget(),
"todos" to TodosWidget(),
"packing" to PackingWidget(),
"atlas" to AtlasWidget(),
@@ -142,6 +142,15 @@
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_bookings" />
</receiver>
<receiver
android:name=".widget.FlightWidgetReceiver"
android:label="@string/widget_flight_name"
android:exported="false">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_flight" />
</receiver>
<receiver
android:name=".widget.TodosWidgetReceiver"
android:label="@string/widget_todos_name"
@@ -1,11 +1,20 @@
package com.liketrek.trek;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.getcapacitor.BridgeActivity;
import com.liketrek.trek.screen.TrekKeyCommands;
import com.liketrek.trek.tiles.TrekTileStore;
@@ -26,6 +35,19 @@ public class MainActivity extends BridgeActivity {
// runs and on its own origin. BridgeActivity reads `config` while it
// builds the bridge inside super.onCreate().
boolean restarting = TrekServerStore.consumeRestart(this);
// Without a network the server cannot answer: with a copy of its UI the
// app starts on that at once (TrekOfflineShell), as it does when the
// address screen found the server out of reach. The check an update asks
// for waits for a launch that can reach the server.
boolean offlineStart = TrekServerStore.consumeOfflineStart(this)
|| (!TrekOfflineShell.hasNetwork(this) && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this)));
if (offlineStart && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this))) {
TrekServerStore.restoreForOffline(this);
TrekOfflineShell.activate(TrekServerStore.getUrl(this));
} else {
TrekOfflineShell.deactivate();
TrekServerStore.recheckAfterUpdate(this);
}
String server = TrekServerStore.getUrl(this);
boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this);
config = TrekServerStore.configFor(this, onServer ? server : null, restarting);
@@ -36,7 +58,17 @@ public class MainActivity extends BridgeActivity {
// scroller natively. It scales the whole view, top bar and bottom dock included.
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
// Set before any WebView callback can run: they are posted to this thread.
if (onServer) bridge.setWebViewClient(new TrekWebViewClient(bridge, this::showAddressScreen));
if (onServer) {
bridge.setWebViewClient(
new TrekWebViewClient(
bridge,
this::showAddressScreen,
this::showSignInBar,
this::showErrorPageBar,
TrekServerStore.getSignInHosts(this)
)
);
}
TrekSharedFiles.receive(this, getIntent());
// Android 15's widget picker draws the widgets live from a sample trip.
TrekWidgetUpdater.publishPreviews(this);
@@ -60,6 +92,18 @@ public class MainActivity extends BridgeActivity {
if (group != null) data.add(group);
}
/**
* The web view keeps new cookies in memory and writes them to disk on its
* own schedule, about half a minute later. An app Android ends in that time
* (swiped away, or reclaimed for memory) forgets the sign-in it just had, so
* the session is written down whenever the app leaves the screen.
*/
@Override
public void onPause() {
super.onPause();
CookieManager.getInstance().flush();
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
@@ -68,6 +112,122 @@ public class MainActivity extends BridgeActivity {
private boolean leavingServer;
private View signInBar;
/** Whether the page is a proxy's sign-in page, and whether the keyboard is up over it. */
private boolean onSignInPage;
/** Whether the page is an error page in place of the server's (TrekWebViewClient.onReceivedHttpError). */
private boolean onErrorPage;
private boolean keyboardUp;
private TextView signInHint;
/**
* Over a proxy's sign-in page (Pangolin, authentik, ...): the server's UI is
* not there, so nothing else would lead back to the address screen, and a
* passkey cannot work in a web view for a domain the app is not tied to.
* The bar says so and offers to change the server.
*/
private void showSignInBar(boolean show) {
runOnUiThread(() -> {
onSignInPage = show;
if (show && signInBar == null) signInBar = buildSignInBar();
updateSignInBar();
});
}
/** The same bar over an error page in place of the server's, with words for that. */
private void showErrorPageBar(boolean show) {
runOnUiThread(() -> {
onErrorPage = show;
if (show && signInBar == null) signInBar = buildSignInBar();
updateSignInBar();
});
}
/** Out of the way while the keyboard is up: the form needs the room, and the bar is there again once it closes. */
private void updateSignInBar() {
if (signInBar == null) return;
if (signInHint != null) {
signInHint.setText(onSignInPage ? TrekServerStore.signInHintLabel(this) : TrekServerStore.errorPageHintLabel(this));
}
signInBar.setVisibility((onSignInPage || onErrorPage) && !keyboardUp ? View.VISIBLE : View.GONE);
}
private View buildSignInBar() {
float dp = getResources().getDisplayMetrics().density;
LinearLayout bar = new LinearLayout(this);
bar.setOrientation(LinearLayout.HORIZONTAL);
bar.setGravity(Gravity.CENTER_VERTICAL);
bar.setPaddingRelative(Math.round(16 * dp), Math.round(10 * dp), Math.round(10 * dp), Math.round(10 * dp));
// The look of the app's own first screens: a white card with a sand edge,
// warm grey text and a dark button, over whatever page the proxy shows.
GradientDrawable background = new GradientDrawable();
background.setColor(0xF7FFFFFF);
background.setCornerRadius(18 * dp);
background.setStroke(Math.max(1, Math.round(dp)), 0xFFEFE4D8);
bar.setBackground(background);
bar.setElevation(8 * dp);
TextView hint = new TextView(this);
signInHint = hint;
hint.setText(TrekServerStore.signInHintLabel(this));
hint.setTextColor(0xFF6B5F57);
hint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
bar.addView(hint, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
Button change = new Button(this, null, android.R.attr.borderlessButtonStyle);
change.setText(TrekServerStore.changeServerLabel(this));
change.setAllCaps(false);
change.setTextColor(0xFFFFFFFF);
GradientDrawable pill = new GradientDrawable();
pill.setColor(0xFF111827);
pill.setCornerRadius(12 * dp);
change.setBackground(pill);
change.setMinHeight(0);
change.setMinimumHeight(0);
change.setPaddingRelative(Math.round(14 * dp), Math.round(9 * dp), Math.round(14 * dp), Math.round(9 * dp));
LinearLayout.LayoutParams changeParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
changeParams.setMarginStart(Math.round(10 * dp));
change.setOnClickListener((v) -> {
TrekServerStore.setUrl(this, null);
TrekServerStore.markRestart(this);
recreate();
});
bar.addView(change, changeParams);
int margin = Math.round(12 * dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
params.setMargins(margin, 0, margin, margin);
FrameLayout root = findViewById(android.R.id.content);
root.addView(bar, params);
// Above the gesture bar, and above the keyboard while it is up.
bar.setOnApplyWindowInsetsListener((v, insets) -> {
// Read off the window's own insets: Capacitor hands the views below the
// decor a copy with the system bars zeroed, and before Android 11 that
// takes the keyboard with it.
androidx.core.view.WindowInsetsCompat window = androidx.core.view.ViewCompat.getRootWindowInsets(getWindow().getDecorView());
int bottom = window != null
? window.getInsets(androidx.core.view.WindowInsetsCompat.Type.navigationBars()).bottom
: insets.getStableInsetBottom();
boolean imeVisible = window != null && window.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime());
if (imeVisible != keyboardUp) {
keyboardUp = imeVisible;
updateSignInBar();
}
FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) v.getLayoutParams();
if (p.bottomMargin != margin + bottom) {
p.bottomMargin = margin + bottom;
v.setLayoutParams(p);
}
return insets;
});
bar.requestApplyInsets();
return bar;
}
/**
* The server did not load: back to the address screen, which offers retry
* and change. A fresh task rather than recreate(), because this usually
@@ -0,0 +1,57 @@
package com.liketrek.trek;
import java.net.URI;
import java.util.Locale;
/**
* A sign-in page in front of the server that the address screen never saw.
* A proxy can let the app's check through (an Authelia or Authentik rule that
* bypasses /api) and still send the page itself to its sign-in. Handed to the
* browser, that sign-in leaves its session there and the app stays blank on
* every launch. So a redirect away from the server, while the server's first
* page is still loading, is taken as the proxy's sign-in: it loads in the web
* view and its host is kept, the way the address screen keeps the ones it saw.
* A link the user follows is no redirect, and once a page of the server has
* shown, nothing is learned any more.
*/
final class SignInRedirect {
private SignInRedirect() {}
/** The host (host:port with an explicit port) to keep as a sign-in host, or null. */
static String learnedHost(String server, String target, boolean mainFrame, boolean redirect, boolean serverShown) {
if (!mainFrame || !redirect || serverShown || server == null || target == null) return null;
URI from;
URI to;
try {
from = new URI(server);
to = new URI(target);
} catch (Exception e) {
return null;
}
String fromHost = lower(from.getHost());
String toHost = lower(to.getHost());
String toScheme = lower(to.getScheme());
if (fromHost == null || toHost == null) return null;
if (!"https".equals(toScheme) && !"http".equals(toScheme)) return null;
// Never from https down to plain http: the sign-in would send a password in the clear.
if ("https".equals(lower(from.getScheme())) && !"https".equals(toScheme)) return null;
if (toHost.equals(fromHost)) return null;
return to.getPort() == -1 ? toHost : toHost + ":" + to.getPort();
}
/** Whether `url` is on the server's host, where the app's own pages come from. */
static boolean onServer(String server, String url) {
if (server == null || url == null) return false;
try {
String serverHost = lower(new URI(server).getHost());
return serverHost != null && serverHost.equals(lower(new URI(url).getHost()));
} catch (Exception e) {
return false;
}
}
private static String lower(String value) {
return value == null ? null : value.toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,330 @@
package com.liketrek.trek;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import com.getcapacitor.Bridge;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* The server's UI kept on the device, so the app starts without its server: on
* a trip without reception, or away from home with a server on the home
* network. The web view runs no service worker on a plain-http server, the
* usual address of a server at home, so the app keeps the start page and every
* file of the build itself (refreshed by native/offlineShell.ts while the
* server is reachable) and serves them under the server's own origin while it
* is not. The data comes from the UI's own offline store; the API is tried as
* usual and answers again once the server is back.
*/
final class TrekOfflineShell {
private static final String DIR = "offline-shell";
private static final String PAGE = "index.html";
private static final String STAMP = "server.txt";
private static final String FILES = "files";
/** A path of the build: no "..", no query, nothing outside the copy's folder. */
private static final Pattern SAFE_PATH = Pattern.compile("^[A-Za-z0-9._@\\-]+(?:/[A-Za-z0-9._@\\-]+)*$");
private static final Map<String, String> TYPES = new HashMap<>();
static {
TYPES.put("js", "text/javascript");
TYPES.put("mjs", "text/javascript");
TYPES.put("css", "text/css");
TYPES.put("json", "application/json");
TYPES.put("webmanifest", "application/manifest+json");
TYPES.put("svg", "image/svg+xml");
TYPES.put("png", "image/png");
TYPES.put("jpg", "image/jpeg");
TYPES.put("jpeg", "image/jpeg");
TYPES.put("webp", "image/webp");
TYPES.put("ico", "image/x-icon");
TYPES.put("woff", "font/woff");
TYPES.put("woff2", "font/woff2");
TYPES.put("ttf", "font/ttf");
TYPES.put("wasm", "application/wasm");
TYPES.put("html", "text/html");
}
/**
* The server whose copy the UI comes from in this run: it did not answer
* when the app started. Null while the UI comes from the server itself.
* Bound to the server, so a copy never answers for another one.
*/
private static volatile String activeServer;
/** Capacitor's JSInjector (package-private there) and its getInjectedStream, found once. */
private static volatile Object injector;
private static volatile Method injectMethod;
private static volatile boolean injectorLooked;
private TrekOfflineShell() {}
static boolean isActive() {
return activeServer != null;
}
static void activate(String server) {
activeServer = server;
}
/**
* A start that goes to the server. The flag lives in the process, and
* restart() recreates the activity in that same process (another server
* picked, the address screen, a reload once the server is back), so each
* start sets it anew instead of keeping the last run's copy in front.
*/
static void deactivate() {
activeServer = null;
}
/** Whether the copy stands in for this server in this run. */
static boolean isActiveFor(String server) {
String current = activeServer;
return current != null && current.equals(server);
}
private static File root(Context context) {
return new File(context.getFilesDir(), DIR);
}
/** Whether there is a copy of this server's UI to start from. */
static boolean hasCopy(Context context, String server) {
return hasCopy(root(context), server);
}
static boolean hasCopy(File root, String server) {
if (server == null) return false;
File page = new File(root, PAGE);
return page.isFile() && server.equals(readStamp(root));
}
/** Whether the device has a network at all; with none, the server cannot answer and the copy starts at once. */
static boolean hasNetwork(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return true;
Network network = cm.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities caps = cm.getNetworkCapabilities(network);
return caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
} catch (RuntimeException e) {
return true;
}
}
/**
* Before a refresh fetches the files of a build: a copy of another server
* is thrown away, one of this server stays as it is until savePage.
*/
static boolean beginRefresh(Context context, String server) {
return beginRefresh(root(context), server);
}
static boolean beginRefresh(File root, String server) {
if (!server.equals(readStamp(root))) deleteTree(root);
return root.isDirectory() || root.mkdirs();
}
/**
* Keeps the start page, and only once every file it names is stored: the
* page points at the build's files by their hashes, so a refresh cut off
* halfway (no reception, the app ended) keeps the previous page with its
* complete build instead of a new page whose scripts are missing.
*/
static boolean savePage(Context context, String server, byte[] html) {
return savePage(root(context), server, html);
}
static boolean savePage(File root, String server, byte[] html) {
if (!root.isDirectory() && !root.mkdirs()) return false;
return write(new File(root, STAMP), server.getBytes(StandardCharsets.UTF_8)) && write(new File(root, PAGE), html);
}
static boolean hasFile(Context context, String path) {
return hasFile(root(context), path);
}
static boolean hasFile(File root, String path) {
File file = fileFor(root, path);
return file != null && file.isFile();
}
static boolean saveFile(Context context, String path, byte[] data) {
return saveFile(root(context), path, data);
}
static boolean saveFile(File root, String path, byte[] data) {
File file = fileFor(root, path);
if (file == null) return false;
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) return false;
return write(file, data);
}
/** Drops the files of older builds once the current one is complete. */
static void prune(Context context, Set<String> keep) {
prune(root(context), keep);
}
static void prune(File root, Set<String> keep) {
File base = new File(root, FILES);
pruneDir(base, base, keep);
}
/**
* The copy's answer for a request of the server's UI while it is active:
* the start page for any page of the app (it routes itself), with
* Capacitor's bridge injected as into the server's own page, and a file of
* the build by its path. Null for anything else, which goes on as usual.
*/
static WebResourceResponse serve(Context context, Bridge bridge, String server, WebResourceRequest request) {
if (!isActiveFor(server) || !"GET".equalsIgnoreCase(request.getMethod())) return null;
Uri url = request.getUrl();
Uri origin = Uri.parse(server);
if (!sameOrigin(url, origin)) return null;
try {
if (request.isForMainFrame()) {
File page = new File(root(context), PAGE);
if (!page.isFile()) return null;
InputStream html = withBridge(bridge, new FileInputStream(page));
return response("text/html", html);
}
String path = url.getPath();
if (path == null) return null;
File file = fileFor(root(context), path);
if (file == null || !file.isFile()) return null;
return response(typeOf(path), new FileInputStream(file));
} catch (IOException e) {
Log.w("TrekShell", "Offline copy could not answer " + url, e);
return null;
}
}
private static WebResourceResponse response(String type, InputStream body) {
Map<String, String> headers = new HashMap<>();
headers.put("Cache-Control", "no-store");
String charset = type.startsWith("text/") || type.endsWith("json") ? "utf-8" : null;
return new WebResourceResponse(type, charset, 200, "OK", headers, body);
}
/**
* Capacitor injects its bridge into the server's page as it passes through;
* the copy gets the same script. Its builder is internal to Capacitor, hence
* the reflection on both (kept in proguard-rules.pro). Without it the UI still runs,
* as it would in a browser, just without the app's native parts.
*/
private static InputStream withBridge(Bridge bridge, InputStream html) {
if (!injectorLooked) {
injectorLooked = true;
try {
Method method = Bridge.class.getDeclaredMethod("getJSInjector");
method.setAccessible(true);
Object built = method.invoke(bridge);
if (built != null) {
Method inject = built.getClass().getDeclaredMethod("getInjectedStream", InputStream.class);
inject.setAccessible(true);
injectMethod = inject;
injector = built;
}
} catch (ReflectiveOperationException | RuntimeException e) {
Log.w("TrekShell", "No bridge for the offline copy", e);
}
}
Object current = injector;
Method inject = injectMethod;
if (current == null || inject == null) return html;
try {
Object injected = inject.invoke(current, html);
return injected instanceof InputStream ? (InputStream) injected : html;
} catch (ReflectiveOperationException | RuntimeException e) {
Log.w("TrekShell", "Bridge not injected into the offline copy", e);
return html;
}
}
private static boolean sameOrigin(Uri a, Uri b) {
if (a.getScheme() == null || b.getScheme() == null || a.getHost() == null || b.getHost() == null) return false;
return a.getScheme().equalsIgnoreCase(b.getScheme())
&& a.getHost().equalsIgnoreCase(b.getHost())
&& port(a) == port(b);
}
private static int port(Uri uri) {
if (uri.getPort() != -1) return uri.getPort();
return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
}
private static File fileFor(File root, String path) {
String clean = path.startsWith("/") ? path.substring(1) : path;
if (clean.isEmpty() || clean.contains("..") || !SAFE_PATH.matcher(clean).matches()) return null;
return new File(new File(root, FILES), clean);
}
private static String typeOf(String path) {
int dot = path.lastIndexOf('.');
String ext = dot < 0 ? "" : path.substring(dot + 1).toLowerCase(Locale.ROOT);
String type = TYPES.get(ext);
return type == null ? "application/octet-stream" : type;
}
private static String readStamp(File root) {
File stamp = new File(root, STAMP);
if (!stamp.isFile()) return null;
try (FileInputStream in = new FileInputStream(stamp)) {
byte[] data = new byte[(int) Math.min(stamp.length(), 4096)];
int read = in.read(data);
return read <= 0 ? null : new String(data, 0, read, StandardCharsets.UTF_8);
} catch (IOException e) {
return null;
}
}
/** Written beside the target and moved over it, so a cut-off write never leaves half a file. */
private static boolean write(File target, byte[] data) {
File temp = new File(target.getPath() + ".part");
try (FileOutputStream out = new FileOutputStream(temp)) {
out.write(data);
out.getFD().sync();
} catch (IOException e) {
temp.delete();
return false;
}
return temp.renameTo(target);
}
private static void pruneDir(File base, File dir, Set<String> keep) {
File[] children = dir.listFiles();
if (children == null) return;
for (File child : children) {
if (child.isDirectory()) {
pruneDir(base, child, keep);
String[] left = child.list();
if (left != null && left.length == 0) child.delete();
} else {
String relative = base.toURI().relativize(child.toURI()).getPath();
if (!keep.contains(relative)) child.delete();
}
}
}
private static void deleteTree(File file) {
File[] children = file.listFiles();
if (children != null) for (File child : children) deleteTree(child);
file.delete();
}
}
@@ -10,6 +10,10 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
@@ -18,27 +22,159 @@ final class TrekServerStore {
private static final String PREFS = "trek_shell";
private static final String KEY_URL = "server_url";
private static final String KEY_PREVIOUS_URL = "previous_server_url";
private static final String KEY_SERVER_CHECK = "server_check";
private static final String KEY_LABEL_SIGN_IN_HINT = "label_sign_in_hint";
private static final String KEY_LABEL_CHANGE_SERVER = "label_change_server";
private static final String KEY_LABEL_ERROR_PAGE_HINT = "label_error_page_hint";
/**
* The server API this build needs (MIN_NATIVE_API in serverAddress.ts). A
* server remembered under a lower value is checked once more: the first
* launch after an update that raised it puts the address screen back up,
* filled in with that server (getPreviousUrl). Raise both together.
*/
private static final int SERVER_CHECK = 3;
private static final String KEY_SIGN_IN_HOSTS = "sign_in_hosts";
private static final String KEY_SHELL_ONCE = "shell_once";
private static final String KEY_RESTART = "restart";
private static final String KEY_OFFLINE_START = "offline_start";
private static final String KEY_WELCOME = "welcome";
private static final String CONFIG_DIR = "trek-server-config";
private TrekServerStore() {}
/**
* The one-time code of a TREK Cloud purchase (setServer's `welcome`). The
* server's first page opens its welcome page with it once, which signs the
* buyer in (TrekWebViewClient). Kept only until the restart has loaded.
*/
static void setWelcome(Context context, String code) {
SharedPreferences.Editor editor = prefs(context).edit();
if (code == null) editor.remove(KEY_WELCOME);
else editor.putString(KEY_WELCOME, code);
editor.commit();
}
/** The welcome page for the pending code, handed out once; null when there is none. */
static String takeWelcomeUrl(Context context) {
String code = prefs(context).getString(KEY_WELCOME, null);
String server = getUrl(context);
if (code == null) return null;
prefs(context).edit().remove(KEY_WELCOME).commit();
if (server == null) return null;
return (server.endsWith("/") ? server : server + "/") + "api/managed/welcome#" + code;
}
static String getUrl(Context context) {
return prefs(context).getString(KEY_URL, null);
}
/** Runs before the bridge is built, so a server picked under an older minimum is not loaded unchecked. */
static void recheckAfterUpdate(Context context) {
SharedPreferences prefs = prefs(context);
if (prefs.getInt(KEY_SERVER_CHECK, 0) >= SERVER_CHECK) return;
String server = getUrl(context);
SharedPreferences.Editor editor = prefs.edit().putInt(KEY_SERVER_CHECK, SERVER_CHECK);
if (server != null) editor.remove(KEY_URL).remove(KEY_SIGN_IN_HOSTS).putString(KEY_PREVIOUS_URL, server);
editor.commit();
}
/**
* The words of the bar over a proxy's sign-in page, in the user's language,
* as the address screen passed them (setServer's `labels`): the server's UI
* is not there to say them. Null keeps the English fallback.
*/
static void setLabels(Context context, String signInHint, String changeServer, String errorPageHint) {
SharedPreferences.Editor editor = prefs(context).edit();
if (signInHint != null) editor.putString(KEY_LABEL_SIGN_IN_HINT, signInHint);
if (changeServer != null) editor.putString(KEY_LABEL_CHANGE_SERVER, changeServer);
if (errorPageHint != null) editor.putString(KEY_LABEL_ERROR_PAGE_HINT, errorPageHint);
editor.commit();
}
static String errorPageHintLabel(Context context) {
return prefs(context).getString(
KEY_LABEL_ERROR_PAGE_HINT,
"This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
);
}
static String signInHintLabel(Context context) {
return prefs(context).getString(
KEY_LABEL_SIGN_IN_HINT,
"Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
);
}
static String changeServerLabel(Context context) {
return prefs(context).getString(KEY_LABEL_CHANGE_SERVER, "Change server");
}
/** The server an update asked to check again, until a server is set. */
static String getPreviousUrl(Context context) {
return prefs(context).getString(KEY_PREVIOUS_URL, null);
}
/** Remembers the server; its sign-in hosts go with it and are replaced or dropped too. */
static void setUrl(Context context, String url) {
setServer(context, url, null);
}
static void setServer(Context context, String url, Set<String> signInHosts) {
SharedPreferences.Editor editor = prefs(context).edit();
if (url == null) {
editor.remove(KEY_URL);
} else {
editor.putString(KEY_URL, url);
editor.putString(KEY_URL, url).remove(KEY_PREVIOUS_URL);
}
if (signInHosts == null || signInHosts.isEmpty()) {
editor.remove(KEY_SIGN_IN_HOSTS);
} else {
Set<String> lower = new HashSet<>();
for (String host : signInHosts) lower.add(host.toLowerCase(Locale.ROOT));
editor.putStringSet(KEY_SIGN_IN_HOSTS, lower);
}
editor.commit();
}
/**
* The hosts of a sign-in page that stands in front of the server (a proxy
* such as Cloudflare Access or Pangolin), as the address screen found them.
* Only these may load inside the web view besides the server itself, so
* the proxy's session lands where the app can use it (TrekWebViewClient).
*/
static Set<String> getSignInHosts(Context context) {
Set<String> hosts = prefs(context).getStringSet(KEY_SIGN_IN_HOSTS, null);
return hosts == null ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(hosts));
}
/** Keeps one more sign-in host for the remembered server, as the web view met it (SignInRedirect). */
static void addSignInHost(Context context, String host) {
Set<String> hosts = new HashSet<>(getSignInHosts(context));
if (!hosts.add(host.toLowerCase(Locale.ROOT))) return;
prefs(context).edit().putStringSet(KEY_SIGN_IN_HOSTS, hosts).commit();
}
/** Start the next launch on the bundled address screen, even with a server remembered. */
private static final String KEY_FAILURE = "last_failure";
/**
* Why the server's page did not load, in the WebView's own terms
* ("net::ERR_NAME_NOT_RESOLVED (-2)", "HTTP 503"): the address screen shows
* it small under its message, so a report carries the cause.
*/
static void setFailure(Context context, String failure) {
prefs(context).edit().putString(KEY_FAILURE, failure).commit();
}
/** The failure behind this address screen, once. */
static String takeFailure(Context context) {
String failure = prefs(context).getString(KEY_FAILURE, null);
if (failure != null) prefs(context).edit().remove(KEY_FAILURE).commit();
return failure;
}
static void showShellOnce(Context context) {
prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit();
}
@@ -56,6 +192,37 @@ final class TrekServerStore {
return consume(context, KEY_RESTART);
}
/** The next onCreate starts on the stored copy of the server's UI (TrekOfflineShell). */
static void markOfflineStart(Context context) {
prefs(context).edit().putBoolean(KEY_OFFLINE_START, true).commit();
}
static boolean consumeOfflineStart(Context context) {
return consume(context, KEY_OFFLINE_START);
}
/**
* The remembered server, or the one an update asked to check again: the
* server the stored copy of the UI belongs to.
*/
static String getUrlOrPrevious(Context context) {
String url = getUrl(context);
return url != null ? url : getPreviousUrl(context);
}
/**
* Starting on the stored copy while the check an update asked for could not
* run: the server goes back in place, unchecked for now, and the check runs
* again on the next launch, which reaches the server.
*/
static void restoreForOffline(Context context) {
SharedPreferences prefs = prefs(context);
if (prefs.getString(KEY_URL, null) != null) return;
String previous = prefs.getString(KEY_PREVIOUS_URL, null);
if (previous == null) return;
prefs.edit().putString(KEY_URL, previous).remove(KEY_PREVIOUS_URL).putInt(KEY_SERVER_CHECK, 0).commit();
}
private static boolean consume(Context context, String key) {
boolean set = prefs(context).getBoolean(key, false);
if (set) prefs(context).edit().remove(key).commit();
@@ -1,23 +1,32 @@
package com.liketrek.trek;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.activity.result.ActivityResult;
import com.liketrek.trek.clientcert.ClientCertActions;
import com.liketrek.trek.clientcert.TrekClientIdentity;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.app.NotificationManagerCompat;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.ActivityCallback;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.HashSet;
import java.util.Set;
import org.json.JSONObject;
/** The native half of client/src/native/trekShell.ts. */
@@ -62,6 +71,8 @@ public class TrekShellPlugin extends Plugin {
"googleWallet",
"keyCommands",
"windowLayout",
"clientCertificate",
"filePreview",
};
/** liketrek's push relay: the endpoint for this device's FCM token (trek-hosted push-relay.ts). */
@@ -259,11 +270,53 @@ public class TrekShellPlugin extends Plugin {
call.resolve();
}
/**
* Opens a file the UI wrote to the cache in the app that views it, a PDF in
* the system's PDF viewer, instead of the share sheet. "unsupported" where no
* app on the device views the type; the UI then hands it to the share sheet.
*/
@PluginMethod
public void previewFile(PluginCall call) {
String path = call.getString("path");
Uri parsed = path == null ? null : Uri.parse(path);
java.io.File file = parsed != null && "file".equals(parsed.getScheme()) && parsed.getPath() != null ? new java.io.File(parsed.getPath()) : null;
java.io.File cache = getContext().getCacheDir();
boolean inCache;
try {
inCache = file != null && file.getCanonicalPath().startsWith(cache.getCanonicalPath() + java.io.File.separator);
} catch (java.io.IOException e) {
inCache = false;
}
if (!inCache || !file.isFile()) {
call.reject("a file in the app's cache is required", "INVALID");
return;
}
String type = call.getString("mimeType", "application/octet-stream");
Uri content = androidx.core.content.FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
Intent view = new Intent(Intent.ACTION_VIEW)
.setDataAndType(content, type)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().runOnUiThread(() -> {
JSObject result = new JSObject();
try {
getActivity().startActivity(view);
result.put("result", "shown");
} catch (ActivityNotFoundException e) {
result.put("result", "unsupported");
}
call.resolve(result);
});
}
@PluginMethod
public void getServer(PluginCall call) {
String url = TrekServerStore.getUrl(getContext());
String previous = TrekServerStore.getPreviousUrl(getContext());
JSObject result = new JSObject();
result.put("url", url == null ? JSONObject.NULL : url);
result.put("previousUrl", previous == null ? JSONObject.NULL : previous);
String failure = TrekServerStore.takeFailure(getContext());
result.put("failure", failure == null ? JSONObject.NULL : failure);
call.resolve(result);
}
@@ -275,11 +328,35 @@ public class TrekShellPlugin extends Plugin {
call.reject("A http(s) URL is required");
return;
}
TrekServerStore.setUrl(getContext(), url);
TrekServerStore.setServer(getContext(), url, signInHostsOf(call));
JSObject labels = call.getObject("labels");
if (labels != null) {
TrekServerStore.setLabels(
getContext(),
labels.getString("signInHint"),
labels.getString("changeServer"),
labels.getString("errorPageHint")
);
}
// A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page.
String welcome = call.getString("welcome");
TrekServerStore.setWelcome(getContext(), welcome != null && welcome.matches("[A-Za-z0-9_-]{43}") ? welcome : null);
call.resolve();
restart();
}
/** The sign-in hosts the address screen passes along, plain host names only. */
private static Set<String> signInHostsOf(PluginCall call) {
Set<String> hosts = new HashSet<>();
JSArray list = call.getArray("signInHosts");
if (list == null) return hosts;
for (int i = 0; i < list.length(); i++) {
String host = list.optString(i, "");
if (host.matches("[A-Za-z0-9.-]+(:[0-9]+)?")) hosts.add(host);
}
return hosts;
}
@PluginMethod
public void resetServer(PluginCall call) {
TrekServerStore.setUrl(getContext(), null);
@@ -359,7 +436,11 @@ public class TrekShellPlugin extends Plugin {
}
Uri data = intent.getData();
PluginCall call = pendingAuthCall();
if (call == null || data == null || !authScheme.equals(data.getScheme())) return;
if (call == null) {
keepOrphanAuthReturn(intent);
return;
}
if (data == null || !authScheme.equals(data.getScheme())) return;
JSObject result = new JSObject();
result.put("url", data.toString());
call.resolve(result);
@@ -385,6 +466,48 @@ public class TrekShellPlugin extends Plugin {
}, CANCEL_GRACE_MS);
}
private static final String AUTH_PREFS = "trek_auth_return";
/** As long as the server keeps the code it carries (NATIVE_HANDOFF_CODE_TTL_MS), with room to spare. */
private static final long ORPHAN_AUTH_TTL_MS = 2 * 60 * 1000;
/**
* A return to the sign-in scheme with no call waiting for it: Android ended
* the app while the browser was in front, and the browser's return started
* it anew (the launch intent comes through here as well). Kept on disk, as
* the process may be new too, until the sign-in page takes it. The return
* is then taken off the activity's intent: Capacitor hands the launch intent
* in again whenever the activity is created, and Android does as well when
* it rebuilds the task from the recent apps.
*/
private void keepOrphanAuthReturn(Intent intent) {
Uri data = intent.getData();
if (data == null || !"auth".equals(data.getHost())) return;
if (!getContext().getString(R.string.custom_url_scheme).equals(data.getScheme())) return;
if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getData() != null
&& data.equals(getActivity().getIntent().getData())) {
getActivity().setIntent(new Intent(getActivity().getIntent()).setData(null));
}
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return;
getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE)
.edit()
.putString("url", data.toString())
.putLong("at", System.currentTimeMillis())
.commit();
}
/** The kept return of a sign-in (keepOrphanAuthReturn), once and while fresh; null otherwise. */
@PluginMethod
public void takeAuthCallback(PluginCall call) {
android.content.SharedPreferences prefs = getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE);
String url = prefs.getString("url", null);
long at = prefs.getLong("at", 0);
prefs.edit().clear().commit();
boolean fresh = url != null && System.currentTimeMillis() - at <= ORPHAN_AUTH_TTL_MS;
JSObject result = new JSObject();
result.put("url", fresh ? url : JSONObject.NULL);
call.resolve(result);
}
private PluginCall pendingAuthCall() {
return authCallId == null ? null : getBridge().getSavedCall(authCallId);
}
@@ -403,19 +526,98 @@ public class TrekShellPlugin extends Plugin {
authBrowserOpen = false;
}
/** iOS only: Android keeps the service worker, which already starts TREK offline. */
/**
* Keeps the server's UI on the device for a start without the server
* (TrekOfflineShell): the start page, and each file of the build that
* native/offlineShell.ts lists from the server's manifest and the copy does
* not hold yet. Once all of them are there, files of older builds go. A web
* view runs no service worker on a plain-http server, the usual address of a
* server at home, so without this the app could not start away from it.
*/
@PluginMethod
public void refreshOfflineCopy(PluginCall call) {
JSObject result = new JSObject();
result.put("saved", false);
call.resolve(result);
Context context = getContext();
String server = TrekServerStore.getUrl(context);
JSArray listed = call.getArray("files");
if (server == null || TrekOfflineShell.isActive()) {
JSObject result = new JSObject();
result.put("saved", false);
call.resolve(result);
return;
}
new Thread(() -> {
JSObject result = new JSObject();
byte[] page = download(server, "", "text/html");
boolean complete = page != null && TrekOfflineShell.beginRefresh(context, server);
Set<String> keep = new HashSet<>();
if (complete && listed != null) {
for (int i = 0; i < listed.length(); i++) {
String path = listed.optString(i, null);
if (path == null || path.isEmpty()) continue;
String clean = path.startsWith("/") ? path.substring(1) : path;
keep.add(clean);
if (TrekOfflineShell.hasFile(context, clean)) continue;
byte[] data = download(server, clean, null);
if (data == null || !TrekOfflineShell.saveFile(context, clean, data)) complete = false;
}
}
// The new page goes in last: until all its files are there the
// stored page stays the previous one, whose build is still whole.
boolean saved = complete && TrekOfflineShell.savePage(context, server, page);
complete = saved;
if (saved && listed != null) TrekOfflineShell.prune(context, keep);
result.put("saved", saved);
result.put("complete", complete);
call.resolve(result);
}).start();
}
/** A file of the server's UI, or null: only a 200 counts, and the page only as HTML. */
private static byte[] download(String server, String path, String wantType) {
java.net.HttpURLConnection connection = null;
try {
java.net.URL base = new java.net.URL(server.endsWith("/") ? server : server + "/");
java.net.URL url = new java.net.URL(base, path);
connection = (java.net.HttpURLConnection) url.openConnection();
connection.setConnectTimeout(15000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
if (wantType != null) connection.setRequestProperty("Accept", wantType);
if (connection.getResponseCode() != 200) return null;
String type = connection.getContentType();
if (wantType != null && (type == null || !type.startsWith(wantType))) return null;
try (java.io.InputStream in = connection.getInputStream()) {
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[16384];
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) out.write(buffer, 0, n);
return out.toByteArray();
}
} catch (java.io.IOException | RuntimeException e) {
return null;
} finally {
if (connection != null) connection.disconnect();
}
}
/**
* The address screen found the server out of reach: with a copy of its UI
* the app restarts on that instead (TrekOfflineShell), the same way it
* leaves the server for the address screen. Also for the server an update
* asked to check again, whose check then waits for the next launch.
*/
@PluginMethod
public void openOfflineCopy(PluginCall call) {
Context context = getContext();
JSObject result = new JSObject();
result.put("opened", false);
if (!TrekOfflineShell.hasCopy(context, TrekServerStore.getUrlOrPrevious(context)) || getActivity() == null) {
result.put("opened", false);
call.resolve(result);
return;
}
TrekServerStore.markOfflineStart(context);
result.put("opened", true);
call.resolve(result);
restart();
}
// ---- Widgets, shortcuts and the travel day ----
@@ -610,6 +812,12 @@ public class TrekShellPlugin extends Plugin {
com.liketrek.trek.billing.TrekBilling.INSTANCE.restore(getContext(), call);
}
/** Whether this Google account already holds a delivered cloud subscription. */
@PluginMethod
public void storeHeld(PluginCall call) {
com.liketrek.trek.billing.TrekBilling.INSTANCE.held(getContext(), call);
}
/** A paid subscription never delivered (it cleared while the app was closed), for the shell to redeem. */
@PluginMethod
public void storeUnfinished(PluginCall call) {
@@ -658,4 +866,129 @@ public class TrekShellPlugin extends Plugin {
// The last layout WindowManager reported, posture and hinge included; the bare window before the first.
getActivity().runOnUiThread(() -> call.resolve(com.liketrek.trek.screen.TrekWindowLayout.INSTANCE.current(getActivity())));
}
// ---- Client certificates (mutual TLS) ----
/**
* The address screen's check of a server, made natively so it notices
* whether the server asks for a client certificate and can show the stored
* one (clientcert/ClientCertActions.request).
*/
@PluginMethod
public void requestServer(PluginCall call) {
String url = call.getString("url");
Uri parsed = url == null ? null : Uri.parse(url);
if (parsed == null || parsed.getHost() == null || !("https".equals(parsed.getScheme()) || "http".equals(parsed.getScheme()))) {
call.reject("A http(s) URL is required");
return;
}
int timeout = Math.max(1000, Math.min(call.getInt("timeoutMs", 10000), 30000));
new Thread(() -> {
try {
call.resolve(ClientCertActions.request(getContext(), url, timeout));
} catch (Exception e) {
call.reject(e.getMessage() == null ? "request failed" : e.getMessage());
}
}, "trek-request-server").start();
}
/** The stored certificate's details, or none. */
@PluginMethod
public void clientCertificate(PluginCall call) {
TrekClientIdentity.Info info = TrekClientIdentity.info(getContext());
JSObject result = new JSObject();
result.put("certificate", info == null ? JSONObject.NULL : ClientCertActions.infoObject(info));
TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest();
if (asked != null) {
JSObject request = new JSObject();
request.put("host", asked.getHost());
request.put("port", asked.getPort());
request.put("served", asked.getServed());
result.put("request", request);
}
call.resolve(result);
}
@PluginMethod
public void removeClientCertificate(PluginCall call) {
TrekClientIdentity.remove(getContext());
forgetCertificateAnswers();
call.resolve();
}
/** The WebView keeps its answer to a certificate request per host; a changed certificate needs a fresh one. */
private void forgetCertificateAnswers() {
com.liketrek.trek.clientcert.ClientCertWatch.reset();
getActivity().runOnUiThread(() -> android.webkit.WebView.clearClientCertPreferences(null));
}
/**
* Picks a .p12/.pfx file, asks for its password until it opens or the user
* gives up, and keeps it for the server at host and port. Resolves with
* result "imported" (and the certificate), "cancelled", or "failed" and why.
*/
@PluginMethod
public void importClientCertificate(PluginCall call) {
String host = call.getString("host");
if (host == null || !host.matches("[A-Za-z0-9.-]+")) {
call.reject("A host is required");
return;
}
Intent pick = new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*");
pick.putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "application/x-pkcs12", "application/pkcs12", "application/octet-stream" });
startActivityForResult(call, pick, "clientCertificatePicked");
}
@ActivityCallback
private void clientCertificatePicked(PluginCall call, ActivityResult picked) {
if (call == null) return;
Uri uri = picked.getData() == null ? null : picked.getData().getData();
if (picked.getResultCode() != android.app.Activity.RESULT_OK || uri == null) {
resolveImport(call, "cancelled", null);
return;
}
new Thread(() -> {
byte[] bytes = ClientCertActions.readFile(getContext(), uri);
if (bytes == null) resolveImport(call, "failed", TrekClientIdentity.Failure.FORMAT.name());
else askPasswordFor(call, bytes, false);
}, "trek-client-cert").start();
}
private void askPasswordFor(PluginCall call, byte[] bytes, boolean wrong) {
JSObject labels = call.getObject("labels", new JSObject());
ClientCertActions.askPassword(getActivity(), labels, wrong, password -> {
if (password == null) {
resolveImport(call, "cancelled", null);
return kotlin.Unit.INSTANCE;
}
new Thread(() -> openWith(call, bytes, password), "trek-client-cert").start();
return kotlin.Unit.INSTANCE;
});
}
private void openWith(PluginCall call, byte[] bytes, char[] password) {
try {
TrekClientIdentity.Identity identity = TrekClientIdentity.read(bytes, password);
TrekClientIdentity.save(getContext(), identity, call.getString("host"), call.getInt("port", 443));
forgetCertificateAnswers();
resolveImport(call, "imported", null);
} catch (TrekClientIdentity.ImportException e) {
if (e.getReason() == TrekClientIdentity.Failure.PASSWORD) askPasswordFor(call, bytes, true);
else resolveImport(call, "failed", e.getReason().name());
} catch (Exception e) {
Log.w(TAG, "client certificate not kept", e);
resolveImport(call, "failed", "STORE");
} finally {
java.util.Arrays.fill(password, '\0');
}
}
private void resolveImport(PluginCall call, String result, String failure) {
JSObject out = new JSObject();
out.put("result", result);
if (failure != null) out.put("failure", failure.toLowerCase(java.util.Locale.ROOT));
TrekClientIdentity.Info info = TrekClientIdentity.info(getContext());
if ("imported".equals(result) && info != null) out.put("certificate", ClientCertActions.infoObject(info));
call.resolve(out);
}
}
@@ -1,11 +1,20 @@
package com.liketrek.trek;
import android.net.Uri;
import android.util.Log;
import android.webkit.ClientCertRequest;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.getcapacitor.Bridge;
import com.getcapacitor.BridgeWebViewClient;
import com.liketrek.trek.clientcert.TrekClientIdentity;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.function.Consumer;
/**
* Used while the WebView shows the user's server. When that server cannot be
@@ -18,15 +27,105 @@ import com.getcapacitor.BridgeWebViewClient;
class TrekWebViewClient extends BridgeWebViewClient {
private final Runnable onUnreachable;
/** Told whether the page now shown is a proxy's sign-in page, for the bar with the way out. */
private final Consumer<Boolean> onSignInPage;
/** Told whether the page now shown is an error page in place of the server's, for the same bar. */
private final Consumer<Boolean> onErrorPage;
/** The main-frame address that last came back as a 4xx page nobody else handled. */
private String errorPageUrl;
private final Set<String> signInHosts;
/** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */
private boolean serverShown;
/** The page itself failed on the network once already; the next failure goes to the address screen. */
private boolean retriedMainFrame;
/** The page loaded again after a network error, until that load starts: its error page counts for nothing. */
private String retryUrl;
private final Bridge bridge;
TrekWebViewClient(Bridge bridge, Runnable onUnreachable) {
TrekWebViewClient(
Bridge bridge,
Runnable onUnreachable,
Consumer<Boolean> onSignInPage,
Consumer<Boolean> onErrorPage,
Set<String> signInHosts
) {
super(bridge);
this.bridge = bridge;
this.onUnreachable = onUnreachable;
this.onSignInPage = onSignInPage;
this.onErrorPage = onErrorPage;
this.signInHosts = new HashSet<>(signInHosts);
}
/** Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt). */
/**
* The sign-in page of a proxy in front of the server loads here rather than
* in the browser, so its session cookie is the web view's and every request
* of the app carries it, as in a browser. Only the hosts the address screen
* saw that proxy send it to (TrekServerStore.getSignInHosts), and only as a
* page: Capacitor injects its bridge into the server's origin alone, so the
* proxy's page gets no access to the app. Everything else goes on to
* Capacitor, which opens a foreign page in the browser.
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.isForMainFrame() && isSignInHost(request.getUrl())) return false;
String learned = SignInRedirect.learnedHost(
TrekServerStore.getUrl(view.getContext()),
request.getUrl().toString(),
request.isForMainFrame(),
request.isRedirect(),
serverShown
);
if (learned != null) {
signInHosts.add(learned);
TrekServerStore.addSignInHost(view.getContext(), learned);
return false;
}
return super.shouldOverrideUrlLoading(view, request);
}
/** Every page the main frame shows, pushState included: is it a proxy's sign-in page? */
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
if (retryUrl != null) return;
onSignInPage.accept(url != null && isSignInHost(Uri.parse(url)));
// The 4xx answer arrives before this commit or after it; either way the
// flag is read once here, so the next page clears the bar again.
boolean error = url != null && url.equals(errorPageUrl);
errorPageUrl = null;
onErrorPage.accept(error);
}
/** After the server's first page, a pending welcome code opens the welcome page once (TrekServerStore.takeWelcomeUrl). */
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// The error page of a load that is about to be retried: not the server's
// first page, so no welcome page and no learning of sign-in hosts yet.
if (retryUrl != null) return;
if (SignInRedirect.onServer(TrekServerStore.getUrl(view.getContext()), url)) serverShown = true;
String welcome = TrekServerStore.takeWelcomeUrl(view.getContext());
if (welcome != null) view.loadUrl(welcome);
}
private boolean isSignInHost(Uri url) {
String scheme = url.getScheme();
String host = url.getHost();
if (host == null || !("https".equals(scheme) || "http".equals(scheme))) return false;
String key = host.toLowerCase(Locale.ROOT);
return signInHosts.contains(key) || (url.getPort() != -1 && signInHosts.contains(key + ":" + url.getPort()));
}
/**
* Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt),
* and while the server is out of reach the UI comes from its stored copy
* (TrekOfflineShell).
*/
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse copy = TrekOfflineShell.serve(view.getContext(), bridge, TrekServerStore.getUrl(view.getContext()), request);
if (copy != null) return copy;
if (com.liketrek.trek.tiles.TrekTileStore.INSTANCE.handles(request)) {
WebResourceResponse stored = com.liketrek.trek.tiles.TrekTileStore.INSTANCE.serve(request);
if (stored != null) return stored;
@@ -34,9 +133,62 @@ class TrekWebViewClient extends BridgeWebViewClient {
return super.shouldInterceptRequest(view, request);
}
/**
* A proxy in front of the server asks for a client certificate (mutual TLS).
* The stored one goes only to the host and port it was imported for; every
* other site that asks is told there is none, as a browser without a
* matching certificate would. The WebView remembers either answer for the
* host until the app restarts, which a new certificate always brings along.
*/
@Override
public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
TrekClientIdentity.Identity identity = TrekClientIdentity.identityFor(view.getContext(), request.getHost(), request.getPort());
TrekClientIdentity.noteRequest(request.getHost(), request.getPort(), identity != null);
if (identity != null) request.proceed(identity.getKey(), identity.getChain());
else request.ignore();
// The page may still come from the service worker's cache while every
// request fails: check natively whether the server lets the app in.
String server = TrekServerStore.getUrl(view.getContext());
Uri serverUri = server == null ? null : Uri.parse(server);
if (serverUri != null && TrekClientIdentity.matches(String.valueOf(serverUri.getHost()), serverUri.getPort() > 0 ? serverUri.getPort() : 443, request.getHost(), request.getPort())) {
com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, () -> {
TrekServerStore.setFailure(view.getContext(), "client certificate requested");
onUnreachable.run();
});
}
}
/**
* A page that failed on the network is loaded once more before the app says
* the server is unreachable. Started from the background, as when the
* browser hands a sign-in back to an app Android had ended, a Samsung phone
* may hold its network back for a moment, and the first load fails with the
* server there all along. The error is logged, as a report has nothing else.
*/
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.isForMainFrame()) {
Log.w("TrekShell", "Page failed: " + error.getErrorCode() + " " + error.getDescription());
if (!retriedMainFrame && isNetworkError(error.getErrorCode())) {
retriedMainFrame = true;
retryUrl = request.getUrl().toString();
view.postDelayed(() -> {
String url = retryUrl;
retryUrl = null;
view.loadUrl(url);
}, 1500);
return;
}
// Out of reach for good (a trip without reception, a server at home):
// the stored copy of the UI takes over, with the app's own offline data.
String server = TrekServerStore.getUrl(view.getContext());
if (isNetworkError(error.getErrorCode()) && !TrekOfflineShell.isActive() && TrekOfflineShell.hasCopy(view.getContext(), server)) {
TrekOfflineShell.activate(server);
String url = request.getUrl().toString();
view.post(() -> view.loadUrl(url));
return;
}
TrekServerStore.setFailure(view.getContext(), error.getDescription() + " (" + error.getErrorCode() + ")");
onUnreachable.run();
return;
}
@@ -45,15 +197,37 @@ class TrekWebViewClient extends BridgeWebViewClient {
/**
* Only a 5xx on the page itself means the server is down (a proxy's 502 or
* 503 while TREK restarts). A 4xx page is left alone: the server answered,
* and TREK serves its UI for every other path.
* 503 while TREK restarts). A 4xx page is not TREK's, which serves its UI for
* every path: a proxy that asked this page for a client certificate and got
* none, as Cloudflare does with a 403, sends the app to the address screen,
* which says so and offers to add one. Any other 4xx page (a proxy's block
* page, a certificate it refused) stays up with the bar and its way out, so
* the app is never stuck on a page without TREK's UI.
*/
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
int status = errorResponse.getStatusCode();
if (!request.isForMainFrame()) {
super.onReceivedHttpError(view, request, errorResponse);
} else if (errorResponse.getStatusCode() >= 500) {
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
onUnreachable.run();
} else if (status >= 400) {
errorPageUrl = request.getUrl().toString();
onErrorPage.accept(true);
}
}
private static boolean isNetworkError(int code) {
return code == WebViewClient.ERROR_HOST_LOOKUP
|| code == WebViewClient.ERROR_CONNECT
|| code == WebViewClient.ERROR_TIMEOUT
|| code == WebViewClient.ERROR_IO
|| code == WebViewClient.ERROR_UNKNOWN;
}
private static boolean wantedCertificate(Uri url) {
TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest();
return asked != null && !asked.getServed() && TrekClientIdentity.matches(asked.getHost(), asked.getPort(), url.getHost(), url.getPort());
}
}
@@ -119,23 +119,38 @@ object TrekBilling {
val id = call.getString("productId") ?: return call.reject("productId is required")
ready(activity) { ok ->
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
details(activity, listOf(id)) { found ->
val product = found.firstOrNull()
val offer = product?.let(::baseOffer)
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
pendingPurchase = call
pendingProduct = id
val params = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
)
.build()
activity.runOnUiThread {
val launch = client(activity).launchBillingFlow(activity, params)
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
}
// One subscription per Google account: a second plan would run beside the first.
// A delivered one stops the purchase here; one that was paid but never set up is
// handed back as bought, so its instance is set up now.
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
client(activity).queryPurchasesAsync(params) { result, purchases ->
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
when {
held == null -> launchPurchase(activity, call, id)
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
else -> call.resolve(receipt(held).put("kind", "bought"))
}
}
}
}
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
details(activity, listOf(id)) { found ->
val product = found.firstOrNull()
val offer = product?.let(::baseOffer)
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
pendingPurchase = call
pendingProduct = id
val params = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
)
.build()
activity.runOnUiThread {
val launch = client(activity).launchBillingFlow(activity, params)
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
}
}
}
@@ -208,6 +223,19 @@ object TrekBilling {
}
}
/** Whether this Google account holds a delivered subscription under `prefix`; while one runs, the shell offers no purchase. */
fun held(context: Context, call: PluginCall) {
val prefix = call.getString("prefix") ?: PREFIX
ready(context) { ok ->
if (!ok) return@ready call.resolve(JSObject().put("held", false))
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
client(context).queryPurchasesAsync(params) { result, purchases ->
val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, prefix) else null
call.resolve(JSObject().put("held", found?.isAcknowledged == true))
}
}
}
/** The newest active subscription under `prefix` on this Google account, if any. */
fun restore(context: Context, call: PluginCall) {
val prefix = call.getString("prefix") ?: "cloud."
@@ -0,0 +1,151 @@
package com.liketrek.trek.clientcert
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.net.Uri
import android.text.InputType
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import com.getcapacitor.JSObject
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
/**
* What TrekShellPlugin does for client certificates (TrekClientIdentity):
* check a server while noticing whether it asks for one, read a picked file,
* and ask for its password.
*/
object ClientCertActions {
private const val MAX_BODY_BYTES = 512 * 1024
private const val MAX_FILE_BYTES = 256 * 1024
private const val MAX_REDIRECTS = 5
/**
* A GET against the user's server for the address screen: status, body, final
* URL and headers, plus whether the server asked for a client certificate and
* whether one was shown. A failed connection answers status 0 instead of
* throwing, so a handshake the server broke off for want of a certificate
* still reports that it asked.
*/
@JvmStatic
fun request(context: Context, url: String, timeoutMs: Int): JSObject {
var asked: Triple<String, Int, Boolean>? = null
val factory = TrekClientIdentity.socketFactory(context) { host, port, served -> asked = Triple(host, port, served) }
val result = JSObject()
var current = URL(url)
try {
for (hop in 0..MAX_REDIRECTS) {
val connection = current.openConnection() as HttpURLConnection
if (connection is HttpsURLConnection) connection.sslSocketFactory = factory
connection.instanceFollowRedirects = false
connection.connectTimeout = timeoutMs
connection.readTimeout = timeoutMs
connection.setRequestProperty("Accept", "application/json, text/html;q=0.9, */*;q=0.8")
try {
val status = connection.responseCode
val location = connection.getHeaderField("Location")
if (status in 300..399 && location != null && hop < MAX_REDIRECTS) {
current = URL(current, location)
continue
}
val stream = if (status >= 400) connection.errorStream else connection.inputStream
result.put("status", status)
result.put("data", stream?.use { readCapped(it, MAX_BODY_BYTES) }?.toString(Charsets.UTF_8) ?: "")
result.put("url", current.toString())
val headers = JSObject()
for ((name, values) in connection.headerFields) if (name != null && values.isNotEmpty()) headers.put(name, values.first())
result.put("headers", headers)
} finally {
connection.disconnect()
}
break
}
} catch (e: IOException) {
result.put("status", 0)
result.put("data", "")
result.put("url", current.toString())
result.put("error", e.javaClass.simpleName)
}
val seen = asked
result.put("certRequested", seen != null)
result.put("certSent", seen?.third == true)
if (seen != null) result.put("certHost", "${seen.first}:${seen.second}")
return result
}
/** The bytes of a picked file, or null when it cannot be read or is far too big for a certificate. */
@JvmStatic
fun readFile(context: Context, uri: Uri): ByteArray? = try {
context.contentResolver.openInputStream(uri)?.use { readCapped(it, MAX_FILE_BYTES + 1) }?.takeIf { it.size <= MAX_FILE_BYTES }
} catch (e: Exception) {
null
}
/**
* The password prompt, with the UI's own words (`labels`: title, message,
* placeholder, ok, cancel, wrongPassword). `wrong` shows that the last try
* did not open the file. `done` gets the password, or null when cancelled.
*/
@JvmStatic
fun askPassword(activity: Activity, labels: JSObject, wrong: Boolean, done: (CharArray?) -> Unit) {
activity.runOnUiThread {
val input = EditText(activity).apply {
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
hint = labels.getString("placeholder") ?: ""
}
val frame = FrameLayout(activity).apply {
val pad = (20 * activity.resources.displayMetrics.density).toInt()
setPadding(pad, pad / 2, pad, 0)
addView(input, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
val message = if (wrong) labels.getString("wrongPassword") else labels.getString("message")
var answered = false
val dialog = AlertDialog.Builder(activity)
.setTitle(labels.getString("title"))
.setMessage(message)
.setView(frame)
.setPositiveButton(labels.getString("ok") ?: "OK") { _, _ ->
answered = true
val text = input.text
val password = CharArray(text.length) { text[it] }
done(password)
}
.setNegativeButton(labels.getString("cancel") ?: "Cancel") { _, _ ->
answered = true
done(null)
}
.setOnDismissListener { if (!answered) done(null) }
.create()
dialog.show()
input.requestFocus()
}
}
/** The settings' view of the stored certificate. */
@JvmStatic
fun infoObject(info: TrekClientIdentity.Info): JSObject = JSObject().apply {
put("host", info.host)
put("port", info.port)
put("subject", info.subject)
put("issuer", info.issuer)
put("notAfter", info.notAfter)
}
private fun readCapped(stream: InputStream, max: Int): ByteArray {
val out = ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (out.size() < max) {
val n = stream.read(buffer, 0, minOf(buffer.size, max - out.size()))
if (n < 0) break
out.write(buffer, 0, n)
}
return out.toByteArray()
}
}
@@ -0,0 +1,50 @@
package com.liketrek.trek.clientcert
import android.content.Context
import java.util.concurrent.atomic.AtomicLong
/**
* Notices when the user's server stops letting the app in for want of a
* client certificate: one removed, expired, or no longer trusted by the proxy.
*
* The page alone does not show it. The service worker serves TREK's start page
* from its cache, so the page loads and only its requests fail, and the UI
* reports a server it cannot reach with no way to add a certificate. So when
* the server asks for one, the app checks once natively whether TREK answers
* with what it holds. Only a check that fails at the certificate (the handshake
* broke off, or the proxy answered with its own 4xx) sends the app to the
* address screen, which says so and offers to add one. A server that merely
* asks and lets everyone in answers TREK's 200, and nothing happens.
*/
object ClientCertWatch {
private const val MIN_INTERVAL_MS = 60_000L
private const val FEATURES_PATH = "/api/health/features"
private const val TIMEOUT_MS = 8000
private val lastCheck = AtomicLong(0)
/** Called where the server asked for a certificate; `onRefused` runs at most once a minute, on a background thread. */
@JvmStatic
fun serverAsked(context: Context, serverUrl: String?, onRefused: Runnable) {
if (serverUrl == null) return
val now = System.currentTimeMillis()
val last = lastCheck.get()
if (now - last < MIN_INTERVAL_MS || !lastCheck.compareAndSet(last, now)) return
val appContext = context.applicationContext
Thread({
val result = ClientCertActions.request(appContext, serverUrl.trimEnd('/') + FEATURES_PATH, TIMEOUT_MS)
if (refused(result.optBoolean("certRequested"), result.optInt("status"))) onRefused.run()
}, "trek-client-cert-watch").start()
}
/** A new or removed certificate is worth a check of its own, whenever the last one ran. */
@JvmStatic
fun reset() {
lastCheck.set(0)
}
/** The server asked for a certificate and did not answer with TREK. */
@JvmStatic
fun refused(certRequested: Boolean, status: Int): Boolean = certRequested && (status == 0 || status in 400..499)
}
@@ -0,0 +1,261 @@
package com.liketrek.trek.clientcert
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.io.ByteArrayInputStream
import java.io.IOException
import java.net.Socket
import java.security.KeyFactory
import java.security.KeyStore
import java.security.Principal
import java.security.PrivateKey
import java.security.UnrecoverableKeyException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.security.spec.PKCS8EncodedKeySpec
import java.util.Date
import java.util.Locale
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLEngine
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509ExtendedKeyManager
/**
* The client certificate a user's TREK server asks for (mutual TLS): a proxy
* such as Cloudflare, nginx, Caddy or Traefik in front of TREK lets through only
* devices that show one. The app holds at most one, for one server.
*
* It comes in as a PKCS#12 file (.p12, .pfx) and its password. Neither is kept:
* the private key is sealed with an AES key of the Android keystore, which
* never leaves it, and stored with the certificate chain in the app's private
* preferences. In memory the key is an ordinary one, which TLS 1.2 and 1.3 and
* the WebView all take, whatever its kind; a key imported into the keystore
* itself would be refused by some of them for its padding or digest rules.
*
* Only the host and port it was imported for ever see it (`identityFor`), so a
* login page, a map tile provider or liketrek.com never learns of it.
*/
object TrekClientIdentity {
private const val PREFS = "trek_client_identity"
private const val WRAP_ALIAS = "trek-client-identity-wrap"
private const val KEYMANAGER_ALIAS = "trek-client-identity"
private const val GCM_TAG_BITS = 128
/** Why a file could not be taken. */
enum class Failure { PASSWORD, FORMAT, NO_KEY, EXPIRED, NOT_YET_VALID }
class ImportException(val reason: Failure) : Exception(reason.name)
class Identity(val key: PrivateKey, val chain: Array<X509Certificate>)
/** What the settings show: who the certificate names, who issued it, until when, and for which server. */
data class Info(val host: String, val port: Int, val subject: String, val issuer: String, val notAfter: Long)
/** The opened identity, with the sealed key text it was opened from: opened once, not per request. */
@Volatile private var cached: Pair<String, Identity>? = null
/** The last time a server asked for a certificate while the app showed it: for the address screen. */
@Volatile var lastRequest: Request? = null
private set
data class Request(val host: String, val port: Int, val served: Boolean)
private class Stored(val host: String, val port: Int, val algorithm: String, val sealedText: String, val iv: ByteArray, val chain: List<ByteArray>)
/**
* Reads a PKCS#12 file: the first entry that holds a private key, with its chain.
* Throws ImportException naming what is wrong with it.
*/
@JvmStatic
@JvmOverloads
@Throws(ImportException::class)
fun read(bytes: ByteArray, password: CharArray, now: Date = Date()): Identity {
val store = KeyStore.getInstance("PKCS12")
try {
store.load(ByteArrayInputStream(bytes), password)
} catch (e: IOException) {
throw ImportException(if (isPasswordFailure(e)) Failure.PASSWORD else Failure.FORMAT)
} catch (e: Exception) {
throw ImportException(Failure.FORMAT)
}
val alias = store.aliases().toList().firstOrNull { store.isKeyEntry(it) } ?: throw ImportException(Failure.NO_KEY)
val key = try {
store.getKey(alias, password) as? PrivateKey
} catch (e: UnrecoverableKeyException) {
throw ImportException(Failure.PASSWORD)
} ?: throw ImportException(Failure.NO_KEY)
val chain = store.getCertificateChain(alias)?.mapNotNull { it as? X509Certificate }?.toTypedArray()
if (chain.isNullOrEmpty()) throw ImportException(Failure.NO_KEY)
val leaf = chain[0]
if (now.after(leaf.notAfter)) throw ImportException(Failure.EXPIRED)
if (now.before(leaf.notBefore)) throw ImportException(Failure.NOT_YET_VALID)
return Identity(key, chain)
}
/** A wrong password shows up as a failed MAC check or an unrecoverable key, wrapped in an IOException. */
private fun isPasswordFailure(e: Throwable): Boolean {
var cause: Throwable? = e
while (cause != null) {
if (cause is UnrecoverableKeyException || cause is javax.crypto.BadPaddingException) return true
if (cause.message?.lowercase(Locale.ROOT)?.contains("password") == true) return true
cause = cause.cause
}
return false
}
/** Keeps the identity for this host and port, replacing any other. */
@JvmStatic
fun save(context: Context, identity: Identity, host: String, port: Int) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, wrapKey())
val sealed = cipher.doFinal(identity.key.encoded)
prefs(context).edit()
.putString("host", host.lowercase(Locale.ROOT))
.putInt("port", port)
.putString("algorithm", identity.key.algorithm)
.putString("key", encode(sealed))
.putString("iv", encode(cipher.iv))
.putString("chain", identity.chain.joinToString(",") { encode(it.encoded) })
.apply()
cached = null
}
@JvmStatic
fun remove(context: Context) {
prefs(context).edit().clear().apply()
cached = null
}
@JvmStatic
fun info(context: Context): Info? {
val stored = stored(context) ?: return null
val leaf = runCatching { certificate(stored.chain.first()) }.getOrNull() ?: return null
return Info(stored.host, stored.port, commonName(leaf.subjectX500Principal), commonName(leaf.issuerX500Principal), leaf.notAfter.time)
}
/** The identity for a server at this host and port, or null when there is none for it. */
@JvmStatic
fun identityFor(context: Context, host: String?, port: Int): Identity? {
val stored = stored(context) ?: return null
if (!matches(stored.host, stored.port, host, port)) return null
return opened(stored)
}
private fun opened(stored: Stored): Identity? {
cached?.let { (from, identity) -> if (from == stored.sealedText) return identity }
val identity = runCatching { open(stored) }.getOrNull() ?: return null
cached = stored.sealedText to identity
return identity
}
/** Whether a request to host and port (-1 or 0 for the scheme's default) goes to the server the identity is for. */
@JvmStatic
fun matches(storedHost: String, storedPort: Int, host: String?, port: Int): Boolean {
if (host == null || !host.equals(storedHost, ignoreCase = true)) return false
val effective = if (port <= 0) 443 else port
return effective == storedPort
}
/** Called where a server asked for a certificate, so the address screen can offer one. */
@JvmStatic
fun noteRequest(host: String?, port: Int, served: Boolean) {
if (host == null) return
lastRequest = Request(host.lowercase(Locale.ROOT), if (port <= 0) 443 else port, served)
}
/**
* A socket factory for the app's own requests (the server check, map tiles).
* It offers the identity only when the server it is talking to asks for one
* and is the one the identity is for, and tells `onAsked` about every ask.
*/
@JvmStatic
fun socketFactory(context: Context, onAsked: ((host: String, port: Int, served: Boolean) -> Unit)? = null): SSLSocketFactory {
val appContext = context.applicationContext
val manager = object : X509ExtendedKeyManager() {
// Decided per handshake in choose(); the key and chain are then read for
// the one alias, so parallel connections never see each other's choice.
private fun choose(host: String?, port: Int): String? {
val identity = identityFor(appContext, host, port)
if (host != null) {
noteRequest(host, port, identity != null)
onAsked?.invoke(host.lowercase(Locale.ROOT), if (port <= 0) 443 else port, identity != null)
}
return if (identity != null) KEYMANAGER_ALIAS else null
}
override fun chooseClientAlias(keyType: Array<out String>?, issuers: Array<out Principal>?, socket: Socket?): String? {
val session = (socket as? SSLSocket)?.handshakeSession
return choose(session?.peerHost, session?.peerPort ?: -1)
}
override fun chooseEngineClientAlias(keyType: Array<out String>?, issuers: Array<out Principal>?, engine: SSLEngine?): String? =
choose(engine?.peerHost, engine?.peerPort ?: -1)
override fun getCertificateChain(alias: String?): Array<X509Certificate>? =
if (alias == KEYMANAGER_ALIAS) stored(appContext)?.let { opened(it) }?.chain else null
override fun getPrivateKey(alias: String?): PrivateKey? =
if (alias == KEYMANAGER_ALIAS) stored(appContext)?.let { opened(it) }?.key else null
override fun getClientAliases(keyType: String?, issuers: Array<out Principal>?): Array<String>? = null
override fun getServerAliases(keyType: String?, issuers: Array<out Principal>?): Array<String>? = null
override fun chooseServerAlias(keyType: String?, issuers: Array<out Principal>?, socket: Socket?): String? = null
}
val tls = SSLContext.getInstance("TLS")
tls.init(arrayOf(manager), null, null)
return tls.socketFactory
}
private fun open(stored: Stored): Identity {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, wrapKey(), GCMParameterSpec(GCM_TAG_BITS, stored.iv))
val key = KeyFactory.getInstance(stored.algorithm).generatePrivate(PKCS8EncodedKeySpec(cipher.doFinal(decode(stored.sealedText))))
return Identity(key, stored.chain.map { certificate(it) }.toTypedArray())
}
private fun stored(context: Context): Stored? {
val p = prefs(context)
val host = p.getString("host", null) ?: return null
val algorithm = p.getString("algorithm", null) ?: return null
val key = p.getString("key", null) ?: return null
val iv = p.getString("iv", null) ?: return null
val chain = p.getString("chain", null)?.split(",")?.filter { it.isNotEmpty() }?.map { decode(it) } ?: return null
if (chain.isEmpty()) return null
return Stored(host, p.getInt("port", 443), algorithm, key, decode(iv), chain)
}
/** The keystore's AES key that seals the private key; made once, never leaves the keystore. */
private fun wrapKey(): SecretKey {
val keystore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keystore.getKey(WRAP_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
)
return generator.generateKey()
}
private fun certificate(der: ByteArray): X509Certificate =
CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(der)) as X509Certificate
/** The CN of a name, or the whole name when it has none. */
@JvmStatic
fun commonName(principal: javax.security.auth.x500.X500Principal): String {
val name = principal.getName(javax.security.auth.x500.X500Principal.RFC2253)
return Regex("(?:^|,)CN=((?:\\\\.|[^,])*)").find(name)?.groupValues?.get(1)?.replace("\\", "") ?: name
}
private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun encode(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP)
private fun decode(text: String) = Base64.decode(text, Base64.NO_WRAP)
}
@@ -32,6 +32,10 @@ class BookingsWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = BookingsWidget()
}
class FlightWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = FlightWidget()
}
class TodosWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = TodosWidget()
}
@@ -56,6 +60,7 @@ object TrekWidgetUpdater {
TripWidgetReceiver::class,
TodayWidgetReceiver::class,
BookingsWidgetReceiver::class,
FlightWidgetReceiver::class,
TodosWidgetReceiver::class,
PackingWidgetReceiver::class,
AtlasWidgetReceiver::class,
@@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() {
// Read inside the composition: a session outlives one update, and every
// write (the dashboard's, then each trip's) must reach it.
val version by WidgetStore.version.collectAsState()
val snapshot = remember(version) {
val stored = remember(version) {
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
WidgetStore.load(context, tripId)
}
// The day of the trip is today's on every update, not the one the app last wrote.
val snapshot = stored?.on(LocalDate.now())
TrekWidgetTheme.Themed { Content(snapshot) }
}
}
@@ -448,6 +450,173 @@ private fun BookingRow(booking: WidgetSnapshot.Booking, labels: WidgetSnapshot.L
}
}
// ---- Flight ----
/**
* Where a flight stands now (as FlightMoment on iOS). What the feed saw wins: a
* flight still at the gate past its planned departure is not flown along the
* arc, and it is only landed once confirmed. Only a flight the feed never heard
* of moves on by its schedule alone; a lost one stops two hours after arrival.
*/
private class FlightMoment(f: WidgetSnapshot.Flight, nowSeconds: Long) {
val start: Long = f.depActual ?: f.depExpected ?: f.dep
val end: Long = maxOf(f.arrExpected ?: f.arr, start + 60)
private val heard = f.seen != null
val landed = f.landed || (!heard && nowSeconds >= end) || nowSeconds >= end + 7200
val airborne = !landed && (f.airborne || f.depActual != null || (!heard && nowSeconds >= start))
val ready = !landed && !airborne && nowSeconds >= start
val progress: Float = when {
landed -> 1f
airborne -> ((nowSeconds - start).toFloat() / (end - start)).coerceIn(0f, 0.98f)
else -> 0f
}
}
/** A duration in the app's words: "2 d 4 h", "1 h 5 min", "12 min". */
private fun durationText(seconds: Long, labels: WidgetSnapshot.Labels): String {
val minutes = ((seconds + 59) / 60).coerceAtLeast(1)
val days = minutes / 1440
val hours = (minutes % 1440) / 60
val rest = minutes % 60
return when {
days > 0 -> labels.durDaysHours.replace("{d}", "$days").replace("{h}", "$hours")
hours > 0 -> labels.durHoursMinutes.replace("{h}", "$hours").replace("{m}", "$rest")
else -> labels.durMinutes.replace("{m}", "$rest")
}
}
/** "Departs in 2 h 10 min", "Lands in 1 h 5 min", "Landed". */
private fun momentText(m: FlightMoment, labels: WidgetSnapshot.Labels, nowSeconds: Long): String = when {
m.landed -> labels.flightLanded
m.ready -> labels.flightReady
m.airborne -> labels.flightLands.replace("{time}", durationText(m.end - nowSeconds, labels))
else -> labels.flightDeparts.replace("{time}", durationText(m.start - nowSeconds, labels))
}
/** The delay as a chip's text and colour; nothing to say without data. */
private fun delayChip(delay: Int?, labels: WidgetSnapshot.Labels): Pair<String, ColorProvider>? = when {
delay == null -> null
delay > 5 -> labels.flightLate.replace("{m}", "$delay") to (if (delay >= 30) TrekStatus.danger else TrekStatus.pending)
delay < -5 -> labels.flightEarly.replace("{m}", "${-delay}") to TrekStatus.confirmed
else -> labels.flightOnTime to TrekStatus.confirmed
}
private const val FLIGHT_BLUE = 0xFF4A7DDB.toInt()
/**
* The trip's next flight, or the one in the air: both airports large, the
* route as an arc with the aircraft on it, the moment in words and the delay.
* The arc and the words follow the clock each time the widget is drawn.
*/
class FlightWidget : TrekWidget() {
@Composable
override fun Content(snapshot: WidgetSnapshot?) {
val context = LocalContext.current
val size = LocalSize.current
val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context))
val flight = snapshot.flight
WidgetFrame(onClick = openPath(context, flight?.path ?: snapshot.trip?.path ?: "/")) {
Column(modifier = GlanceModifier.fillMaxSize()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp)
Spacer(GlanceModifier.width(5.dp))
Eyebrow(flight?.number ?: labels.flight, GlanceTheme.colors.primary, GlanceModifier.defaultWeight())
flight?.let { f ->
delayChip(f.delay, labels)?.let { (text, color) ->
if (size.isWide || (f.delay ?: 0) > 5) Chip(text, GlanceTheme.colors.surfaceVariant, color)
}
}
}
if (flight == null) {
Spacer(GlanceModifier.defaultWeight())
Line(labels.noFlight, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2)
Spacer(GlanceModifier.defaultWeight())
} else {
FlightBody(flight, labels, size.isWide, size.isTall)
}
}
}
}
}
/**
* The origin stands on the right in a right-to-left layout, so the drawn arc is
* mirrored with it. Read from the locale the widget speaks, not from the
* Configuration, which a composition may not read directly.
*/
private fun isRtl(): Boolean =
android.text.TextUtils.getLayoutDirectionFromLocale(java.util.Locale.getDefault()) == android.view.View.LAYOUT_DIRECTION_RTL
@Composable
private fun ColumnScope.FlightBody(f: WidgetSnapshot.Flight, labels: WidgetSnapshot.Labels, wide: Boolean, tall: Boolean) {
val now = System.currentTimeMillis() / 1000
val m = FlightMoment(f, now)
val arrival = f.arrTimeExpected ?: f.arrTime
val momentColor = if (m.airborne) GlanceTheme.colors.primary else GlanceTheme.colors.onSurface
Spacer(GlanceModifier.defaultWeight())
if (!wide) Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold, maxLines = 2)
Spacer(GlanceModifier.height(6.dp))
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
Column(modifier = GlanceModifier.defaultWeight()) {
Line(f.from, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
if (wide) f.fromCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
}
if (wide) {
Image(
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = GlanceModifier.width(120.dp).height(26.dp),
)
}
Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.End) {
Line(f.to, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
if (wide) f.toCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
}
}
if (!wide) {
Image(
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = GlanceModifier.fillMaxWidth().height(22.dp),
)
}
Spacer(GlanceModifier.height(4.dp))
Row(modifier = GlanceModifier.fillMaxWidth()) {
Line(f.depTime, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold, modifier = GlanceModifier.defaultWeight())
Line(arrival, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold)
}
if (wide) {
Spacer(GlanceModifier.height(8.dp))
Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold)
if (m.airborne) {
Spacer(GlanceModifier.height(5.dp))
Bar(m.progress, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant, 5.dp)
}
}
if (tall) {
Spacer(GlanceModifier.height(10.dp))
f.aircraft?.let { FlightFact(it) }
f.fromCity?.let { from -> f.toCity?.let { to -> FlightFact("$from \u2192 $to") } }
}
Spacer(GlanceModifier.defaultWeight())
}
@Composable
private fun FlightFact(text: String) {
Row(
modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.surfaceVariant).cornerRadius(12.dp)
.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 13.dp)
Spacer(GlanceModifier.width(7.dp))
Line(text, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium)
}
Spacer(GlanceModifier.height(5.dp))
}
// ---- To-dos ----
/** What is still open for the trip, and how far the packing has come. */
@@ -149,4 +149,100 @@ object WidgetArt {
}
return bitmap
}
/**
* A flight's route as an arc: dashed ahead, solid where it has flown, a dot
* at either airport and an airliner riding the curve at its heading. White
* on a translucent track, like the ring; the widget tints nothing, so the
* caller passes the flight colour.
*/
fun flightArc(
progress: Float,
color: Int,
track: Int,
width: Int = 600,
height: Int = 120,
showPlane: Boolean = true,
rtl: Boolean = false,
): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Right to left the origin stands on the right: the whole drawing is mirrored.
if (rtl) canvas.scale(-1f, 1f, width / 2f, height / 2f)
val p = progress.coerceIn(0f, 1f)
val inset = height * 0.14f
val sx = inset
val sy = height - inset
val ex = width - inset
val ey = height - inset
val cx = width / 2f
val cy = -height * 0.45f
val path = android.graphics.Path().apply {
moveTo(sx, sy)
quadTo(cx, cy, ex, ey)
}
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
strokeWidth = height * 0.035f
this.color = track
pathEffect = android.graphics.DashPathEffect(floatArrayOf(height * 0.02f, height * 0.07f), 0f)
}
canvas.drawPath(path, line)
val measure = android.graphics.PathMeasure(path, false)
if (p > 0f) {
val flown = android.graphics.Path()
measure.getSegment(0f, measure.length * p, flown, true)
line.pathEffect = null
line.strokeWidth = height * 0.045f
line.color = color
canvas.drawPath(flown, line)
}
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
canvas.drawCircle(sx, sy, height * 0.05f, dot)
val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = if (p >= 1f) Paint.Style.FILL else Paint.Style.STROKE
strokeWidth = height * 0.03f
this.color = color
}
canvas.drawCircle(ex, ey, height * 0.06f, ring)
if (showPlane) {
val pos = FloatArray(2)
val tan = FloatArray(2)
measure.getPosTan(measure.length * p, pos, tan)
canvas.save()
canvas.translate(pos[0], pos[1])
canvas.rotate(Math.toDegrees(kotlin.math.atan2(tan[1].toDouble(), tan[0].toDouble())).toFloat())
val scale = height * 0.012f
canvas.scale(scale, scale)
canvas.drawCircle(0f, 0f, 13f, Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE })
canvas.drawPath(airliner(), Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color })
canvas.restore()
}
return bitmap
}
/** An airliner seen from above, nose along +x, about 18 units long, centred. */
private fun airliner(): android.graphics.Path = android.graphics.Path().apply {
moveTo(9f, 0f)
cubicTo(9f, -0.9f, 8.3f, -1.3f, 7.4f, -1.3f)
lineTo(3.2f, -1.3f)
lineTo(-1.6f, -7.6f)
lineTo(-3.7f, -7.6f)
lineTo(-1.4f, -1.3f)
lineTo(-5.5f, -1.3f)
lineTo(-7.2f, -3.7f)
lineTo(-8.8f, -3.7f)
lineTo(-7.8f, 0f)
lineTo(-8.8f, 3.7f)
lineTo(-7.2f, 3.7f)
lineTo(-5.5f, 1.3f)
lineTo(-1.4f, 1.3f)
lineTo(-3.7f, 7.6f)
lineTo(-1.6f, 7.6f)
lineTo(3.2f, 1.3f)
lineTo(7.4f, 1.3f)
cubicTo(8.3f, 1.3f, 9f, 0.9f, 9f, 0f)
close()
}
}
@@ -11,6 +11,19 @@ import org.json.JSONObject
* (WidgetSnapshot.sample in TrekFamily.swift).
*/
object WidgetSamples {
/** In the air on a running trip, two days ahead before one: the same LH 716 as the iOS sample. */
private fun flightJson(running: Boolean): String {
val now = System.currentTimeMillis() / 1000
val dep = if (running) now - 4 * 3600 else now + 2 * 86_400 + 5 * 3600
val live = if (running) {
""""depActual": ${dep + 18 * 60}, "arrExpected": ${dep + 12 * 3600 + 41 * 60}, "arrTimeExpected": "08:46", "delay": 16, "aircraft": "A359 D-AIXA","""
} else {
""
}
return """{"number": "LH 716", "from": "FRA", "to": "HND", "fromCity": "Frankfurt", "toCity": "Tokyo Haneda",
"dep": $dep, "arr": ${dep + 12 * 3600 + 25 * 60}, $live "depTime": "13:05", "arrTime": "08:30", "path": "/trips/1?booking=1"}"""
}
fun emptyText(context: Context): String = context.getString(R.string.widget_empty)
fun snapshot(running: Boolean, now: LocalDate = LocalDate.now()): WidgetSnapshot = WidgetSnapshot.fromJson(JSONObject(json(running, now)))
@@ -37,6 +50,7 @@ object WidgetSamples {
"place": "Kyoto, Japan", "dayCount": 9, "placeCount": 34, "memberCount": 3},
$today
"weather": {"temp": 18, "high": 21, "low": 11, "main": "${if (running) "Clear" else "Clouds"}", "label": "Mostly sunny", "place": "Kyoto", "rain": 10},
"flight": ${flightJson(running)},
"bookings": [
{"title": "LH 716", "kind": "flight", "date": "${iso(if (running) 6 else 12)}", "time": "13:05", "detail": "FRA → HND", "confirmed": true, "path": "/trips/1"},
{"title": "Shinkansen Nozomi 21", "kind": "train", "date": "${iso(if (running) 0 else 13)}", "time": "09:12", "detail": "Tokyo → Kyoto", "confirmed": true, "path": "/trips/1"},
@@ -25,7 +25,30 @@ data class WidgetSnapshot(
val atlas: Atlas?,
val collab: Collab?,
val labels: Labels,
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
val flight: Flight? = null,
/**
* The trip's days from the day the app wrote this on, each with its date, so
* the widget turns to the next day itself (see [on]); empty from an app
* that predates them.
*/
val days: List<Today> = emptyList(),
) {
/**
* The snapshot as it reads on [date]: that date's trip day out of [days],
* none before or after the trip, and only the bookings from that date on.
* The app writes its snapshot only while it runs, so without this a widget
* showed the day it last ran. A snapshot without [days] reads as written.
*/
fun on(date: LocalDate): WidgetSnapshot {
if (days.isEmpty()) return this
val key = date.toString()
return copy(
today = days.firstOrNull { it.date == key },
bookings = bookings.filter { (it.date ?: key) >= key },
)
}
data class Trip(
val title: String,
val start: String,
@@ -50,7 +73,8 @@ data class WidgetSnapshot(
val symbol: String?,
)
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
data class Weather(
val temp: Int,
@@ -105,6 +129,39 @@ data class WidgetSnapshot(
data class Collab(val members: List<Member>, val messages: List<Message>, val poll: Poll?, val path: String)
/**
* The flight widget's flight. Times are epoch seconds, so the widget moves on
* with the clock between two snapshots; the clock times at either airport
* come formatted, since the widget has no zone data.
*/
data class Flight(
val number: String,
val from: String,
val to: String,
val fromCity: String?,
val toCity: String?,
val dep: Long,
val arr: Long,
/** Observed take-off. */
val depActual: Long?,
/** Before take-off: the planned departure plus the delay seen so far. */
val depExpected: Long?,
/** The feed saw the aircraft in the air when the app last looked. */
val airborne: Boolean,
/** Touchdown once landed, else the estimate while in the air. */
val arrExpected: Long?,
val landed: Boolean,
val depTime: String,
val arrTime: String,
val arrTimeExpected: String?,
/** Minutes late against the schedule, negative when early. */
val delay: Int?,
val aircraft: String?,
/** When the feed last heard the aircraft; null for a flight it never heard of. */
val seen: Long?,
val path: String,
)
/** The labels, translated by the app. The optional ones fall back to English. */
data class Labels(private val raw: JSONObject) {
val nextTrip get() = text("nextTrip", "Next trip")
@@ -137,6 +194,23 @@ data class WidgetSnapshot(
val votes get() = text("votes", "votes")
val noMessages get() = text("noMessages", "No messages yet")
val departure get() = text("departure", "Departure")
val flight get() = text("flight", "Flight")
/** Contains "{time}". */
val flightDeparts get() = text("flightDeparts", "Departs in {time}")
/** Contains "{time}". */
val flightLands get() = text("flightLands", "Lands in {time}")
val flightLanded get() = text("flightLanded", "Landed")
val flightReady get() = text("flightReady", "Ready for departure")
val noFlight get() = text("noFlight", "No flight ahead")
val flightOnTime get() = text("flightOnTime", "On time")
/** Contains "{m}". */
val flightLate get() = text("flightLate", "+{m} min")
/** Contains "{m}". */
val flightEarly get() = text("flightEarly", "{m} min early")
/** Contain "{d}" and "{h}", "{h}" and "{m}", and "{m}". */
val durDaysHours get() = text("durDaysHours", "{d} d {h} h")
val durHoursMinutes get() = text("durHoursMinutes", "{h} h {m} min")
val durMinutes get() = text("durMinutes", "{m} min")
private fun text(key: String, fallback: String): String = raw.optString(key).ifBlank { fallback }
}
@@ -160,6 +234,16 @@ data class WidgetSnapshot(
null
}
private fun dayOf(t: JSONObject): Today = Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
date = t.str("date"),
)
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
trip = o.optJSONObject("trip")?.let {
Trip(
@@ -174,16 +258,8 @@ data class WidgetSnapshot(
memberCount = it.int("memberCount"),
)
},
today = o.optJSONObject("today")?.let { t ->
Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
)
},
today = o.optJSONObject("today")?.let(::dayOf),
days = o.optJSONArray("days").objects().map(::dayOf),
weather = o.optJSONObject("weather")?.let {
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
},
@@ -240,6 +316,29 @@ data class WidgetSnapshot(
)
},
labels = Labels(o.optJSONObject("labels") ?: JSONObject()),
flight = o.optJSONObject("flight")?.let { f ->
Flight(
number = f.optString("number"),
from = f.optString("from"),
to = f.optString("to"),
fromCity = f.str("fromCity"),
toCity = f.str("toCity"),
dep = f.optLong("dep"),
arr = f.optLong("arr"),
depActual = f.long("depActual"),
depExpected = f.long("depExpected"),
airborne = f.optBoolean("airborne"),
arrExpected = f.long("arrExpected"),
landed = f.optBoolean("landed"),
depTime = f.optString("depTime"),
arrTime = f.optString("arrTime"),
arrTimeExpected = f.str("arrTimeExpected"),
delay = f.int("delay"),
aircraft = f.str("aircraft"),
seen = f.long("seen"),
path = f.optString("path", "/"),
)
}?.takeIf { it.dep > 0 && it.arr > 0 },
)
fun day(iso: String?): LocalDate? {
@@ -258,6 +357,8 @@ data class WidgetSnapshot(
private fun JSONObject.int(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null
private fun JSONObject.long(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
private fun JSONArray?.objects(): List<JSONObject> =
if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
@@ -8,6 +8,8 @@
<string name="widget_today_description">خطة اليوم كخط زمني، مع الطقس والمحطة التالية.</string>
<string name="widget_bookings_name">الحجوزات</string>
<string name="widget_bookings_description">رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.</string>
<string name="widget_flight_name">الرحلة</string>
<string name="widget_flight_description">رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.</string>
<string name="widget_todos_name">المهام</string>
<string name="widget_todos_description">ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.</string>
<string name="widget_packing_name">قائمة الأمتعة</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.</string>
<string name="widget_bookings_name">Bronlar</string>
<string name="widget_bookings_description">Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.</string>
<string name="widget_flight_name">Uçuş</string>
<string name="widget_flight_description">Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.</string>
<string name="widget_todos_name">Tapşırıqlar</string>
<string name="widget_todos_description">Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.</string>
<string name="widget_packing_name">Yük siyahısı</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">以时间线显示今天的计划,附带天气和下一站。</string>
<string name="widget_bookings_name">预订</string>
<string name="widget_bookings_description">你接下来的航班、火车、酒店和餐厅,以及时间。</string>
<string name="widget_flight_name">航班</string>
<string name="widget_flight_description">实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。</string>
<string name="widget_todos_name">待办</string>
<string name="widget_todos_description">旅行还剩哪些事没做,以及行李收拾到哪一步。</string>
<string name="widget_packing_name">行李</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">以時間軸顯示今天的計畫,附上天氣與下一站。</string>
<string name="widget_bookings_name">預訂</string>
<string name="widget_bookings_description">你接下來的航班、火車、飯店與餐廳,以及時間。</string>
<string name="widget_flight_name">航班</string>
<string name="widget_flight_description">即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。</string>
<string name="widget_todos_name">待辦</string>
<string name="widget_todos_description">旅行還剩哪些事沒做,以及行李整理到哪一步。</string>
<string name="widget_packing_name">行李</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">El pla del dia com a línia de temps, amb el temps i la propera parada.</string>
<string name="widget_bookings_name">Reserves</string>
<string name="widget_bookings_description">Els teus propers vols, trens, hotels i taules, i quan toquen.</string>
<string name="widget_flight_name">Vol</string>
<string name="widget_flight_description">El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.</string>
<string name="widget_todos_name">Tasques</string>
<string name="widget_todos_description">El que encara queda per al viatge i com va l\'equipatge.</string>
<string name="widget_packing_name">Equipatge</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plán dne jako časová osa, s počasím a další zastávkou.</string>
<string name="widget_bookings_name">Rezervace</string>
<string name="widget_bookings_description">Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají.</string>
<string name="widget_flight_name">Let</string>
<string name="widget_flight_description">Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet.</string>
<string name="widget_todos_name">Úkoly</string>
<string name="widget_todos_description">Co ještě zbývá k cestě a jak daleko je balení.</string>
<string name="widget_packing_name">Balení</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp.</string>
<string name="widget_bookings_name">Buchungen</string>
<string name="widget_bookings_description">Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen.</string>
<string name="widget_flight_name">Flug</string>
<string name="widget_flight_description">Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft.</string>
<string name="widget_todos_name">To-dos</string>
<string name="widget_todos_description">Was für die Reise noch offen ist und wie weit das Packen ist.</string>
<string name="widget_packing_name">Packliste</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση.</string>
<string name="widget_bookings_name">Κρατήσεις</string>
<string name="widget_bookings_description">Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι.</string>
<string name="widget_flight_name">Πτήση</string>
<string name="widget_flight_description">Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη.</string>
<string name="widget_todos_name">Εκκρεμότητες</string>
<string name="widget_todos_description">Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα.</string>
<string name="widget_packing_name">Αποσκευές</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">El plan del día como línea de tiempo, con el tiempo y la próxima parada.</string>
<string name="widget_bookings_name">Reservas</string>
<string name="widget_bookings_description">Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan.</string>
<string name="widget_flight_name">Vuelo</string>
<string name="widget_flight_description">Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada.</string>
<string name="widget_todos_name">Tareas</string>
<string name="widget_todos_description">Lo que aún queda para el viaje y cómo va la maleta.</string>
<string name="widget_packing_name">Equipaje</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Päeva plaan ajajoonena, koos ilma ja järgmise peatusega.</string>
<string name="widget_bookings_name">Broneeringud</string>
<string name="widget_bookings_description">Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on.</string>
<string name="widget_flight_name">Lend</string>
<string name="widget_flight_description">Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine.</string>
<string name="widget_todos_name">Ülesanded</string>
<string name="widget_todos_description">Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on.</string>
<string name="widget_packing_name">Pakkimine</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Le programme du jour en frise, avec la météo et la prochaine étape.</string>
<string name="widget_bookings_name">Réservations</string>
<string name="widget_bookings_description">Vos prochains vols, trains, hôtels et tables, et quand ils arrivent.</string>
<string name="widget_flight_name">Vol</string>
<string name="widget_flight_description">Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée.</string>
<string name="widget_todos_name">À faire</string>
<string name="widget_todos_description">Ce qui reste à faire pour le voyage et où en sont les bagages.</string>
<string name="widget_packing_name">Bagages</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">A nap terve idővonalon, az időjárással és a következő megállóval.</string>
<string name="widget_bookings_name">Foglalások</string>
<string name="widget_bookings_description">A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek.</string>
<string name="widget_flight_name">Járat</string>
<string name="widget_flight_description">A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés.</string>
<string name="widget_todos_name">Teendők</string>
<string name="widget_todos_description">Ami még hátravan az utazáshoz, és hol tart a csomagolás.</string>
<string name="widget_packing_name">Csomagolás</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya.</string>
<string name="widget_bookings_name">Pemesanan</string>
<string name="widget_bookings_description">Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya.</string>
<string name="widget_flight_name">Penerbangan</string>
<string name="widget_flight_description">Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan.</string>
<string name="widget_todos_name">Tugas</string>
<string name="widget_todos_description">Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang.</string>
<string name="widget_packing_name">Barang bawaan</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Il programma del giorno come linea del tempo, con il meteo e la prossima tappa.</string>
<string name="widget_bookings_name">Prenotazioni</string>
<string name="widget_bookings_description">I tuoi prossimi voli, treni, hotel e tavoli, e quando sono.</string>
<string name="widget_flight_name">Volo</string>
<string name="widget_flight_description">Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo.</string>
<string name="widget_todos_name">Da fare</string>
<string name="widget_todos_description">Cosa manca ancora per il viaggio e a che punto è la valigia.</string>
<string name="widget_packing_name">Bagagli</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה.</string>
<string name="widget_bookings_name">הזמנות</string>
<string name="widget_bookings_description">הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם.</string>
<string name="widget_flight_name">טיסה</string>
<string name="widget_flight_description">הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה.</string>
<string name="widget_todos_name">משימות</string>
<string name="widget_todos_description">מה עוד פתוח לטיול וכמה התקדמה האריזה.</string>
<string name="widget_packing_name">אריזה</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">今日の予定をタイムラインで、天気と次の予定とともに表示します。</string>
<string name="widget_bookings_name">予約</string>
<string name="widget_bookings_description">次のフライト、列車、ホテル、レストランとその日時。</string>
<string name="widget_flight_name">フライト</string>
<string name="widget_flight_description">次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。</string>
<string name="widget_todos_name">やること</string>
<string name="widget_todos_description">旅行のために残っていることと、荷造りの進み具合。</string>
<string name="widget_packing_name">持ち物</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다.</string>
<string name="widget_bookings_name">예약</string>
<string name="widget_bookings_description">다가오는 항공편, 기차, 호텔, 식당과 그 시간.</string>
<string name="widget_flight_name">항공편</string>
<string name="widget_flight_description">다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착.</string>
<string name="widget_todos_name">할 일</string>
<string name="widget_todos_description">여행을 위해 남은 일과 짐 싸기 진행 상황.</string>
<string name="widget_packing_name">짐 싸기</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Het dagplan als tijdlijn, met het weer en de volgende stop.</string>
<string name="widget_bookings_name">Boekingen</string>
<string name="widget_bookings_description">Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn.</string>
<string name="widget_flight_name">Vlucht</string>
<string name="widget_flight_description">Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst.</string>
<string name="widget_todos_name">Taken</string>
<string name="widget_todos_description">Wat er nog openstaat voor de reis en hoe ver het inpakken is.</string>
<string name="widget_packing_name">Bagage</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem.</string>
<string name="widget_bookings_name">Rezerwacje</string>
<string name="widget_bookings_description">Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy.</string>
<string name="widget_flight_name">Lot</string>
<string name="widget_flight_description">Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot.</string>
<string name="widget_todos_name">Zadania</string>
<string name="widget_todos_description">Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie.</string>
<string name="widget_packing_name">Pakowanie</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">O plano do dia como linha do tempo, com o clima e a próxima parada.</string>
<string name="widget_bookings_name">Reservas</string>
<string name="widget_bookings_description">Seus próximos voos, trens, hotéis e mesas, e quando acontecem.</string>
<string name="widget_flight_name">Voo</string>
<string name="widget_flight_description">Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada.</string>
<string name="widget_todos_name">Tarefas</string>
<string name="widget_todos_description">O que ainda falta para a viagem e quanto da mala já está pronto.</string>
<string name="widget_packing_name">Bagagem</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">План дня в виде ленты времени, с погодой и следующей остановкой.</string>
<string name="widget_bookings_name">Бронирования</string>
<string name="widget_bookings_description">Ближайшие рейсы, поезда, отели и столики и когда они.</string>
<string name="widget_flight_name">Рейс</string>
<string name="widget_flight_description">Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие.</string>
<string name="widget_todos_name">Задачи</string>
<string name="widget_todos_description">Что ещё осталось сделать к поездке и как идут сборы.</string>
<string name="widget_packing_name">Сборы</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plán dňa ako časová os, s počasím a ďalšou zastávkou.</string>
<string name="widget_bookings_name">Rezervácie</string>
<string name="widget_bookings_description">Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú.</string>
<string name="widget_flight_name">Let</string>
<string name="widget_flight_description">Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet.</string>
<string name="widget_todos_name">Úlohy</string>
<string name="widget_todos_description">Čo ešte zostáva na cestu a ako ďaleko je balenie.</string>
<string name="widget_packing_name">Balenie</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Dagens plan som tidslinje, med vädret och nästa stopp.</string>
<string name="widget_bookings_name">Bokningar</string>
<string name="widget_bookings_description">Dina nästa flyg, tåg, hotell och bord, och när de är.</string>
<string name="widget_flight_name">Flyg</string>
<string name="widget_flight_description">Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst.</string>
<string name="widget_todos_name">Att göra</string>
<string name="widget_todos_description">Vad som återstår inför resan och hur långt packningen har kommit.</string>
<string name="widget_packing_name">Packning</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป</string>
<string name="widget_bookings_name">การจอง</string>
<string name="widget_bookings_description">เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ</string>
<string name="widget_flight_name">เที่ยวบิน</string>
<string name="widget_flight_description">เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง</string>
<string name="widget_todos_name">สิ่งที่ต้องทำ</string>
<string name="widget_todos_description">สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า</string>
<string name="widget_packing_name">จัดกระเป๋า</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla.</string>
<string name="widget_bookings_name">Rezervasyonlar</string>
<string name="widget_bookings_description">Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile.</string>
<string name="widget_flight_name">Uçuş</string>
<string name="widget_flight_description">Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış.</string>
<string name="widget_todos_name">Yapılacaklar</string>
<string name="widget_todos_description">Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu.</string>
<string name="widget_packing_name">Bavul</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">План дня у вигляді стрічки часу, з погодою і наступною зупинкою.</string>
<string name="widget_bookings_name">Бронювання</string>
<string name="widget_bookings_description">Найближчі рейси, поїзди, готелі й столики та коли вони.</string>
<string name="widget_flight_name">Рейс</string>
<string name="widget_flight_description">Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття.</string>
<string name="widget_todos_name">Завдання</string>
<string name="widget_todos_description">Що ще лишилося зробити до подорожі і як просувається пакування.</string>
<string name="widget_packing_name">Пакування</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo.</string>
<string name="widget_bookings_name">Đặt chỗ</string>
<string name="widget_bookings_description">Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian.</string>
<string name="widget_flight_name">Chuyến bay</string>
<string name="widget_flight_description">Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến.</string>
<string name="widget_todos_name">Việc cần làm</string>
<string name="widget_todos_description">Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu.</string>
<string name="widget_packing_name">Hành lý</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Today\'s plan as a timeline, with the weather and what is next.</string>
<string name="widget_bookings_name">Bookings</string>
<string name="widget_bookings_description">Your next flights, trains, hotels and tables, and when they are due.</string>
<string name="widget_flight_name">Flight</string>
<string name="widget_flight_description">Your next flight live: departure countdown, the aircraft on its way, delay and arrival.</string>
<string name="widget_todos_name">To-dos</string>
<string name="widget_todos_description">What is still open for the trip, and how far the packing has come.</string>
<string name="widget_packing_name">Packing</string>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The flight widget (widget/TrekWidgets.kt). Sizes in cells for Android 12+, dp before.
No previewImage: Glance draws the picker preview from the sample trip (providePreview). -->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_flight_description"
android:initialLayout="@layout/glance_default_loading_layout"
android:minWidth="110dp"
android:minHeight="110dp"
android:minResizeWidth="110dp"
android:minResizeHeight="110dp"
android:maxResizeWidth="530dp"
android:maxResizeHeight="450dp"
android:targetCellWidth="4"
android:targetCellHeight="2"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen"
android:configure="com.liketrek.trek.widget.WidgetConfigActivity"
android:widgetFeatures="reconfigurable|configuration_optional" />
@@ -0,0 +1,89 @@
package com.liketrek.trek
import com.liketrek.trek.clientcert.ClientCertWatch
import com.liketrek.trek.clientcert.TrekClientIdentity
import com.liketrek.trek.clientcert.TrekClientIdentity.Failure
import java.util.Date
import javax.security.auth.x500.X500Principal
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
/**
* Reading a client certificate file (TrekClientIdentity.read) and the rule for
* which server sees it. The files in test/resources/clientcert are test-only:
* a throwaway CA, password "trek-test". valid.p12 has OpenSSL 3's default
* encryption (AES-256, PBKDF2), valid-legacy.p12 the older RC2/3DES one that
* many routers and NAS systems still export.
*/
class ClientIdentityTest {
private val password = "trek-test".toCharArray()
private val inside = Date(1_800_000_000_000L) // 2027-01-15, inside every valid test certificate
private fun file(name: String): ByteArray =
requireNotNull(javaClass.classLoader?.getResourceAsStream("clientcert/$name")) { name }.use { it.readBytes() }
private fun failure(name: String, pass: CharArray = password, now: Date = inside): Failure {
try {
TrekClientIdentity.read(file(name), pass, now)
} catch (e: TrekClientIdentity.ImportException) {
return e.reason
}
fail("$name opened")
throw AssertionError()
}
@Test
fun opensModernAndLegacyFiles() {
for (name in listOf("valid.p12", "valid-legacy.p12")) {
val identity = TrekClientIdentity.read(file(name), password, inside)
assertEquals("trek-test-valid", TrekClientIdentity.commonName(identity.chain[0].subjectX500Principal))
assertEquals("TREK mTLS Test CA", TrekClientIdentity.commonName(identity.chain[0].issuerX500Principal))
assertEquals("RSA", identity.key.algorithm)
}
}
@Test
fun namesWhatIsWrongWithAFile() {
assertEquals(Failure.PASSWORD, failure("valid.p12", "wrong".toCharArray()))
assertEquals(Failure.PASSWORD, failure("valid-legacy.p12", "wrong".toCharArray()))
assertEquals(Failure.EXPIRED, failure("expired.p12"))
assertEquals(Failure.NOT_YET_VALID, failure("future.p12"))
assertEquals(Failure.NO_KEY, failure("cert-only.p12"))
try {
TrekClientIdentity.read("not a certificate".toByteArray(), password, inside)
fail("text opened")
} catch (e: TrekClientIdentity.ImportException) {
assertEquals(Failure.FORMAT, e.reason)
}
}
@Test
fun showsTheCertificateOnlyToItsHostAndPort() {
assertTrue(TrekClientIdentity.matches("trek.example.com", 443, "Trek.Example.com", -1))
assertTrue(TrekClientIdentity.matches("trek.example.com", 443, "trek.example.com", 443))
assertTrue(TrekClientIdentity.matches("nas.local", 8443, "nas.local", 8443))
assertFalse(TrekClientIdentity.matches("trek.example.com", 443, "auth.example.com", 443))
assertFalse(TrekClientIdentity.matches("trek.example.com", 443, "trek.example.com", 8443))
assertFalse(TrekClientIdentity.matches("nas.local", 8443, "nas.local", -1))
assertFalse(TrekClientIdentity.matches("trek.example.com", 443, null, 443))
}
@Test
fun leavesForTheAddressScreenOnlyWhenTheCertificateIsWhatFails() {
assertTrue(ClientCertWatch.refused(true, 0)) // handshake broken off: nginx, Caddy, Traefik
assertTrue(ClientCertWatch.refused(true, 403)) // Cloudflare's block page
assertTrue(ClientCertWatch.refused(true, 400)) // nginx without a valid certificate
assertFalse(ClientCertWatch.refused(true, 200)) // asks, but lets everyone in
assertFalse(ClientCertWatch.refused(true, 502)) // TREK restarting behind the proxy
assertFalse(ClientCertWatch.refused(false, 0)) // simply offline
}
@Test
fun readsTheCommonNameOrFallsBackToTheWholeName() {
assertEquals("Phone, home", TrekClientIdentity.commonName(X500Principal("CN=Phone\\, home,O=Family")))
assertEquals("O=Family", TrekClientIdentity.commonName(X500Principal("O=Family")))
}
}
@@ -13,11 +13,33 @@ import java.time.LocalDate
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** The native side's own decisions, apart from the views. */
class NativeLogicTest {
@Test
fun aRedirectAwayWhileTheServerLoadsIsTakenAsItsSignIn() {
val server = "https://trek.example.com"
// Authelia in front of the page, its check let through on /api.
assertEquals("auth.example.com", SignInRedirect.learnedHost(server, "https://auth.example.com/?rd=https%3A%2F%2Ftrek.example.com%2F", true, true, false))
assertEquals("auth.example.com:9091", SignInRedirect.learnedHost(server, "https://Auth.example.com:9091/", true, true, false))
// A link the user follows, a frame, or anything after the server's page has shown: the browser, as before.
assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", true, false, false))
assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", false, true, false))
assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", true, true, true))
// The server's own host, another scheme, or a step down to plain http.
assertNull(SignInRedirect.learnedHost(server, "https://trek.example.com/login", true, true, false))
assertNull(SignInRedirect.learnedHost(server, "intent://auth.example.com/", true, true, false))
assertNull(SignInRedirect.learnedHost(server, "http://auth.example.com/", true, true, false))
assertEquals("auth.lan", SignInRedirect.learnedHost("http://trek.lan:3000", "http://auth.lan/", true, true, false))
assertNull(SignInRedirect.learnedHost(null, "https://auth.example.com/", true, true, false))
assertTrue(SignInRedirect.onServer(server, "https://TREK.example.com/dashboard"))
assertFalse(SignInRedirect.onServer(server, "https://auth.example.com/"))
}
@Test
fun pushesLandInTheChannelOfTheirEvent() {
assertEquals(TrekPushService.CHANNEL_CHAT, TrekPushService.channelFor("collab_message"))
@@ -0,0 +1,91 @@
package com.liketrek.trek
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** The stored copy of the server's UI (TrekOfflineShell), on a plain folder. */
class TrekOfflineShellTest {
private val root: File = Files.createTempDirectory("offline-shell").toFile()
@After
fun cleanUp() {
TrekOfflineShell.deactivate()
root.deleteRecursively()
}
@Test
fun theCopyAnswersOnlyForTheServerItWasStartedFor() {
TrekOfflineShell.activate("https://a.example.com")
assertTrue(TrekOfflineShell.isActive())
assertTrue(TrekOfflineShell.isActiveFor("https://a.example.com"))
// Another server picked in the same process: its pages come from the server.
assertFalse(TrekOfflineShell.isActiveFor("https://b.example.com"))
assertFalse(TrekOfflineShell.isActiveFor(null))
// A start that reaches the server leaves the copy behind.
TrekOfflineShell.deactivate()
assertFalse(TrekOfflineShell.isActive())
assertFalse(TrekOfflineShell.isActiveFor("https://a.example.com"))
}
@Test
fun aRefreshCutOffHalfwayKeepsThePreviousBuildWhole() {
val server = "https://a.example.com"
val oldPage = "<script src=/assets/index-old.js>".toByteArray()
assertTrue(TrekOfflineShell.beginRefresh(root, server))
assertTrue(TrekOfflineShell.saveFile(root, "assets/index-old.js", byteArrayOf(1)))
assertTrue(TrekOfflineShell.savePage(root, server, oldPage))
assertTrue(TrekOfflineShell.hasCopy(root, server))
// The next build: one file arrives, then the connection drops before the page is taken over.
assertTrue(TrekOfflineShell.beginRefresh(root, server))
assertTrue(TrekOfflineShell.saveFile(root, "assets/index-new.js", byteArrayOf(2)))
assertTrue(TrekOfflineShell.hasCopy(root, server))
assertArrayEquals(oldPage, File(root, "index.html").readBytes())
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-old.js"))
// The file already fetched stays for the next try.
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-new.js"))
}
@Test
fun aCompleteRefreshTakesTheNewPageAndDropsTheOldBuild() {
val server = "https://a.example.com"
TrekOfflineShell.beginRefresh(root, server)
TrekOfflineShell.saveFile(root, "assets/index-old.js", byteArrayOf(1))
TrekOfflineShell.savePage(root, server, "old".toByteArray())
TrekOfflineShell.beginRefresh(root, server)
TrekOfflineShell.saveFile(root, "assets/index-new.js", byteArrayOf(2))
assertTrue(TrekOfflineShell.savePage(root, server, "new".toByteArray()))
TrekOfflineShell.prune(root, setOf("assets/index-new.js"))
assertArrayEquals("new".toByteArray(), File(root, "index.html").readBytes())
assertTrue(TrekOfflineShell.hasFile(root, "assets/index-new.js"))
assertFalse(TrekOfflineShell.hasFile(root, "assets/index-old.js"))
}
@Test
fun aRefreshForAnotherServerThrowsTheOldCopyAwayFirst() {
TrekOfflineShell.beginRefresh(root, "https://a.example.com")
TrekOfflineShell.saveFile(root, "assets/index-a.js", byteArrayOf(1))
TrekOfflineShell.savePage(root, "https://a.example.com", "a".toByteArray())
assertTrue(TrekOfflineShell.beginRefresh(root, "https://b.example.com"))
assertFalse(TrekOfflineShell.hasCopy(root, "https://a.example.com"))
assertFalse(TrekOfflineShell.hasCopy(root, "https://b.example.com"))
assertFalse(TrekOfflineShell.hasFile(root, "assets/index-a.js"))
}
@Test
fun pathsOutsideTheCopyAreRefused() {
assertFalse(TrekOfflineShell.saveFile(root, "../escape.js", byteArrayOf(1)))
assertFalse(TrekOfflineShell.saveFile(root, "assets/index.js?v=1", byteArrayOf(1)))
assertFalse(TrekOfflineShell.hasFile(root, ""))
}
}
@@ -99,4 +99,34 @@ class WidgetSnapshotTest {
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
}
@Test
fun turnsToTheDayOfTheDateItIsReadOn() {
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
"days":[
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
],
"bookings":[
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
],
"labels":{}}"""
val snapshot = WidgetSnapshot.parse(json)!!
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
val second = snapshot.on(LocalDate.of(2026, 11, 7))
assertEquals("Day 2 of 3", second.today!!.dayLabel)
assertEquals("Harbour", second.today!!.stops.single().name)
assertEquals(listOf("Train"), second.bookings.map { it.title })
// A day the app wrote nothing for (the trip is over) shows no day.
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
}
@Test
fun aSnapshotWithoutDaysReadsAsWritten() {
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
assertTrue(snapshot.days.isEmpty())
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
}
}
+6
View File
@@ -2,9 +2,15 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../../node_modules/@capacitor/android/capacitor')
include ':capacitor-action-sheet'
project(':capacitor-action-sheet').projectDir = new File('../../node_modules/@capacitor/action-sheet/android')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../../node_modules/@capacitor/app/android')
include ':capacitor-dialog'
project(':capacitor-dialog').projectDir = new File('../../node_modules/@capacitor/dialog/android')
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../../node_modules/@capacitor/filesystem/android')
+1 -1
View File
@@ -375,7 +375,7 @@ const SCRIPTS: Record<string, GuideScript> = {
only(p => section(p, 'Authentication Methods').getByText('Password Login', { exact: true }).locator('xpath=../..')),
// The SSO rows exist only once OIDC is configured; the run shows where that happens.
only(p => section(p, 'Single Sign-On (OIDC)')),
only(p => section(p, 'Require two-factor authentication (2FA)')),
only(p => section(p, 'Require 2FA')),
],
},
'admin-passkeys': {
+18
View File
@@ -0,0 +1,18 @@
// The chunk group that holds the lucide icons the app loads at startup (vite.config.js).
//
// Every lucide icon is a module of its own, and the plugin icon lookup
// (src/components/shared/PluginIcon.tsx) reaches all of them by name, from the navigation
// every page renders. Left to itself the bundler puts each icon that some other chunk
// also uses into a chunk of its own, so that neither side holds a copy: 187 files of a few
// hundred bytes each, every one a request of its own on a first visit and an entry of its
// own in the service worker's precache. In one group they are one file, whose hash changes
// only when lucide-react does.
//
// `tags: ['$initial']` for the reason the other groups carry it: without it the group would
// also take icons that today sit behind a lazy route and make them part of the first load.
export const ICON_CHUNK = {
name: 'vendor-icons',
priority: 20,
tags: ['$initial'],
test: /[\\/]node_modules[\\/]lucide-react[\\/]/,
};
@@ -37,6 +37,7 @@
512499AF65E091B2BBC9A7BB /* UniformTypeIdentifiers.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E45050B942C96E1ACCAB7CE9 /* UniformTypeIdentifiers.framework */; };
5480CCC12F42E9605044AB6B /* ShareHandoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56050CCA8DE4BEB4680D9E0B /* ShareHandoff.swift */; };
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */; };
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */; };
5BBE9EE02A47EC67C31F5E21 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = D0A4B2C6C93971E884561CFA /* Localizable.strings */; };
612BB9680DC27BB8BF553060 /* TrekFamily.swift in Sources */ = {isa = PBXBuildFile; fileRef = A030A06726542A2D7F61C54B /* TrekFamily.swift */; };
634F4E63DC7C2A0027F0D118 /* Details.swift in Sources */ = {isa = PBXBuildFile; fileRef = F406A4A31BD875A880A7CA14 /* Details.swift */; };
@@ -51,6 +52,7 @@
81E4582AD7514CA1AF373E48 /* WatchSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 842D54F96D80A1D1C4C21457 /* WatchSnapshot.swift */; };
84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
8925D4B7322D6930F3C02959 /* TrekWatchLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 125A1BB381BBF7E58B8902FD /* TrekWatchLink.swift */; };
A1C3E5F70913B5D7F9E1A301 /* TrekClientIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1C3E5F70913B5D7F9E1A302 /* TrekClientIdentity.swift */; };
896952F864B35C647FF6910A /* WatchSample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10FB55D221F4BA18795F33B5 /* WatchSample.swift */; };
8FC5873BE6A8CB2AFB31A46A /* TripContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE6873D246AC6B8E2CB6C8B4 /* TripContent.swift */; };
8FFB2B488E43AD339D0BB450 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 3A6054202DCC03D83C2C9602 /* Localizable.strings */; };
@@ -172,6 +174,7 @@
10FB55D221F4BA18795F33B5 /* WatchSample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WatchSample.swift; sourceTree = "<group>"; };
114C13FB91B554AE8DC4372B /* et */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = et; path = et.lproj/Localizable.strings; sourceTree = "<group>"; };
125A1BB381BBF7E58B8902FD /* TrekWatchLink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TrekWatchLink.swift; sourceTree = "<group>"; };
A1C3E5F70913B5D7F9E1A302 /* TrekClientIdentity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TrekClientIdentity.swift; sourceTree = "<group>"; };
12DE24E0B7E2E5F3564D952B /* he */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = he; path = he.lproj/Localizable.strings; sourceTree = "<group>"; };
1335F1EEB49D744B27A00F31 /* th */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = th; path = th.lproj/Localizable.strings; sourceTree = "<group>"; };
15884CA899CAD3FFD98BA927 /* hu */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = hu; path = hu.lproj/Localizable.strings; sourceTree = "<group>"; };
@@ -303,6 +306,7 @@
E5800E4ECECED54A47CDABAA /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Localizable.strings; sourceTree = "<group>"; };
E6831E849332626BE8D54CEF /* ShareView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShareView.swift; sourceTree = "<group>"; };
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BookingsContent.swift; sourceTree = "<group>"; };
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FlightContent.swift; sourceTree = "<group>"; };
EAFBDD97043B34E4B64FDA86 /* pt-BR */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = "<group>"; };
EC8D1292C9FC6430C059960A /* nl */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = nl; path = nl.lproj/Localizable.strings; sourceTree = "<group>"; };
ECC80E1314B31ED2D2347411 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/Localizable.strings; sourceTree = "<group>"; };
@@ -420,6 +424,7 @@
2FAD9762203C412B000D30F8 /* config.xml */,
50B271D01FEDC1A000F3C39B /* public */,
125A1BB381BBF7E58B8902FD /* TrekWatchLink.swift */,
A1C3E5F70913B5D7F9E1A302 /* TrekClientIdentity.swift */,
);
path = App;
sourceTree = "<group>";
@@ -535,6 +540,7 @@
DE6873D246AC6B8E2CB6C8B4 /* TripContent.swift */,
24B175DE91E1E6E850DB0285 /* TodayContent.swift */,
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */,
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */,
AEF7DCAA1AEE67F1291668D1 /* TodosContent.swift */,
);
name = TREKWidgets;
@@ -823,6 +829,7 @@
7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */,
0C2D60A4950D7293E1F282CB /* TripDayAttributes.swift in Sources */,
8925D4B7322D6930F3C02959 /* TrekWatchLink.swift in Sources */,
A1C3E5F70913B5D7F9E1A301 /* TrekClientIdentity.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -845,6 +852,7 @@
8FC5873BE6A8CB2AFB31A46A /* TripContent.swift in Sources */,
9A175689CFCC630BE9BB9EE1 /* TodayContent.swift in Sources */,
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */,
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */,
F1E29B18C5B1E75A5BC01B57 /* TodosContent.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<string>TREK</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
+96 -1
View File
@@ -6,6 +6,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
// Launched by a quick action on the app icon: held until the UI asks for it.
if let item = connectionOptions.shortcutItem { _ = TrekQuickActions.open(item) }
window = UIWindow(windowScene: windowScene)
window?.rootViewController = TrekBridgeViewController()
@@ -15,6 +17,11 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
for context in connectionOptions.urlContexts where context.url.isFileURL {
TrekSharedFiles.receive(context.url)
}
// Launched by a tap on a widget or a Live Activity: held like a quick action.
// Capacitor still hears of the link, the UI ignores it there (feature appLinks).
for context in connectionOptions.urlContexts {
if let path = TrekQuickActions.appLinkPath(context.url) { TrekQuickActions.open(path: path) }
}
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
}
@@ -38,13 +45,101 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// com.liketrek.trek://share: the share sheet left an item for the import.
let handoffs = URLContexts.filter { $0.url.scheme == "com.liketrek.trek" && $0.url.host == "share" }
if !handoffs.isEmpty { TrekSharedFiles.receiveFromShareExtension() }
let others = URLContexts.subtracting(files).subtracting(handoffs)
// com.liketrek.trek://navigate/<path>: a widget or Live Activity tap. Through
// Capacitor it was an event a page reloading after the system ended its process
// never heard, and that page then took the same link for one already followed.
let appLinks = URLContexts.filter { TrekQuickActions.appLinkPath($0.url) != nil }
for context in appLinks {
if let path = TrekQuickActions.appLinkPath(context.url) { TrekQuickActions.open(path: path) }
}
let others = URLContexts.subtracting(files).subtracting(handoffs).subtracting(appLinks)
if !others.isEmpty { SceneDelegateProxy.shared.scene(scene, openURLContexts: others) }
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
SceneDelegateProxy.shared.scene(scene, continue: userActivity)
}
// A quick action on the app icon while the app was running in the background.
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void) {
completionHandler(TrekQuickActions.open(shortcutItem))
}
}
/// The quick actions on the app icon (a long press on it): "New trip" and the
/// trip coming up, set by the UI in its language (TrekShell.setQuickActions).
/// Each carries the path it opens; a tap goes to the UI as that path, at once
/// when it listens, or held for it to take when the tap launched the app.
enum TrekQuickActions {
private static let pathKey = "path"
private static var pending: String?
static var onOpen: ((String) -> Void)?
struct Item {
let type: String
let title: String
let subtitle: String?
let icon: String
let path: String
init?(raw: JSObject) {
guard let type = raw["type"] as? String, let title = raw["title"] as? String,
let path = raw["path"] as? String, path.hasPrefix("/") else { return nil }
self.type = type
self.title = title
self.subtitle = raw["subtitle"] as? String
self.icon = raw["icon"] as? String ?? ""
self.path = path
}
}
static func set(_ items: [Item]) {
UIApplication.shared.shortcutItems = items.prefix(4).map { item in
UIApplicationShortcutItem(
type: "com.liketrek.trek.\(item.type)",
localizedTitle: item.title,
localizedSubtitle: item.subtitle,
icon: icon(item.icon),
userInfo: [pathKey: item.path as NSString]
)
}
}
private static func icon(_ name: String) -> UIApplicationShortcutIcon {
switch name {
case "add": return UIApplicationShortcutIcon(type: .add)
case "trip": return UIApplicationShortcutIcon(systemImageName: "suitcase")
default: return UIApplicationShortcutIcon(type: .compose)
}
}
static func open(_ item: UIApplicationShortcutItem) -> Bool {
guard let path = item.userInfo?[pathKey] as? String, path.hasPrefix("/") else { return false }
open(path: path)
return true
}
/// A path to open: at once when the UI listens, else held for it to take.
/// Widget and Live Activity taps come this way too, so each is followed once.
static func open(path: String) {
if let onOpen { onOpen(path) } else { pending = path }
}
/// The path in com.liketrek.trek://navigate/<path>, the link widgets and Live Activities open.
static func appLinkPath(_ url: URL) -> String? {
let prefix = "com.liketrek.trek://navigate"
guard url.absoluteString.hasPrefix(prefix) else { return nil }
let path = String(url.absoluteString.dropFirst(prefix.count))
if path.isEmpty { return "/" }
return path.hasPrefix("/") ? path : nil
}
/// The action the app was launched with, once.
static func take() -> String? {
defer { pending = nil }
return pending
}
}
/// The blur over the app while it sits in the app switcher, when the app lock
@@ -10,6 +10,7 @@ import WebKit
class TrekBridgeViewController: CAPBridgeViewController {
override func instanceDescriptor() -> InstanceDescriptor {
let descriptor = super.instanceDescriptor()
TrekServerStore.recheckAfterUpdate()
if let server = TrekServerStore.url {
// The trailing slash matters: Capacitor treats every URL that starts
// with this string as the app's own, and without it that would take
@@ -40,15 +41,318 @@ class TrekBridgeViewController: CAPBridgeViewController {
// reachable" with a server that was there all along.
if let webView, let inner = webView.navigationDelegate {
let proxy = TrekNavigationProxy(inner: inner)
proxy.onErrorPage = { [weak self] error in self?.errorPageChanged(error) }
proxy.onPageShown = { [weak self] in self?.publishSafeArea(force: true) }
navigationProxy = proxy
webView.navigationDelegate = proxy
}
guardBridgeMessages()
watchSignInPages()
bridge?.registerPluginInstance(TrekShellPlugin())
// WebKit's own swipe back slides away a screenshot of the whole page,
// closes no sheet and takes every drag near the edge from the UI. The UI
// draws its own (mobile/components/MEdgeBack.tsx, feature "edgeBack"):
// the page follows the finger and an open sheet closes first.
webView?.allowsBackForwardNavigationGestures = false
// A long press on a link would lift a preview of the page it points to,
// which no native list does; the press means "drag" or nothing here.
webView?.allowsLinkPreview = false
paintBehindWebView()
}
// MARK: - What shows where the web view does not reach
/// The UI reports its theme through StatusBar.setStyle (native/nativeApp.ts),
/// which lands here; the colour behind the web view follows it.
override func setNeedsStatusBarAppearanceUpdate() {
super.setNeedsStatusBarAppearanceUpdate()
paintBehindWebView()
}
/// Some iOS releases (27.0.x) lay the web view out below the status bar
/// instead of under it, and the strip above the page then showed this
/// view's black. It now carries the top colour of the screen background
/// (mobile.css --m-scr), so the strip reads as part of the page on every
/// release, and the rubber band at the ends shows the same colour.
private func paintBehindWebView() {
let dark: Bool
switch preferredStatusBarStyle {
case .lightContent: dark = true
case .darkContent: dark = false
default: dark = traitCollection.userInterfaceStyle == .dark
}
let color = dark
? UIColor(red: 0x17 / 255, green: 0x17 / 255, blue: 0x1C / 255, alpha: 1)
: UIColor(red: 0xFB / 255, green: 0xFA / 255, blue: 0xF7 / 255, alpha: 1)
view.backgroundColor = color
webView?.scrollView.backgroundColor = color
webView?.underPageBackgroundColor = color
}
// MARK: - The safe area the page keeps clear of
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
publishSafeArea()
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
publishSafeArea()
}
private var publishedSafeArea: UIEdgeInsets?
/// WebKit's env(safe-area-inset-*) is the window's safe area only where the
/// web view overlaps it. Where a release lays the web view out below the
/// status bar it reports 0, yet a camera in a corner can still reach into
/// the page. The part of the window's safe area (and of the status bar) that
/// falls inside the web view goes to the page as --trek-native-safe-*, which
/// mobile.css takes as a floor under env(), never in its place.
func publishSafeArea(force: Bool = false) {
guard let webView, let window = view.window else { return }
let frame = webView.convert(webView.bounds, to: window)
let safe = window.safeAreaInsets
let statusBar = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let insets = UIEdgeInsets(
top: max(0, max(safe.top, statusBar) - frame.minY),
left: max(0, safe.left - frame.minX),
bottom: max(0, safe.bottom - (window.bounds.maxY - frame.maxY)),
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
let corner = cornerElement(in: frame, window: window)
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
publishedSafeArea = insets
publishedCorner = corner
let px = { (v: CGFloat) in "'\(Int(v.rounded(.up)))px'" }
let js = "(function(s){"
+ "s.setProperty('--trek-native-safe-top',\(px(insets.top)));"
+ "s.setProperty('--trek-native-safe-left',\(px(insets.left)));"
+ "s.setProperty('--trek-native-safe-right',\(px(insets.right)));"
+ "s.setProperty('--trek-native-safe-bottom',\(px(insets.bottom)));"
+ "s.setProperty('--trek-native-corner-bottom',\(px(corner.top)));"
+ "s.setProperty('--trek-native-corner-left',\(px(corner.left)));"
+ "s.setProperty('--trek-native-corner-right',\(px(corner.right)));"
+ "})(document.documentElement.style)"
webView.evaluateJavaScript(js, completionHandler: nil)
}
private var publishedCorner: UIEdgeInsets?
/// An element in a top corner of the screen, such as the status capsule of
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
/// side (left/right), in the web view's coordinates; zero where there is
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
/// the corner avoided vertically reaches lower than the one avoiding it
/// horizontally, which in turn is wider on the corner's side. The page puts
/// its top bar beside the element and starts its content below it, using
/// the full width (mobile.css), instead of giving up a strip of the whole
/// height.
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
guard #available(iOS 26.0, *) else { return .zero }
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
let horizontal = view.edgeInsets(for: .safeArea(cornerAdaptation: .horizontal))
guard vertical.top > horizontal.top + 1 else { return .zero }
return UIEdgeInsets(
top: max(0, vertical.top - frame.minY),
left: max(0, horizontal.left - vertical.left - frame.minX),
bottom: 0,
right: max(0, horizontal.right - vertical.right - (window.bounds.maxX - frame.maxX))
)
}
// MARK: - A proxy's sign-in page
/// Over a proxy's sign-in page (Pangolin, authentik, ...) the server's UI is
/// not there, so nothing else leads back to the address screen, and a passkey
/// cannot work in a web view for a domain the app is not tied to. A bar says
/// so and offers to change the server; the keyboard gets room on that page,
/// which TREK's own script makes everywhere else (native/keepFieldInView.ts).
private var signInBar: UIView?
private var urlObservation: NSKeyValueObservation?
private var insetObservation: NSKeyValueObservation?
private var onSignInPage = false
/// Whether the main frame shows an error page in place of the server's (a 4xx
/// nobody else handled: a proxy's block page, a client certificate it refused).
private var onErrorPage = false
private var signInHint: UILabel?
private var keyboardUp = false
/// How far the keyboard reaches into the view while it is up.
private var keyboardRoom: CGFloat = 0
/// Whether the bottom inset is this controller's, so leaving the page puts it back.
private var ownsInset = false
private var bodyReset: DispatchWorkItem?
private func watchSignInPages() {
urlObservation = webView?.observe(\.url, options: [.initial, .new]) { [weak self] webView, _ in
let signIn = TrekServerStore.isSignInHost(webView.url)
DispatchQueue.main.async { self?.signInPageChanged(signIn) }
}
// The keyboard plugin zeroes the scroll inset on every frame change it
// makes, the last one a while after the keyboard is up. On a sign-in
// page the inset wanted here is put back each time.
insetObservation = webView?.scrollView.observe(\.contentInset, options: [.new]) { [weak self] _, _ in
DispatchQueue.main.async { self?.applyInset() }
}
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
private func signInPageChanged(_ signIn: Bool) {
onSignInPage = signIn
if signIn && signInBar == nil { signInBar = makeSignInBar() }
updateSignInBar()
}
private func errorPageChanged(_ error: Bool) {
onErrorPage = error
if error && signInBar == nil { signInBar = makeSignInBar() }
updateSignInBar()
}
/// Out of the way while the keyboard is up: the form needs the room.
private func updateSignInBar() {
let labels = TrekServerStore.labels
signInHint?.text = onSignInPage
? labels["signInHint"]
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
: labels["errorPageHint"] ?? "This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
signInBar?.isHidden = !((onSignInPage || onErrorPage) && !keyboardUp)
applyInset()
}
/// On a sign-in page the page can scroll past what covers its end: the
/// keyboard while it is up, the bar otherwise. TREK's own pages are left alone.
private func applyInset() {
guard let scrollView = webView?.scrollView else { return }
let wanted: CGFloat
if onSignInPage || onErrorPage {
if keyboardUp {
wanted = keyboardRoom
} else if let bar = signInBar {
view.layoutIfNeeded()
wanted = max(0, view.bounds.height - bar.frame.minY)
} else {
wanted = 0
}
ownsInset = true
} else if ownsInset {
wanted = 0
ownsInset = false
} else {
return
}
if scrollView.contentInset.bottom != wanted { scrollView.contentInset.bottom = wanted }
if scrollView.verticalScrollIndicatorInsets.bottom != wanted { scrollView.verticalScrollIndicatorInsets.bottom = wanted }
}
/// The keyboard plugin also sizes the body to the area above the keyboard,
/// after the keyboard's animation and a further 0.2 s. On a sign-in page the
/// body gets its height back once that has run, so the button under the
/// keyboard can be scrolled into view through the inset above.
@objc private func keyboardWillShow(_ note: Notification) {
keyboardUp = true
if let frame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
keyboardRoom = max(0, view.bounds.height - view.convert(frame, from: nil).minY)
}
bodyReset?.cancel()
if onSignInPage {
let duration = note.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0.25
let reset = DispatchWorkItem { [weak self] in
guard let self, self.onSignInPage, self.keyboardUp, let webView = self.webView else { return }
webView.evaluateJavaScript("document.body.style.height = ''", completionHandler: nil)
self.applyInset()
}
bodyReset = reset
DispatchQueue.main.asyncAfter(deadline: .now() + duration + 0.35, execute: reset)
}
updateSignInBar()
}
@objc private func keyboardWillHide() {
keyboardUp = false
bodyReset?.cancel()
updateSignInBar()
}
private func makeSignInBar() -> UIView {
let labels = TrekServerStore.labels
// The look of the app's own first screens: a white card with a sand edge,
// warm grey text and a dark button, over whatever page the proxy shows.
let bar = UIView()
bar.backgroundColor = UIColor(white: 1, alpha: 0.97)
bar.layer.cornerRadius = 18
bar.layer.cornerCurve = .continuous
bar.layer.borderWidth = 1
bar.layer.borderColor = UIColor(red: 0xEF / 255, green: 0xE4 / 255, blue: 0xD8 / 255, alpha: 1).cgColor
bar.layer.shadowColor = UIColor(red: 0x1F / 255, green: 0x1A / 255, blue: 0x17 / 255, alpha: 1).cgColor
bar.layer.shadowOpacity = 0.18
bar.layer.shadowRadius = 18
bar.layer.shadowOffset = CGSize(width: 0, height: 10)
bar.translatesAutoresizingMaskIntoConstraints = false
let hint = UILabel()
hint.text = labels["signInHint"]
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
hint.textColor = UIColor(red: 0x6B / 255, green: 0x5F / 255, blue: 0x57 / 255, alpha: 1)
hint.font = .preferredFont(forTextStyle: .footnote)
hint.adjustsFontForContentSizeCategory = true
hint.numberOfLines = 0
signInHint = hint
hint.translatesAutoresizingMaskIntoConstraints = false
var look = UIButton.Configuration.filled()
look.baseBackgroundColor = UIColor(red: 0x11 / 255, green: 0x18 / 255, blue: 0x27 / 255, alpha: 1)
look.baseForegroundColor = .white
look.cornerStyle = .fixed
look.background.cornerRadius = 12
look.contentInsets = NSDirectionalEdgeInsets(top: 9, leading: 14, bottom: 9, trailing: 14)
let change = UIButton(configuration: look)
change.setTitle(labels["changeServer"] ?? "Change server", for: .normal)
change.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
change.addTarget(self, action: #selector(changeServerFromSignIn), for: .touchUpInside)
change.translatesAutoresizingMaskIntoConstraints = false
change.setContentHuggingPriority(.required, for: .horizontal)
change.setContentCompressionResistancePriority(.required, for: .horizontal)
bar.addSubview(hint)
bar.addSubview(change)
view.addSubview(bar)
NSLayoutConstraint.activate([
bar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 12),
bar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -12),
bar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -8),
hint.leadingAnchor.constraint(equalTo: bar.leadingAnchor, constant: 14),
hint.topAnchor.constraint(equalTo: bar.topAnchor, constant: 10),
hint.bottomAnchor.constraint(equalTo: bar.bottomAnchor, constant: -10),
change.leadingAnchor.constraint(equalTo: hint.trailingAnchor, constant: 8),
change.trailingAnchor.constraint(equalTo: bar.trailingAnchor, constant: -12),
change.centerYAnchor.constraint(equalTo: bar.centerYAnchor),
])
return bar
}
/// What resetServer does from the UI: forget the server, back to the address screen.
@objc private func changeServerFromSignIn() {
TrekServerStore.url = nil
view.window?.rootViewController = TrekBridgeViewController()
}
/// Kept alive here: the content controller holds it, but only for as long as it is registered.
private var messageGuard: TrekBridgeMessageGuard?
/// Capacitor answers bridge messages from any page in the web view. With a
/// proxy's sign-in page loading there, its messages are dropped before they
/// reach the plugins. Always in place: a sign-in host can also be learned
/// while the app runs (TrekSignInRedirect).
private func guardBridgeMessages() {
guard let handler = (bridge as? CapacitorBridge)?.webViewDelegationHandler,
let controller = webView?.configuration.userContentController else { return }
let guarded = TrekBridgeMessageGuard(inner: handler)
controller.removeScriptMessageHandler(forName: TrekBridgeMessageGuard.name)
controller.add(guarded, name: TrekBridgeMessageGuard.name)
messageGuard = guarded
}
/// A key command of the UI's (TrekKeyCommands) was pressed. The commands sit
@@ -137,14 +441,136 @@ enum TrekKeyCommands {
enum TrekServerStore {
private static let key = "TrekServerURL"
private static let failureKey = "TrekLastFailure"
/// Why the server's page did not load ("NSURLErrorDomain -1003"): the
/// address screen shows it small under its message, so a report carries
/// the cause. Taken once.
static func noteFailure(_ error: Error) {
let ns = error as NSError
UserDefaults.standard.set("\(ns.domain) \(ns.code)", forKey: failureKey)
}
static func takeFailure() -> String? {
let failure = UserDefaults.standard.string(forKey: failureKey)
UserDefaults.standard.removeObject(forKey: failureKey)
return failure
}
private static let previousKey = "TrekPreviousServerURL"
private static let checkedKey = "TrekServerCheck"
private static let labelsKey = "TrekShellLabels"
/// The words of the bar over a proxy's sign-in page, in the user's language,
/// as the address screen passed them (setServer's `labels`): the server's UI
/// is not there to say them. Empty keeps the English fallback.
static var labels: [String: String] {
get { UserDefaults.standard.dictionary(forKey: labelsKey) as? [String: String] ?? [:] }
set { UserDefaults.standard.set(newValue, forKey: labelsKey) }
}
/// The server API this build needs (MIN_NATIVE_API in serverAddress.ts).
/// A server remembered under a lower value is checked once more: the first
/// launch after an update that raised it puts the address screen back up,
/// filled in with that server (previousURL). Raise both together.
private static let serverCheck = 3
/// Runs before the first bridge is built, so a server picked under an older
/// minimum is not loaded unchecked.
static func recheckAfterUpdate() {
let defaults = UserDefaults.standard
guard defaults.integer(forKey: checkedKey) < serverCheck else { return }
defaults.set(serverCheck, forKey: checkedKey)
guard let server = url else { return }
// Not through `url`, which throws the offline copy away: it still belongs
// to this server, and is what the app starts on if the check cannot run.
defaults.removeObject(forKey: key)
defaults.removeObject(forKey: signInHostsKey)
defaults.set(server, forKey: previousKey)
}
/// The check an update asked for cannot run (the server is out of reach),
/// but there is a copy of its UI: the server goes back in place, unchecked
/// for now, and the check runs again on the next launch.
static func restoreForOffline() -> Bool {
let defaults = UserDefaults.standard
guard url == nil, let previous = previousURL,
FileManager.default.fileExists(atPath: offlineCopyURL.path) else { return false }
defaults.set(previous, forKey: key)
defaults.removeObject(forKey: previousKey)
defaults.set(0, forKey: checkedKey)
return true
}
/// The server an update asked to check again, until a server is set.
static var previousURL: String? {
UserDefaults.standard.string(forKey: previousKey)
}
private static let signInHostsKey = "TrekServerSignInHosts"
/// Setting the server drops the sign-in hosts of the one before it.
static var url: String? {
get { UserDefaults.standard.string(forKey: key) }
set {
if let newValue { UserDefaults.standard.set(newValue, forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) }
if let newValue {
UserDefaults.standard.set(newValue, forKey: key)
UserDefaults.standard.removeObject(forKey: previousKey)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
UserDefaults.standard.removeObject(forKey: signInHostsKey)
try? FileManager.default.removeItem(at: offlineCopyURL)
}
}
/// The hosts of a sign-in page in front of the server (a proxy such as
/// Cloudflare Access or Pangolin), as the address screen found them. Only
/// these load in the web view besides the server, so the proxy's session
/// cookie is the web view's (TrekNavigationProxy), and none of them may
/// talk to the app (TrekBridgeMessageGuard).
static var signInHosts: Set<String> {
get { Set((UserDefaults.standard.stringArray(forKey: signInHostsKey) ?? []).map { $0.lowercased() }) }
set {
if newValue.isEmpty {
UserDefaults.standard.removeObject(forKey: signInHostsKey)
} else {
UserDefaults.standard.set(Array(newValue).sorted(), forKey: signInHostsKey)
}
}
}
/// Keeps one more sign-in host for the remembered server, as the web view met it (TrekSignInRedirect).
static func addSignInHost(_ host: String) {
var hosts = signInHosts
guard hosts.insert(host.lowercased()).inserted else { return }
signInHosts = hosts
}
/// Whether `url` is one of the sign-in hosts, matched on host or host:port.
static func isSignInHost(_ url: URL?) -> Bool {
guard let url, ["https", "http"].contains(url.scheme?.lowercased() ?? ""), let host = url.host?.lowercased() else { return false }
let hosts = signInHosts
if hosts.contains(host) { return true }
if let port = url.port { return hosts.contains("\(host):\(port)") }
return false
}
/// The one-time code of a TREK Cloud purchase (setServer's `welcome`). The
/// server's first page opens its welcome page with it once, which signs the
/// buyer in (TrekNavigationProxy). Kept in memory only, never on disk.
static var pendingWelcome: String?
/// The welcome page for the pending code, handed out once.
static func takeWelcomeURL() -> URL? {
guard let code = pendingWelcome, let server = url else { return nil }
pendingWelcome = nil
let base = server.hasSuffix("/") ? server : server + "/"
return URL(string: base + "api/managed/welcome#" + code)
}
static var offlineCopyURL: URL {
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
return support.appendingPathComponent("offline-start-page.html")
@@ -366,12 +792,48 @@ final class TrekTileSchemeHandler: NSObject, WKURLSchemeHandler {
}
}
/// A sign-in page in front of the server that the address screen never saw.
/// A proxy can let the app's check through (an Authelia or Authentik rule that
/// bypasses /api) and still send the page itself to its sign-in. Handed to
/// Safari, that sign-in leaves its session there and the app stays blank on
/// every launch. So a redirect away from the server, while the server's first
/// page is still loading, is taken as the proxy's sign-in: it loads in the web
/// view and its host is kept, the way the address screen keeps the ones it saw.
/// A link the user taps is no redirect, and once a page of the server has
/// shown, nothing is learned any more.
enum TrekSignInRedirect {
/// The host (host:port with an explicit port) to keep as a sign-in host, or nil.
static func learnedHost(server: String?, target: URL?, mainFrame: Bool, redirect: Bool, serverShown: Bool) -> String? {
guard mainFrame, redirect, !serverShown,
let server, let from = URL(string: server), let fromHost = from.host?.lowercased(),
let target, let toHost = target.host?.lowercased(),
let toScheme = target.scheme?.lowercased(), ["https", "http"].contains(toScheme) else { return nil }
// Never from https down to plain http: the sign-in would send a password in the clear.
if from.scheme?.lowercased() == "https", toScheme != "https" { return nil }
guard toHost != fromHost else { return nil }
if let port = target.port { return "\(toHost):\(port)" }
return toHost
}
/// Whether `url` is on the server's host, where the app's own pages come from.
static func onServer(server: String?, url: URL?) -> Bool {
guard let server, let host = URL(string: server)?.host?.lowercased() else { return false }
return url?.host?.lowercased() == host
}
}
/// Stands in front of Capacitor's navigation delegate and hands it everything
/// but the failures of a navigation that another one replaced: a cancelled
/// load (NSURLErrorCancelled) or an interrupted frame load (WebKit 102). Those
/// are no fault, and Capacitor would answer them with its error page.
final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
private let inner: WKNavigationDelegate
/// A page of the server has shown since launch; from then on no sign-in host is learned (TrekSignInRedirect).
private var serverShown = false
/// Told on the main thread whether the main frame now shows an error page in place of the server's.
var onErrorPage: ((Bool) -> Void)?
/// Told when a page has finished loading: a new document starts without the safe area the controller handed the last one.
var onPageShown: (() -> Void)?
init(inner: WKNavigationDelegate) {
self.inner = inner
@@ -391,13 +853,133 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
(inner as AnyObject).responds(to: aSelector) ? inner : nil
}
/// The sign-in page of a proxy in front of the server loads here instead of
/// in Safari, so its session is the web view's and every request carries it.
/// Only the hosts the address screen saw (TrekServerStore.signInHosts), and
/// only in the main frame; everything else is Capacitor's decision as before.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame?.isMainFrame == true, TrekServerStore.isSignInHost(navigationAction.request.url) {
decisionHandler(.allow)
return
}
// WebKit asks again for every server redirect, as a navigation of type .other.
if let host = TrekSignInRedirect.learnedHost(
server: TrekServerStore.url,
target: navigationAction.request.url,
mainFrame: navigationAction.targetFrame?.isMainFrame == true,
redirect: navigationAction.navigationType == .other,
serverShown: serverShown
) {
TrekServerStore.addSignInHost(host)
decisionHandler(.allow)
return
}
let selector = NSSelectorFromString("webView:decidePolicyForNavigationAction:decisionHandler:")
guard (inner as AnyObject).responds(to: selector) else {
decisionHandler(.allow)
return
}
inner.webView?(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
}
/// After the server's first page, a pending welcome code opens the welcome
/// page once (TrekServerStore.takeWelcomeURL); it is on the server's origin.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
inner.webView?(webView, didFinish: navigation)
onPageShown?()
if TrekSignInRedirect.onServer(server: TrekServerStore.url, url: webView.url) {
serverShown = true
// The server's page is up: an earlier failure is no cause any more.
_ = TrekServerStore.takeFailure()
}
if let welcome = TrekServerStore.takeWelcomeURL() {
webView.load(URLRequest(url: welcome))
}
}
/// A proxy in front of the server asks for a client certificate (mutual TLS):
/// the stored one goes to the host and port it was imported for and nowhere
/// else (TrekClientIdentity). Every other challenge is Capacitor's as before.
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if TrekClientIdentity.answer(challenge, completionHandler) {
let space = challenge.protectionSpace
TrekClientCertWatch.serverAsked(host: space.host, port: space.port) { [weak self, weak webView] in
guard let self, let webView else { return }
// Capacitor's own answer to a failed load: the address screen (errorPath).
TrekServerStore.noteFailure(URLError(.clientCertificateRejected))
self.inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRejected))
}
return
}
let selector = NSSelectorFromString("webView:didReceiveAuthenticationChallenge:completionHandler:")
guard (inner as AnyObject).responds(to: selector) else {
completionHandler(.performDefaultHandling, nil)
return
}
inner.webView?(webView, didReceive: challenge, completionHandler: completionHandler)
}
/// A proxy that asked the page for a client certificate, got none and
/// answered with its own refusal (Cloudflare's 403, nginx's 400) sends the
/// app to the address screen, which says so and offers to add one, rather
/// than leaving the proxy's error page up. Any other 4xx page is not TREK's,
/// which serves its UI for every path (a proxy's block page, a certificate it
/// refused): it stays up with the bar and its way out to another server.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse,
http.statusCode >= 400, http.statusCode < 500, let asked = TrekClientIdentity.lastRequest, !asked.served,
let url = http.url, url.host?.lowercased() == asked.host, (url.port ?? 443) == asked.port {
decisionHandler(.cancel)
TrekServerStore.noteFailure(URLError(.clientCertificateRequired))
inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRequired))
return
}
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse {
let error = http.statusCode >= 400 && http.statusCode < 500
DispatchQueue.main.async { [weak self] in self?.onErrorPage?(error) }
}
let selector = NSSelectorFromString("webView:decidePolicyForNavigationResponse:decisionHandler:")
guard (inner as AnyObject).responds(to: selector) else {
decisionHandler(.allow)
return
}
inner.webView?(webView, decidePolicyFor: navigationResponse, decisionHandler: decisionHandler)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if Self.isReplaced(error) { return }
TrekServerStore.noteFailure(error)
inner.webView?(webView, didFail: navigation, withError: error)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
if Self.isReplaced(error) { return }
TrekServerStore.noteFailure(error)
inner.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
}
}
/// Stands in front of Capacitor's bridge message handler and drops what a
/// proxy's sign-in page posts: that page loads in the web view (see
/// TrekNavigationProxy), and Capacitor itself would hand its messages to the
/// plugins whatever page they come from.
final class TrekBridgeMessageGuard: NSObject, WKScriptMessageHandler {
static let name = "bridge"
private let inner: WKScriptMessageHandler
init(inner: WKScriptMessageHandler) {
self.inner = inner
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let origin = message.frameInfo.securityOrigin
var components = URLComponents()
components.scheme = origin.protocol
components.host = origin.host
if origin.port != 0 { components.port = origin.port }
if TrekServerStore.isSignInHost(components.url) { return }
inner.userContentController(userContentController, didReceive: message)
}
}
+393
View File
@@ -0,0 +1,393 @@
import Foundation
import Security
import UIKit
import UniformTypeIdentifiers
/// The client certificate a user's TREK server asks for (mutual TLS): a proxy
/// such as Cloudflare, nginx, Caddy or Traefik in front of TREK lets through
/// only devices that show one. The app holds at most one, for one server.
///
/// It comes in as a PKCS#12 file (.p12, .pfx) and its password. The password is
/// never kept; the identity goes into the keychain, this device only, readable
/// after the first unlock (so a background refresh can show it too). Only the
/// host and port it was imported for ever see it (`identity(forHost:port:)`), so a
/// sign-in page, a map tile provider or liketrek.com never learns of it.
enum TrekClientIdentity {
private static let label = "trek-client-identity"
private static let hostKey = "TrekClientIdentityHost"
private static let portKey = "TrekClientIdentityPort"
enum Failure: String, Error {
case password, format, noKey = "no_key", expired, notYetValid = "not_yet_valid", store
}
/// The last server that asked for a certificate while the app ran, and whether it got one.
struct Request {
let host: String
let port: Int
let served: Bool
}
private static let lock = NSLock()
private static var _lastRequest: Request?
static var lastRequest: Request? {
lock.lock(); defer { lock.unlock() }
return _lastRequest
}
static func noteRequest(host: String, port: Int, served: Bool) {
lock.lock(); defer { lock.unlock() }
_lastRequest = Request(host: host.lowercased(), port: port > 0 ? port : 443, served: served)
}
// MARK: Reading a file
/// Opens a PKCS#12 file: the identity and the rest of its chain.
static func read(_ data: Data, password: String, now: Date = Date()) -> Result<(SecIdentity, [SecCertificate]), Failure> {
var items: CFArray?
let status = SecPKCS12Import(data as CFData, [kSecImportExportPassphrase as String: password] as CFDictionary, &items)
switch status {
case errSecSuccess: break
case errSecAuthFailed, errSecPkcs12VerifyFailure: return .failure(.password)
default: return .failure(.format)
}
guard let first = (items as? [[String: Any]])?.first,
let value = first[kSecImportItemIdentity as String] else { return .failure(.noKey) }
let identity = value as! SecIdentity
var leaf: SecCertificate?
guard SecIdentityCopyCertificate(identity, &leaf) == errSecSuccess, let leaf else { return .failure(.noKey) }
if let validity = validity(of: leaf) {
if now > validity.notAfter { return .failure(.expired) }
if now < validity.notBefore { return .failure(.notYetValid) }
}
let leafData = SecCertificateCopyData(leaf) as Data
let chain = (first[kSecImportItemCertChain as String] as? [SecCertificate] ?? []).filter {
SecCertificateCopyData($0) as Data != leafData
}
return .success((identity, chain))
}
// MARK: Keeping it
/// Keeps the identity for this host and port, replacing any other.
static func save(_ identity: SecIdentity, chain: [SecCertificate], host: String, port: Int) -> Bool {
remove()
let query: [String: Any] = [
kSecValueRef as String: identity,
kSecAttrLabel as String: label,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
]
guard SecItemAdd(query as CFDictionary, nil) == errSecSuccess else { return false }
// The chain's intermediates go along so a proxy that wants them gets them.
let encoded = chain.map { SecCertificateCopyData($0) as Data }
UserDefaults.standard.set(encoded, forKey: chainKey)
UserDefaults.standard.set(host.lowercased(), forKey: hostKey)
UserDefaults.standard.set(port, forKey: portKey)
return true
}
private static let chainKey = "TrekClientIdentityChain"
static func remove() {
TrekClientCertWatch.reset()
for itemClass in [kSecClassIdentity, kSecClassCertificate, kSecClassKey] {
SecItemDelete([kSecClass as String: itemClass, kSecAttrLabel as String: label] as CFDictionary)
}
UserDefaults.standard.removeObject(forKey: hostKey)
UserDefaults.standard.removeObject(forKey: portKey)
UserDefaults.standard.removeObject(forKey: chainKey)
}
private static func storedIdentity() -> SecIdentity? {
var item: CFTypeRef?
let query: [String: Any] = [
kSecClass as String: kSecClassIdentity,
kSecAttrLabel as String: label,
kSecReturnRef as String: true,
]
guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let item else { return nil }
return (item as! SecIdentity)
}
/// Whether a request to host and port (0 or less for https' default) goes to the server the identity is for.
static func matches(host: String?, port: Int) -> Bool {
guard let host, let stored = UserDefaults.standard.string(forKey: hostKey) else { return false }
let storedPort = UserDefaults.standard.integer(forKey: portKey)
return host.lowercased() == stored && (port > 0 ? port : 443) == (storedPort > 0 ? storedPort : 443)
}
/// The credential for a server at host and port, or nil when the stored one is for another.
static func credential(forHost host: String, port: Int) -> URLCredential? {
guard matches(host: host, port: port), let identity = storedIdentity() else { return nil }
let chain = (UserDefaults.standard.array(forKey: chainKey) as? [Data] ?? []).compactMap {
SecCertificateCreateWithData(nil, $0 as CFData)
}
// Per session: a replaced certificate takes effect on the next connection.
return URLCredential(identity: identity, certificates: chain.isEmpty ? nil : chain, persistence: .forSession)
}
/// Answers a challenge if it asks for a client certificate; false leaves it to the caller.
static func answer(_ challenge: URLAuthenticationChallenge, _ completion: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Bool {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate else { return false }
let space = challenge.protectionSpace
let credential = credential(forHost: space.host, port: space.port)
noteRequest(host: space.host, port: space.port, served: credential != nil)
if let credential {
completion(.useCredential, credential)
} else {
// As a browser without a matching certificate: go on without one.
completion(.performDefaultHandling, nil)
}
return true
}
// MARK: What the settings show
static func info() -> [String: Any]? {
guard let host = UserDefaults.standard.string(forKey: hostKey), let identity = storedIdentity() else { return nil }
var leaf: SecCertificate?
guard SecIdentityCopyCertificate(identity, &leaf) == errSecSuccess, let leaf else { return nil }
let port = UserDefaults.standard.integer(forKey: portKey)
var result: [String: Any] = [
"host": host,
"port": port > 0 ? port : 443,
"subject": SecCertificateCopySubjectSummary(leaf) as String? ?? "",
"issuer": issuerName(of: leaf) ?? "",
]
if let validity = validity(of: leaf) { result["notAfter"] = Int(validity.notAfter.timeIntervalSince1970 * 1000) }
return result
}
// MARK: Certificate fields
/// notBefore and notAfter from the DER: iOS has no public API for them.
static func validity(of certificate: SecCertificate) -> (notBefore: Date, notAfter: Date)? {
DER.validity(SecCertificateCopyData(certificate) as Data)
}
private static func issuerName(of certificate: SecCertificate) -> String? {
DER.issuerCommonName(SecCertificateCopyData(certificate) as Data)
}
/// Just enough DER to read an X.509 certificate's validity and a name's CN.
enum DER {
private struct Node {
let tag: UInt8
let body: Range<Int>
let end: Int
}
private static func node(_ bytes: [UInt8], at offset: Int) -> Node? {
guard offset + 2 <= bytes.count else { return nil }
let tag = bytes[offset]
var length = Int(bytes[offset + 1])
var start = offset + 2
if length & 0x80 != 0 {
let count = length & 0x7f
guard count > 0, count <= 4, start + count <= bytes.count else { return nil }
length = bytes[start..<start + count].reduce(0) { $0 << 8 | Int($1) }
start += count
}
guard start + length <= bytes.count else { return nil }
return Node(tag: tag, body: start..<start + length, end: start + length)
}
private static func children(_ bytes: [UInt8], in range: Range<Int>) -> [Node] {
var result: [Node] = []
var offset = range.lowerBound
while offset < range.upperBound, let child = node(bytes, at: offset) {
result.append(child)
offset = child.end
}
return result
}
/// The fields of the TBSCertificate after the version: serial, signature algorithm, issuer, validity, ...
private static func tbsFields(_ bytes: [UInt8]) -> [Node]? {
guard let certificate = node(bytes, at: 0), let tbs = children(bytes, in: certificate.body).first else { return nil }
var fields = children(bytes, in: tbs.body)
if fields.first?.tag == 0xa0 { fields.removeFirst() }
return fields.count > 3 ? fields : nil
}
static func validity(_ data: Data) -> (notBefore: Date, notAfter: Date)? {
let bytes = [UInt8](data)
guard let fields = tbsFields(bytes) else { return nil }
let times = children(bytes, in: fields[3].body)
guard times.count == 2, let from = time(bytes, times[0]), let to = time(bytes, times[1]) else { return nil }
return (from, to)
}
private static func time(_ bytes: [UInt8], _ node: Node) -> Date? {
guard let text = String(bytes: bytes[node.body], encoding: .ascii) else { return nil }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = node.tag == 0x17 ? "yyMMddHHmmss'Z'" : "yyyyMMddHHmmss'Z'"
return formatter.date(from: text)
}
/// The CN of the issuer's Name (a SEQUENCE of SETs of type and value), or nil.
static func issuerCommonName(_ data: Data) -> String? {
let bytes = [UInt8](data)
guard let fields = tbsFields(bytes) else { return nil }
for set in children(bytes, in: fields[2].body) {
for pair in children(bytes, in: set.body) {
let parts = children(bytes, in: pair.body)
guard parts.count == 2, Array(bytes[parts[0].body]) == [0x55, 0x04, 0x03] else { continue }
return String(bytes: bytes[parts[1].body], encoding: .utf8)
}
}
return nil
}
}
}
/// Notices when the user's server stops letting the app in for want of a
/// client certificate (one removed, expired, or no longer trusted). The page can
/// still be the stored offline copy while every request fails, so when the server
/// asks for a certificate the app checks once natively whether TREK answers with
/// what it holds. Only a check that fails at the certificate (the handshake broke
/// off, or the proxy's own 4xx) calls `onRefused`; a server that merely asks and
/// lets everyone in answers TREK's 200. At most once a minute.
enum TrekClientCertWatch {
private static let lock = NSLock()
private static var lastCheck = Date.distantPast
/// A new or removed certificate is worth a check of its own, whenever the last one ran.
static func reset() {
lock.lock(); defer { lock.unlock() }
lastCheck = .distantPast
}
static func serverAsked(host: String, port: Int, onRefused: @escaping () -> Void) {
guard let raw = TrekServerStore.url, let server = URL(string: raw), server.scheme == "https",
server.host?.lowercased() == host.lowercased(), (server.port ?? 443) == (port > 0 ? port : 443),
let features = URL(string: raw.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/api/health/features") else { return }
lock.lock()
let due = Date().timeIntervalSince(lastCheck) >= 60
if due { lastCheck = Date() }
lock.unlock()
guard due else { return }
var request = URLRequest(url: features, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 8)
request.setValue("application/json", forHTTPHeaderField: "Accept")
var task: URLSessionDataTask?
task = TrekClientCertSessionDelegate.session.dataTask(with: request) { _, response, _ in
let asked = task.flatMap { TrekClientCertSessionDelegate.shared.ask(for: $0) } != nil
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
if asked && (status == 0 || (400..<500).contains(status)) {
DispatchQueue.main.async(execute: onRefused)
}
}
task?.resume()
}
}
/// A URLSession delegate for the app's own requests to the user's server: it
/// shows the client certificate where the server asks for it and notes the ask.
final class TrekClientCertSessionDelegate: NSObject, URLSessionTaskDelegate {
static let shared = TrekClientCertSessionDelegate()
/// The app's session for the user's server (offline copy, watch, address check).
static let session = URLSession(configuration: .default, delegate: shared, delegateQueue: nil)
/// Per task: whether the server asked, and whether it got a certificate (address check only).
private let lock = NSLock()
private var asks: [Int: Bool] = [:]
func ask(for task: URLSessionTask) -> Bool? {
lock.lock(); defer { lock.unlock() }
return asks.removeValue(forKey: task.taskIdentifier)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let handled = TrekClientIdentity.answer(challenge) { disposition, credential in
self.lock.lock()
self.asks[task.taskIdentifier] = credential != nil
self.lock.unlock()
completionHandler(disposition, credential)
}
if !handled { completionHandler(.performDefaultHandling, nil) }
}
}
/// The file picker and password prompt of an import, in the UI's words.
final class TrekClientCertImporter: NSObject, UIDocumentPickerDelegate {
private let presenter: UIViewController
private let labels: [String: String]
private let host: String
private let port: Int
private let done: ([String: Any]) -> Void
private var keepAlive: TrekClientCertImporter?
init(presenter: UIViewController, labels: [String: String], host: String, port: Int, done: @escaping ([String: Any]) -> Void) {
self.presenter = presenter
self.labels = labels
self.host = host
self.port = port
self.done = done
}
func start() {
keepAlive = self
let types = [UTType(filenameExtension: "p12"), UTType(filenameExtension: "pfx"), UTType("com.rsa.pkcs-12")].compactMap { $0 }
let picker = UIDocumentPickerViewController(forOpeningContentTypes: types.isEmpty ? [.data] : types, asCopy: true)
picker.delegate = self
presenter.present(picker, animated: true)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
finish(["result": "cancelled"])
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first,
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
(attributes[.size] as? Int ?? 0) <= 256 * 1024,
let data = try? Data(contentsOf: url) else {
finish(["result": "failed", "failure": TrekClientIdentity.Failure.format.rawValue])
return
}
try? FileManager.default.removeItem(at: url)
askPassword(for: data, wrong: false)
}
private func askPassword(for data: Data, wrong: Bool) {
let alert = UIAlertController(title: labels["title"], message: wrong ? labels["wrongPassword"] : labels["message"], preferredStyle: .alert)
alert.addTextField { field in
field.isSecureTextEntry = true
field.placeholder = self.labels["placeholder"]
field.textContentType = .password
}
alert.addAction(UIAlertAction(title: labels["cancel"] ?? "Cancel", style: .cancel) { _ in
self.finish(["result": "cancelled"])
})
alert.addAction(UIAlertAction(title: labels["ok"] ?? "OK", style: .default) { _ in
self.open(data, password: alert.textFields?.first?.text ?? "")
})
presenter.present(alert, animated: true)
}
private func open(_ data: Data, password: String) {
switch TrekClientIdentity.read(data, password: password) {
case .failure(.password):
askPassword(for: data, wrong: true)
case .failure(let failure):
finish(["result": "failed", "failure": failure.rawValue])
case .success(let (identity, chain)):
guard TrekClientIdentity.save(identity, chain: chain, host: host, port: port) else {
finish(["result": "failed", "failure": TrekClientIdentity.Failure.store.rawValue])
return
}
var result: [String: Any] = ["result": "imported"]
if let info = TrekClientIdentity.info() { result["certificate"] = info }
finish(result)
}
}
private func finish(_ result: [String: Any]) {
done(result)
keepAlive = nil
}
}
+312 -10
View File
@@ -11,6 +11,7 @@ import ActivityKit
#endif
import LocalAuthentication
import PassKit
import QuickLook
import UIKit
import WebKit
@@ -45,10 +46,18 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
CAPPluginMethod(name: "storePurchase", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeFinish", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeRestore", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeHeld", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "addToWallet", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setWatchSnapshot", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "takeWatchActions", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setKeyCommands", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setQuickActions", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "takeQuickAction", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "requestServer", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "clientCertificate", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "importClientCertificate", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "removeClientCertificate", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "previewFile", returnType: CAPPluginReturnPromise),
]
/// What this binary offers the server's UI, raised with every native feature
@@ -60,7 +69,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
/// builds a snapshot for nothing; "wallet" only where Wallet can take a pass (an
/// iPhone: an iPad has no Wallet app), so the UI offers no button that does nothing.
static var features: [String] {
var names = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "keyCommands"]
var names = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "keyCommands", "quickActions", "appLinks", "clientCertificate", "filePreview"]
if canAddWalletPasses { names.append("wallet") }
if TrekWatchLink.isAvailable { names.append("watch") }
return names
@@ -85,6 +94,32 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
TrekKeyCommands.onPress = { [weak self] id in
self?.notifyListeners("keyCommand", data: ["id": id])
}
// Kept until a listener takes it: a tap while the page reloads reaches the new page.
TrekQuickActions.onOpen = { [weak self] path in
DispatchQueue.main.async { self?.notifyListeners("quickAction", data: ["path": path], retainUntilConsumed: true) }
}
}
// MARK: - Quick actions on the app icon
/// The app icon's quick actions, in the UI's language (TrekQuickActions).
@objc func setQuickActions(_ call: CAPPluginCall) {
let items = (call.getArray("items", JSObject.self) ?? []).compactMap { TrekQuickActions.Item(raw: $0) }
DispatchQueue.main.async {
TrekQuickActions.set(items)
call.resolve()
}
}
/// The quick action the app was launched with, before the UI was there to hear of it.
@objc func takeQuickAction(_ call: CAPPluginCall) {
DispatchQueue.main.async {
if let path = TrekQuickActions.take() {
call.resolve(["path": path])
} else {
call.resolve(["path": NSNull()])
}
}
}
// MARK: - Hardware keyboard
@@ -139,7 +174,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
nextName: nextName,
nextTime: call.getString("nextTime"),
done: call.getInt("done") ?? 0,
total: call.getInt("total") ?? 0
total: call.getInt("total") ?? 0,
flight: TrekShellPlugin.activityFlight(call.getObject("flight"))
)
// Stale at the end of the day, so a forgotten one fades out on its own.
let stale = Calendar.current.startOfDay(for: Date().addingTimeInterval(86_400))
@@ -159,6 +195,19 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
call.resolve(["running": false])
}
/// The day's flight the UI sent along (native/widgets.ts tripDayState), when complete.
@available(iOS 16.1, *)
static func activityFlight(_ raw: JSObject?) -> TripDayAttributes.Flight? {
guard let raw, let number = raw["number"] as? String, let from = raw["from"] as? String, let to = raw["to"] as? String,
let dep = (raw["dep"] as? NSNumber)?.doubleValue, let arr = (raw["arr"] as? NSNumber)?.doubleValue, arr > dep,
let depTime = raw["depTime"] as? String, let arrTime = raw["arrTime"] as? String else { return nil }
return TripDayAttributes.Flight(
number: number, from: from, to: to, dep: dep, arr: arr, depTime: depTime, arrTime: arrTime,
delay: (raw["delay"] as? NSNumber)?.intValue,
airborne: (raw["airborne"] as? Bool) ?? false
)
}
@objc func endTripDay(_ call: CAPPluginCall) {
#if canImport(ActivityKit)
if #available(iOS 16.2, *) {
@@ -315,7 +364,11 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
private var authSession: ASWebAuthenticationSession?
@objc func getServer(_ call: CAPPluginCall) {
call.resolve(["url": TrekServerStore.url ?? NSNull()])
call.resolve([
"url": TrekServerStore.url ?? NSNull(),
"previousUrl": TrekServerStore.previousURL ?? NSNull(),
"failure": TrekServerStore.takeFailure() ?? NSNull(),
])
}
@objc func setServer(_ call: CAPPluginCall) {
@@ -324,6 +377,14 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
return
}
TrekServerStore.url = raw
let labels = (call.getObject("labels") ?? [:]).compactMapValues { $0 as? String }
if !labels.isEmpty { TrekServerStore.labels = labels }
// After the URL: setting it clears the hosts of the server before.
let hosts = (call.getArray("signInHosts", String.self) ?? []).filter { $0.range(of: "^[A-Za-z0-9.-]+(:[0-9]+)?$", options: .regularExpression) != nil }
TrekServerStore.signInHosts = Set(hosts.map { $0.lowercased() })
// A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page.
let welcome = call.getString("welcome") ?? ""
TrekServerStore.pendingWelcome = welcome.range(of: "^[A-Za-z0-9_-]{43}$", options: .regularExpression) != nil ? welcome : nil
call.resolve()
restartBridge()
}
@@ -396,7 +457,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
}
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
request.setValue("text/html", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) { data, response, _ in
// The app's session, so a server behind mutual TLS gets the client certificate.
TrekClientCertSessionDelegate.session.dataTask(with: request) { data, response, _ in
guard let data, let http = response as? HTTPURLResponse, http.statusCode == 200,
http.value(forHTTPHeaderField: "Content-Type")?.hasPrefix("text/html") == true,
TrekServerStore.url == raw else {
@@ -415,6 +477,18 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
}
@objc func openOfflineCopy(_ call: CAPPluginCall) {
// The server an update asked to check again, out of reach: back to it on
// its copy. The new bridge loads the server, fails, and this screen comes
// back with the server set, which then opens the copy below.
if TrekServerStore.url == nil {
if TrekServerStore.restoreForOffline() {
call.resolve(["opened": true])
restartBridge()
} else {
call.resolve(["opened": false])
}
return
}
// With the trailing slash, like the bridge's serverURL: Capacitor only
// keeps a navigation in the app when it starts with that exact string,
// and hands anything else to Safari.
@@ -435,8 +509,123 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
}
}
// MARK: - Client certificates (mutual TLS)
extension TrekShellPlugin {
/// The address screen's check of a server, made natively so it notices
/// whether the server asks for a client certificate and can show the stored
/// one. A failed connection resolves with status 0 instead of rejecting.
@objc func requestServer(_ call: CAPPluginCall) {
guard let raw = call.getString("url"), let url = URL(string: raw),
["https", "http"].contains(url.scheme?.lowercased() ?? ""), url.host != nil else {
call.reject("A http(s) URL is required")
return
}
let timeout = min(max(Double(call.getInt("timeoutMs") ?? 10000), 1000), 30000) / 1000
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.setValue("application/json, text/html;q=0.9, */*;q=0.8", forHTTPHeaderField: "Accept")
let delegate = TrekClientCertSessionDelegate.shared
var task: URLSessionDataTask?
task = TrekClientCertSessionDelegate.session.dataTask(with: request) { data, response, error in
let asked = task.flatMap { delegate.ask(for: $0) }
var result: [String: Any] = [
"certRequested": asked != nil,
"certSent": asked == true,
"url": response?.url?.absoluteString ?? raw,
]
if asked != nil, let host = url.host?.lowercased() { result["certHost"] = "\(host):\(url.port ?? 443)" }
if let http = response as? HTTPURLResponse {
result["status"] = http.statusCode
let body = (data ?? Data()).prefix(512 * 1024)
result["data"] = String(data: body, encoding: .utf8) ?? ""
var headers: [String: String] = [:]
for (name, value) in http.allHeaderFields {
if let name = name as? String, let value = value as? String { headers[name] = value }
}
result["headers"] = headers
} else {
result["status"] = 0
result["data"] = ""
if let error { result["error"] = (error as NSError).domain + ":" + String((error as NSError).code) }
}
call.resolve(result)
}
task?.resume()
}
/// The stored client certificate's details, and the last server that asked for one.
@objc func clientCertificate(_ call: CAPPluginCall) {
var result: [String: Any] = [:]
if let info = TrekClientIdentity.info() { result["certificate"] = info } else { result["certificate"] = NSNull() }
if let asked = TrekClientIdentity.lastRequest {
result["request"] = ["host": asked.host, "port": asked.port, "served": asked.served]
}
call.resolve(result)
}
@objc func removeClientCertificate(_ call: CAPPluginCall) {
TrekClientIdentity.remove()
call.resolve()
}
/// Picks a .p12/.pfx file, asks for its password until it opens or the user
/// gives up, and keeps it for the server at host and port.
@objc func importClientCertificate(_ call: CAPPluginCall) {
guard let host = call.getString("host"), host.range(of: "^[A-Za-z0-9.-]+$", options: .regularExpression) != nil else {
call.reject("A host is required")
return
}
let port = call.getInt("port") ?? 443
let labels = (call.getObject("labels") ?? [:]).compactMapValues { $0 as? String }
DispatchQueue.main.async { [weak self] in
guard let presenter = self?.bridge?.viewController else {
call.resolve(["result": "failed", "failure": TrekClientIdentity.Failure.store.rawValue])
return
}
TrekClientCertImporter(presenter: presenter, labels: labels, host: host, port: port) { result in
call.resolve(result)
}.start()
}
}
}
/// Positions and errors for the UI, shaped like the Geolocation API's, with the
/// When-In-Use permission asked the first time.
// MARK: - Quick Look
extension TrekShellPlugin {
/// Kept while Quick Look shows a file: the controller holds its data source weakly.
/// One preview at a time, so a static: an extension cannot store per instance.
private static var previewSource: TrekFilePreviewSource?
/// Shows a file the UI wrote to the cache in Quick Look: a PDF to page through,
/// an image, a document, with the system's own share button. "unsupported" for
/// a file Quick Look cannot show, which the UI then hands to the share sheet.
@objc func previewFile(_ call: CAPPluginCall) {
guard let path = call.getString("path"), let url = URL(string: path), url.isFileURL,
FileManager.default.fileExists(atPath: url.path) else {
call.reject("a file in the app's cache is required", "INVALID")
return
}
DispatchQueue.main.async { [weak self] in
guard let self, let presenter = self.bridge?.viewController else {
call.reject("nothing to show the preview from", "UNAVAILABLE")
return
}
guard QLPreviewController.canPreview(url as QLPreviewItem) else {
call.resolve(["result": "unsupported"])
return
}
let source = TrekFilePreviewSource(url: url, title: call.getString("title"))
TrekShellPlugin.previewSource = source
let preview = QLPreviewController()
preview.dataSource = source
presenter.present(preview, animated: true)
call.resolve(["result": "shown"])
}
}
}
// MARK: - Apple Wallet
extension TrekShellPlugin {
@@ -497,9 +686,8 @@ extension TrekShellPlugin {
/// know are left out, so the shell offers only what can really be bought.
@objc func storeProducts(_ call: CAPPluginCall) {
let ids = call.getArray("ids", String.self) ?? []
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
Task {
let sandbox = await Self.buysInSandbox()
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
call.resolve(["products": [], "sandbox": sandbox])
return
@@ -508,6 +696,26 @@ extension TrekShellPlugin {
}
}
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
/// The signed app transaction names its environment; the receipt's file name,
/// which App Review builds do not always carry, is only the fallback where the
/// app transaction is missing (iOS 15) or cannot be read.
static func buysInSandbox() async -> Bool {
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
return receiptSaysSandbox
}
// An unverified transaction still names the environment it was signed in;
// it only decides whether the button shows, the cloud checks every purchase itself.
let transaction: AppTransaction
switch result {
case .verified(let signed), .unverified(let signed, _):
transaction = signed
}
return transaction.environment != .production || receiptSaysSandbox
}
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
/// bought (with the signed transaction the control plane verifies), cancelled,
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
@@ -519,6 +727,17 @@ extension TrekShellPlugin {
return
}
Task {
// One subscription per Apple ID: another plan would change it, not add one.
// A held one that was delivered stops the purchase here. One that was paid
// but never set up is handed back as bought, so its instance is set up now.
if let held = await TrekStore.currentEntitlement(prefix: "cloud.") {
if await TrekStore.awaitingSetup(held) {
call.resolve(["kind": "bought", "jws": held.jws, "transactionId": String(held.id), "productId": held.productId])
} else {
call.resolve(["kind": "subscribed"])
}
return
}
do {
guard let product = try await Product.products(for: [id]).first else {
call.resolve(["kind": "failed"])
@@ -575,6 +794,21 @@ extension TrekShellPlugin {
call.resolve(["jws": found.jws, "transactionId": String(found.id)])
}
}
/// Feature storeKit: whether this Apple ID holds a delivered subscription under
/// `prefix`. Read from the entitlements on the device, so no password is asked;
/// while one runs, the shell offers no purchase.
@objc func storeHeld(_ call: CAPPluginCall) {
let prefix = call.getString("prefix") ?? "cloud."
Task {
guard let held = await TrekStore.currentEntitlement(prefix: prefix) else {
call.resolve(["held": false])
return
}
let awaiting = await TrekStore.awaitingSetup(held)
call.resolve(["held": !awaiting])
}
}
}
enum TrekStore {
@@ -605,17 +839,62 @@ enum TrekStore {
}
}
static func currentEntitlement(prefix: String) async -> (jws: String, id: UInt64)? {
var newest: (date: Date, jws: String, id: UInt64)?
typealias Held = (jws: String, id: UInt64, productId: String, firstPurchase: Bool)
/// The subscription this Apple ID holds under `prefix`, newest first. The
/// entitlements on the device come first; on a fresh install they can still
/// be empty while the subscription runs, so the status of the subscription
/// group, which StoreKit asks the App Store for, decides then.
static func currentEntitlement(prefix: String) async -> Held? {
var newest: (date: Date, held: Held)?
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result,
transaction.productID.hasPrefix(prefix),
transaction.revocationDate == nil else { continue }
if newest == nil || transaction.purchaseDate > newest!.date {
newest = (transaction.purchaseDate, result.jwsRepresentation, transaction.id)
newest = (transaction.purchaseDate, held(result.jwsRepresentation, transaction))
}
}
return newest.map { ($0.jws, $0.id) }
if let newest { return newest.held }
return await subscriptionGroupHeld(prefix: prefix)
}
/// The plans the control plane sells (`cloud.<plan>.<monthly|yearly>`, as
/// productIdFor in iap.ts); one of them is enough to find their group.
private static let plans = ["start", "basis", "plus", "pro"]
private static func subscriptionGroupHeld(prefix: String) async -> Held? {
let ids = plans.flatMap { ["\(prefix)\($0).monthly", "\(prefix)\($0).yearly"] }
guard let products = try? await Product.products(for: ids),
let group = products.compactMap({ $0.subscription?.subscriptionGroupID }).first,
let statuses = try? await Product.SubscriptionInfo.status(for: group) else { return nil }
let running: [Product.SubscriptionInfo.RenewalState] = [.subscribed, .inGracePeriod, .inBillingRetryPeriod]
for status in statuses where running.contains(status.state) {
if case .verified(let transaction) = status.transaction, transaction.revocationDate == nil {
return held(status.transaction.jwsRepresentation, transaction)
}
}
return nil
}
private static func held(_ jws: String, _ transaction: Transaction) -> Held {
(jws: jws, id: transaction.id, productId: transaction.productID, firstPurchase: transaction.originalID == transaction.id)
}
/// A first purchase that was paid but whose instance was never set up: handed
/// back as bought so it is set up now. A renewal the device has not finished
/// yet is no such purchase; its subscription is running and counts as held.
static func awaitingSetup(_ held: Held) async -> Bool {
guard held.firstPurchase else { return false }
return await isUnfinished(held.id)
}
/// Paid but not delivered yet: the shell finishes a transaction once its instance exists.
static func isUnfinished(_ id: UInt64) async -> Bool {
for await result in Transaction.unfinished {
if case .verified(let transaction) = result, transaction.id == id { return true }
}
return false
}
}
@@ -839,3 +1118,26 @@ enum TrekSharedKeychain {
return SecItemAdd(q as CFDictionary, nil) == errSecSuccess
}
}
/// The one file Quick Look shows, under the name the user knows it by.
final class TrekFilePreviewSource: NSObject, QLPreviewControllerDataSource {
private let item: Item
init(url: URL, title: String?) {
item = Item(url: url, title: title)
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { item }
final class Item: NSObject, QLPreviewItem {
let previewItemURL: URL?
let previewItemTitle: String?
init(url: URL, title: String?) {
previewItemURL = url
previewItemTitle = title
}
}
}
+1 -1
View File
@@ -237,7 +237,7 @@ enum TrekWatchWriter {
for (field, value) in HTTPCookie.requestHeaderFields(with: session) {
signed.setValue(value, forHTTPHeaderField: field)
}
URLSession.shared.dataTask(with: signed) { data, response, error in
TrekClientCertSessionDelegate.session.dataTask(with: signed) { data, response, error in
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
completion(data, error == nil && (200..<300).contains(status))
}.resume()
+4
View File
@@ -12,7 +12,9 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.5.2"),
.package(name: "CapacitorActionSheet", path: "../../../../node_modules/@capacitor/action-sheet"),
.package(name: "CapacitorApp", path: "../../../../node_modules/@capacitor/app"),
.package(name: "CapacitorDialog", path: "../../../../node_modules/@capacitor/dialog"),
.package(name: "CapacitorFilesystem", path: "../../../../node_modules/@capacitor/filesystem"),
.package(name: "CapacitorHaptics", path: "../../../../node_modules/@capacitor/haptics"),
.package(name: "CapacitorKeyboard", path: "../../../../node_modules/@capacitor/keyboard"),
@@ -26,7 +28,9 @@ let package = Package(
dependencies: [
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Cordova", package: "capacitor-swift-pm"),
.product(name: "CapacitorActionSheet", package: "CapacitorActionSheet"),
.product(name: "CapacitorApp", package: "CapacitorApp"),
.product(name: "CapacitorDialog", package: "CapacitorDialog"),
.product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"),
.product(name: "CapacitorHaptics", package: "CapacitorHaptics"),
.product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"),
Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 49 KiB

@@ -0,0 +1,266 @@
import SwiftUI
/// The trip's next flight, or the one in the air: both airports large, the
/// route as an arc with the aircraft riding it, the moment in words with a
/// countdown the system keeps running, and the delay. Between two snapshots
/// the widget moves on with the clock: it takes off at the observed (or
/// planned) time, flies along the arc and lands at the expected (or planned)
/// arrival.
struct FlightContent: View {
let snapshot: WidgetSnapshot?
let family: TrekFamily
let now: Date
@Environment(\.colorScheme) private var scheme
private let accent = Trek.booking("flight").color
var body: some View {
if let flight = snapshot?.flight, let labels = snapshot?.labels {
let moment = FlightMoment(flight, now: now)
switch family {
case .circular: circular(flight, moment)
case .rectangular: rectangular(flight, moment, labels)
case .inline: inline(flight, moment, labels)
case .small: small(flight, moment, labels)
case .medium: medium(flight, moment, labels)
default: large(flight, moment, labels)
}
} else {
empty(snapshot?.labels)
}
}
// MARK: Small: the moment above, the route below
private func small(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 6) {
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(accent)
Text(f.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(Trek.ink(scheme)).lineLimit(1)
Spacer(minLength: 0)
delayChip(f, labels, compact: true)
}
Spacer(minLength: 0)
momentText(f, m, labels)
.font(.system(size: 13, weight: .bold))
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
.lineLimit(2)
.minimumScaleFactor(0.85)
Spacer(minLength: 6)
HStack(alignment: .firstTextBaseline) {
Text(f.from).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
Spacer(minLength: 2)
Text(f.to).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
}
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 20).padding(.vertical, 3)
HStack {
Text(f.depTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
Spacer(minLength: 2)
Text(f.arrTimeExpected ?? f.arrTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
}
}
}
// MARK: Medium: a boarding pass
private func medium(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 7) {
Text(labels.flight ?? "").trekEyebrow(scheme)
Text(f.number).font(.system(size: 11, weight: .heavy)).foregroundStyle(accent)
Spacer(minLength: 4)
delayChip(f, labels, compact: false)
}
Spacer(minLength: 4)
HStack(alignment: .center, spacing: 10) {
airport(f.from, f.fromCity, time: f.depTime, planned: nil, align: .leading)
VStack(spacing: 4) {
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 30)
progressBar(m)
}
.frame(maxWidth: .infinity)
airport(f.to, f.toCity, time: f.arrTimeExpected ?? f.arrTime, planned: f.arrTimeExpected.flatMap { $0 == f.arrTime ? nil : f.arrTime }, align: .trailing)
}
Spacer(minLength: 6)
momentText(f, m, labels)
.font(.system(size: 13, weight: .bold))
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
.lineLimit(1)
.minimumScaleFactor(0.85)
}
}
// MARK: Large and extra large: the pass with the details under it
private func large(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 12) {
medium(f, m, labels).frame(maxHeight: 150)
Rectangle().fill(Trek.track(scheme)).frame(height: 0.8)
LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) {
if let aircraft = f.aircraft { detail(systemImage: "airplane.circle", value: aircraft) }
detail(systemImage: "clock", value: "\(f.depTime) → \(f.arrTimeExpected ?? f.arrTime)")
if let fromCity = f.fromCity { detail(systemImage: "airplane.departure", value: fromCity) }
if let toCity = f.toCity { detail(systemImage: "airplane.arrival", value: toCity) }
}
Spacer(minLength: 0)
}
}
// MARK: Lock screen
private func circular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment) -> some View {
ProgressRing(value: m.progress, lineWidth: 5, colors: [.white], trackColor: Color.white.opacity(0.25)) {
Image(systemName: m.stage == .landed ? "airplane.arrival" : m.stage == .airborne ? "airplane" : "airplane.departure")
.font(.system(size: 17, weight: .bold))
}
.padding(4)
}
private func rectangular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
Image(systemName: "airplane").font(.system(size: 11, weight: .bold))
Text("\(f.number) \(f.from) → \(f.to)").font(.system(size: 12, weight: .heavy)).lineLimit(1)
}
momentText(f, m, labels).font(.system(size: 13, weight: .semibold)).lineLimit(1)
if m.stage == .airborne {
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
private func inline(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
Text("\(Image(systemName: "airplane")) \(f.number) ") + momentText(f, m, labels)
}
// MARK: Parts
private func airport(_ code: String, _ city: String?, time: String, planned: String?, align: HorizontalAlignment) -> some View {
VStack(alignment: align, spacing: 1) {
Text(code).font(Trek.number(28, .heavy)).foregroundStyle(Trek.ink(scheme))
if let city { Text(city).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Trek.faint(scheme)).lineLimit(1) }
if let planned { Text(planned).font(Trek.number(10.5, .bold)).strikethrough().foregroundStyle(Trek.faint(scheme)) }
Text(time).font(Trek.number(14, .heavy)).foregroundStyle(Trek.ink(scheme))
}
.frame(maxWidth: 96, alignment: align == .leading ? .leading : .trailing)
}
@ViewBuilder
private func progressBar(_ m: FlightMoment) -> some View {
if m.stage == .airborne {
// The system runs this bar on its own, so it fills between two snapshots too.
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
.tint(accent)
} else {
Capsule().fill(m.stage == .landed ? accent : Trek.track(scheme)).frame(height: 4)
}
}
private func detail(systemImage: String, value: String) -> some View {
HStack(spacing: 6) {
Image(systemName: systemImage).font(.system(size: 12, weight: .semibold)).foregroundStyle(accent)
Text(value).font(.system(size: 12, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(1)
Spacer(minLength: 0)
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Trek.card(scheme)))
}
/// "Departs in 2 hr, 10 min", "Lands in 1 hr", "Landed": the countdowns are the system's own running text.
private func momentText(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> Text {
switch m.stage {
case .upcoming:
return Countdown.text(labels.flightDeparts ?? "{time}", until: m.start)
case .ready:
return Text(labels.flightReady ?? "")
case .airborne:
// "In the air" is what the blue line and the moving aircraft say; the words count down to landing.
return Countdown.text(labels.flightLands ?? "{time}", until: m.end)
case .landed:
return Text(labels.flightLanded ?? "")
}
}
@ViewBuilder
private func delayChip(_ f: WidgetSnapshot.Flight, _ labels: WidgetSnapshot.Labels, compact: Bool) -> some View {
if let delay = f.delay {
let late = delay > 5
let early = delay < -5
let color = late ? (delay >= 30 ? Trek.danger : Trek.pending) : Trek.confirmed
let text = late
? (labels.flightLate ?? "+{m}").replacingOccurrences(of: "{m}", with: "\(delay)")
: early ? (labels.flightEarly ?? "{m}").replacingOccurrences(of: "{m}", with: "\(-delay)") : (labels.flightOnTime ?? "")
if !(compact && !late) {
Text(text)
.font(.system(size: 10.5, weight: .heavy))
.foregroundStyle(color)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Capsule().fill(color.opacity(scheme == .dark ? 0.22 : 0.14)))
.lineLimit(1)
}
}
}
private func empty(_ labels: WidgetSnapshot.Labels?) -> some View {
VStack(alignment: .leading, spacing: 6) {
Text(labels?.flight ?? "").trekEyebrow(scheme)
Spacer(minLength: 0)
Image(systemName: "airplane").font(.system(size: 30, weight: .bold)).foregroundStyle(accent.opacity(0.35))
Text(labels?.noFlight ?? labels?.noBookings ?? "").font(.system(size: 13, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(2)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
}
/// Where a flight stands at a given moment, from the snapshot's times. What the
/// feed saw wins: a flight still at the gate past its planned departure is not
/// flown along the arc, and a flight is only landed once confirmed. Only a
/// flight the feed never heard of moves on by its schedule alone.
struct FlightMoment {
enum Stage { case upcoming, ready, airborne, landed }
let stage: Stage
/// 0 at the gate, 1 at the destination.
let progress: Double
/// Take-off and touchdown the moment is measured between: observed or expected where known, planned otherwise.
let start: Date
let end: Date
init(_ f: WidgetSnapshot.Flight, now: Date) {
let start = Date(timeIntervalSince1970: f.depActual ?? f.depExpected ?? f.dep)
let end = max(Date(timeIntervalSince1970: f.arrExpected ?? f.arr), start.addingTimeInterval(60))
self.start = start
self.end = end
let heard = f.seen != nil
let flying = f.airborne == true || f.depActual != nil || (!heard && now >= start)
// A flight the feed lost stops counting two hours after its arrival.
if f.landed == true || (!heard && now >= end) || now >= end.addingTimeInterval(7200) {
stage = .landed
progress = 1
} else if flying {
stage = .airborne
// Unconfirmed, it never quite arrives on the arc.
progress = min(0.98, max(0, now.timeIntervalSince(start) / end.timeIntervalSince(start)))
} else if now >= start {
stage = .ready
progress = 0
} else {
stage = .upcoming
progress = 0
}
}
}
/// A sentence with "{time}" in it, the placeholder replaced by a countdown the system keeps running.
enum Countdown {
static func text(_ sentence: String, until date: Date) -> Text {
let parts = sentence.components(separatedBy: "{time}")
guard parts.count == 2 else { return Text(sentence) }
return Text(parts[0]) + Text(date, style: .relative) + Text(parts[1])
}
}
@@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider {
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
let stored = WidgetSnapshot.load()
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
completion(TrekEntry(date: Date(), snapshot: snapshot))
let now = Date()
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
}
/// An entry every quarter hour for the next six hours, so the now line and
/// the next stop move on without the app; the app reloads the timeline
/// whenever it writes a new snapshot.
/// the next stop move on without the app, each with the trip day of its own
/// date: the one at midnight turns to the next day. The app reloads the
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
completion(TrekProvider.timeline(WidgetSnapshot.load()))
}
@@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider {
let calendar = Calendar.current
let minute = calendar.component(.minute, from: now)
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
var entries = [TrekEntry(date: now, snapshot: snapshot)]
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
for step in 0..<24 {
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
}
}
return Timeline(entries: entries, policy: .atEnd)
@@ -158,6 +161,30 @@ private struct BookingsFamilyView: View {
var body: some View { BookingsContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
}
// MARK: - Flight
struct FlightWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: "TripFlight", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.flight.flatMap { WidgetSnapshot.link($0.path) }) {
FlightFamilyView(entry: entry)
} background: {
TrekPaper()
}
}
.configurationDisplayName("widget.flight.name")
.description("widget.flight.description")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .accessoryCircular, .accessoryRectangular, .accessoryInline])
}
}
private struct FlightFamilyView: View {
@Environment(\.widgetFamily) private var family
let entry: TrekEntry
var body: some View { FlightContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
}
// MARK: - To-dos
struct TodosWidget: Widget {
@@ -1,7 +1,7 @@
import SwiftUI
import WidgetKit
/// The TREK widgets: the trip, today's plan, the bookings ahead, the to-dos,
/// The TREK widgets: the trip, today's plan, the bookings ahead, the next flight, the to-dos,
/// the packing list, the Atlas and the travel group on the home and lock
/// screen, and the travel day as a Live Activity.
@main
@@ -10,6 +10,7 @@ struct TREKWidgetsBundle: WidgetBundle {
NextTripWidget()
TodayWidget()
BookingsWidget()
FlightWidget()
TodosWidget()
PackingWidget()
AtlasWidget()
@@ -115,6 +115,29 @@ extension WidgetSnapshot {
poll: "Poll", votes: "votes", noMessages: "No messages yet", departure: "Departure"
)
)
// In the air on a running trip, two days ahead before one.
let departure = running ? now.addingTimeInterval(-4 * 3600) : now.addingTimeInterval(2 * 86_400 + 5 * 3600)
snapshot.flight = Flight(
number: "LH 716", from: "FRA", to: "HND", fromCity: "Frankfurt", toCity: "Tokyo Haneda",
dep: departure.timeIntervalSince1970, arr: departure.addingTimeInterval(12 * 3600 + 25 * 60).timeIntervalSince1970,
depActual: running ? departure.addingTimeInterval(18 * 60).timeIntervalSince1970 : nil,
depExpected: nil, airborne: running ? true : nil,
arrExpected: running ? departure.addingTimeInterval(12 * 3600 + 41 * 60).timeIntervalSince1970 : nil,
landed: nil, depTime: "13:05", arrTime: "08:30", arrTimeExpected: running ? "08:46" : nil,
delay: running ? 16 : nil, aircraft: running ? "A359 D-AIXA" : nil, seen: running ? now.timeIntervalSince1970 : nil,
path: "/trips/1?booking=1"
)
snapshot.labels.flight = "Flight"
snapshot.labels.flightDeparts = "Departs in {time}"
snapshot.labels.flightInAir = "In the air"
snapshot.labels.flightLands = "Lands in {time}"
snapshot.labels.flightLanded = "Landed"
snapshot.labels.flightOnTime = "On time"
snapshot.labels.flightLate = "+{m} min"
snapshot.labels.flightEarly = "{m} min early"
snapshot.labels.flightEstimated = "estimated"
snapshot.labels.flightReady = "Ready for departure"
snapshot.labels.noFlight = "No flight ahead"
snapshot.packing?.bags = [
.init(name: "Suitcase", color: "#4A7DDB", grams: 14_200, limit: 23_000, packed: 15, total: 19),
.init(name: "Daypack", color: "#2FA37A", grams: 4_100, limit: 8_000, packed: 8, total: 12),
@@ -174,6 +197,7 @@ extension WidgetSnapshot {
snapshot.packing = nil
snapshot.atlas = Atlas(count: 0, codes: [], recent: [], continents: [])
snapshot.collab = nil
snapshot.flight = nil
return snapshot
}
}
@@ -16,6 +16,27 @@ struct TripDayAttributes: ActivityAttributes {
/// Stops behind, out of the day's stops.
var done: Int
var total: Int
/// The day's flight while it is near or in the air, so the activity turns into
/// a boarding pass. Optional: a state written by an older app decodes without it.
var flight: Flight?
}
/// A flight the activity follows on its own between two updates: the system
/// runs the bar and the countdown from the two times.
struct Flight: Codable, Hashable {
var number: String
var from: String
var to: String
/// Take-off and touchdown, epoch seconds: observed or expected where known.
var dep: Double
var arr: Double
/// The clock at either airport, formatted by the app.
var depTime: String
var arrTime: String
/// Minutes late, for the colour of the arrival time.
var delay: Int?
/// In the air when the app last looked: the countdown runs to touchdown.
var airborne: Bool?
}
var tripTitle: String
@@ -7,11 +7,17 @@ import WidgetKit
struct TripDayLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: TripDayAttributes.self) { context in
TripDayBanner(
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
nextName: context.state.nextName, nextTime: context.state.nextTime,
done: context.state.done, total: context.state.total
)
Group {
if let flight = context.state.flight {
FlightBanner(flight: flight, tripTitle: context.attributes.tripTitle)
} else {
TripDayBanner(
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
nextName: context.state.nextName, nextTime: context.state.nextTime,
done: context.state.done, total: context.state.total
)
}
}
.activityBackgroundTint(Color(hex: 0x0C0C0F).opacity(0.92))
.activitySystemActionForegroundColor(.white)
.widgetURL(WidgetSnapshot.link(context.attributes.path))
@@ -33,17 +39,32 @@ struct TripDayLiveActivity: Widget {
}
}
DynamicIslandExpandedRegion(.bottom) {
VStack(alignment: .leading, spacing: 8) {
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
DayStopProgress(done: state.done, total: state.total)
if let flight = state.flight {
FlightPass(flight: flight).padding(.horizontal, 4)
} else {
VStack(alignment: .leading, spacing: 8) {
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
DayStopProgress(done: state.done, total: state.total)
}
.padding(.horizontal, 4)
}
.padding(.horizontal, 4)
}
} compactLeading: {
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
if let flight = state.flight {
HStack(spacing: 3) {
Image(systemName: "airplane").foregroundStyle(Trek.info)
Text(flight.to).font(Trek.number(13, .heavy))
}
} else {
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
}
} compactTrailing: {
Text(state.nextTime ?? "\(state.done)/\(state.total)")
.font(Trek.number(13, .heavy))
if let flight = state.flight {
FlightCountdown(flight: flight).font(Trek.number(13, .heavy)).frame(maxWidth: 64)
} else {
Text(state.nextTime ?? "\(state.done)/\(state.total)")
.font(Trek.number(13, .heavy))
}
} minimal: {
ZStack {
Circle().stroke(Color.white.opacity(0.25), lineWidth: 2.5)
@@ -59,3 +80,76 @@ struct TripDayLiveActivity: Widget {
}
}
}
/// The day's flight on the lock screen: both airports, the bar the system runs
/// from take-off to touchdown, and a countdown to whichever comes next.
struct FlightBanner: View {
let flight: TripDayAttributes.Flight
let tripTitle: String
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 6) {
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(Trek.info)
Text(flight.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(.white)
Text(tripTitle)
.font(.system(size: 11, weight: .bold))
.tracking(0.5)
.textCase(.uppercase)
.foregroundStyle(.white.opacity(0.55))
.lineLimit(1)
Spacer(minLength: 4)
FlightCountdown(flight: flight).font(Trek.number(15, .heavy)).foregroundStyle(.white)
}
FlightPass(flight: flight)
}
.padding(16)
}
}
/// The two airports with their times and the bar between them.
struct FlightPass: View {
let flight: TripDayAttributes.Flight
var body: some View {
let start = Date(timeIntervalSince1970: flight.dep)
let end = Date(timeIntervalSince1970: flight.arr)
let late = (flight.delay ?? 0) > 5
HStack(alignment: .center, spacing: 12) {
VStack(alignment: .leading, spacing: 0) {
Text(flight.from).font(Trek.number(26, .heavy)).foregroundStyle(.white)
Text(flight.depTime).font(Trek.number(13, .bold)).foregroundStyle(.white.opacity(0.7))
}
VStack(spacing: 4) {
Image(systemName: "airplane").font(.system(size: 13, weight: .bold)).foregroundStyle(Trek.info)
ProgressView(timerInterval: start...end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
.tint(Trek.info)
}
.frame(maxWidth: .infinity)
VStack(alignment: .trailing, spacing: 0) {
Text(flight.to).font(Trek.number(26, .heavy)).foregroundStyle(.white)
Text(flight.arrTime).font(Trek.number(13, .bold)).foregroundStyle(late ? Trek.pending : .white.opacity(0.7))
}
}
}
}
/// A running countdown, in the system's own format: to touchdown once the app saw
/// the aircraft in the air, to take-off before. The system runs it between two
/// updates; the stage changes with the app's next update after take-off.
struct FlightCountdown: View {
let flight: TripDayAttributes.Flight
var body: some View {
let start = Date(timeIntervalSince1970: flight.dep)
let end = Date(timeIntervalSince1970: flight.arr)
let flying = flight.airborne == true
let target = flying ? end : start
HStack(spacing: 3) {
Image(systemName: flying ? "airplane.arrival" : "airplane.departure")
Text(timerInterval: min(Date(), target)...target, countsDown: true)
.multilineTextAlignment(.trailing)
}
}
}
+2 -1
View File
@@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider {
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
return TrekEntry(date: Date(), snapshot: snapshot)
let now = Date()
return TrekEntry(date: now, snapshot: snapshot?.on(now))
}
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
@@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable {
}
struct Today: Codable {
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
var date: String?
var dayLabel: String
var stops: [Stop]
/// 1-based position of today in the trip.
@@ -160,6 +162,38 @@ struct WidgetSnapshot: Codable {
}
}
/// The trip's next flight or the one in the air, for the flight widget.
/// Times are epoch seconds, so the widget moves its countdown and its
/// aircraft on with the clock between two snapshots; the clock times at
/// either airport come formatted, the widget has no zone data.
struct Flight: Codable {
var number: String
var from: String
var to: String
var fromCity: String?
var toCity: String?
var dep: Double
var arr: Double
/// Observed take-off.
var depActual: Double?
/// Before take-off: the planned departure plus the delay seen so far.
var depExpected: Double?
/// The feed saw the aircraft in the air when the app last looked.
var airborne: Bool?
/// Touchdown once landed, else the estimate while in the air.
var arrExpected: Double?
var landed: Bool?
var depTime: String
var arrTime: String
var arrTimeExpected: String?
/// Minutes late against the schedule, negative when early.
var delay: Int?
var aircraft: String?
/// When the feed last heard the aircraft.
var seen: Double?
var path: String
}
struct Labels: Codable {
var nextTrip: String
var today: String
@@ -193,16 +227,36 @@ struct WidgetSnapshot: Codable {
var votes: String?
var noMessages: String?
var departure: String?
var flight: String?
/// Contains "{time}", where the widget puts its running countdown.
var flightDeparts: String?
var flightInAir: String?
/// Contains "{time}".
var flightLands: String?
var flightLanded: String?
var flightOnTime: String?
/// Contains "{m}".
var flightLate: String?
/// Contains "{m}".
var flightEarly: String?
var flightEstimated: String?
/// Past the departure time with the aircraft not yet in the air.
var flightReady: String?
var noFlight: String?
}
var trip: Trip?
var today: Today?
/// The trip's days from the day the app wrote this on, each with its date,
/// so the widget turns to the next day itself (see `on(_:)`).
var days: [Today]?
var weather: Weather?
var bookings: [Booking]?
var todos: Todos?
var packing: Packing?
var atlas: Atlas?
var collab: Collab?
var flight: Flight?
var labels: Labels
/// The dashboard's snapshot.
@@ -257,6 +311,26 @@ struct WidgetSnapshot: Codable {
return days + 1
}
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
/// none before or after the trip, and only the bookings from that date on.
/// The app writes its snapshot only while it runs, so without this a widget
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
/// snapshot from an app without `days` reads as it was written.
func on(_ date: Date) -> WidgetSnapshot {
guard let days, !days.isEmpty else { return self }
let key = WidgetSnapshot.key(date)
var snapshot = self
snapshot.today = days.first { $0.date == key }
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
return snapshot
}
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
static func key(_ date: Date) -> String {
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
let calendar = Calendar.current
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
@@ -5,6 +5,8 @@
"widget.today.description" = "خطة اليوم كخط زمني، مع الطقس والمحطة التالية.";
"widget.bookings.name" = "الحجوزات";
"widget.bookings.description" = "رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.";
"widget.flight.name" = "الرحلة";
"widget.flight.description" = "رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.";
"widget.todos.name" = "المهام";
"widget.todos.description" = "ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.";
"widget.packing.name" = "قائمة الأمتعة";
@@ -5,6 +5,8 @@
"widget.today.description" = "Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.";
"widget.bookings.name" = "Bronlar";
"widget.bookings.description" = "Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.";
"widget.flight.name" = "Uçuş";
"widget.flight.description" = "Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.";
"widget.todos.name" = "Tapşırıqlar";
"widget.todos.description" = "Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.";
"widget.packing.name" = "Yük siyahısı";
@@ -5,6 +5,8 @@
"widget.today.description" = "El pla del dia com a línia de temps, amb el temps i la propera parada.";
"widget.bookings.name" = "Reserves";
"widget.bookings.description" = "Els teus propers vols, trens, hotels i taules, i quan toquen.";
"widget.flight.name" = "Vol";
"widget.flight.description" = "El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.";
"widget.todos.name" = "Tasques";
"widget.todos.description" = "El que encara queda per al viatge i com va l'equipatge.";
"widget.packing.name" = "Equipatge";

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