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.
This commit is contained in:
Maurice
2026-09-24 12:19:10 +02:00
parent 14825df993
commit 9832d12751
17 changed files with 545 additions and 5 deletions
+2 -1
View File
@@ -60,6 +60,7 @@ import { ReservationImportModule } from './reservation-import/reservation-import
import { LlmParseModule } from './llm-parse/llm-parse.module';
import { AuthModule } from './auth/auth.module';
import { OidcModule } from './oidc/oidc.module';
import { NativeAuthModule } from './native-auth/native-auth.module';
import { OauthModule } from './oauth/oauth.module';
import { AdminModule } from './admin/admin.module';
import { AddonsModule } from './addons/addons.module';
@@ -82,7 +83,7 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
* migrated.
*/
@Module({
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, PlaceShadowModule, RouteUsageModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, SchoolHolidaysModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, RoadtripModule, TripsModule, CollabModule, FilesModule, DocSyncModule, PhotosModule, MemoriesModule, AirtrailModule, DawarichModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, PlaceShadowModule, RouteUsageModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, SchoolHolidaysModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, RoadtripModule, TripsModule, CollabModule, FilesModule, DocSyncModule, PhotosModule, MemoriesModule, AirtrailModule, DawarichModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, NativeAuthModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
@@ -139,6 +139,9 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [
'McpTransportController.delete',
'McpTransportController.get',
'McpTransportController.post',
// The native app redeems a one-time code from the system browser here. The
// code is only good together with the verifier the app kept to itself.
'NativeAuthController.exchange',
'OauthPublicController.revoke',
'OauthPublicController.token',
'OauthPublicController.userinfo',
@@ -31,6 +31,10 @@ export class FeaturesController {
// Addon-level flag (per-user config availability is reported per-file in
// the preview response). Drives whether the client shows AI affordances.
aiParsing: this.addons.isAddonEnabled(ADDON_IDS.LLM_PARSING),
// The native apps refuse to connect to a server without this: an older
// one serves a UI that knows neither the sign-in hand-off nor the way
// back to the server picker, and the user would be stuck in it.
nativeApp: true,
};
}
}
@@ -0,0 +1,54 @@
import { Body, Controller, HttpCode, HttpException, Post, Req, Res, UseGuards } from '@nestjs/common';
import type { Request, Response } from 'express';
import { NativeAuthService } from './native-auth.service';
import { NativeExchangeDto, NativeHandoffDto } from './native-auth.dto';
import { AuthService } from '../auth/auth.service';
import { CookieAuthGuard } from '../auth/cookie-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { Public } from '../auth/public.decorator';
import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { RateLimitService } from '../common/rate-limit.service';
import type { User } from '../../types';
const EXCHANGE_WINDOW_MS = 15 * 60 * 1000;
const EXCHANGE_MAX = 20;
/**
* /api/auth/native: the sign-in hand-off between the system browser and the
* native app. See the contract in @trek/shared for the whole round trip.
*/
@Controller('api/auth/native')
export class NativeAuthController {
constructor(
private readonly nativeAuth: NativeAuthService,
private readonly auth: AuthService,
private readonly audit: AuditService,
private readonly rl: RateLimitService,
) {}
/**
* Cookie only: an API or MCP bearer token must not be able to mint itself a
* full browser session this way.
*/
@Post('handoff')
@UseGuards(CookieAuthGuard)
@HttpCode(200)
handoff(@Body() body: NativeHandoffDto, @CurrentUser() user: User) {
return { code: this.nativeAuth.issueCode(user.id, body.challenge) };
}
@Post('exchange')
@Public('the one-time code together with its verifier is the credential')
@HttpCode(200)
exchange(@Body() body: NativeExchangeDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
if (!this.rl.check('native-exchange', req.ip || 'unknown', EXCHANGE_MAX, EXCHANGE_WINDOW_MS, Date.now())) {
throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429);
}
const session = this.nativeAuth.redeem(body.code, body.verifier);
if (!session) throw new HttpException({ error: 'Invalid or expired code' }, 400);
this.auth.setAuthCookie(res, session.token, req, true);
this.audit.writeAudit({ userId: session.userId, action: 'user.login', ip: getClientIp(req), details: { method: 'native_app' } });
return { ok: true };
}
}
@@ -0,0 +1,5 @@
import { createZodDto } from 'nestjs-zod';
import { nativeExchangeRequestSchema, nativeHandoffRequestSchema } from '@trek/shared';
export class NativeHandoffDto extends createZodDto(nativeHandoffRequestSchema) {}
export class NativeExchangeDto extends createZodDto(nativeExchangeRequestSchema) {}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { NativeAuthController } from './native-auth.controller';
import { NativeAuthService } from './native-auth.service';
import { AuthModule } from '../auth/auth.module';
import { AuditModule } from '../audit/audit.module';
import { RateLimitModule } from '../common/rate-limit.module';
@Module({
imports: [AuthModule, AuditModule, RateLimitModule],
controllers: [NativeAuthController],
providers: [NativeAuthService],
})
export class NativeAuthModule {}
@@ -0,0 +1,78 @@
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import crypto from 'crypto';
import { DatabaseService } from '../database/database.service';
import { AuthService } from '../auth/auth.service';
export const NATIVE_HANDOFF_CODE_TTL_MS = 60_000;
const SWEEP_INTERVAL_MS = 5 * 60_000;
interface PendingHandoff {
userId: number;
challenge: string;
created: number;
}
/** Constant-time check that sha256(verifier) is the challenge the code was issued for. */
function verifierMatches(challenge: string, verifier: string): boolean {
const expected = Buffer.from(challenge, 'hex');
const actual = crypto.createHash('sha256').update(verifier, 'utf8').digest();
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
/**
* Carries a session from the system browser into the native app's WebView.
*
* Codes live in memory like the OIDC auth codes: they are good for a minute,
* a restart simply means signing in again, and nothing about them is worth
* a table.
*/
@Injectable()
export class NativeAuthService implements OnModuleDestroy {
private readonly pending = new Map<string, PendingHandoff>();
private readonly sweeper: NodeJS.Timeout;
constructor(
private readonly db: DatabaseService,
private readonly auth: AuthService,
) {
this.sweeper = setInterval(() => {
const now = Date.now();
for (const [code, entry] of this.pending) {
if (now - entry.created > NATIVE_HANDOFF_CODE_TTL_MS) this.pending.delete(code);
}
}, SWEEP_INTERVAL_MS);
this.sweeper.unref();
}
onModuleDestroy(): void {
clearInterval(this.sweeper);
}
issueCode(userId: number, challenge: string): string {
const code = crypto.randomBytes(32).toString('base64url');
this.pending.set(code, { userId, challenge, created: Date.now() });
return code;
}
/**
* Burns the code on every attempt, right or wrong, so a code that leaked
* through the URL scheme gets exactly one guess. The session is always the
* long one: an app that forgets its login whenever iOS unloads it would be
* useless on the road.
*/
redeem(code: string, verifier: string): { token: string; userId: number } | null {
const entry = this.pending.get(code);
if (!entry) return null;
this.pending.delete(code);
if (Date.now() - entry.created > NATIVE_HANDOFF_CODE_TTL_MS) return null;
if (!verifierMatches(entry.challenge, verifier)) return null;
const user = this.db.get<{ id: number; password_version: number }>(
'SELECT id, password_version FROM users WHERE id = ?',
entry.userId,
);
if (!user) return null;
this.db.run('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?', user.id);
return { token: this.auth.generateToken(user, true), userId: user.id };
}
}
@@ -185,6 +185,8 @@ export function applyPlatformSpa(app: express.Application): void {
});
}
const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+$/;
/**
* Production static serving of the built client (JS/CSS/assets). Split out from
* applyPlatformSpa because the NestJS bootstrap needs the static files served
@@ -200,6 +202,11 @@ export function applyPlatformStatic(app: express.Application): void {
setHeaders: (res, filePath) => {
if (filePath.endsWith('index.html')) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
} else if (HASHED_ASSET.test(filePath)) {
// Vite puts a content hash in every name under assets/, so a file there
// never changes. Without this the iOS app, which has no service worker,
// cannot start offline: WebKit would revalidate each script and fail.
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
},
}),