Files
TREK/server/tests/unit/nest/platform.controller.test.ts
T
jubnl d7c4324afc chore(capacitor): base files for capacitor (#2020)
* chore(capacitor): base files for capacitor

* chore(capacitor): base plugins

* feat(auth): hand a browser sign-in over to the native app

The native apps show the server's own UI in a WebView, where neither SSO nor
passkeys can run. They sign in through the system browser instead and need a
way to carry that session back.

The app keeps a random verifier and sends only its sha256 into the browser.
Once signed in there, the browser trades that challenge for a one-time code
(cookie session only, so an API or MCP token cannot mint itself a browser
session), and the WebView redeems the code together with the verifier. The
code rides through a URL scheme any app could claim, so on its own it is
worthless; it is single use and good for a minute.

Also: /api/health/features reports nativeApp so the apps can refuse servers
that predate this, and hashed files under assets/ are served immutable,
which the iOS app needs to start offline without a service worker.

* feat(native): the apps load the server's own UI

The apps ship only an address screen now. Once a server is picked, the
native side points the WebView at it: TrekBridgeViewController on iOS and a
config copy with server.url on Android. The UI then comes from that server,
in the version it runs and on its own origin, so the session cookie,
uploads, /ws and plugins work exactly as in a browser and no app release
has to keep pace with the servers out there.

The address screen (native-shell/, built into native-dist/) probes
/api/health/features through native HTTP, tries https before http when no
scheme was typed, and refuses servers without the nativeApp flag. It also
serves as the error page when the remembered server does not load: retry,
change server, or on iOS the stored copy of the server's start page.

TrekShell is the app's own plugin for all of that: remember, change and
reload the server, sign in through ASWebAuthenticationSession or a Custom
Tab, and on iOS keep and open the offline copy of the start page, because
WKWebView runs no service worker for a domain the app does not list.

Plugins the frame does not use are gone (push, camera, geolocation,
calendar, file transfer, in-app browser and more): the WebView covers the
camera and location itself, and push needs a relay before it is worth
shipping. With them go the push entitlement, the calendar usage strings
and the Firebase bits. The iOS scheme falls back to capacitor://, since
Capacitor drops an iosScheme of https, and the arm64 capability replaces
armv7.

* feat(native): the UI knows when it runs inside the app

Everything the server's UI does differently inside the iOS and Android app
lives under src/native and is inert in a browser.

Sign-in: SSO and the passkey button go through the system browser
(signInThroughBrowser), because identity providers refuse embedded
browsers and WebAuthn needs a domain association no build can have for
every server. The browser end is the new /native-handoff page: it signs
the user in if needed and hands the session over only after an explicit
tap, so a link carrying somebody else's challenge cannot pass a session
on silently. The verifier is hashed with @noble/hashes because
crypto.subtle is missing on the plain-http servers many home networks
use. An OIDC-only install no longer bounces to the IdP inside the
WebView, and passkey management is hidden in the app.

Downloads: the WebView cannot save a blob, so downloadBlob, downloadFile
and openFile write to the app cache and open the share sheet. The eight
places that built their own download anchor now use downloadBlob, which
they should have anyway.

The rest: "Change server" on the login page and in the account settings,
the splash hides after the first frame, Android's back button walks
history before it leaves the app, the status bar follows the scheme, and
on iOS the start page is refreshed and every chunk of the build (listed
in the new asset-manifest.json) is pulled into WebKit's cache so the app
can start without network.

* ci(native): build the Android and iOS shells on every change to them

Compiles the Swift side on a macOS runner so nobody needs a Mac to know it
still builds, and leaves a debug APK on every run to install on a phone.
Unsigned: signing and store uploads need secrets fork PRs do not get.

* feat(native): offline vector maps in the iOS app

In a browser the service worker answers MapLibre from the gl-map-offline
cache that glPrefetcher fills for trips marked for offline. The iOS app has
no service worker, so nothing read that cache there and the map went blank
without network.

A trek-offline:// protocol takes the service worker's place. Inside the iOS
app the MapLibre style URL is rewritten to it, the handler rewrites every
https URL inside the style and its TileJSON the same way, and then serves
documents network first and tiles, glyphs and sprites cache first. Outside
the iOS app nothing changes. The default OpenFreeMap basemap is covered;
Mapbox GL has no protocol hook and stays online-only in the app, as does a
custom raster template, whose opaque responses only a service worker can
store.

* fix(native): keep the iOS offline copy inside the app

loadSimulatedRequest went to the server URL without its trailing slash, and
Capacitor keeps a navigation in the WebView only when it starts with the
bridge's serverURL, slash included. The offline start page would have
opened in Safari instead. Also covers the platform helpers and the
hand-off API module.

* feat(native): the small things that give a WebView away

- A short haptic tap on success, warning and error toasts, which is where
  every save and delete already reports. Info toasts stay silent.
- No "‹ › Done" strip above the iOS keyboard.
- No Safari preview when a link is long-pressed.
- The swipe from the left edge goes back on iOS, through the same history
  Android's back button walks.

* test(mobile): the backup-code download revokes its URL after the shared delay

The mobile twin of the AccountTab test still expected the object URL to be
revoked in the same tick. Since both screens download through downloadBlob,
the revoke happens after its 100 ms grace period.

* fix(native): remember the login by default inside the app

With the switch off the app got a session cookie, which dies with the app
process, so every time the phone unloaded TREK the user had to sign in
again. Found while running the Android build in the emulator.

* fix(native): no overscroll stretch on Android

The UI asks for no overscroll effect with overscroll-behavior: none on html,
and Chrome honours it. The Android WebView draws the stretch on its root
scroller natively, though, and it scales the whole view, so the top bar and
the bottom dock were pulled along with the page. Found in the emulator.

* fix(native): Android shows "server not reachable" instead of a blank page

Capacitor injects its bridge on Android only into the server's origin once
server.url is set, so the local error page it switches to when the server
does not load had no bridge. It could neither retry nor change the server
and stayed blank.

TrekWebViewClient now catches a failed page load (a network error, or a 5xx
from a proxy while TREK restarts) and the app starts over on the bundled
address screen, where the bridge is present and the screen offers exactly
those two choices. The server config no longer carries errorPath.

Two traps on the way, both found in the emulator: a restart during launch
has to be a fresh task, since recreate() leaves the system splash lying over
the new page; and a restart shows no launch splash at all, because the
splash plugin cannot take it down again when the page hides it early.

* feat(native): TREK's own app icon and launch screen, named just TREK

The shells still carried Capacitor's placeholder icon and splash, the blue
X on a grid. They now show the white TREK mark on a dark, slightly glassy
tile: a soft light from the top left and a sheen over the upper half, in
the app's launch colour #09090b. Android 12+ draws its launch screen on the
same colour instead of light grey.

scripts/generate-app-icons.mjs renders the sources into assets/ from
public/icons/icon-white.svg, and `npm run icons:app` turns them into every
size both platforms ask for through @capacitor/assets. The Android
foreground mark is sized for the adaptive icon's round mask.

The home screen label is TREK: the old "TREK - Plan your trips!" was cut
off under the icon, and the longer title belongs to the store listings.

* fix(native): new lint warnings and the MapLibre protocol type after the dev merge

Awaits that sat in loops in the native-auth tests run together, the hand-off hook marks its navigations as ignored, the native tests drop their non-null assertions, and the offline protocol answers with the data type MapLibre 6.15 expects.

* fix(native): strict types in the address screen, Prettier on the native-auth e2e suite, file-local exports

The address screen's element helper returns the plain element instead of Object.assign's intersection, which strict mode could not represent; the haptics test reads an optional argument as optional; three exports only their own file used are local now.

* fix(native): Prettier on the native client files, rate-limit e2e requests in sequence

Formats the files the client formatting gate listed, and NATIVE-E2E-005 sends its twenty exchange attempts one after another: all at once they reset the test server's connections.

* fix(native): hide passkeys in the app through usePasskeys

The flag in useAccountSettings grew the identical destructuring in both account views past the duplication threshold; the shared passkeys hook already decides when its card is hidden, so the app check lives there now.

* feat(native): everything the App Store and Google Play submissions need

- iOS: microphone usage text for "Take Video", no-export-compliance flag,
  ExportOptions.plist for App Store Connect uploads, the unused push
  forwarders gone; CI builds with Xcode 26 and lints the property lists.
- Android: version and signing from Gradle properties (unsigned without
  them), R8 with keep rules for TREK's and Capacitor's reflective classes,
  no Auto Backup of the session cookie, no external file provider path,
  template and Firebase leftovers removed, keystores and service accounts
  ignored, full-size adaptive icon layers with a monochrome layer; CI also
  builds the release APK.
- native-release.yml: signed bundle to a Play testing track and archive to
  TestFlight, by hand or on a v* tag, behind the store environment.
- Version handshake: the server reports nativeApi 1, the app refuses a
  server below its minimum and tolerates an app older than the offline copy.
- Address screen: privacy policy link, "Try the demo" and "What is a TREK
  server?"; the privacy link also in the app's server settings. Three new
  native strings in all 27 locales.
- Donation links and the notices asking for one are hidden in the app.
- Store listings for "TREK Travel Planner" in client/fastlane: texts, review
  notes with placeholders, privacy and account deletion page drafts, the
  feature graphic and icon, a length and image check in CI, and a Playwright
  store project with the scripts that turn its captures into screenshots.
- Docs: wiki/Native-Apps.md, README no longer says there is no store app.

* fix(native): read a notice button's href without a weak type

An action button carries no href, so a parameter typed as only an optional href refused the notice DTO; the button type now names its kind as well.

* feat(native): a welcoming onboarding for the address screen

The app's own screen now opens on a welcome: the TREK mark, a line about what
TREK is, and two clear paths — connect the TREK you already open in the browser,
or get TREK Cloud. Both lead to polished screens: the address field with live
validation, a shake and haptic on a bad address and a success tick before the
server takes over; and a TREK Cloud intro with what it offers and a way in.
Screens slide and stagger in, buttons give a tap, and it all respects the safe
areas, light and dark, and reduced motion. Self-hosters are unaffected: cloud is
its own path, never in the way. New native strings are added across all locales
(English placeholders outside en/de, to translate).

* feat(native): a plan picker for TREK Cloud, with live prices

The Get TREK Cloud path now leads to a plan picker that reads the live plans
from the site (/api/plans), so the prices and quotas always match the website.
Monthly and yearly in a segmented toggle, the year marked with its saving, each
plan a card with its price and what it includes. Subscribe is wired to finish on
the web order for now; it becomes an Apple/Google in-app purchase once the store
products exist. New strings across all locales (en and de translated).

* feat(native): light status bar and a Go key on the address screen

The address screen sits on the near-black surface, so set the status bar to draw
its clock and icons in light while it is up; the server's own UI takes over the
style once it loads. The address field's on-screen return key now reads Go. Both
fail quietly where there is no native status bar (web, the simulator).

* i18n(native): translate the onboarding into es, fr, it, nl and pl

The welcome, TREK Cloud and plan-picker strings were English placeholders in
every locale but en and de. The five largest remaining European languages are
now translated in full; the others still carry the English text and are a
follow-up for native speakers.

* feat(native): the in-app TREK Cloud subscription flow

After picking a plan, the app now carries the whole purchase itself when the build
can take one: choose your address (checked for free as you type, against the same
endpoint the website uses), your email, and subscribe. The receipt goes to
/api/iap/redeem, and a Setting up your TREK screen waits on the new address and
loads it the moment it answers.

The purchase sits behind an IapClient seam (src/native/iap.ts): a fake drives the
whole flow in development and preview, the native client reports itself
unavailable until the store plugin and products exist, and until then the plan
picker still finishes on the web, so nothing half-wired faces a customer. New
claim and provisioning strings across all locales (en, de and the five largest
European languages translated).

* i18n(native): translate the app into the remaining 20 languages

The onboarding, plan picker, claim and provisioning strings were English
placeholders outside en, de and the five largest European languages. They are
now translated in full across the other 20 locales (ar, az, br, ca, cs, et, gr,
hu, id, ja, ko, ru, sk, sv, th, tr, uk, vi, zh, zh-TW), placeholders and brand
kept. The app now speaks every language TREK does.

* fix(i18n): add the Hebrew native strings, and correct the LoginPage size baseline

The he locale had every domain but native.ts, which broke i18n parity, the shared
coverage specs and the client parity test once the native strings existed. Add
he/native.ts with all native keys translated. Also correct the LoginPage size
baseline to its current line count.

* i18n(native): excuse the TREK Cloud brand, mark Email same-as-en, exempt the quota counts

The strict i18n checks, which the feature-branch CI does not run, catch three
things now that the native strings exist in every locale: TREK Cloud read as an
untranslated English phrase (it is a product name, like Vacay and Atlas, so add
it to the brand list); Email left identical in Italian, Indonesian and
Vietnamese, where it is the local word too (mark same-as-en) and in Greek (give
it a Greek term); and the GB and AI-document quota strings carrying {n} without
being plural groups (both are figures that never show a singular, like the other
unit-symbol counts in NOT_PLURAL).

* fix(native): typecheck, lint and knip on the native code; wire he's native bundle

The full suite, which the feature-branch CI does not run, catches four things the
native work still had: a non-narrowed union in the claim flow (tsc), a helper
named useFake that the react-hooks rule read as a hook (eslint), two iap types
exported but used only inside the file (knip), and the Hebrew native strings
present as a file but never spread into he's merged bundle (the aggregated key
parity test). All four fixed.

* fix(native): a flat redeem result, so the claim flow typechecks

The discriminated union did not narrow under the native-shell tsconfig, so the
failure code read as absent on the whole type. Use a flat result with optional
instanceUrl and code instead: both are always present on the type, no narrowing
needed, and the ok plus instanceUrl guard still routes success from refusal.

* style: prettier-format the native and i18n changes

The feature-branch CI does not run the formatting check, so the conflict-resolved
files (AboutTab, useAccountSettings, useTripExport), the native shell and iap
module, and the i18n files touched by the translation scripts were never run
through Prettier. Format them all; no behaviour changes.

* chore(native): re-trigger CI on the formatted tree

---------

Co-authored-by: Maurice <mauriceboe@icloud.com>
2026-11-05 21:09:04 +01:00

708 lines
28 KiB
TypeScript

import { Photos } from '../../../src/db/entities/Photos.entity';
import { ShareTokens } from '../../../src/db/entities/ShareTokens.entity';
import {
applyPlatformUploads,
applyPlatformSpa,
applyPlatformStatic,
storageStaticHandler,
isBuildFilePath,
PUBLIC_DIR,
} from '../../../src/nest/platform/platform.routes';
import { SpaFallbackFilter } from '../../../src/nest/platform/spa-fallback.filter';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import { StorageNotFoundError, StorageInvalidKeyError } from '../../../src/nest/storage/storage.types';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createUser, createTrip } from '../../helpers/factories';
import { deleteRows, insertRow } from '../../helpers/factories/rows';
import { makeShareToken } from '../../helpers/factories/trips';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { NotFoundException } from '@nestjs/common';
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
// --- hoisted mock fns so the vi.mock factories can reference them -----------------
const h = vi.hoisted(() => ({
verifyJwtAndLoadUser: vi.fn(),
dbPrepare: vi.fn(),
exists: vi.fn(),
sendToResponse: vi.fn(),
}));
vi.mock('../../../src/nest/auth-core/jwt-verify', () => ({ verifyJwtAndLoadUser: h.verifyJwtAndLoadUser }));
vi.mock('../../../src/db/database', () => ({ db: { prepare: h.dbPrepare } }));
// The serving swap addresses files as (category, name) on the injected facade;
// these unit tests only assert routing/auth/error mapping, so a two-method stub
// is the whole storage surface.
const storage = { exists: h.exists, sendToResponse: h.sendToResponse } as unknown as StorageService;
// Tagged sentinel for express.static — we only need to know it was registered on
// the right path, not run it.
vi.mock('express', async () => {
const staticFn = vi.fn(() => 'STATIC' as unknown);
const fn: unknown = () => ({});
Object.assign(fn as object, { static: staticFn });
return { default: fn, static: staticFn };
});
type Handler = (...args: unknown[]) => unknown;
/**
* A fake express.Application that records every route/middleware registration so
* individual handlers can be pulled out and exercised in isolation.
*/
function fakeApp() {
const calls: Array<{ method: string; path?: string; handlers: Handler[] }> = [];
const record =
(method: string) =>
(...args: unknown[]) => {
if (typeof args[0] === 'string' || args[0] instanceof RegExp) {
calls.push({ method, path: String(args[0]), handlers: args.slice(1) as Handler[] });
} else {
calls.push({ method, handlers: args as Handler[] });
}
};
const app = {
use: record('use'),
get: record('get'),
post: record('post'),
delete: record('delete'),
} as never;
return { app, calls };
}
function makeRes() {
const res = {
statusCode: 200,
body: undefined as unknown,
headers: {} as Record<string, string>,
status: vi.fn(function (this: typeof res, c: number) {
this.statusCode = c;
return this;
}),
json: vi.fn(function (this: typeof res, b: unknown) {
this.body = b;
return this;
}),
send: vi.fn(function (this: typeof res, b: unknown) {
this.body = b;
return this;
}),
end: vi.fn(function (this: typeof res) {
return this;
}),
sendFile: vi.fn(function (this: typeof res, p: string) {
this.body = `FILE:${p}`;
return this;
}),
setHeader: vi.fn(function (this: typeof res, k: string, v: string) {
this.headers[k] = v;
return this;
}),
};
return res;
}
// Task 0 (D6): applyPlatformUploads now wraps servePhoto in withRequestContext,
// so every call site below needs a real `{ em }` to hand it — none of these
// cases touch the ORM (jwt-verify and db/database are both mocked above), but
// RequestContext.create needs a genuine EntityManager to open the ALS scope
// around, not a hand-built stub.
const uploadsTestDb = createSnapshotTestDb();
let uploadsOrm: TestOrm;
beforeAll(async () => {
uploadsOrm = await createTestOrm(uploadsTestDb);
});
afterAll(async () => {
await uploadsOrm.close();
uploadsTestDb.close();
});
beforeEach(() => {
vi.clearAllMocks();
});
describe('applyPlatformUploads', () => {
it('registers the four static mounts + the files block', () => {
const { app, calls } = fakeApp();
applyPlatformUploads(app, storage, uploadsOrm.orm);
const paths = calls.filter((c) => c.method === 'use').map((c) => c.path);
expect(paths).toEqual(
expect.arrayContaining([
'/uploads/avatars',
'/uploads/covers',
'/uploads/journey',
'/uploads/places',
'/uploads/files',
]),
);
});
it('the /uploads/files block always answers 401', () => {
const { app, calls } = fakeApp();
applyPlatformUploads(app, storage, uploadsOrm.orm);
const filesBlock = calls.find((c) => c.path === '/uploads/files')!.handlers[0];
const res = makeRes();
filesBlock({}, res);
expect(res.statusCode).toBe(401);
expect(res.body).toBe('Authentication required');
});
describe('GET /uploads/photos/:filename', () => {
function photoHandler() {
const { app, calls } = fakeApp();
applyPlatformUploads(app, storage, uploadsOrm.orm);
return calls.find((c) => c.method === 'get' && c.path === '/uploads/photos/:filename')!.handlers[0];
}
const next = vi.fn();
it('403 when the basename is a bare traversal segment', async () => {
// Parity pin: the old resolve()+startsWith guard could only fire after
// basename() when the remaining segment was '..'.
const res = makeRes();
await photoHandler()({ params: { filename: '..' }, headers: {}, query: {} }, res, next);
expect(res.statusCode).toBe(403);
expect(res.body).toBe('Forbidden');
expect(h.exists).not.toHaveBeenCalled();
});
it('404 when the object does not exist — checked before auth', async () => {
h.exists.mockResolvedValue(false);
const res = makeRes();
await photoHandler()({ params: { filename: 'a.jpg' }, headers: {}, query: {} }, res, next);
expect(h.exists).toHaveBeenCalledWith('photos', 'a.jpg');
expect(res.statusCode).toBe(404);
expect(res.body).toBe('Not found');
expect(h.verifyJwtAndLoadUser).not.toHaveBeenCalled();
});
it('404 when the key is invalid (exists rejects) — still before auth', async () => {
h.exists.mockRejectedValue(new StorageInvalidKeyError('photos/.'));
const res = makeRes();
await photoHandler()({ params: { filename: '.' }, headers: {}, query: {} }, res, next);
expect(res.statusCode).toBe(404);
expect(res.body).toBe('Not found');
});
it('401 when no token is supplied', async () => {
h.exists.mockResolvedValue(true);
const res = makeRes();
await photoHandler()({ params: { filename: 'a.jpg' }, headers: {}, query: {} }, res, next);
expect(res.statusCode).toBe(401);
expect(res.body).toBe('Authentication required');
});
it('serves the file for a valid JWT session (Bearer header)', async () => {
h.exists.mockResolvedValue(true);
h.sendToResponse.mockResolvedValue(undefined);
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
const res = makeRes();
await photoHandler()(
{ params: { filename: 'a.jpg' }, headers: { authorization: 'Bearer jwt123' }, query: {} },
res,
next,
);
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith(
'jwt123',
expect.objectContaining({ findByIdWithPasswordVersion: expect.any(Function) }),
// the session gate's lookup (UserSessionsRepository)
expect.objectContaining({ findActive: expect.any(Function), touchLastSeen: expect.any(Function) }),
);
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'a.jpg', res);
});
it('reads the token from the query string when there is no Bearer header', async () => {
h.exists.mockResolvedValue(true);
h.sendToResponse.mockResolvedValue(undefined);
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
const res = makeRes();
await photoHandler()({ params: { filename: 'a.jpg' }, headers: {}, query: { token: 'qtok' } }, res, next);
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith(
'qtok',
expect.objectContaining({ findByIdWithPasswordVersion: expect.any(Function) }),
// the session gate's lookup (UserSessionsRepository)
expect.objectContaining({ findActive: expect.any(Function), touchLastSeen: expect.any(Function) }),
);
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'a.jpg', res);
});
it('401 when the token is not a session and the photo row is missing', async () => {
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
h.dbPrepare.mockReturnValue({ get: vi.fn().mockReturnValue(undefined) });
const res = makeRes();
await photoHandler()({ params: { filename: 'a.jpg' }, headers: {}, query: { token: 'share1' } }, res, next);
expect(res.statusCode).toBe(401);
});
// R1/R5 (Plan 3h Task 6, R1 (Plan 4 Task 1)): both the share-token lookup
// AND the sibling `photos` read now go through the SAME real ORM
// (`ShareTokensRepository.findTripIdByToken` / `PhotosRepository
// .findTripIdByFilename`, `orm.em.getRepository(...)` inside the SAME
// `withRequestContext` wrap `applyPlatformUploads` already uses) — so
// every case here seeds REAL rows in `uploadsTestDb` (bound to
// `uploadsOrm.orm`) rather than mocking `db.prepare`'s return value; the
// `h.dbPrepare` stub is dead for this whole describe block now.
async function insertShareToken(tripId: number, userId: number, token: string, expiresAt: string | null = null) {
await makeShareToken(uploadsOrm, tripId, userId, { token, expires_at: expiresAt });
}
async function insertPhoto(tripId: number, filename: string) {
await insertRow(uploadsOrm, Photos, { trip: tripId, filename, original_name: filename });
}
it('401 when a share token does not cover the photo trip', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
const otherTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(otherTrip.id, user.id, 'share-mismatch');
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-mismatch.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-mismatch.jpg' }, headers: {}, query: { token: 'share-mismatch' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('R5: 401 when there is no matching share token at all (unknown)', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-unknown-token.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-unknown-token.jpg' }, headers: {}, query: { token: 'never-issued' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('R5: 401 when the token is revoked (deleted, not merely unknown)', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-revoked');
await deleteRows(uploadsOrm, ShareTokens, { token: 'share-revoked' });
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-revoked.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-revoked.jpg' }, headers: {}, query: { token: 'share-revoked' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('R5: 401 when the token is expired', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-expired', '2020-01-01 00:00:00');
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-expired.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-expired.jpg' }, headers: {}, query: { token: 'share-expired' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('R5: 401 for a wrong-case token — no case-folding is introduced', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-CaseSensitive');
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-case.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-case.jpg' }, headers: {}, query: { token: 'share-casesensitive' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('R5: 401 for a token with an embedded NUL byte', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-nul');
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-nul.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-nul.jpg' }, headers: {}, query: { token: 'share-nul\0extra' } },
res,
next,
);
expect(res.statusCode).toBe(401);
});
it('serves the file when the share token covers the photo trip (R1 valid-token case)', async () => {
const { user } = createUser(uploadsTestDb);
const photoTrip = createTrip(uploadsTestDb, user.id);
await insertShareToken(photoTrip.id, user.id, 'share-valid');
h.exists.mockResolvedValue(true);
h.sendToResponse.mockResolvedValue(undefined);
h.verifyJwtAndLoadUser.mockReturnValue(null);
await insertPhoto(photoTrip.id, 'photo-valid.jpg');
const res = makeRes();
await photoHandler()(
{ params: { filename: 'photo-valid.jpg' }, headers: { authorization: 'Bearer share-valid' }, query: {} },
res,
next,
);
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'photo-valid.jpg', res);
});
it('404 when the object vanishes between the exists check and the send', async () => {
// Approved deviation D7: the delete race maps to the same 404 text.
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
h.sendToResponse.mockRejectedValue(new StorageNotFoundError('photos/a.jpg'));
const res = makeRes();
const resAny = res as unknown as { headersSent?: boolean };
resAny.headersSent = false;
await photoHandler()(
{ params: { filename: 'a.jpg' }, headers: { authorization: 'Bearer jwt123' }, query: {} },
res,
next,
);
expect(res.statusCode).toBe(404);
expect(res.body).toBe('Not found');
});
it('rethrows a non-miss send failure to the route error handler', async () => {
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
const boom = new Error('disk on fire');
h.sendToResponse.mockRejectedValue(boom);
const res = makeRes();
const localNext = vi.fn();
await photoHandler()(
{ params: { filename: 'a.jpg' }, headers: { authorization: 'Bearer jwt123' }, query: {} },
res,
localNext,
);
expect(localNext).toHaveBeenCalledWith(boom);
expect(res.statusCode).toBe(200); // untouched — finalhandler owns it now
});
it('does not write a second 404 when the send fails after headers were flushed', async () => {
h.exists.mockResolvedValue(true);
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
h.sendToResponse.mockRejectedValue(new StorageNotFoundError('photos/a.jpg'));
const res = makeRes();
(res as unknown as { headersSent: boolean }).headersSent = true;
const localNext = vi.fn();
await photoHandler()(
{ params: { filename: 'a.jpg' }, headers: { authorization: 'Bearer jwt123' }, query: {} },
res,
localNext,
);
expect(res.status).not.toHaveBeenCalled();
expect(localNext).toHaveBeenCalledWith(expect.any(StorageNotFoundError));
});
});
});
describe('storageStaticHandler', () => {
const req = (over: Record<string, unknown> = {}) => ({ method: 'GET', path: '/x.png', ...over });
function run(over: Record<string, unknown> = {}) {
const handler = storageStaticHandler(storage, 'avatars');
const res = makeRes();
const next = vi.fn();
const out = handler(req(over) as never, res as never, next as never);
return { res, next, out };
}
it('serves a hit through sendToResponse with the decoded name', async () => {
h.sendToResponse.mockResolvedValue(undefined);
const { res, next, out } = run({ path: '//caf%C3%A9.png' });
await out;
expect(h.sendToResponse).toHaveBeenCalledWith('avatars', 'café.png', res);
expect(next).not.toHaveBeenCalled();
});
it('non-GET/HEAD methods fall through without touching storage', async () => {
const { next } = run({ method: 'POST' });
expect(next).toHaveBeenCalledWith();
expect(h.sendToResponse).not.toHaveBeenCalled();
});
it('undecodable percent-encoding falls through', async () => {
const { next } = run({ path: '/%ZZ' });
expect(next).toHaveBeenCalledWith();
expect(h.sendToResponse).not.toHaveBeenCalled();
});
it('a miss calls next() with no args', async () => {
h.sendToResponse.mockRejectedValue(new StorageNotFoundError('avatars/x.png'));
const { next, out } = run();
await out;
expect(next).toHaveBeenCalledWith();
});
it('an invalid key calls next() with no args', async () => {
h.sendToResponse.mockRejectedValue(new StorageInvalidKeyError('avatars/..'));
const { next, out } = run();
await out;
expect(next).toHaveBeenCalledWith();
});
it('a send-layer 404 (stat→send race) falls through', async () => {
h.sendToResponse.mockRejectedValue(Object.assign(new Error('ENOENT'), { status: 404 }));
const { next, out } = run();
await out;
expect(next).toHaveBeenCalledWith();
});
it('EISDIR falls through', async () => {
h.sendToResponse.mockRejectedValue(Object.assign(new Error('dir'), { code: 'EISDIR' }));
const { next, out } = run();
await out;
expect(next).toHaveBeenCalledWith();
});
it('a client abort is swallowed', async () => {
h.sendToResponse.mockRejectedValue(Object.assign(new Error('aborted'), { code: 'ECONNABORTED' }));
const { next, out } = run();
await out;
expect(next).not.toHaveBeenCalled();
});
it('a mid-stream write error is swallowed', async () => {
h.sendToResponse.mockRejectedValue(Object.assign(new Error('write EPIPE'), { syscall: 'write' }));
const { next, out } = run();
await out;
expect(next).not.toHaveBeenCalled();
});
it('anything else goes to next(err) for finalhandler', async () => {
const boom = new Error('boom');
h.sendToResponse.mockRejectedValue(boom);
const { next, out } = run();
await out;
expect(next).toHaveBeenCalledWith(boom);
});
});
describe('applyPlatformStatic', () => {
const original = process.env.NODE_ENV;
afterEach(() => {
process.env.NODE_ENV = original;
});
it('is a no-op outside production', () => {
process.env.NODE_ENV = 'development';
const { app, calls } = fakeApp();
applyPlatformStatic(app);
expect(calls).toHaveLength(0);
});
it('serves the built client statics in production', () => {
process.env.NODE_ENV = 'production';
const { app, calls } = fakeApp();
applyPlatformStatic(app);
expect(calls.some((c) => c.method === 'use')).toBe(true);
});
it('the static setHeaders callback adds no-cache for index.html only', async () => {
process.env.NODE_ENV = 'production';
const expressMod = (await import('express')).default as unknown as { static: ReturnType<typeof vi.fn> };
expressMod.static.mockClear();
const { app } = fakeApp();
applyPlatformStatic(app);
const opts = expressMod.static.mock.calls[0][1] as { setHeaders: (res: unknown, p: string) => void };
const indexRes = makeRes();
opts.setHeaders(indexRes, '/some/index.html');
expect(indexRes.headers['Cache-Control']).toBe('no-cache, no-store, must-revalidate');
const assetRes = makeRes();
opts.setHeaders(assetRes, '/some/app.js');
expect(assetRes.headers['Cache-Control']).toBeUndefined();
});
it('marks the hashed files under assets/ immutable, and nothing else', async () => {
process.env.NODE_ENV = 'production';
const expressMod = (await import('express')).default as unknown as { static: ReturnType<typeof vi.fn> };
expressMod.static.mockClear();
const { app } = fakeApp();
applyPlatformStatic(app);
const opts = expressMod.static.mock.calls[0][1] as { setHeaders: (res: unknown, p: string) => void };
const header = (p: string) => {
const res = makeRes();
opts.setHeaders(res, p);
return res.headers['Cache-Control'];
};
expect(header('/app/public/assets/index-DbM4_q2x.js')).toBe('public, max-age=31536000, immutable');
expect(header('C:\\app\\public\\assets\\Map-a1B2c3D4.css')).toBe('public, max-age=31536000, immutable');
expect(header('/app/public/sw.js')).toBeUndefined();
expect(header('/app/public/icons/icon-192.png')).toBeUndefined();
expect(header('/app/public/assets/plain.js')).toBeUndefined();
});
});
describe('applyPlatformSpa', () => {
const original = process.env.NODE_ENV;
afterEach(() => {
process.env.NODE_ENV = original;
});
it('only serves statics (no catch-all) outside production', () => {
process.env.NODE_ENV = 'development';
const { app, calls } = fakeApp();
applyPlatformSpa(app);
expect(calls.some((c) => c.method === 'get' && c.path === '/.*/')).toBe(false);
});
it('registers the index.html catch-all in production', () => {
process.env.NODE_ENV = 'production';
const { app, calls } = fakeApp();
applyPlatformSpa(app);
const catchAll = calls.find((c) => c.method === 'get');
expect(catchAll).toBeDefined();
const res = makeRes();
catchAll!.handlers[0]({ path: '/trips/7' }, res);
expect(res.headers['Cache-Control']).toBe('no-cache, no-store, must-revalidate');
expect(String(res.body)).toContain('FILE:');
expect(String(res.body)).toContain('index.html');
expect(res.sendFile).toHaveBeenCalledWith('index.html', { root: PUBLIC_DIR });
});
it('answers a missing build file with a 404, not index.html (#2524)', () => {
process.env.NODE_ENV = 'production';
const { app, calls } = fakeApp();
applyPlatformSpa(app);
const catchAll = calls.find((c) => c.method === 'get');
const res = makeRes();
catchAll!.handlers[0]({ path: '/assets/DashboardPage-v4ODOTOr.js' }, res);
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'Not Found' });
expect(res.headers['Cache-Control']).toBe('no-store');
expect(res.sendFile).not.toHaveBeenCalled();
});
});
describe('isBuildFilePath', () => {
it.each([
'/assets/DashboardPage-v4ODOTOr.js',
'/assets/index-cFGeBWen.css',
'/assets/poppins-latin-400-normal-abc.woff2',
'/assets/anything-without-a-known-extension',
'/sw.js',
'/workbox-2da51cb1.js',
'/registerSW.js',
'/manifest.webmanifest',
'/icons/icon-192x192.png',
'/favicon.ico',
'/fonts/Inter.TTF',
])('treats %s as a build file', (p) => {
expect(isBuildFilePath(p)).toBe(true);
});
it.each([
'/',
'/dashboard',
'/trips/12/files',
'/journey/3/studio',
'/plugins/trip-todos',
'/help/Atlas',
'/shared/0f3a9c',
'/public/journey/AbC_-12',
'/oauth/consent',
])('treats the page %s as a page', (p) => {
expect(isBuildFilePath(p)).toBe(false);
});
});
describe('SpaFallbackFilter', () => {
const original = process.env.NODE_ENV;
afterEach(() => {
process.env.NODE_ENV = original;
});
function host(req: { method: string; path?: string }, res: ReturnType<typeof makeRes>) {
return { switchToHttp: () => ({ getRequest: () => req, getResponse: () => res }) } as never;
}
it('serves index.html for an unmatched GET in production', () => {
process.env.NODE_ENV = 'production';
const res = makeRes();
new SpaFallbackFilter().catch(new NotFoundException('nope'), host({ method: 'GET', path: '/dashboard' }, res));
expect(res.headers['Cache-Control']).toBe('no-cache, no-store, must-revalidate');
expect(String(res.body)).toContain('index.html');
});
it('answers a GET for a chunk that is not on disk with a 404 in production (#2524)', () => {
process.env.NODE_ENV = 'production';
const res = makeRes();
new SpaFallbackFilter().catch(
new NotFoundException('Cannot GET /assets/DashboardPage-v4ODOTOr.js'),
host({ method: 'GET', path: '/assets/DashboardPage-v4ODOTOr.js' }, res),
);
// A 200 with index.html here is what a service worker precached as the chunk.
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'Cannot GET /assets/DashboardPage-v4ODOTOr.js' });
expect(res.headers['Cache-Control']).toBe('no-store');
expect(res.sendFile).not.toHaveBeenCalled();
});
it('answers a missing top-level build file with a 404 too', () => {
process.env.NODE_ENV = 'production';
const res = makeRes();
new SpaFallbackFilter().catch(new NotFoundException(), host({ method: 'GET', path: '/workbox-0000aaaa.js' }, res));
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'Not Found' });
});
it('answers a missing build file whose exception has no message with Not Found (#2524)', () => {
process.env.NODE_ENV = 'production';
const res = makeRes();
const exc = new NotFoundException();
Object.defineProperty(exc, 'message', { value: '' });
new SpaFallbackFilter().catch(exc, host({ method: 'GET', path: '/assets/gone-0000aaaa.js' }, res));
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'Not Found' });
expect(res.sendFile).not.toHaveBeenCalled();
});
it('keeps the JSON 404 envelope for a non-GET miss in production', () => {
process.env.NODE_ENV = 'production';
const res = makeRes();
new SpaFallbackFilter().catch(new NotFoundException('gone'), host({ method: 'POST', path: '/dashboard' }, res));
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'gone' });
});
it('keeps the JSON 404 envelope outside production even for GET', () => {
process.env.NODE_ENV = 'development';
const res = makeRes();
new SpaFallbackFilter().catch(new NotFoundException('missing'), host({ method: 'GET', path: '/dashboard' }, res));
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'missing' });
});
it('falls back to Not Found when the exception has no message', () => {
process.env.NODE_ENV = 'development';
const res = makeRes();
const exc = new NotFoundException();
// force an empty message so the || branch is taken
Object.defineProperty(exc, 'message', { value: '' });
new SpaFallbackFilter().catch(exc, host({ method: 'GET', path: '/dashboard' }, res));
expect(res.body).toEqual({ error: 'Not Found' });
});
});