Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
+11 -3
View File
@@ -1,7 +1,8 @@
import { readEnv } from '../../app-config';
import type { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { cleanupOpenApiDoc } from 'nestjs-zod';
import { readEnv } from '../../app-config';
/**
* Swagger UI + OpenAPI spec for the REST API (#1412), gated behind
@@ -21,8 +22,15 @@ export function setupApiDocs(app: INestApplication): void {
const config = new DocumentBuilder()
.setTitle('TREK API')
.setDescription(
'The REST API the TREK web app itself runs on. Authenticate with a session JWT — '
+ 'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.',
'The REST API the TREK web app itself runs on. Authenticate with a session JWT — ' +
'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.\n\n' +
'Every session can be ended before it expires: `POST /api/auth/logout` ends the one it is called with, ' +
'`GET /api/auth/sessions` lists the signed-in sessions, `DELETE /api/auth/sessions/{id}` ends one and ' +
'`POST /api/auth/sessions/revoke-others` ends all but the current one.\n\n' +
'**Deprecated:** the `token` field in the bodies of `POST /api/auth/login`, `/register`, `/demo-login`, ' +
'`/mfa/verify-login`, `/passkey/login/verify` and `GET /api/auth/oidc/exchange`. It is still sent, for ' +
'clients that read it, but will be removed in a future major version. Use the `trek_session` cookie the ' +
'same response sets; the SSO exchange also answers `success: true`.',
)
.setVersion(version)
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'session')
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import type { NestMiddleware } from '@nestjs/common';
import type { Request, Response, NextFunction } from 'express';
/**
@@ -1,9 +1,10 @@
import { Injectable } from '@nestjs/common';
import type express from 'express';
import { getMcpSafeUrl } from '../../app-config';
import { ALL_SCOPES } from '../../mcp/scopes';
import { mcpAuthMetadataRouter } from '@modelcontextprotocol/sdk/server/auth/router';
import type { OAuthMetadata } from '@modelcontextprotocol/sdk/shared/auth';
import { ALL_SCOPES } from '../../mcp/scopes';
import { getMcpSafeUrl } from '../../app-config';
import { Injectable } from '@nestjs/common';
import type express from 'express';
/**
* OAuth/MCP discovery metadata, built lazily on first request so the issuer URL
@@ -24,16 +25,18 @@ export class DiscoveryMetadataService {
if (this.oauthMetadata) return this.oauthMetadata;
const base = getMcpSafeUrl().replace(/(?<!\/)\/+$/, '');
this.oauthMetadata = {
issuer: base,
authorization_endpoint: `${base}/oauth/authorize`,
token_endpoint: `${base}/oauth/token`,
revocation_endpoint: `${base}/oauth/revoke`,
registration_endpoint: `${base}/oauth/register`,
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
code_challenge_methods_supported: ['S256'],
issuer: base,
authorization_endpoint: `${base}/oauth/authorize`,
token_endpoint: `${base}/oauth/token`,
revocation_endpoint: `${base}/oauth/revoke`,
registration_endpoint: `${base}/oauth/register`,
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
scopes_supported: ALL_SCOPES,
scopes_supported: ALL_SCOPES,
// An https client_id is resolved as its metadata document (nest/oauth/oauth-cimd.ts).
client_id_metadata_document_supported: true,
};
return this.oauthMetadata;
}
@@ -1,10 +1,11 @@
import { All, Controller, Get, NotFoundException, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import { Public } from '../auth/public.decorator';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { AddonsService } from '../addons/addons.service';
import { ADDON_IDS } from '../../addons';
import { ALL_SCOPES } from '../../mcp/scopes';
import { AddonsService } from '../addons/addons.service';
import { Public } from '../auth-core/public.decorator';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { All, Controller, Get, NotFoundException, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
/**
* The hand-rolled halves of OAuth discovery (the SDK metadata router itself is
@@ -44,18 +45,18 @@ export class DiscoveryController {
// them with invalid_target — showing the user the TREK home page instead of the
// consent form.
@Get('oauth-protected-resource')
protectedResource(@Res() res: Response): void {
if (!this.addons.isAddonEnabled(ADDON_IDS.MCP)) {
async protectedResource(@Res() res: Response): Promise<void> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.MCP))) {
res.status(404).end();
return;
}
const meta = this.meta.getOAuthMetadata();
res.json({
resource: `${meta.issuer}/mcp`,
authorization_servers: [meta.issuer],
resource: `${meta.issuer}/mcp`,
authorization_servers: [meta.issuer],
bearer_methods_supported: ['header'],
scopes_supported: ALL_SCOPES,
resource_name: 'TREK MCP',
scopes_supported: ALL_SCOPES,
resource_name: 'TREK MCP',
});
}
@@ -117,8 +118,8 @@ export class McpResourceDiscoveryController {
}
@Get('oauth-protected-resource')
protectedResource(@Res() res: Response): void {
this.documents.protectedResource(res);
async protectedResource(@Res() res: Response): Promise<void> {
await this.documents.protectedResource(res);
}
@All('*path')
@@ -1,7 +1,10 @@
import type { RequestHandler } from 'express';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { AddonsService } from '../addons/addons.service';
import { ADDON_IDS } from '../../addons';
import { AddonsService } from '../addons/addons.service';
import { withRequestContext } from '../database/request-context';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { MikroORM } from '@mikro-orm/core';
import type { RequestHandler } from 'express';
/**
* The SDK discovery router plus its addon gate: 404 (empty body) on every
@@ -16,24 +19,54 @@ import { ADDON_IDS } from '../../addons';
* from the container by token (the httpConfig.KEY precedent). A factory
* provider rather than a NestMiddleware class because nothing consumer-mounts
* it: the deliverable is the bare Express RequestHandler itself.
*
* D6 boot rule (Plan 3a Task 4): a pathless pre-init `app.use` runs on the raw
* Express instance, before `@mikro-orm/nestjs`'s per-request EntityManager
* fork middleware — unlike `createMcpAddonGate`'s OTHER mount in
* `oauth.module.ts`, which goes through a normal `MiddlewareConsumer.forRoutes()`
* and so is already inside that fork. Once `AddonsService.isAddonEnabled`
* became repository-backed, a request here threw MikroORM's
* `cannotUseGlobalContext` (proven: every `/.well-known/*` integration test
* failed with a 500 until this wrap). `withRequestContext` is this file's own
* choke point — every request through this middleware, gated or not, gets a
* context the same way the boot-time `getAdminUserDefaults()` read in
* `bootstrap.ts` already does.
*/
export const MCP_METADATA_MIDDLEWARE = Symbol('MCP_METADATA_MIDDLEWARE');
export function createMcpMetadataMiddleware(
meta: DiscoveryMetadataService,
addons: AddonsService,
orm: MikroORM,
): RequestHandler {
// Express cannot await a middleware, so the now-async addon check runs in a
// helper and its rejection is handed to next() — the same error path a
// synchronous throw took before (recipe R1.5).
return (req, res, next) => {
if (req.path.startsWith('/.well-known/') && !addons.isAddonEnabled(ADDON_IDS.MCP)) {
res.status(404).end();
if (!req.path.startsWith('/.well-known/')) {
meta.getMetaRouter()(req, res, next);
return;
}
meta.getMetaRouter()(req, res, next);
// Only the addon read needs an ORM request context: this middleware sits
// before Nest's per-request EntityManager fork (a pathless pre-init
// app.use), and wrapping the router delegation too would fork an unused
// EntityManager for every request the server answers.
// Promise.resolve: the helper returns whatever the callback returns, and a
// test double may answer the addon read synchronously.
void Promise.resolve(withRequestContext(orm, () => addons.isAddonEnabled(ADDON_IDS.MCP)))
.then((enabled) => {
if (!enabled) {
res.status(404).end();
return;
}
meta.getMetaRouter()(req, res, next);
})
.catch(next);
};
}
export const mcpMetadataMiddlewareProvider = {
provide: MCP_METADATA_MIDDLEWARE,
useFactory: createMcpMetadataMiddleware,
inject: [DiscoveryMetadataService, AddonsService],
inject: [DiscoveryMetadataService, AddonsService, MikroORM],
};
+4 -4
View File
@@ -1,9 +1,9 @@
import { Module, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
import { AddonsModule } from '../addons/addons.module';
import { DiscoveryController, McpResourceDiscoveryController } from './discovery.controller';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { mcpMetadataMiddlewareProvider } from './mcp-metadata.middleware';
import { ConsentCoopMiddleware } from './consent-coop.middleware';
import { DiscoveryMetadataService } from './discovery-metadata.service';
import { DiscoveryController, McpResourceDiscoveryController } from './discovery.controller';
import { mcpMetadataMiddlewareProvider } from './mcp-metadata.middleware';
import { Module, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
/**
* The platform surface that lives behind the container: OAuth/OIDC discovery
+125 -20
View File
@@ -1,11 +1,20 @@
import express, { Request, Response, NextFunction } from 'express';
import path from 'node:path';
import { readEnv } from '../../app-config';
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
import { db } from '../../db/database';
import { Photos } from '../../db/entities/Photos.entity';
import { ShareTokens } from '../../db/entities/ShareTokens.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { Users } from '../../db/entities/Users.entity';
import type { PhotosRepository } from '../../db/repositories/Photos.repository';
import type { ShareTokensRepository } from '../../db/repositories/ShareTokens.repository';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { verifyJwtAndLoadUser } from '../auth-core/jwt-verify';
import { withRequestContext } from '../database/request-context';
import { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
import type { EntityManager } from '@mikro-orm/core';
import express, { Request, Response, NextFunction } from 'express';
import path from 'node:path';
// Platform / transport routes extracted verbatim from createApp() (app.ts) so they can be
// mounted on either the legacy Express app or the NestJS Express instance (strangler A6/A8).
@@ -20,6 +29,43 @@ import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } fr
export const PUBLIC_DIR = path.join(__dirname, '../../../public');
// File types the client build emits. No page of the app ends in one of these.
const BUILD_FILE_RE = /\.(?:m?js|css|map|wasm|webmanifest|json|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf)$/i;
/**
* Whether a request asks for a file of the built client rather than a page of it.
*
* Such a request that the static handler could not answer is a file that does not
* exist, and it must end in a 404. It used to get index.html like a page (#2524).
* A tab still running the previous build asks for a chunk the update removed and
* gets HTML with a 200, which the module loader rejects. Worse, a 200 is a success
* to everything that caches: a service worker's precache stores the HTML under the
* chunk's name and keeps reusing it in every later version that keeps the name,
* and a reverse proxy that caches static files by extension hands it out as the
* chunk. A 404 is refused by the precache and never stands in for the file.
*/
export function isBuildFilePath(pathname: string): boolean {
return pathname.startsWith('/assets/') || BUILD_FILE_RE.test(pathname);
}
/**
* The production answer to a GET that nothing else matched: index.html for a page
* of the app, a plain 404 in the TREK envelope for a build file that is not there.
* Shared by both fallback forms (applyPlatformSpa and SpaFallbackFilter).
*/
export function answerUnmatchedGet(req: Request, res: Response, message = 'Not Found'): void {
if (isBuildFilePath(req.path)) {
res.setHeader('Cache-Control', 'no-store');
res.status(404).json({ error: message });
return;
}
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
// Relative to root, so that send() checks only 'index.html' for dot segments. Given
// the absolute path it refused an install living under a dot directory (a
// ~/.local checkout, say) and every deep link came back as a 404.
res.sendFile('index.html', { root: PUBLIC_DIR });
}
/**
* express.static replacement for the four public /uploads mounts (storage
* slice 3). Parity contract (spec §Serving): identical ETag / Last-Modified /
@@ -70,7 +116,15 @@ export function storageStaticHandler(storage: StorageService, category: StorageC
};
}
async function servePhoto(storage: StorageService, req: Request, res: Response): Promise<void> {
async function servePhoto(
storage: StorageService,
req: Request,
res: Response,
users: UsersRepository,
shareTokens: ShareTokensRepository,
photos: PhotosRepository,
sessions: UserSessionsRepository,
): Promise<void> {
const safeName = path.basename(req.params.filename);
// Parity: after basename(), the old resolve()+startsWith guard could only
// fire when the remaining segment was '..' — keep that exact 403.
@@ -102,19 +156,17 @@ async function servePhoto(storage: StorageService, req: Request, res: Response):
}
// JWT session path (with pv check).
const user = verifyJwtAndLoadUser(rawToken);
const user = await verifyJwtAndLoadUser(rawToken, users, sessions);
if (user) return sendPhoto();
// Share-token path: require the token to cover the exact trip the
// photo belongs to. Expired tokens fall through to 401.
const photo = db.prepare('SELECT trip_id FROM photos WHERE filename = ?').get(safeName) as { trip_id: number } | undefined;
const photo = await photos.findTripIdByFilename(safeName);
if (!photo) {
res.status(401).send('Authentication required');
return;
}
const share = db
.prepare("SELECT trip_id FROM share_tokens WHERE token = ? AND (expires_at IS NULL OR expires_at > datetime('now'))")
.get(rawToken) as { trip_id: number } | undefined;
const share = await shareTokens.findTripIdByToken(rawToken);
if (!share || share.trip_id !== photo.trip_id) {
res.status(401).send('Authentication required');
return;
@@ -125,8 +177,50 @@ async function servePhoto(storage: StorageService, req: Request, res: Response):
/**
* Static + guarded /uploads/* routes. Must be applied BEFORE the API route mounts
* (identical to its original position near the top of createApp).
*
* `orm` (Plan 3b Task 0, D6/plan3b-sql-inventory.md §5/§6): `servePhoto` is
* mounted here, on the raw Express instance, BEFORE `app.init()` — every
* `/uploads/photos/*` request runs this handler entirely outside Nest's
* per-request EntityManager fork, forever, not just during a boot window.
* `verifyJwtAndLoadUser` (`jwt-verify.ts`, JV1) now reads `users` through
* `UsersRepository` (Plan 3b Task 1) rather than the legacy `db` proxy — the
* exact case Task 0's wrap was built for. The anonymous share-token fallback
* (used when no JWT is present) now reads `share_tokens` through
* `ShareTokensRepository.findTripIdByToken` the SAME way (Plan 3h Task 6, R1
* — the plan's single highest-severity finding: this branch ran unconverted,
* against the legacy `db` proxy, for three plans after the JWT half above
* was fixed). The sibling `photos` table read (Plan 4 Task 1) now goes
* through `PhotosRepository.findTripIdByFilename` the same way — its
* `trip_id` MATCH against the converted `share` read is the handler's whole
* authorization and is untouched, only the read itself moved off the legacy
* `db` proxy. `orm.em.getRepository(Users)`, `orm.em.getRepository
* (ShareTokens)` and `orm.em.getRepository(Photos)` are all resolved inside
* the arrow passed to `withRequestContext` below: `orm.em` is the global,
* context-resolving EntityManager, and MikroORM's repository object holds a
* reference to that same proxy rather than a snapshot, so a query issued
* through it later resolves whatever `AsyncLocalStorage` context is active
* AT QUERY TIME — not at the moment `getRepository()` was called. What
* actually gates this is `withRequestContext` wrapping the whole
* `servePhoto(...)` call (every repository read included): removing the
* wrapper entirely reproduces Task 0's `ValidationError: Using global
* EntityManager instance...` (verified directly — mutation-proof in
* `task-1-report.md`), exactly the failure `PHOTOCTX-002`/`SEAM-002` guard
* against.
*
* Optional at the type level only, the same shape `TrekWsAdapter` uses for
* its own D6 wrapper (`src/nest/realtime/trek-ws.adapter.ts`): `bootstrap.ts`
* always passes the real `MikroORM` it already resolved. Fail-closed shape
* per the Plan 3b Rulings — a request-time choke point THROWS when the ORM
* is absent rather than running `servePhoto` unwrapped: the photo route
* answers 500 through Express's error path (`next(err)`), the same shape the
* WS adapter's message dispatch already uses (throw before calling the
* handler at all, never a silent degrade).
*/
export function applyPlatformUploads(app: express.Application, storage: StorageService): void {
export function applyPlatformUploads(
app: express.Application,
storage: StorageService,
orm?: { em: EntityManager },
): void {
// Static: avatars, covers, and journey photos.
//
// Security model (audit SEC-M9): these paths are unauthenticated by
@@ -155,9 +249,23 @@ export function applyPlatformUploads(app: express.Application, storage: StorageS
// photo's trip. Previously any share token for any trip could request
// any photo filename by UUID — fine in practice because UUIDs are
// unguessable, but the auth model was wrong.
app.get('/uploads/photos/:filename', (req: Request, res: Response, next: NextFunction) =>
servePhoto(storage, req, res).catch(next),
);
app.get('/uploads/photos/:filename', (req: Request, res: Response, next: NextFunction) => {
if (!orm) {
next(new Error('applyPlatformUploads: no MikroORM available to build a request context for /uploads/photos/*'));
return;
}
return withRequestContext(orm, () =>
servePhoto(
storage,
req,
res,
orm.em.getRepository(Users),
orm.em.getRepository(ShareTokens),
orm.em.getRepository(Photos),
orm.em.getRepository(UserSessions),
),
).catch(next);
});
// Block direct access to /uploads/files
app.use('/uploads/files', (_req: Request, res: Response) => {
@@ -172,17 +280,14 @@ export function applyPlatformUploads(app: express.Application, storage: StorageS
* NOT use this (its router terminates unmatched requests with a 404 before any
* post-init route runs, and Express 5's path-to-regexp rejects a bare '*'); it serves
* the SPA via the SpaFallbackFilter instead. Both produce the identical result:
* unmatched GET → index.html in production.
* unmatched GET → index.html in production, or a 404 for a missing build file.
*/
export function applyPlatformSpa(app: express.Application): void {
applyPlatformStatic(app);
// Case-sensitive on purpose (legacy parity).
if (readEnv().app.nodeEnv !== 'production') return;
// /.*/ rather than '*' so the helper is Express-4 and Express-5 safe.
app.get(/.*/, (_req: Request, res: Response) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.sendFile(path.join(PUBLIC_DIR, 'index.html'));
});
app.get(/.*/, (req: Request, res: Response) => answerUnmatchedGet(req, res));
}
const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+$/;
@@ -1,8 +1,8 @@
import { ArgumentsHost, Catch, ExceptionFilter, NotFoundException } from '@nestjs/common';
import type { Request, Response } from 'express';
import path from 'node:path';
import { readEnv } from '../../app-config';
import { PUBLIC_DIR } from './platform.routes';
import { answerUnmatchedGet } from './platform.routes';
import { ArgumentsHost, Catch, ExceptionFilter, NotFoundException } from '@nestjs/common';
import type { Request, Response } from 'express';
/**
* Serves the built SPA (index.html) for any request the NestJS router did not
@@ -17,6 +17,9 @@ import { PUBLIC_DIR } from './platform.routes';
* client) keeps the standard TREK `{ error }` 404 envelope. The `@Catch(NotFoundException)`
* is more specific than the global TrekExceptionFilter, so Nest routes 404s here
* while every other error still flows through TrekExceptionFilter.
*
* A GET for a build file that is not on disk (a chunk of the previous release,
* say) is not a page and gets the 404 envelope too, never index.html (#2524).
*/
@Catch(NotFoundException)
export class SpaFallbackFilter implements ExceptionFilter {
@@ -27,8 +30,7 @@ export class SpaFallbackFilter implements ExceptionFilter {
// Case-sensitive on purpose (legacy parity).
if (readEnv().app.nodeEnv === 'production' && req.method === 'GET') {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.sendFile(path.join(PUBLIC_DIR, 'index.html'));
answerUnmatchedGet(req, res, exception.message || 'Not Found');
return;
}