feat(assistant): an admin can share their ChatGPT plan with everyone

The connection for everyone can now also be the admin's own ChatGPT sign-in.
Whether a plan may be shared that way is the self-hoster's call under their
plan and OpenAI's terms; the form says what it means before the sign-in.
The sign-in starts on the admin route and finishes on the shared one, which
refuses a sign-in for everyone to anyone who is not an admin. The ChatGPT
return reads the clipboard only once the paste handler exists.
This commit is contained in:
Maurice
2026-10-21 22:57:40 +02:00
parent 422e213438
commit a372313ea1
38 changed files with 220 additions and 68 deletions
@@ -9,6 +9,7 @@ import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { AiAdminSettingsDto, AiInstanceConnectionDto } from './ai-connections.dto';
import { AiConnectionsService } from './ai-connections.service';
import { ChatgptAuthService } from './chatgpt-auth.service';
import { OpenrouterAuthService } from './openrouter-auth.service';
import { Body, Controller, Delete, Get, HttpCode, Post, Put, UseGuards } from '@nestjs/common';
import {
@@ -34,6 +35,7 @@ export class AiAdminController {
constructor(
private readonly connections: AiConnectionsService,
private readonly openrouter: OpenrouterAuthService,
private readonly chatgpt: ChatgptAuthService,
) {}
@Get('settings')
@@ -81,4 +83,20 @@ export class AiAdminController {
startOpenrouter(@CurrentUser() user: User) {
return this.openrouter.start(user.id, 'instance');
}
/** The admin shares their own ChatGPT plan with everyone here; the sign-in finishes on the user route. */
@Post('connect/chatgpt/start')
@HttpCode(200)
@ResponseContract(aiAuthStartResponseSchema)
startChatgpt(@CurrentUser() user: User) {
return this.chatgpt.start(user.id, 'instance');
}
@Post('connect/chatgpt/sign-out')
@HttpCode(200)
@ResponseContract(aiAdminConnectionResponseSchema)
async signOutChatgpt(@CurrentUser() user: User) {
await this.chatgpt.signOut(user.id, 'instance');
return this.connections.instanceConnection();
}
}
@@ -7,6 +7,8 @@ export const AI_AUTH_FLOW_TTL_MS = 10 * 60_000;
export interface ChatgptAuthFlow {
provider: 'chatgpt';
userId: number;
/** A user's own plan, or the plan an admin shares with everyone on the instance. */
scope: AiConnectionScope;
verifier: string;
state: string;
nonce: string;
@@ -96,8 +96,9 @@ export class AiConnectionsController {
@HttpCode(200)
@ResponseContract(aiConnectionViewSchema)
async finishChatgpt(@CurrentUser() user: User, @Body() body: AiChatgptFinishDto) {
await this.chatgpt.finish(user.id, body.flowId, body.pastedUrl);
return this.connections.ownView(user.id);
// A sign-in an admin started for everyone answers with the instance's connection.
const scope = await this.chatgpt.finish(user, body.flowId, body.pastedUrl);
return scope === 'instance' ? this.connections.instanceView() : this.connections.ownView(user.id);
}
@Post('connect/chatgpt/sign-out')
@@ -243,6 +243,13 @@ export class AiConnectionsService implements SharedAiConnectionPort {
return saved;
}
/** The instance's connection as a user's own is shown, once a sign-in saved it. */
async instanceView(): Promise<AiConnectionView> {
const row = await this.connections.findInstance();
if (!row) throw aiRefusal('not_found', 'No connection for everyone yet');
return viewOf(row);
}
async instanceConnection(): Promise<AiAdminConnectionResponse> {
const row = await this.connections.findInstance();
return {
@@ -15,7 +15,7 @@ import { ModelCatalogService, pickDefaultModel } from './model-catalog.service';
import { AiProviderError, errorCodeOf } from './providers/provider-errors';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { AiAuthStartResponse, AiModelInfo } from '@trek/shared';
import type { AiAuthStartResponse, AiConnectionScope, AiModelInfo } from '@trek/shared';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { z } from 'zod';
@@ -150,9 +150,15 @@ export class ChatgptAuthService {
private readonly lock: AiRefreshLock,
) {}
async start(userId: number): Promise<AiAuthStartResponse> {
await this.settings.assertCanConnectOwn(userId);
const existing = await this.connections.findForUser(userId);
/**
* Starts a sign-in for the user's own connection, or for the instance's:
* an admin may share their plan with everyone here. Whether that suits
* their plan and OpenAI's terms is the admin's call; the setting says so.
*/
async start(userId: number, scope: AiConnectionScope = 'user'): Promise<AiAuthStartResponse> {
if (scope === 'user') await this.settings.assertCanConnectOwn(userId);
const existing =
scope === 'instance' ? await this.connections.findInstance() : await this.connections.findForUser(userId);
const savedClientId = existing?.kind === 'chatgpt' ? (this.accountOf(existing).clientId ?? null) : null;
const verifier = randomToken();
const state = randomToken();
@@ -173,7 +179,16 @@ export class ChatgptAuthService {
});
const flowId = randomUUID();
const expiresAt = Date.now() + AI_AUTH_FLOW_TTL_MS;
await this.flows.put(flowId, { provider: 'chatgpt', userId, verifier, state, nonce, savedClientId, expiresAt });
await this.flows.put(flowId, {
provider: 'chatgpt',
userId,
scope,
verifier,
state,
nonce,
savedClientId,
expiresAt,
});
return {
flowId,
authorizeUrl: `${AUTHORIZE_URL}?${params.toString()}`,
@@ -183,16 +198,18 @@ export class ChatgptAuthService {
/**
* Finishes a sign-in from the pasted callback address and saves the
* connection. The address is checked before the flow is taken, so a wrong
* paste can be corrected without starting over.
* connection, the user's or (started by an admin) the instance's; answers
* which. The address is checked before the flow is taken, so a wrong paste
* can be corrected without starting over.
*/
async finish(userId: number, flowId: string, pastedUrl: string): Promise<void> {
await this.settings.assertCanConnectOwn(userId);
async finish(user: { id: number; role: string }, flowId: string, pastedUrl: string): Promise<AiConnectionScope> {
const callback = readPastedCallback(pastedUrl);
const flow = await this.flows.take(flowId, userId, Date.now());
const flow = await this.flows.take(flowId, user.id, Date.now());
if (flow?.provider !== 'chatgpt' || callback.state !== flow.state) {
throw aiRefusal('expired', 'The sign-in took too long; start it again');
}
if (flow.scope === 'instance' && user.role !== 'admin') throw aiRefusal('forbidden', 'Admin access required');
if (flow.scope === 'user') await this.settings.assertCanConnectOwn(user.id);
if (callback.error) throw aiRefusal('generic', 'ChatGPT did not complete the sign-in');
// A first sign-in names the client id issued to this user's registration;
// a later one may leave it out, but must not name another.
@@ -214,7 +231,8 @@ export class ChatgptAuthService {
throw aiRefusal('generic', 'The sign-in could not be verified');
}
const existing = await this.connections.findForUser(userId);
const existing =
flow.scope === 'instance' ? await this.connections.findInstance() : await this.connections.findForUser(user.id);
const previous: AiConnectionAccount = existing?.kind === 'chatgpt' ? this.accountOf(existing) : {};
if (previous.sub && previous.sub !== claims.sub) {
throw aiRefusal('account_mismatch', 'This is another ChatGPT account; remove the connection first');
@@ -225,7 +243,7 @@ export class ChatgptAuthService {
}
const model = await this.modelFor(existing, tokens.access_token);
await this.connections.save(userId, {
await this.connections.save(flow.scope === 'instance' ? null : user.id, {
kind: 'chatgpt',
model,
baseUrl: null,
@@ -237,14 +255,16 @@ export class ChatgptAuthService {
hint: typeof claims.email === 'string' ? claims.email : null,
account: encodeJson(AI_CONNECTION_ACCOUNT, { clientId, sub: claims.sub, scopes }),
});
return flow.scope;
}
/**
* Signs the user out: the tokens go, the registration stays (the client id
* and the account), so signing in again is the same registration.
*/
async signOut(userId: number): Promise<void> {
const row = await this.connections.findForUser(userId);
async signOut(userId: number, scope: AiConnectionScope = 'user'): Promise<void> {
const row =
scope === 'instance' ? await this.connections.findInstance() : await this.connections.findForUser(userId);
if (row?.kind !== 'chatgpt') throw aiRefusal('not_found', 'No ChatGPT sign-in to sign out of');
await this.connections.clearSecrets(row.id, 'signed_out');
}