mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
Give the ephemeral tokens a provider, and clear the next wave of type errors
ephemeral-tokens.ts was free functions, and AuthService owned the cleanup timer only because it happened to be the domain that mints tokens. Issuing them and sweeping them are different jobs, and FilesService and TokenService mint or consume them too. EphemeralTokenService owns the lifecycle and hands the three operations out. The store and the interval stay module state next door, and that is load-bearing rather than a leftover: src/websocket.ts consumes ws tokens on the upgrade handshake, outside the container, before any injector is in reach. Per-instance state would hand it an empty Map and close every connection with 4001, which no test would catch because the ws suites drive the transport directly. WS-027 through WS-029 pin the session gate that runs through exactly that path. The MAX_STORE_SIZE back-pressure is the second reason: createEphemeralToken returns null at 10,000 live tokens and TokenService turns that into a 503. A second store would raise the real ceiling with nobody noticing. Its own leaf module rather than a provider in AuthModule: TokensModule mints download and ws tokens as well, AuthModule already imports TokensModule, and TokensModule is documented as a deliberate leaf that three graphs reach for. Same shape as MailerModule, which broke AuthModule <-> NotificationsModule. Twelve hand-wired construction sites in tests needed the new collaborator. The typecheck named all twelve; before this branch they would have been undefined at runtime. Sixteen more test files are cleared here too, each at its root cause. Four of them were passing for the wrong reason: files.controller.test.ts drove two handlers with shifted arguments, a string tripId where the trip row belongs and undefined where tripId and id belong. It stayed green because FilesService is fully stubbed and the stubs ignore what they are given, so DELETE /:id/permanent and DELETE /trash/empty never covered that the trip row reaches the permission check. conflictUpdate.test.ts was missing real collaborators on PlacesService and PackingService. None of the exercised paths reach them, so it passed by luck. assignments.service.test.ts builds its service by hand, and the one consumer of the collaborator it was missing swallows every throw in a bare catch. A broken journey reconciliation would still have shown 28 green tests. scheduler.test.ts mocks two modules with paths that resolve one directory above the server root, so they mock nothing at all. Harmless only because src/scheduler.ts imports neither.
This commit is contained in:
@@ -16,6 +16,7 @@ import { NtfyService } from '../notifications/transports/ntfy.service';
|
||||
import { WebhookService } from '../notifications/transports/webhook.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { AdminService } from './admin.service';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
|
||||
/**
|
||||
* Non-Nest entry point for the admin domain — for code running OUTSIDE the Nest
|
||||
@@ -40,7 +41,7 @@ const webauthn = new WebauthnConfigService(dbs);
|
||||
const userCleanup = new UserCleanupService(dbs);
|
||||
const mailer = new MailerService(dbs);
|
||||
const notifPrefs = new NotificationPreferencesService(dbs, mailer);
|
||||
const auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, mailer);
|
||||
const auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, mailer, new EphemeralTokenService());
|
||||
const admin = new AdminService(
|
||||
dbs,
|
||||
new AddonsService(dbs),
|
||||
|
||||
@@ -8,6 +8,7 @@ import { MailerService } from '../notifications/mailer/mailer.service';
|
||||
import { UserCleanupService } from './user-cleanup.service';
|
||||
import { WebauthnConfigService } from './webauthn-config.service';
|
||||
import { User } from '../../types';
|
||||
import { EphemeralTokenService } from './ephemeral-token.service';
|
||||
|
||||
/**
|
||||
* Non-Nest entry point for the auth domain — for code running OUTSIDE the
|
||||
@@ -45,9 +46,10 @@ const auth = new AuthService(
|
||||
new WebauthnConfigService(dbs),
|
||||
new UserCleanupService(dbs),
|
||||
new MailerService(dbs),
|
||||
new EphemeralTokenService(),
|
||||
);
|
||||
|
||||
const tokens = new TokenService(dbs);
|
||||
const tokens = new TokenService(dbs, new EphemeralTokenService());
|
||||
|
||||
export { stripUserForClient } from './auth.helpers';
|
||||
export { avatarUrl } from '../common/avatarUrl';
|
||||
|
||||
@@ -16,6 +16,7 @@ import { AuditModule } from '../audit/audit.module';
|
||||
import { MailerModule } from '../notifications/mailer/mailer.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { EphemeralTokenModule } from './ephemeral-token.module';
|
||||
|
||||
/**
|
||||
* Auth module — public flows (login/register/reset/mfa-verify/logout) and the
|
||||
@@ -38,7 +39,7 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
|
||||
* through auth.bridge.ts.
|
||||
*/
|
||||
@Module({
|
||||
imports: [RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule],
|
||||
imports: [EphemeralTokenModule, RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule],
|
||||
controllers: [AuthPublicController, AuthController, PasskeyController],
|
||||
providers: [AuthService, UserProfileService, RegistrationInvitesService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
|
||||
exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService],
|
||||
|
||||
@@ -14,7 +14,7 @@ import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { validatePassword } from '../common/passwordPolicy';
|
||||
import { encryptMfaSecret, decryptMfaSecret } from '../common/crypto/mfaCrypto';
|
||||
import { decrypt_api_key, maybe_encrypt_api_key, encrypt_api_key } from '../common/crypto/apiKeyCrypto';
|
||||
import { createEphemeralToken, startTokenCleanup, stopTokenCleanup } from './ephemeral-tokens';
|
||||
import { EphemeralTokenService } from './ephemeral-token.service';
|
||||
// Import from sessionManager directly, NOT the ../../mcp barrel: the barrel pulls
|
||||
// the whole tools fan-out (and via the domain bridges, the Nest services) into
|
||||
// every consumer of this module — a nest→mcp→nest module cycle.
|
||||
@@ -118,20 +118,7 @@ export interface ResetPasswordOutcome {
|
||||
* AtlasModule import AuthModule instead of going the other way around.
|
||||
*/
|
||||
@Injectable()
|
||||
export class AuthService implements OnModuleInit, OnModuleDestroy {
|
||||
/**
|
||||
* The ephemeral-token store sweeps itself every minute. index.ts used to kick
|
||||
* that off with a bare require() after listen(); it belongs to the domain that
|
||||
* issues the tokens.
|
||||
*/
|
||||
onModuleInit(): void {
|
||||
startTokenCleanup();
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
stopTokenCleanup();
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly permissions: PermissionsService,
|
||||
@@ -139,6 +126,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly webauthn: WebauthnConfigService,
|
||||
private readonly userCleanup: UserCleanupService,
|
||||
private readonly mailer: MailerService,
|
||||
private readonly tokens: EphemeralTokenService,
|
||||
) {}
|
||||
|
||||
// Cookie
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { EphemeralTokenService } from './ephemeral-token.service';
|
||||
|
||||
/**
|
||||
* A leaf module whose only job is to hand EphemeralTokenService out.
|
||||
*
|
||||
* It cannot live in AuthModule: TokensModule mints download and ws tokens too,
|
||||
* and AuthModule already imports TokensModule, so importing it back would close
|
||||
* a cycle. TokensModule is also documented as a deliberate leaf that three
|
||||
* graphs reach for, so a dependency added there lands in all of them.
|
||||
*
|
||||
* Same shape and same reason as MailerModule, which broke
|
||||
* AuthModule <-> NotificationsModule, and PluginGuardsModule.
|
||||
*/
|
||||
@Module({
|
||||
providers: [EphemeralTokenService],
|
||||
exports: [EphemeralTokenService],
|
||||
})
|
||||
export class EphemeralTokenModule {}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
createEphemeralToken,
|
||||
consumeEphemeralToken,
|
||||
consumeEphemeralTokenWithMeta,
|
||||
startTokenCleanup,
|
||||
stopTokenCleanup,
|
||||
type EphemeralTokenMeta,
|
||||
} from './ephemeral-tokens';
|
||||
|
||||
/**
|
||||
* The injectable face of the ephemeral-token store, and the owner of its
|
||||
* cleanup timer.
|
||||
*
|
||||
* The store itself stays module state next door, and that is load-bearing
|
||||
* rather than a leftover: `src/websocket.ts` consumes ws tokens from OUTSIDE
|
||||
* the container, on the upgrade handshake, before any injector is in reach.
|
||||
* Per-instance state would hand it an empty Map and every connection would
|
||||
* close with 4001 "Invalid or expired token" — a failure that no test sees,
|
||||
* because the ws suites drive the transport directly. Same reasoning as the
|
||||
* geo throttle cursor and the permissions cache.
|
||||
*
|
||||
* The MAX_STORE_SIZE back-pressure is the other reason: `createEphemeralToken`
|
||||
* returns null at 10,000 live tokens and TokenService turns that into a 503.
|
||||
* A second store would raise the real ceiling without anyone noticing.
|
||||
*
|
||||
* The lifecycle moved off AuthService, which owned it only because it was the
|
||||
* domain that mints tokens. Issuing them and sweeping them are different jobs,
|
||||
* and FilesService and TokenService mint or consume them too.
|
||||
*/
|
||||
@Injectable()
|
||||
export class EphemeralTokenService implements OnModuleInit, OnModuleDestroy {
|
||||
onModuleInit(): void {
|
||||
startTokenCleanup();
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
stopTokenCleanup();
|
||||
}
|
||||
|
||||
/** Returns null when the store is at capacity; callers answer 503. */
|
||||
create(userId: number, purpose: string, meta?: EphemeralTokenMeta): string | null {
|
||||
return createEphemeralToken(userId, purpose, meta);
|
||||
}
|
||||
|
||||
/** Single-use: the token is deleted whether or not it validates. */
|
||||
consume(token: string, purpose: string): number | null {
|
||||
return consumeEphemeralToken(token, purpose);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, plus the password_version the token was minted with. Only the ws
|
||||
* handshake needs it, for the session gate that rejects a token minted before
|
||||
* a password change.
|
||||
*/
|
||||
consumeWithMeta(token: string, purpose: string): { userId: number; pv?: number } | null {
|
||||
return consumeEphemeralTokenWithMeta(token, purpose);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { DatabaseService } from '../database/database.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { FilesService } from './files.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
|
||||
/**
|
||||
* Non-Nest entry point for the files domain. Unlike todo.bridge.ts this does
|
||||
@@ -16,7 +17,7 @@ import { PermissionsService } from '../permissions/permissions.service';
|
||||
* Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
|
||||
* the shared better-sqlite3 singleton.
|
||||
*/
|
||||
const files = new FilesService(new DatabaseService(db), new PermissionsService(new DatabaseService(db)), new RealtimeService());
|
||||
const files = new FilesService(new DatabaseService(db), new PermissionsService(new DatabaseService(db)), new RealtimeService(), new EphemeralTokenService());
|
||||
|
||||
export function getAllowedExtensions(): string {
|
||||
return files.getAllowedExtensions();
|
||||
|
||||
@@ -7,9 +7,10 @@ import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { EphemeralTokenModule } from '../auth/ephemeral-token.module';
|
||||
|
||||
@Module({
|
||||
imports: [PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule],
|
||||
imports: [EphemeralTokenModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule],
|
||||
controllers: [FilesController, FilesDownloadController],
|
||||
providers: [FilesService, FilesRpc],
|
||||
exports: [FilesService],
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { consumeEphemeralToken } from '../auth/ephemeral-tokens';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
|
||||
import type { User, TripFile } from '../../types';
|
||||
import { DatabaseService, type TripAccess } from '../database/database.service';
|
||||
@@ -59,6 +59,7 @@ export class FilesService {
|
||||
private readonly db: DatabaseService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly tokens: EphemeralTokenService,
|
||||
) {}
|
||||
|
||||
verifyTripAccess(tripId: string | number, userId: number) {
|
||||
@@ -103,7 +104,7 @@ export class FilesService {
|
||||
}
|
||||
|
||||
if (queryToken) {
|
||||
const uid = consumeEphemeralToken(queryToken, 'download');
|
||||
const uid = this.tokens.consume(queryToken, 'download');
|
||||
if (!uid) return { error: 'Invalid or expired token', status: 401 };
|
||||
return { userId: uid };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomBytes, createHash } from 'crypto';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { createEphemeralToken } from '../auth/ephemeral-tokens';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
// Import from sessionManager directly, NOT the ../../mcp barrel: the barrel pulls
|
||||
// the whole tools fan-out (and via the domain bridges, the Nest services) into
|
||||
// every consumer of this module — a nest→mcp→nest module cycle.
|
||||
@@ -27,7 +27,10 @@ import { User } from '../../types';
|
||||
*/
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly ephemeral: EphemeralTokenService,
|
||||
) {}
|
||||
|
||||
listMcpTokens(userId: number) {
|
||||
return this.db.all(
|
||||
@@ -79,7 +82,7 @@ export class TokenService {
|
||||
// Bind the ws-token to the user's current password_version so a token minted
|
||||
// before a password reset is rejected on connect (defence-in-depth session gate).
|
||||
const pv = this.db.get<{ password_version?: number }>('SELECT password_version FROM users WHERE id = ?', userId)?.password_version ?? 0;
|
||||
const token = createEphemeralToken(userId, 'ws', { pv });
|
||||
const token = this.ephemeral.create(userId, 'ws', { pv });
|
||||
if (!token) return { error: 'Service unavailable', status: 503 };
|
||||
return { token };
|
||||
}
|
||||
@@ -89,7 +92,7 @@ export class TokenService {
|
||||
if (purpose !== 'download') {
|
||||
return { error: 'Invalid purpose', status: 400 };
|
||||
}
|
||||
const token = createEphemeralToken(userId, purpose);
|
||||
const token = this.ephemeral.create(userId, purpose);
|
||||
if (!token) return { error: 'Service unavailable', status: 503 };
|
||||
return { token };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TokenService } from './token.service';
|
||||
import { EphemeralTokenModule } from '../auth/ephemeral-token.module';
|
||||
|
||||
/**
|
||||
* Tokens that are not the login JWT: the long-lived MCP tokens a user manages
|
||||
@@ -10,6 +11,7 @@ import { TokenService } from './token.service';
|
||||
* for it, and any dependency added here lands in all three graphs.
|
||||
*/
|
||||
@Module({
|
||||
imports: [EphemeralTokenModule],
|
||||
providers: [TokenService],
|
||||
exports: [TokenService],
|
||||
})
|
||||
|
||||
@@ -25,6 +25,7 @@ import { AccommodationsService } from '../accommodations/accommodations.service'
|
||||
import { TripMembersService } from '../trip-members/trip-members.service';
|
||||
import { TripReadModelService } from '../trip-read-model/trip-read-model.service';
|
||||
import { notificationsInstance } from '../notifications/notifications.instance';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
|
||||
/**
|
||||
* Non-Nest entry point for the trip domain — for the two consumers that cannot
|
||||
@@ -75,7 +76,7 @@ const readModel = new TripReadModelService(
|
||||
new CollabService(dbs(), permissions, realtime, notificationsInstance()),
|
||||
places,
|
||||
new TodoService(dbs(), permissions, realtime),
|
||||
new FilesService(dbs(), permissions, realtime),
|
||||
new FilesService(dbs(), permissions, realtime, new EphemeralTokenService()),
|
||||
);
|
||||
|
||||
export function getTripOwner(tripId: string | number) {
|
||||
|
||||
Reference in New Issue
Block a user