From 00e98b8711e35eb998eb49f0c7ccd91e62592666 Mon Sep 17 00:00:00 2001 From: Maurice Date: Tue, 1 Dec 2026 00:27:08 +0100 Subject: [PATCH] feat(assistant): support the managed TREK gateway --- client/src/store/assistantStore.ts | 10 +-- server/src/app-config/README.md | 2 +- server/src/app-config/derive.ts | 11 +-- server/src/app-config/env.schema.ts | 3 + server/src/app-config/env.ts | 26 +++++++ .../ai-connections/ai-chat-client.service.ts | 10 +++ .../ai-connections.controller.ts | 4 + .../ai-connections/ai-connections.service.ts | 74 +++++++++++++++++-- .../ai-connections/ai-connections.types.ts | 2 + .../assistant-attachments.controller.ts | 4 +- .../assistant/assistant-renders.controller.ts | 4 +- .../nest/assistant/assistant.controller.ts | 2 +- .../src/nest/assistant/assistant.service.ts | 7 +- .../assistant/home-assistant.controller.ts | 2 +- .../assistant/journey-assistant.controller.ts | 2 +- server/src/nest/common/managed.guard.ts | 10 +-- server/src/nest/common/managed.ts | 12 ++- server/tests/e2e/ai-connections.e2e.test.ts | 38 ++++++++++ server/tests/unit/nest/managed.guard.test.ts | 23 +++++- 19 files changed, 207 insertions(+), 39 deletions(-) diff --git a/client/src/store/assistantStore.ts b/client/src/store/assistantStore.ts index 3c0156f92..a873452da 100644 --- a/client/src/store/assistantStore.ts +++ b/client/src/store/assistantStore.ts @@ -37,7 +37,6 @@ import { type WindowRect, } from './assistantMapModel'; import { applyChunk, closeUndo, markDecisions } from './assistantMessages'; -import { useAuthStore } from './authStore'; import { useSettingsStore } from './settingsStore'; import { useTripStore } from './tripStore'; @@ -124,7 +123,7 @@ interface UndoBlockResult { interface AssistantState { /** * What the assistant runs on for this user; null until loaded, while no addon - * opens /api/ai (aiRoutesOpen) and on a managed install, and the assistant stays hidden then. + * opens /api/ai (aiRoutesOpen). Otherwise the assistant stays hidden. */ status: AiStatusResponse | null; window: { open: boolean; minimized: boolean }; @@ -325,7 +324,7 @@ export function chatOf(state: Pick, key: AssistantChat * Whether the addons open /api/ai: the server opens it while the assistant or * AI parsing is on, the two sharing one connection, and answers 404 while * both are off. Closed until the addon list is in. A selector on the addon - * store; a managed install refuses /api/ai whatever it says (loadStatus). + * store. The server's status response decides availability on managed installs. */ export function aiRoutesOpen({ loaded, @@ -586,9 +585,8 @@ function backToAfter(byTrip: Record): Record { - // While /api/ai is closed the request could only get a 404, or the 403 of a managed install: nothing is asked, - // and the assistant stays hidden. The managed flag comes with the app config, which can land after the addons. - if (useAuthStore.getState().managed || !aiRoutesOpen(useAddonStore.getState())) { + // When both addons are off the status route is closed. + if (!aiRoutesOpen(useAddonStore.getState())) { ctx.set({ status: null }); return; } diff --git a/server/src/app-config/README.md b/server/src/app-config/README.md index 5995d20d8..1dc354d3b 100644 --- a/server/src/app-config/README.md +++ b/server/src/app-config/README.md @@ -165,7 +165,7 @@ below.) **Runtime-toggled** (read live on every access via `readEnv()` / `RuntimeEnvService`; tests mutate these mid-lifetime): -TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED, +TREK_MANAGED, TREK_MANAGED_ASSISTANT_URL, TREK_MANAGED_ASSISTANT_TOKEN, TREK_MANAGED_ASSISTANT_MODEL, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED, TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS, OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL, diff --git a/server/src/app-config/derive.ts b/server/src/app-config/derive.ts index c54188806..12831ba3d 100644 --- a/server/src/app-config/derive.ts +++ b/server/src/app-config/derive.ts @@ -122,17 +122,18 @@ function flagText(raw: string | undefined): 'true' | 'false' | undefined { * Whether this instance is centrally administered: somebody other than its * admin user owns the configuration, the credentials and the upgrade schedule. * - * Only a boolean, on purpose. It answers "who configures this install", and the - * surfaces that care read it themselves rather than being listed here, so adding - * one never touches this file. - * * `=== true` so an unset, empty or unparseable value means off. A managed * install sets it deliberately; nothing should be able to switch it on by * accident, and a typo must not silently take settings away from an admin. */ export function deriveManaged(raw: RawEnv) { + const enabled = parseBool(raw.TREK_MANAGED) === true; + const baseUrl = raw.TREK_MANAGED_ASSISTANT_URL?.trim(); + const token = raw.TREK_MANAGED_ASSISTANT_TOKEN?.trim(); + const model = raw.TREK_MANAGED_ASSISTANT_MODEL?.trim(); return { - enabled: parseBool(raw.TREK_MANAGED) === true, + enabled, + assistant: enabled && baseUrl && token && model ? { baseUrl, token, model } : null, }; } diff --git a/server/src/app-config/env.schema.ts b/server/src/app-config/env.schema.ts index 9acaf78b4..91762cb45 100644 --- a/server/src/app-config/env.schema.ts +++ b/server/src/app-config/env.schema.ts @@ -213,6 +213,9 @@ export const envSchema = z.object({ ADMIN_EMAIL: anyString, ADMIN_PASSWORD: anyString, TREK_MANAGED: boolStr, + TREK_MANAGED_ASSISTANT_URL: url, + TREK_MANAGED_ASSISTANT_TOKEN: anyString, + TREK_MANAGED_ASSISTANT_MODEL: anyString, PLACES_API_BASE: url, GOOGLE_LIST_DATA_BASE: url, TREK_PLACES_URL: url, diff --git a/server/src/app-config/env.ts b/server/src/app-config/env.ts index 4d213194d..11e39c6cf 100644 --- a/server/src/app-config/env.ts +++ b/server/src/app-config/env.ts @@ -28,6 +28,7 @@ export const SECRET_ENV_KEYS: ReadonlySet = new Set([ 'ADMIN_PASSWORD', 'PLACES_API_KEY', 'TREK_SERVICES_KEY', + 'TREK_MANAGED_ASSISTANT_TOKEN', 'AMAP_API_KEY', 'AMAP_API_SECRET', 'MAPBOX_ACCESS_TOKEN', @@ -153,5 +154,30 @@ function managedPreconditions(raw: RawEnv): string[] { ); } + const { + TREK_MANAGED_ASSISTANT_URL: baseUrl, + TREK_MANAGED_ASSISTANT_MODEL: model, + TREK_MANAGED_ASSISTANT_TOKEN: token, + } = raw; + if (baseUrl || model || token) { + if (!baseUrl || !model?.trim() || !token?.trim()) { + problems.push(' - The managed assistant URL, model and token must be configured together.'); + } else { + const endpoint = URL.canParse(baseUrl) ? new URL(baseUrl) : null; + if ( + !endpoint || + endpoint.protocol !== 'https:' || + endpoint.username || + endpoint.password || + endpoint.search || + endpoint.hash + ) { + problems.push( + ' - TREK_MANAGED_ASSISTANT_URL must be an HTTPS URL without credentials, a query or a fragment.', + ); + } + } + } + return problems; } diff --git a/server/src/nest/ai-connections/ai-chat-client.service.ts b/server/src/nest/ai-connections/ai-chat-client.service.ts index d5f325895..787e242d2 100644 --- a/server/src/nest/ai-connections/ai-chat-client.service.ts +++ b/server/src/nest/ai-connections/ai-chat-client.service.ts @@ -16,6 +16,7 @@ import { Injectable } from '@nestjs/common'; * is the adapter's. */ const cloudFetch: AiFetch = (url, init) => safeFetch(url, { ...init, signal: init.signal }, { maxBytes: null }); +const hostedFetch: AiFetch = (url, init) => cloudFetch(url, { ...init, redirect: 'error' }); /** * An admin's own server, which may sit on loopback or in the LAN: the guard @@ -46,6 +47,15 @@ export class AiChatClientService { create(connection: ResolvedAiConnection): AiChatClient { const { credential, kind, model } = connection; if (credential.type === 'chatgpt') return this.chatgptPlan(connection.id, model, credential.accessToken); + if (connection.managed) { + return new OpenAiChatClient( + 'openrouter', + model, + ownServerChatBase(connection.baseUrl), + credential.apiKey, + hostedFetch, + ); + } if (kind === 'openai' && openAiWantsResponses(model)) { const apiKey = credential.apiKey ?? ''; return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai'); diff --git a/server/src/nest/ai-connections/ai-connections.controller.ts b/server/src/nest/ai-connections/ai-connections.controller.ts index b411671ee..224e0f21e 100644 --- a/server/src/nest/ai-connections/ai-connections.controller.ts +++ b/server/src/nest/ai-connections/ai-connections.controller.ts @@ -46,6 +46,7 @@ export class AiConnectionsController { ) {} @Get('status') + @ManagedForbidden('managed status describes the operator gateway', { allowHostedAssistant: true }) @ResponseContract(aiStatusResponseSchema) status(@CurrentUser() user: User) { return this.connections.status(user.id); @@ -78,6 +79,9 @@ export class AiConnectionsController { } @Post('privacy-ack') + @ManagedForbidden('the hosted assistant requires each user to acknowledge the provider', { + allowHostedAssistant: true, + }) @HttpCode(200) @ResponseContract(successResponseSchema) async ackPrivacy(@CurrentUser() user: User, @Body() body: AiPrivacyAckDto) { diff --git a/server/src/nest/ai-connections/ai-connections.service.ts b/server/src/nest/ai-connections/ai-connections.service.ts index 74f9e31cb..620a2658a 100644 --- a/server/src/nest/ai-connections/ai-connections.service.ts +++ b/server/src/nest/ai-connections/ai-connections.service.ts @@ -48,6 +48,27 @@ import { /** A key test asks the provider for its models: a few a minute per user, so the server is no oracle for keys. */ const MODEL_CALLS_PER_MINUTE = 5; +function hostedConnection(): ResolvedAiConnection | null { + const config = readEnv().managed.assistant; + if (!config) return null; + return { + id: 0, + managed: true, + scope: 'instance', + kind: 'openrouter', + model: config.model, + baseUrl: config.baseUrl, + host: aiHostOf('openrouter', null), + paidBy: 'instance', + status: 'ok', + credential: { type: 'api_key', apiKey: config.token }, + }; +} + +function privacyTarget(connection: Pick): string { + return `${connection.kind}@${connection.host}${connection.managed ? ':managed' : ''}`; +} + function kindOf(row: AiConnectionRow): AiConnectionKind { return row.kind as AiConnectionKind; } @@ -94,13 +115,35 @@ export class AiConnectionsService implements SharedAiConnectionPort { /** `kind:model` of the models a provider refused an image for, while this process runs. */ private readonly textOnly = new Set(); - /** Whether the assistant exists here at all: the addon is on and the install is not centrally administered. */ + /** The addon must be on. Managed installs additionally require the operator gateway. */ async enabled(): Promise { - return !readEnv().managed.enabled && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT)); + const managed = readEnv().managed; + return (!managed.enabled || !!managed.assistant) && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT)); } async status(userId: number): Promise { const settings = await this.aiSettings.read(); + const hosted = hostedConnection(); + if (hosted) { + const available = await this.enabled(); + const target = privacyTarget(hosted); + const instance = { kind: hosted.kind, model: hosted.model, host: hosted.host }; + return { + available, + policy: 'instance', + canConnectOwn: false, + effective: available ? { ...instance, source: 'instance', paidBy: 'instance' } : null, + own: null, + instance: available ? instance : null, + quota: null, + privacyAcked: + available && (await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) === target, + studioImages: available && this.readsImages(hosted), + studioImagesAcked: available && (await this.studioImagesAckedFor(userId, target)), + retention: settings.retention, + openrouterOAuth: false, + }; + } const own = await this.connections.findForUser(userId); const instance = await this.connections.findInstance(); const picked = (await this.enabled()) ? pickConnection(settings.policy, own, instance) : null; @@ -148,6 +191,14 @@ export class AiConnectionsService implements SharedAiConnectionPort { */ async resolveForUser(userId: number): Promise { if (!(await this.enabled())) throw aiRefusal('not_connected', 'The AI assistant is not available'); + const hosted = hostedConnection(); + if (hosted) { + const target = privacyTarget(hosted); + if ((await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) !== target) { + throw aiRefusal('forbidden', 'Acknowledge the AI Assistant privacy notice first'); + } + return hosted; + } const { policy } = await this.aiSettings.read(); const picked = pickConnection( policy, @@ -177,6 +228,7 @@ export class AiConnectionsService implements SharedAiConnectionPort { * clears an earlier mark. */ async noteOutcome(connection: ResolvedAiConnection, code: AssistantErrorCode | null): Promise { + if (connection.managed) return; if (code === 'invalid_key' && connection.status !== 'error') { await this.connections.setStatus(connection.id, 'error'); } else if (code === 'needs_reauth' && connection.kind === 'chatgpt') { @@ -241,12 +293,19 @@ export class AiConnectionsService implements SharedAiConnectionPort { */ async ackPrivacy(userId: number, req: AiPrivacyAckRequest): Promise { const key = req.scope === 'studio_images' ? AI_STUDIO_IMAGES_ACK_SETTING : AI_PRIVACY_ACK_SETTING; - await this.settings.upsertSetting(userId, key, `${req.kind}@${req.host}`); + const hosted = hostedConnection(); + if (hosted && (req.kind !== hosted.kind || req.host !== hosted.host)) { + throw aiRefusal('forbidden', 'This is not the configured AI Assistant provider'); + } + await this.settings.upsertSetting(userId, key, privacyTarget(hosted ?? req)); } /** Whether the user let this connection receive images of their Studio pages; without it a turn stays text. */ - async studioImagesAcked(userId: number, connection: Pick): Promise { - return this.studioImagesAckedFor(userId, `${connection.kind}@${connection.host}`); + async studioImagesAcked( + userId: number, + connection: Pick, + ): Promise { + return this.studioImagesAckedFor(userId, privacyTarget(connection)); } private async studioImagesAckedFor(userId: number, target: string): Promise { @@ -259,8 +318,9 @@ export class AiConnectionsService implements SharedAiConnectionPort { * runs. Status asks this too, so the Studio offers images only where a turn * would send them. */ - readsImages({ kind, model }: Pick): boolean { - return modelReadsImages(kind, model) && !this.textOnly.has(`${kind}:${model}`); + readsImages({ kind, model, managed }: Pick): boolean { + const supported = modelReadsImages(kind, model) || (managed === true && model === 'qwen/qwen3.7-flash'); + return supported && !this.textOnly.has(`${kind}:${model}`); } /** A provider refused an image for this model: it reads pages in words until the process restarts. */ diff --git a/server/src/nest/ai-connections/ai-connections.types.ts b/server/src/nest/ai-connections/ai-connections.types.ts index d56aa586c..eeaab6948 100644 --- a/server/src/nest/ai-connections/ai-connections.types.ts +++ b/server/src/nest/ai-connections/ai-connections.types.ts @@ -10,6 +10,8 @@ export type AiCredential = { type: 'api_key'; apiKey: string | null } | { type: */ export interface ResolvedAiConnection { id: number; + /** Operator gateway configuration has no database connection row or tenant daily quota. */ + managed?: true; scope: AiConnectionScope; kind: AiConnectionKind; model: string; diff --git a/server/src/nest/assistant/assistant-attachments.controller.ts b/server/src/nest/assistant/assistant-attachments.controller.ts index fe7c99a0c..ce19ce6e7 100644 --- a/server/src/nest/assistant/assistant-attachments.controller.ts +++ b/server/src/nest/assistant/assistant-attachments.controller.ts @@ -5,7 +5,7 @@ import { aiRefusal } from '../ai-connections/ai-connections.constants'; import { RuntimeEnvService } from '../app-config/runtime-env.service'; import { CurrentUser } from '../auth-core/current-user.decorator'; import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; -import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed'; +import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed'; import { TripAccessService } from '../trip-membership/trip-access.service'; import { MAX_ATTACHMENT_BYTES } from './assistant-tools.constants'; import { channelOf } from './assistant.controller'; @@ -90,7 +90,7 @@ export class AssistantAttachmentsController { if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) { throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404); } - if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403); + if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403); if (!(await this.trips.findAccessible(tripId, user.id))) { throw new HttpException({ error: 'Trip not found' }, 404); } diff --git a/server/src/nest/assistant/assistant-renders.controller.ts b/server/src/nest/assistant/assistant-renders.controller.ts index 37cf2926f..0bffd18dc 100644 --- a/server/src/nest/assistant/assistant-renders.controller.ts +++ b/server/src/nest/assistant/assistant-renders.controller.ts @@ -5,7 +5,7 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service'; import { CurrentUser } from '../auth-core/current-user.decorator'; import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; import { readImageHeader } from '../common/image-header'; -import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed'; +import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed'; import { ResponseContract } from '../common/response-contract'; import { toRowId } from '../common/row-id'; import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service'; @@ -90,7 +90,7 @@ export class AssistantRendersController { if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) { throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404); } - if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403); + if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403); if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) { throw new HttpException({ error: 'Journey addon is not enabled' }, 404); } diff --git a/server/src/nest/assistant/assistant.controller.ts b/server/src/nest/assistant/assistant.controller.ts index 0b02cab35..c8ef36aa1 100644 --- a/server/src/nest/assistant/assistant.controller.ts +++ b/server/src/nest/assistant/assistant.controller.ts @@ -66,7 +66,7 @@ export function channelOf(res: Response): TurnChannel { @Controller('api/trips/:tripId/assistant') @UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard) @RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant') -@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it') +@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true }) export class AssistantController { constructor( private readonly assistant: AssistantService, diff --git a/server/src/nest/assistant/assistant.service.ts b/server/src/nest/assistant/assistant.service.ts index 93057a04d..96a9f70ed 100644 --- a/server/src/nest/assistant/assistant.service.ts +++ b/server/src/nest/assistant/assistant.service.ts @@ -249,7 +249,7 @@ export class AssistantService { if (begun.created) w.thread(begun.threadId, begun.title); await this.usage.record(userId, connection.paidBy, { turns: 1 }); const quota = - connection.paidBy === 'instance' + connection.paidBy === 'instance' && dailyTurns !== null ? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns } : null; const spec: TurnSpec = { @@ -372,7 +372,7 @@ export class AssistantService { const w = new UiStreamWriter(stream); w.start(messageIdOf(await this.answerStart(threadId, decided[0].call.message_id))); const quota = - connection.paidBy === 'instance' + connection.paidBy === 'instance' && dailyTurns !== null ? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns } : null; const spec: TurnSpec = { @@ -530,7 +530,8 @@ export class AssistantService { * day reached the admin's limit; answers that limit. A decision counts no * turn of its own, but runs the model again, so it is held to the limit too. */ - private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise { + private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise { + if (connection.managed) return null; const { dailyTurns } = await this.connections.readSettings(); if (connection.paidBy === 'instance' && (await this.usage.instanceTurnsToday(userId)) >= dailyTurns) { throw aiRefusal('daily_limit', 'The daily limit of the assistant is reached'); diff --git a/server/src/nest/assistant/home-assistant.controller.ts b/server/src/nest/assistant/home-assistant.controller.ts index 46a4d0311..e7fef9389 100644 --- a/server/src/nest/assistant/home-assistant.controller.ts +++ b/server/src/nest/assistant/home-assistant.controller.ts @@ -36,7 +36,7 @@ import type { Response } from 'express'; @Controller('api/assistant') @UseGuards(AddonGuard, JwtAuthGuard) @RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant') -@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it') +@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true }) export class HomeAssistantController { constructor(private readonly assistant: AssistantService) {} diff --git a/server/src/nest/assistant/journey-assistant.controller.ts b/server/src/nest/assistant/journey-assistant.controller.ts index 7f34632eb..c54e7bbf5 100644 --- a/server/src/nest/assistant/journey-assistant.controller.ts +++ b/server/src/nest/assistant/journey-assistant.controller.ts @@ -49,7 +49,7 @@ function journeyScope(journeyId: string, surface?: AssistantJourneySurface): Ass @Controller('api/journeys/:journeyId/assistant') @UseGuards(AddonGuard, JwtAuthGuard, JourneyAssistantGuard) @RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant') -@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it') +@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true }) export class JourneyAssistantController { constructor(private readonly assistant: AssistantService) {} diff --git a/server/src/nest/common/managed.guard.ts b/server/src/nest/common/managed.guard.ts index fed305f34..30c351670 100644 --- a/server/src/nest/common/managed.guard.ts +++ b/server/src/nest/common/managed.guard.ts @@ -1,5 +1,5 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service'; -import { MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed'; +import { isManagedAssistantBlocked, MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed'; import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; @@ -31,10 +31,9 @@ export class ManagedGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { if (!this.env.isManaged()) return true; - const marked = this.reflector.getAllAndOverride<{ enforcedInHandler?: boolean } | undefined>(MANAGED_FORBIDDEN, [ - context.getHandler(), - context.getClass(), - ]); + const marked = this.reflector.getAllAndOverride< + { enforcedInHandler?: boolean; allowHostedAssistant?: boolean } | undefined + >(MANAGED_FORBIDDEN, [context.getHandler(), context.getClass()]); if (!marked) return true; // A multipart handler checks for itself, after the interceptor has drained @@ -42,6 +41,7 @@ export class ManagedGuard implements CanActivate { // see an ECONNRESET rather than the 403 (PROFILE-015). The marker still sits // on the route so the boot gate can inventory it. if (marked.enforcedInHandler) return true; + if (marked.allowHostedAssistant && !isManagedAssistantBlocked(this.env)) return true; throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403); } diff --git a/server/src/nest/common/managed.ts b/server/src/nest/common/managed.ts index 8fbb091a3..c73d9971f 100644 --- a/server/src/nest/common/managed.ts +++ b/server/src/nest/common/managed.ts @@ -38,8 +38,12 @@ export const MANAGED_FORBIDDEN_ERROR = { * still carry the marker, because the boot gate inventories markers and a route * missing from that inventory is exactly what nobody notices. */ -export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true }) => - SetMetadata(MANAGED_FORBIDDEN, { reason, enforcedInHandler: opts?.enforcedInHandler === true }); +export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true; allowHostedAssistant?: true }) => + SetMetadata(MANAGED_FORBIDDEN, { + reason, + enforcedInHandler: opts?.enforcedInHandler === true, + ...(opts?.allowHostedAssistant ? { allowHostedAssistant: true } : {}), + }); /** * The handler-side flavour of the guard below. @@ -53,6 +57,10 @@ export function isManagedBlocked(env: RuntimeEnvService): boolean { return env.isManaged(); } +export function isManagedAssistantBlocked(env: RuntimeEnvService): boolean { + return env.isManaged() && !env.env().managed.assistant; +} + /** * The settings a centrally administered install does not hand to its admin, * because the value belongs to whoever operates it. diff --git a/server/tests/e2e/ai-connections.e2e.test.ts b/server/tests/e2e/ai-connections.e2e.test.ts index f4b25e5f8..a94daff38 100644 --- a/server/tests/e2e/ai-connections.e2e.test.ts +++ b/server/tests/e2e/ai-connections.e2e.test.ts @@ -10,6 +10,7 @@ */ import { AiConnections } from '../../src/db/entities/AiConnections.entity'; import { AiConnectionsModule } from '../../src/nest/ai-connections/ai-connections.module'; +import { AiConnectionsService } from '../../src/nest/ai-connections/ai-connections.service'; import { AppConfigModule } from '../../src/nest/app-config/app-config.module'; import { DemoModule } from '../../src/nest/common/demo.module'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; @@ -24,6 +25,7 @@ import { FakeRealtimeService } from '../helpers/fake-realtime'; import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; import { TestUnitOfWorkModule } from '../helpers/test-uow'; import { sessionCookie } from './harness'; +import { RequestContext } from '@mikro-orm/core'; import { Test } from '@nestjs/testing'; import cookieParser from 'cookie-parser'; @@ -111,6 +113,42 @@ afterAll(async () => { }); describe('AI connections e2e', () => { + it('uses the operator gateway and requires a separate acknowledgement on a managed instance', async () => { + vi.stubEnv('TREK_MANAGED', '1'); + vi.stubEnv('TREK_MANAGED_ASSISTANT_URL', 'https://gate.example.test/ai/v1'); + vi.stubEnv('TREK_MANAGED_ASSISTANT_MODEL', 'qwen/qwen3.7-flash'); + vi.stubEnv('TREK_MANAGED_ASSISTANT_TOKEN', 'synthetic-instance-bearer'); + try { + const connections = app.get(AiConnectionsService); + const resolve = () => RequestContext.create(orm.em, () => connections.resolveForUser(OTHER)); + const first = await request(server).get('/api/ai/status').set(as(OTHER)); + expect(first.status).toBe(200); + expect(first.body).toMatchObject({ + available: true, + canConnectOwn: false, + effective: { kind: 'openrouter', host: 'openrouter.ai', source: 'instance' }, + privacyAcked: false, + quota: null, + studioImages: true, + }); + expect(first.text).not.toContain('synthetic-instance-bearer'); + await expect(resolve()).rejects.toThrow('Acknowledge the AI Assistant privacy notice'); + const ack = await request(server) + .post('/api/ai/privacy-ack') + .set(as(OTHER)) + .send({ kind: 'openrouter', host: 'openrouter.ai' }); + expect(ack.status).toBe(200); + await expect(resolve()).resolves.toMatchObject({ + managed: true, + baseUrl: 'https://gate.example.test/ai/v1', + }); + expect((await request(server).get('/api/ai/status').set(as(OTHER))).body.privacyAcked).toBe(true); + expect(safeFetch).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + } + }); + it('AIE2E-001: the addon gate answers 404 before auth, then auth answers 401', async () => { await setAddonEnabled(orm, 'ai_assistant', false); expect((await request(server).get('/api/ai/status')).status).toBe(404); diff --git a/server/tests/unit/nest/managed.guard.test.ts b/server/tests/unit/nest/managed.guard.test.ts index aac355857..4ecfa865c 100644 --- a/server/tests/unit/nest/managed.guard.test.ts +++ b/server/tests/unit/nest/managed.guard.test.ts @@ -17,12 +17,23 @@ import { Reflector } from '@nestjs/core'; import { describe, it, expect, vi } from 'vitest'; -function makeGuard(managed: boolean, marked: boolean, enforcedInHandler = false) { +function makeGuard( + managed: boolean, + marked: boolean, + enforcedInHandler = false, + hosted = false, + allowHostedAssistant = false, +) { const getAllAndOverride = vi.fn((key: string) => - key === MANAGED_FORBIDDEN && marked ? { reason: 'the operator holds this', enforcedInHandler } : undefined, + key === MANAGED_FORBIDDEN && marked + ? { reason: 'the operator holds this', enforcedInHandler, allowHostedAssistant } + : undefined, ); const guard = new ManagedGuard( - { isManaged: () => managed } as unknown as RuntimeEnvService, + { + isManaged: () => managed, + env: () => ({ managed: { assistant: hosted ? {} : null } }), + } as unknown as RuntimeEnvService, { getAllAndOverride } as unknown as Reflector, ); return { guard, getAllAndOverride }; @@ -80,6 +91,12 @@ describe('ManagedGuard', () => { expect(guard.canActivate(ctx)).toBe(true); }); + it('only lets the hosted assistant through when the operator configured it and the handler permits it', () => { + expect(makeGuard(true, true, false, true, true).guard.canActivate(ctx)).toBe(true); + expect(thrown(() => makeGuard(true, true, false, true).guard.canActivate(ctx))?.getStatus()).toBe(403); + expect(thrown(() => makeGuard(true, true, false, false, true).guard.canActivate(ctx))?.getStatus()).toBe(403); + }); + it('MANAGED-GUARD-005: asks for the decorator on handler and controller, not for a path', () => { const { guard, getAllAndOverride } = makeGuard(true, false); guard.canActivate(ctx);