feat(backend): implement phases 0-6 (auth, kc, wahl, files, chat, sync)

Full NestJS backend for the KC-App platform:
- auth: Authentik OIDC resource-server strategy + guest invite-code JWT
  login, plus TokenVerificationService for the WS handshake path
- kc: Leitungsteam-only KC (event) creation/listing
- wahl: Wahl/Workshop admin, Force-Zuteilung overrides, ZuteilungService
  (port of the WP plugin's kc_run_zuteilung), CSV export
- files: LT-only upload with visibility tiers; list/download filtered by
  caller tier; StorageProvider abstraction (WebDAV/Nextcloud default, S3)
- chat: Gemeinde group / DM / LT-wide / broadcast channels; REST + raw ws
  gateway sharing ChatService access rules
- sync: append-only SyncLogEntry replication log + local<->cloud
  push/pull scheduler, shared-secret guarded
- common: Role enum, @Roles decorator, KC-scoped RolesGuard (LT global)
- serves client/web/ interim static web client under / (API under /api)

Typecheck, nest build and boot test pass; needs real Postgres/Authentik/
Nextcloud to run end to end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-09 16:23:45 +02:00
co-authored by Claude Sonnet 5
parent 327ce43404
commit 8ec127c0fb
42 changed files with 2648 additions and 78 deletions
+7
View File
@@ -0,0 +1,7 @@
import { IsArray, IsNotEmpty } from 'class-validator';
export class IngestEntriesDto {
@IsArray()
@IsNotEmpty()
entries!: unknown[];
}
+32
View File
@@ -0,0 +1,32 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Interval } from '@nestjs/schedule';
import { SyncService } from './sync.service';
/// Periodically pushes/pulls against the configured peer when enabled. Safe
/// to fail silently (e.g. no internet at an on-site event) - just retries
/// on the next tick.
@Injectable()
export class SyncSchedulerService {
private readonly logger = new Logger(SyncSchedulerService.name);
constructor(
private readonly sync: SyncService,
private readonly config: ConfigService,
) {}
@Interval(30_000)
async tick() {
if (this.config.get<string>('SYNC_ENABLED') !== 'true') return;
const peerUrl = this.config.get<string>('SYNC_PEER_URL');
const peerSecret = this.config.get<string>('SYNC_SHARED_SECRET');
if (!peerUrl || !peerSecret) return;
try {
await this.sync.pushToPeer(peerUrl, peerSecret);
await this.sync.pullFromPeer(peerUrl, peerSecret);
} catch (err) {
this.logger.debug(`Sync with peer skipped: ${(err as Error).message}`);
}
}
}
+18
View File
@@ -0,0 +1,18 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
/// Server-to-server auth for /sync/*: a shared secret header, not a user token.
@Injectable()
export class SyncSecretGuard implements CanActivate {
constructor(private readonly config: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const expected = this.config.getOrThrow<string>('SYNC_SHARED_SECRET');
if (request.headers['x-sync-secret'] !== expected) {
throw new ForbiddenException('Invalid sync secret');
}
return true;
}
}
+45
View File
@@ -0,0 +1,45 @@
import { Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';
import { SyncService } from './sync.service';
import { SyncSecretGuard } from './sync-secret.guard';
import { IngestEntriesDto } from './dto/ingest-entries.dto';
import { Roles } from '../common/roles.decorator';
import { RolesGuard } from '../common/roles.guard';
import { Role } from '../common/role.enum';
@Controller('sync')
export class SyncController {
constructor(
private readonly sync: SyncService,
private readonly config: ConfigService,
) {}
/// Peer pushes its new entries to us.
@Post('ingest')
@UseGuards(SyncSecretGuard)
async ingest(@Body() dto: IngestEntriesDto) {
await this.sync.applyIncoming(dto.entries as never);
return { applied: dto.entries.length };
}
/// Peer pulls our new entries since their last known sequence.
@Get('export')
@UseGuards(SyncSecretGuard)
async export(@Query('since') since: string) {
const entries = await this.sync.getEntriesSince(Number(since) || 0);
return { entries };
}
/// Manual on-demand push+pull against the configured peer (Leitungsteam-only).
@Post('trigger')
@UseGuards(AuthGuard('authentik'), RolesGuard)
@Roles(Role.LEITUNGSTEAM)
async trigger() {
const peerUrl = this.config.getOrThrow<string>('SYNC_PEER_URL');
const peerSecret = this.config.getOrThrow<string>('SYNC_SHARED_SECRET');
const pushed = await this.sync.pushToPeer(peerUrl, peerSecret);
const pulled = await this.sync.pullFromPeer(peerUrl, peerSecret);
return { ...pushed, ...pulled };
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Global, Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { SyncService } from './sync.service';
import { SyncController } from './sync.controller';
import { SyncSchedulerService } from './sync-scheduler.service';
/// Global so every feature module can inject SyncService to capture its
/// mutations without each one importing SyncModule explicitly.
@Global()
@Module({
imports: [ScheduleModule.forRoot()],
controllers: [SyncController],
providers: [SyncService, SyncSchedulerService],
exports: [SyncService],
})
export class SyncModule {}
+154
View File
@@ -0,0 +1,154 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SyncOperation } from '@prisma/client';
import { PrismaClient } from '../prisma/prisma.module';
const SYNCED_MODELS = [
'Kc',
'Gemeinde',
'GuestAccount',
'Wahl',
'Workshop',
'Teilnehmer',
'ForceZuteilung',
'Zuteilung',
'File',
'ChatChannel',
'ChatMessage',
] as const;
export type SyncedModel = (typeof SYNCED_MODELS)[number];
interface IncomingEntry {
sequence: number;
model: string;
recordId: string;
operation: SyncOperation;
payload: Record<string, unknown>;
originId: string;
}
/// Replicates mutations between the local (on-site) and cloud server. The
/// local server is the sole source of truth while an event is live, so
/// incoming entries are applied with simple upserts - no conflict resolution
/// is needed by design (see plan doc).
@Injectable()
export class SyncService {
private readonly logger = new Logger(SyncService.name);
readonly serverId: string;
constructor(
private readonly prisma: PrismaClient,
private readonly config: ConfigService,
) {
this.serverId = config.getOrThrow<string>('SERVER_ID');
}
/// Called by feature services right after a mutation to append it to the replication log.
async capture(model: SyncedModel, operation: SyncOperation, recordId: string, payload: object) {
await this.prisma.syncLogEntry.create({
data: {
model,
recordId,
operation,
payload: payload as never,
originId: this.serverId,
},
});
}
async getEntriesSince(sequence: number, limit = 500) {
return this.prisma.syncLogEntry.findMany({
where: { sequence: { gt: sequence } },
orderBy: { sequence: 'asc' },
take: limit,
});
}
/// Applies entries received from a peer; never re-captures them, which is
/// what prevents echo loops between the two servers.
async applyIncoming(entries: IncomingEntry[]) {
for (const entry of entries) {
if (entry.originId === this.serverId) continue;
const delegate = this.delegateFor(entry.model);
if (!delegate) {
this.logger.warn(`Skipping sync entry for unknown model "${entry.model}"`);
continue;
}
try {
if (entry.operation === SyncOperation.DELETE) {
await delegate.delete({ where: { id: entry.recordId } });
} else {
await delegate.upsert({
where: { id: entry.recordId },
create: entry.payload,
update: entry.payload,
});
}
} catch (err) {
this.logger.warn(
`Failed to apply sync entry ${entry.model}/${entry.recordId}: ${(err as Error).message}`,
);
}
}
}
async pushToPeer(peerUrl: string, peerSecret: string) {
const peerId = new URL(peerUrl).host;
const cursor = await this.getOrCreateCursor(peerId);
const entries = await this.getEntriesSince(cursor.lastPushedSequence);
if (entries.length === 0) return { pushed: 0 };
const res = await fetch(`${peerUrl}/sync/ingest`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-sync-secret': peerSecret },
body: JSON.stringify({ entries }),
});
if (!res.ok) {
throw new Error(`Peer rejected sync push: ${res.status}`);
}
await this.prisma.syncCursor.update({
where: { peerId },
data: { lastPushedSequence: entries[entries.length - 1].sequence },
});
return { pushed: entries.length };
}
async pullFromPeer(peerUrl: string, peerSecret: string) {
const peerId = new URL(peerUrl).host;
const cursor = await this.getOrCreateCursor(peerId);
const res = await fetch(`${peerUrl}/sync/export?since=${cursor.lastPulledSequence}`, {
headers: { 'x-sync-secret': peerSecret },
});
if (!res.ok) {
throw new Error(`Peer rejected sync pull: ${res.status}`);
}
const { entries } = (await res.json()) as { entries: IncomingEntry[] };
if (entries.length === 0) return { pulled: 0 };
await this.applyIncoming(entries);
await this.prisma.syncCursor.update({
where: { peerId },
data: { lastPulledSequence: entries[entries.length - 1].sequence },
});
return { pulled: entries.length };
}
private async getOrCreateCursor(peerId: string) {
return this.prisma.syncCursor.upsert({
where: { peerId },
create: { peerId },
update: {},
});
}
private delegateFor(model: string) {
if (!SYNCED_MODELS.includes(model as SyncedModel)) return null;
const key = (model.charAt(0).toLowerCase() + model.slice(1)) as keyof PrismaClient;
// Generic dispatch across models is inherent to a replication log; each
// delegate exposes the same upsert/delete shape we need here.
return this.prisma[key] as unknown as {
upsert: (args: { where: { id: string }; create: object; update: object }) => Promise<unknown>;
delete: (args: { where: { id: string } }) => Promise<unknown>;
};
}
}