Split PluginsModule into four, and gate coverage per domain

PluginsModule was 21 controllers, 24 domain imports and 10 providers in one
class, which made it the hub most of the Nest graph ran through: AdminModule
imported it for a single cascade-disable call and inherited all of it. It is now
PluginsRuntimeModule (supervisor, capability router, hook contracts),
PluginContributionsModule (the 14 read-only hook controllers, moved to
contributions/), PluginOAuthModule (the credential leaf, moved to oauth/) and a
composition root that keeps the install and delivery controllers. AdminModule
imports the runtime alone.

The three plugin files that reached for the db singleton alongside the injected
DatabaseService no longer do. plugin-host-state and signature-status take the
connection from the caller, and the three per-user settings functions that were
bare exports 'so the RPC host wiring can call them directly' are now
PluginUserSettingsService - the host wiring is providers, so it injects them.

Coverage moves from one repo-wide 80% to a per-domain ratchet. The single number
let a well-covered domain subsidise a thin one: booking-import sits at 50% and
integrations at 20%, and the aggregate still cleared the bar, so either could
have lost another ten points unnoticed. Each domain now carries its own measured
floor, regenerated by scripts/coverage-thresholds.mjs.

Two test-side findings on the way:

expect(undefined).toContain(SomeClass) PASSES in this vitest version - it only
throws for a string needle. Every '<X> is listed in its module providers' guard
was written that way, so all twelve of them silently stopped guarding the moment
their class moved. They go through expectRegisteredProvider now, which asserts
the array shape first.

The atlas region test paid for the one-off decompression of the multi-MB admin1
bundle inside its own 5s budget, which is why it failed under load and passed
alone. The bundle is warmed in beforeAll instead.
This commit is contained in:
Maurice
2026-08-09 18:20:54 +02:00
committed by Maurice
parent dc81a5365e
commit 6680bc7c74
66 changed files with 649 additions and 326 deletions
@@ -0,0 +1,104 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JourneyDomainService } from '../../journey/journey-domain.service';
import { AddonsService } from '../../addons/addons.service';
import { ADDON_IDS } from '../../../addons';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/journal-entry-rows/:entryId — extra rows for a journal entry,
* contributed by plugins implementing the `journalEntryProvider` hook. Additive +
* fail-safe like place-details: the entry's journey must be one the caller can
* access (owner/contributor — the same gate as the journal detail routes), the
* Journey addon must be on (an off addon just yields nothing, this endpoint is
* purely additive), each provider runs host->plugin on a short timeout, and one
* that errors/times out contributes nothing.
*
* Unlike place-details, every row is NORMALIZED server-side: strings are
* String()-coerced + length-capped, the row count is capped per plugin, and a
* row url must be http/https/mailto — a javascript:/data: url rendered as an
* <a href> would be click-XSS into the journal page.
*/
interface EntryRow {
label: string;
value?: string;
url?: string;
}
interface ProviderResult {
pluginId: string;
items: EntryRow[];
}
const MAX_ROWS = 12; // per provider — bounds the card footprint
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
function safeUrl(raw: unknown): string | undefined {
if (typeof raw !== 'string' || raw === '') return undefined;
try {
const u = new URL(raw);
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:' ? raw.slice(0, 2048) : undefined;
} catch {
return undefined;
}
}
function normalize(raw: unknown): EntryRow[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: EntryRow[] = [];
for (const r of list) {
if (out.length >= MAX_ROWS) break;
if (!r || typeof r !== 'object') continue;
const label = cap(r.label, 60);
if (!label) continue; // a row without a label is meaningless — drop it
out.push({
label,
value: r.value != null ? cap(r.value, 200) : undefined,
url: safeUrl(r.url),
});
}
return out;
}
@Controller('api/journal-entry-rows')
@UseGuards(JwtAuthGuard)
export class JournalEntryRowsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
private readonly addons: AddonsService,
private readonly journey: JourneyDomainService,
) {}
@Get(':entryId')
async get(
@Param('entryId') entryIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: ProviderResult[] }> {
if (!pluginsEnabled() || !this.addons.isAddonEnabled(ADDON_IDS.JOURNEY)) return { providers: [] };
const entryId = Number(entryIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(entryId) || userId == null) return { providers: [] };
// The entry's journey must be one the caller can access — same gate as a read.
const row = this.dbs.connection.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number } | undefined;
if (!row || !this.journey.canAccessJourney(row.journey_id, userId)) return { providers: [] };
const ids = this.hooks.providersOf('journalEntryProvider');
const results = await Promise.all(
ids.map(async (id): Promise<ProviderResult | null> => {
try {
const raw = await this.hooks.journalRows(id, entryId, userId);
const items = normalize(raw);
return items.length > 0 ? { pluginId: id, items } : null;
} catch {
return null; // a slow / failing provider is skipped, never fatal
}
}),
);
return { providers: results.filter((r): r is ProviderResult => r !== null) };
}
}