feat(ai): add operator-shared central Codex connection with per-user opt-in

Introduce an operator-level ChatGPT-subscription (Codex) credential that the
operator connects once and shares server-wide, plus a per-user switch to route
AI egress through it.

- Schema (migration 0235): three encrypted columns on AppSettings for the
  operator's central Codex access/refresh tokens and the ChatGPT-Account-ID
  claim, plus expiry/connected-at/status; a per-user useCentralCodex flag
  (default false). Register the new encrypted columns in the rotation registry
  and script.
- Resolution: add the admin-codex chain type; append it to a user's resolved
  chain only when they opted in AND the operator connected it. Tokens refresh
  server-side against the singleton row (CAS-style), same primitives as the
  per-user Codex path.
- Budget: bill an admin-codex primary against the operator cost cap, not the
  user plan — it drains the operator's account.
- Consent: admin-codex is server-managed external egress, gated by the existing
  consent machinery (self-snapshot and document surfaces alike). No existing
  consent path is weakened.
- Document order: rank admin-codex with the subscription tier (last), so the
  document class stays local-first.
- UI: admin device-code connect/disconnect card (cookie-only admin routes) with
  honest copy on account pooling, shared rate limits, and training-by-default;
  a per-user opt-in switch shown only once the operator has connected it, off by
  default, behind a one-time honesty confirm.
- i18n across all six locales; unit tests for the chain type, budget cap,
  consent gate, vision capability, and document order; a mocked e2e for both
  the admin connect surface and the per-user switch.

The central credential's tokens are encrypted at rest and never returned to a
non-admin API; the opt-in only takes effect once the operator has connected the
shared account.
This commit is contained in:
Marc-André Bombeck committed 2026-07-10 00:10:56 +02:00
1 parent fa42c8bc0b
commit d7e616eaa8
35 files changed
+1553 -26

No files matched your search

@@ -32,6 +32,7 @@ import { queryKeys } from "@/lib/query-keys";
import { AdminOpenAIProviderForm } from "./admin-openai-provider-form";
import { AnthropicProviderForm } from "./anthropic-provider-form";
import { AutoReadCard } from "./auto-read-card";
import { CentralCodexSwitch } from "./central-codex-switch";
import { CodexProviderForm } from "./codex-provider-form";
import { FallbackChainCard } from "./fallback-chain-card";
import { LocalProviderForm } from "./local-provider-form";
@@ -181,6 +182,10 @@ export function AiInsightsCard({
{/* Read uploaded vault documents automatically with AI (opt-in). */}
<AutoReadCard />
{/* Use the operator's shared central Codex connection (opt-in; only
renders when the operator has connected it). */}
<CentralCodexSwitch settings={insightsSettings} />
<RuntimeActionsRow
provider={selectedProvider}
userProvider={userProvider}
@@ -0,0 +1,143 @@
"use client";
/* ────────────────────────────────────────────────────────────────
* Use the server's shared AI access (per-user opt-in).
*
* Shown ONLY when the operator has connected a shared central Codex
* (ChatGPT-subscription) account. OFF by default. Turning it ON reveals a
* once-shown honesty confirm before the write, because the trade — a shared,
* signed-in AI account bound by the operator's rate limits, on which the
* provider may use content to improve its models with no data-processing
* agreement — must be acknowledged, not buried. Turning it OFF is immediate.
*
* Opting in does not egress anything on its own: the shared connection is
* server-managed external egress, so the existing AI-consent gate still applies
* before any health data leaves for it.
* ──────────────────────────────────────────────────────────────── */
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { apiPatch } from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { InsightsSettings } from "./shared";
interface UseCentralCodexPref {
useCentralCodex: boolean;
}
export function CentralCodexSwitch({
settings,
}: {
settings: InsightsSettings | null | undefined;
}) {
const { t } = useTranslations();
const queryClient = useQueryClient();
// Off→on reveals the honesty confirm; the write only happens on confirm.
const [pendingEnable, setPendingEnable] = useState(false);
const enabled = settings?.useCentralCodex ?? false;
const save = useMutation<UseCentralCodexPref, Error, boolean>({
mutationFn: (next: boolean) =>
apiPatch<UseCentralCodexPref>("/api/auth/me/use-central-codex", {
useCentralCodex: next,
}),
onSuccess: () => {
// The opt-in changes which providers can serve this user — refresh the
// settings summary (which carries the flag) and every insight read.
queryClient.invalidateQueries({
queryKey: queryKeys.insightsSettings(),
});
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
setPendingEnable(false);
},
});
// Only meaningful once the operator has connected the shared account.
if (!settings?.centralCodexAvailable) return null;
function onSwitch(next: boolean) {
if (next) {
if (!enabled) setPendingEnable(true);
return;
}
setPendingEnable(false);
if (enabled) save.mutate(false);
}
const busy = save.isPending;
const checked = enabled || pendingEnable;
return (
<div
data-slot="central-codex-switch-card"
className="bg-muted/50 space-y-4 rounded-lg p-4"
>
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-medium">
{t("settings.ai.centralCodex.title")}
</p>
<p className="text-muted-foreground text-xs">
{t("settings.ai.centralCodex.subLabel")}
</p>
</div>
<Switch
checked={checked}
disabled={busy}
onCheckedChange={onSwitch}
aria-label={t("settings.ai.centralCodex.title")}
data-testid="use-central-codex-enable"
/>
</div>
{pendingEnable ? (
<div
data-slot="central-codex-confirm"
role="note"
className="border-border space-y-3 rounded-lg border border-dashed px-3 py-2.5"
>
<div className="text-muted-foreground flex items-start gap-2 text-xs">
<ShieldAlert className="mt-0.5 size-3.5 shrink-0" aria-hidden />
<p className="min-w-0">{t("settings.ai.centralCodex.honesty")}</p>
</div>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
className="min-h-11 sm:min-h-9"
disabled={save.isPending}
onClick={() => save.mutate(true)}
data-slot="central-codex-confirm-cta"
>
{t("settings.ai.centralCodex.confirm")}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className="min-h-11 sm:min-h-9"
disabled={save.isPending}
onClick={() => setPendingEnable(false)}
>
{t("settings.ai.centralCodex.cancel")}
</Button>
</div>
</div>
) : null}
{save.isError ? (
<p className="text-destructive text-xs">
{t("settings.ai.errorGeneric")}
</p>
) : null}
</div>
);
}
+5
View File
@@ -14,6 +14,11 @@ export interface InsightsSettings {
* false to avoid the v1.4.2 dead-end where the click bounced the
* user to chatgpt.com without any OAuth flow. */
codexOauthConfigured?: boolean;
/** True when the operator has connected the shared central Codex. Drives
* whether the per-user "use the server's shared AI access" switch shows. */
centralCodexAvailable?: boolean;
/** The user's own opt-in to the operator's shared central Codex. */
useCentralCodex?: boolean;
privacyMode: string;
lastInsightAt: string | null;
}