Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧑✈️ feat: Enroll Machines Through Explicit Browser Approval (#17344)
lia-by-librechat[bot]f08868d21f5d
diff --git a/.github/workflows/agents-integration-tests.yml b/.github/workflows/agents-integration-tests.ymlindex 1ef6050e4e..5b214ae1a7 100644--- a/.github/workflows/agents-integration-tests.yml+++ b/.github/workflows/agents-integration-tests.yml@@ -115,3 +115,30 @@ jobs:NODE_ENV: testREDIS_URI: redis://127.0.0.1:6379run: npm run test:integration++ - name: Checkout merged browser enrollment compatibility fixture+ uses: actions/checkout@v5+ with:+ repository: LibreChat-AI/code-interpreter+ ref: a3207a75c8327ba1c9526eff8b06f3588f3739ed+ path: .verification/browser-enrollment-upstream+ persist-credentials: false+ sparse-checkout: |+ packages/code+ service/src/bridge+ service/src/logger.ts+ sparse-checkout-cone-mode: false++ - name: Build the pinned merged CLI+ working-directory: .verification/browser-enrollment-upstream/packages/code+ run: npm ci --no-audit --no-fund && npm run build++ - name: Verify merged CLI enrollment and profile persistence+ working-directory: packages/api+ env:+ NODE_ENV: test+ CODE_SETUP_UPSTREAM: ${{ github.workspace }}/.verification/browser-enrollment-upstream+ CODE_SETUP_REDIS_URI: redis://127.0.0.1:6379/15+ run: >-+ npx jest src/code/setup/compatibility.integration.spec.ts+ --runInBand --coverage=false --forceExitdiff --git a/.prettierignore b/.prettierignoreindex fff14af7ac..6fb7b1ad16 100644--- a/.prettierignore+++ b/.prettierignore@@ -1,3 +1,6 @@# Generated artifact. Owned by `npm run -w @librechat/api openapi:generate`,# checked by `openapi:check`. Do not let Prettier reformat it.packages/api/openapi/agents.openapi.json++# Commit-pinned upstream source and its generated JavaScript.+vendor/code/diff --git a/Dockerfile b/Dockerfileindex 93fca242a5..2ea8f302dd 100644--- a/Dockerfile+++ b/Dockerfile@@ -32,6 +32,7 @@ COPY --chown=node:node client/package.json ./client/package.jsonCOPY --chown=node:node packages/data-provider/package.json ./packages/data-provider/package.jsonCOPY --chown=node:node packages/data-schemas/package.json ./packages/data-schemas/package.jsonCOPY --chown=node:node packages/api/package.json ./packages/api/package.json+COPY --chown=node:node vendor/code ./vendor/codeCOPY --chown=node:node packages/chat/package.json ./packages/chat/package.jsonRUN \diff --git a/Dockerfile.multi b/Dockerfile.multiindex c46eb25ba5..f29ae6e2d3 100644--- a/Dockerfile.multi+++ b/Dockerfile.multi@@ -28,6 +28,7 @@ RUN npm config set fetch-retry-maxtimeout 600000 && \COPY package*.json ./COPY packages/data-provider/package*.json ./packages/data-provider/COPY packages/api/package*.json ./packages/api/+COPY vendor/code ./vendor/codeCOPY packages/data-schemas/package*.json ./packages/data-schemas/COPY packages/client/package*.json ./packages/client/COPY packages/chat/package*.json ./packages/chat/diff --git a/api/server/routes/code-environments.js b/api/server/routes/code-environments.jsindex 3cc88e6d6a..6691c769d7 100644--- a/api/server/routes/code-environments.js+++ b/api/server/routes/code-environments.js@@ -1,15 +1,19 @@const express = require('express');+const mongoose = require('mongoose');const {GenerationJobManager,createCodeEnvironmentHttpHandlers,+ createCodeSetupRouter,codeEnvironmentPairingLimiter,codeEnvironmentStatusIpLimiter,codeEnvironmentStatusLimiter,} = require('@librechat/api');-const { SystemCapabilities } = require('@librechat/data-schemas');+const { SystemCapabilities, createBrowserSetupBackend } = require('@librechat/data-schemas');const { requireCapability } = require('~/server/middleware/roles/capabilities');const { getAppConfig, getCodeEnvironmentRegistry } = require('~/server/services/Config');-const { requireJwtAuth } = require('~/server/middleware');+const { requireJwtAuth, requireSameOrigin, checkBan } = require('~/server/middleware');+const { ViolationTypes } = require('librechat-data-provider');+const getLogStores = require('~/cache/getLogStores');const db = require('~/models');const router = express.Router();@@ -31,6 +35,18 @@ function getHandlers() {}const requireCodeEnvironmentManage = requireCapability(SystemCapabilities.MANAGE_CODE_ENVIRONMENTS);+router.use(+ '/setup',+ createCodeSetupRouter({+ backend: createBrowserSetupBackend(mongoose),+ getAppConfig,+ registry: getCodeEnvironmentRegistry,+ requireJwtAuth,+ requireSameOrigin,+ checkBan,+ banStore: getLogStores(ViolationTypes.BAN),+ }),+);router.use(requireJwtAuth);router.get('/', (req, res, next) => getHandlers().list(req, res, next));router.post('/pairings', codeEnvironmentPairingLimiter, (req, res, next) =>diff --git a/api/server/routes/code-environments.test.js b/api/server/routes/code-environments.test.jsindex d6029cc964..b9630f7ba9 100644--- a/api/server/routes/code-environments.test.js+++ b/api/server/routes/code-environments.test.js@@ -43,6 +43,7 @@ const mockGenerationJobManager = {getCleanupBlockingJobIdsForConversations: jest.fn(),};let mockHandlerDeps;+let mockSetupDeps;const mockModels = {isAgentTriggerPrincipalActive: jest.fn(),getConvoCodeEnvironmentDecision: jest.fn(),@@ -51,10 +52,17 @@ const mockModels = {jest.mock('@librechat/data-schemas', () => ({SystemCapabilities: { MANAGE_CODE_ENVIRONMENTS: 'manage:code_environments' },+ createBrowserSetupBackend: jest.fn(() => ({})),}));jest.mock('@librechat/api', () => ({GenerationJobManager: mockGenerationJobManager,+ createCodeSetupRouter: jest.fn((deps) => {+ mockSetupDeps = deps;+ const router = require('express').Router();+ router.get('/capabilities', (_req, res) => res.json({ browserEnrollmentVersion: 1 }));+ return router;+ }),createCodeEnvironmentRegistry: jest.fn(() => mockRegistry),createCodeEnvironmentHttpHandlers: jest.fn((deps) => {mockHandlerDeps = deps;@@ -68,7 +76,12 @@ jest.mock('@librechat/api', () => ({jest.mock('~/server/middleware/roles/capabilities', () => ({requireCapability: mockRequireCapability,}));-jest.mock('~/server/middleware', () => ({ requireJwtAuth: mockRequireJwtAuth }));+jest.mock('~/server/middleware', () => ({+ requireJwtAuth: mockRequireJwtAuth,+ requireSameOrigin: jest.fn((_req, _res, next) => next()),+ checkBan: jest.fn((_req, _res, next) => next()),+}));+jest.mock('~/cache/getLogStores', () => jest.fn(() => ({ get: jest.fn() })));jest.mock('~/server/services/Config', () => ({getAppConfig: jest.fn(),getCodeEnvironmentRegistry: mockGetCodeEnvironmentRegistry,@@ -96,6 +109,17 @@ describe('code environment routes', () => {expect(mockGetCodeEnvironmentRegistry).not.toHaveBeenCalled();});+ it('mounts machine setup before the browser JWT boundary without initializing the registry', async () => {+ await request(createApp()).get('/api/code-environments/setup/capabilities').expect(200, {+ browserEnrollmentVersion: 1,+ });+ expect(mockRequireJwtAuth).not.toHaveBeenCalled();+ expect(mockGetCodeEnvironmentRegistry).not.toHaveBeenCalled();+ expect(mockSetupDeps.requireJwtAuth).toBe(mockRequireJwtAuth);+ expect(mockSetupDeps.requireSameOrigin).toEqual(expect.any(Function));+ expect(mockSetupDeps.checkBan).toEqual(expect.any(Function));+ });+it('allows authenticated discovery without the management capability', async () => {await request(createApp()).get('/api/code-environments').expect(200, { environments: [] });diff --git a/client/src/components/Auth/TwoFactorScreen.tsx b/client/src/components/Auth/TwoFactorScreen.tsxindex 4fd57fa601..7fbed5d323 100644--- a/client/src/components/Auth/TwoFactorScreen.tsx+++ b/client/src/components/Auth/TwoFactorScreen.tsx@@ -13,6 +13,7 @@ import {InputOTPSeparator,} from '@librechat/client';import { useVerifyTwoFactorTempMutation } from '~/data-provider';+import { useAuthContext } from '~/hooks/AuthContext';import BackupCodeInput from './BackupCodeInput';import { useLocalize } from '~/hooks';@@ -38,13 +39,14 @@ const TwoFactorScreen: React.FC = React.memo(() => {formState: { errors },} = useForm<TwoFactorFormInputs>();const localize = useLocalize();+ const { completeAuthentication } = useAuthContext();const { showToast } = useToastContext();const [useBackup, setUseBackup] = useState<boolean>(false);const [isLoading, setIsLoading] = useState<boolean>(false);const { mutate: verifyTempMutate } = useVerifyTwoFactorTempMutation({onSuccess: (result) => {- if (result.token != null && result.token !== '') {- window.location.href = '/';+ if (result.token != null && result.token !== '' && result.user != null) {+ completeAuthentication(result.token, result.user);}},onMutate: () => {diff --git a/client/src/components/Auth/__tests__/LoginReturn.spec.tsx b/client/src/components/Auth/__tests__/LoginReturn.spec.tsxnew file mode 100644index 0000000000..e8ad1f775b--- /dev/null+++ b/client/src/components/Auth/__tests__/LoginReturn.spec.tsx@@ -0,0 +1,81 @@+/**+ * @jest-environment @happy-dom/jest-environment+ */+import React from 'react';+import { MemoryRouter } from 'react-router-dom';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { TStartupConfig } from 'librechat-data-provider';+import { SESSION_KEY } from '~/utils/redirect';+import SocialButton from '../SocialButton';+import Login from '../Login';++let mockConfig: Partial<TStartupConfig>;+const mockSetError = jest.fn();++jest.mock('react-router-dom', () => ({+ ...jest.requireActual('react-router-dom'),+ useOutletContext: () => ({ startupConfig: mockConfig }),+}));+jest.mock('@librechat/client', () => ({+ ...jest.requireActual('@librechat/client'),+ useToastContext: () => ({ showToast: jest.fn() }),+}));+jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));+jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ error: undefined, setError: mockSetError, login: jest.fn() }),+}));+jest.mock('../LoginForm', () => () => null);++const destination = '/code/setup/setup-attempt';+const entry = `/login?redirect_to=${encodeURIComponent(destination)}`;++beforeEach(() => {+ sessionStorage.clear();+ mockConfig = { serverDomain: 'http://localhost:3080/librechat', emailLoginEnabled: false };+ window.history.replaceState({}, '', `/librechat${entry}`);+});++afterEach(() => {+ sessionStorage.clear();+ window.history.replaceState({}, '', '/');+});++it('persists the setup destination before an OAuth provider navigation', async () => {+ render(+ <MemoryRouter initialEntries={[entry]}>+ <Login />+ <SocialButton+ id="google"+ enabled+ serverDomain={mockConfig.serverDomain}+ oauthPath="google"+ label="Google"+ Icon={() => null}+ />+ </MemoryRouter>,+ );+ const link = screen.getByRole('link', { name: 'Google' });+ // Prevent the external navigation while observing the real provider link and handoff storage.+ link.addEventListener('click', (event) => event.preventDefault());+ fireEvent.click(link);+ expect(link).toHaveAttribute('href', 'http://localhost:3080/librechat/oauth/google');+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(destination);+});++it('persists the same setup destination before automatic OIDC navigation', async () => {+ mockConfig = {+ ...mockConfig,+ openidLoginEnabled: true,+ openidAutoRedirect: true,+ openidLabel: 'OpenID',+ };+ render(+ <MemoryRouter initialEntries={[entry]}>+ <Login />+ </MemoryRouter>,+ );+ await waitFor(() =>+ expect(window.location.href).toBe('http://localhost:3080/librechat/oauth/openid'),+ );+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(destination);+});diff --git a/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsxindex 98cbd2aa17..908aac86c5 100644--- a/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx+++ b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx@@ -5,7 +5,13 @@ import TwoFactorScreen from '../TwoFactorScreen';const mockShowToast = jest.fn();const mockVerify = jest.fn();-let mockVerifyOptions: { onError: (error: unknown) => void } | undefined;+const mockCompleteAuthentication = jest.fn();+let mockVerifyOptions:+ | {+ onError: (error: unknown) => void;+ onSuccess: (data: { token?: string; user?: { id: string } }) => void;+ }+ | undefined;jest.mock('@librechat/client', () => ({...jest.requireActual('@librechat/client'),@@ -16,8 +22,12 @@ jest.mock('~/hooks', () => ({useLocalize: () => (key: string) => key,}));+jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ completeAuthentication: mockCompleteAuthentication }),+}));+jest.mock('~/data-provider', () => ({- useVerifyTwoFactorTempMutation: (options: { onError: (error: unknown) => void }) => {+ useVerifyTwoFactorTempMutation: (options: NonNullable<typeof mockVerifyOptions>) => {mockVerifyOptions = options;return { mutate: mockVerify };},@@ -86,3 +96,15 @@ describe('TwoFactorScreen verification errors', () => {});});});++it('completes normal authentication instead of navigating to the host root', () => {+ renderScreen();+ act(() => mockVerifyOptions?.onSuccess({ token: 'verified-token', user: { id: 'user-1' } }));+ expect(mockCompleteAuthentication).toHaveBeenCalledWith('verified-token', { id: 'user-1' });+});++it('does not finish authentication without both the session token and user', () => {+ renderScreen();+ act(() => mockVerifyOptions?.onSuccess({ token: 'verified-token' }));+ expect(mockCompleteAuthentication).not.toHaveBeenCalled();+});diff --git a/client/src/components/Code/Setup.tsx b/client/src/components/Code/Setup.tsxnew file mode 100644index 0000000000..fa7a8a2c08--- /dev/null+++ b/client/src/components/Code/Setup.tsx@@ -0,0 +1,339 @@+import { useEffect, useState } from 'react';+import { buildLoginRedirectUrl } from 'librechat-data-provider';+import { Alert, Button, Label, Spinner } from '@librechat/client';+import { Navigate, useLocation, useParams } from 'react-router-dom';+import type { CodeSetupStatus } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import type { TranslationKeys } from '~/hooks';+import { useCodeSetupAttemptQuery, useCodeSetupDecisionMutation } from '~/data-provider/CodeSetup';+import TermsAndConditionsModal from '~/components/ui/TermsAndConditionsModal';+import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider';+import { useAuthContext } from '~/hooks/AuthContext';+import { getResponseStatus } from '~/utils/errors';+import { useLocalize } from '~/hooks';++const statusKeys: Record<CodeSetupStatus, TranslationKeys> = {+ pending: 'com_ui_code_setup_pending',+ provisioning: 'com_ui_code_setup_provisioning',+ approved: 'com_ui_code_setup_approved',+ completed: 'com_ui_code_setup_completed',+ denied: 'com_ui_code_setup_denied',+ cancelled: 'com_ui_code_setup_cancelled',+ expired: 'com_ui_code_setup_expired',+ failed: 'com_ui_code_setup_failed',+};++function Loading() {+ const localize = useLocalize();+ return (+ <div role="status" className="flex items-center gap-2">+ <Spinner className="size-5" aria-hidden="true" />+ {localize('com_ui_code_setup_loading')}+ </div>+ );+}++function Page({ children }: { children: ReactNode }) {+ const localize = useLocalize();+ return (+ <main className="bg-surface-primary text-text-primary min-h-dvh px-4 py-8">+ <div className="mx-auto flex max-w-2xl flex-col gap-6">+ <h1 className="text-2xl font-semibold">{localize('com_ui_code_setup_title')}</h1>+ {children}+ </div>+ </main>+ );+}++function Review({ attemptId, userId }: { attemptId: string; userId: string }) {+ const localize = useLocalize();+ const { logout } = useAuthContext();+ const [controlPlaneId, setControlPlaneId] = useState('');+ const [deadlinePassed, setDeadlinePassed] = useState(false);+ const configQuery = useGetStartupConfig();+ const termsConfig = configQuery.data?.interface?.termsOfService;+ const requiresTerms = termsConfig?.modalAcceptance === true;+ const termsQuery = useUserTermsQuery({ enabled: requiresTerms });+ const termsReady =+ configQuery.isSuccess &&+ (!requiresTerms ||+ (termsQuery.isSuccess && !termsQuery.isFetching && termsQuery.data.termsAccepted));+ const query = useCodeSetupAttemptQuery(attemptId, userId, termsReady);+ const { refetch } = query;+ const approve = useCodeSetupDecisionMutation(attemptId, userId, 'approve');+ const deny = useCodeSetupDecisionMutation(attemptId, userId, 'deny');+ const attempt = query.data;+ const expiresAt = attempt?.expiresAt;++ useEffect(() => {+ if (expiresAt == null) {+ return;+ }+ const remaining = Date.parse(expiresAt) - Date.now();+ setDeadlinePassed(remaining <= 0);+ if (remaining <= 0) {+ return;+ }+ let timer: ReturnType<typeof setTimeout>;+ const checkDeadline = () => {+ const remaining = Date.parse(expiresAt) - Date.now();+ if (remaining > 0) {+ timer = setTimeout(checkDeadline, Math.min(remaining, 2_147_483_647));+ return;+ }+ setDeadlinePassed(true);+ void refetch();+ };+ timer = setTimeout(checkDeadline, Math.min(remaining, 2_147_483_647));+ return () => clearTimeout(timer);+ }, [expiresAt, refetch]);++ const isDeciding = approve.isLoading || deny.isLoading;+ const canDecide =+ attempt?.status === 'pending' ||+ (attempt?.status === 'failed' && attempt.failure?.retryable === true);+ const expired =+ canDecide && (deadlinePassed || (expiresAt != null && Date.parse(expiresAt) <= Date.now()));+ const status = expired ? 'expired' : attempt?.status;+ const selectedPlaneExists = attempt?.controlPlanes.some((plane) => plane.id === controlPlaneId);+ const mutationError = approve.error ?? deny.error;+ const unavailable = [400, 403, 404, 410].includes(getResponseStatus(query.error) ?? 0);+ const mutationUnavailable = [400, 403, 404, 410].includes(getResponseStatus(mutationError) ?? 0);++ let content: ReactNode;+ if (configQuery.isError || (requiresTerms && termsQuery.isError)) {+ content = (+ <Alert variant="error">+ <p>{localize('com_ui_code_setup_load_failed')}</p>+ <Button+ variant="outline"+ onClick={() => {+ if (configQuery.isError) {+ void configQuery.refetch();+ } else {+ void termsQuery.refetch();+ }+ }}+ >+ {localize('com_ui_retry')}+ </Button>+ </Alert>+ );+ } else if (!termsReady) {+ content =+ requiresTerms && termsQuery.data?.termsAccepted === false ? (+ <p role="status">{localize('com_ui_code_setup_terms')}</p>+ ) : (+ <Loading />+ );+ } else if (query.isError) {+ content = (+ <Alert variant="error">+ <p>+ {localize(+ unavailable ? 'com_ui_code_setup_unavailable' : 'com_ui_code_setup_load_failed',+ )}+ </p>+ {!unavailable && (+ <Button+ variant="outline"+ onClick={() => void query.refetch()}+ disabled={query.isFetching}+ >+ {localize('com_ui_retry')}+ </Button>+ )}+ </Alert>+ );+ } else if (attempt == null || status == null) {+ content = <Loading />;+ } else {+ content = (+ <>+ <Alert variant={status === 'completed' ? 'success' : 'info'} role="status">+ {localize(+ status === 'failed' && attempt.failure?.retryable+ ? 'com_ui_code_setup_retryable'+ : statusKeys[status],+ )}+ </Alert>+ <dl className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <div>+ <dt className="text-text-secondary text-sm">{localize('com_ui_code_setup_machine')}</dt>+ <dd className="font-medium break-words">{attempt.machineName}</dd>+ </div>+ <div>+ <dt className="text-text-secondary text-sm">{localize('com_ui_code_setup_code')}</dt>+ <dd className="font-mono text-lg">{attempt.verificationCode}</dd>+ </div>+ <div className="sm:col-span-2">+ <dt className="text-text-secondary text-sm">+ {localize('com_ui_code_setup_fingerprint')}+ </dt>+ <dd className="font-mono text-sm break-all">{attempt.keyFingerprint}</dd>+ </div>+ <div>+ <dt className="text-text-secondary text-sm">+ {localize('com_ui_code_setup_workspace')}+ </dt>+ <dd>+ {localize(+ attempt.workspace.type === 'private'+ ? 'com_ui_code_setup_private'+ : 'com_ui_code_setup_directory',+ )}+ </dd>+ </div>+ <div>+ <dt className="text-text-secondary text-sm">{localize('com_ui_code_setup_expires')}</dt>+ <dd>+ <time dateTime={attempt.expiresAt}>+ {new Date(attempt.expiresAt).toLocaleString()}+ </time>+ </dd>+ </div>+ <div>+ <dt className="text-text-secondary text-sm">{localize('com_ui_code_setup_writes')}</dt>+ <dd>{localize(attempt.allowWorkspaceWrites ? 'com_ui_enabled' : 'com_ui_disabled')}</dd>+ </div>+ <div>+ <dt className="text-text-secondary text-sm">+ {localize('com_ui_code_setup_commands')}+ </dt>+ <dd>+ {localize(attempt.allowWorkspaceCommands ? 'com_ui_enabled' : 'com_ui_disabled')}+ </dd>+ </div>+ {attempt.controlPlaneId != null && (+ <div className="sm:col-span-2">+ <dt className="text-text-secondary text-sm">{localize('com_ui_code_setup_plane')}</dt>+ <dd>+ {attempt.controlPlanes.find((plane) => plane.id === attempt.controlPlaneId)?.name ??+ localize('com_ui_code_setup_plane_unavailable')}+ </dd>+ </div>+ )}+ </dl>+ <Alert variant="warning" role="note">+ <p>{localize('com_ui_code_setup_verify')}</p>+ <p className="mt-2">{localize('com_ui_code_setup_command_warning')}</p>+ <p className="mt-2">{localize('com_ui_code_setup_trust_warning')}</p>+ </Alert>+ {mutationError != null && (+ <Alert variant="error">+ {localize(+ mutationUnavailable+ ? 'com_ui_code_setup_unavailable'+ : 'com_ui_code_setup_action_failed',+ )}+ </Alert>+ )}+ {canDecide && !expired && (+ <form+ aria-busy={isDeciding}+ onSubmit={(event) => {+ event.preventDefault();+ if (+ !isDeciding &&+ selectedPlaneExists &&+ Date.parse(attempt.expiresAt) > Date.now()+ ) {+ approve.mutate({ controlPlaneId });+ }+ }}+ className="space-y-4"+ >+ <fieldset disabled={isDeciding} className="space-y-3">+ <legend className="mb-3 font-medium">{localize('com_ui_code_setup_plane')}</legend>+ {attempt.controlPlanes.map((plane) => (+ <div key={plane.id} className="flex items-center gap-3">+ <input+ id={`plane-${plane.id}`}+ type="radio"+ name="controlPlaneId"+ value={plane.id}+ checked={controlPlaneId === plane.id}+ onChange={() => setControlPlaneId(plane.id)}+ />+ <Label htmlFor={`plane-${plane.id}`}>{plane.name}</Label>+ </div>+ ))}+ {attempt.controlPlanes.length === 0 && (+ <p>{localize('com_ui_code_setup_no_planes')}</p>+ )}+ </fieldset>+ <div className="flex flex-wrap gap-3">+ <Button+ type="submit"+ variant="submit"+ disabled={isDeciding || !selectedPlaneExists || mutationUnavailable}+ >+ {localize('com_ui_code_setup_approve')}+ </Button>+ <Button+ type="button"+ variant="outline"+ disabled={isDeciding || mutationUnavailable}+ onClick={() => deny.mutate(undefined)}+ >+ {localize('com_ui_code_setup_deny')}+ </Button>+ </div>+ {isDeciding && <p role="status">{localize('com_ui_code_setup_saving')}</p>}+ </form>+ )}+ </>+ );+ }++ return (+ <>+ {content}+ <TermsAndConditionsModal+ open={requiresTerms && termsQuery.data?.termsAccepted === false}+ onOpenChange={() => undefined}+ onAccept={() => {+ approve.reset();+ deny.reset();+ }}+ onDecline={() => logout('/login?redirect=false')}+ title={termsConfig?.modalTitle}+ modalContent={termsConfig?.modalContent}+ />+ </>+ );+}++export default function CodeSetup() {+ const localize = useLocalize();+ const location = useLocation();+ const { attemptId } = useParams();+ const { user, isAuthenticated, isAuthReady } = useAuthContext();+ if (!isAuthReady) {+ return (+ <Page>+ <Loading />+ </Page>+ );+ }+ if (!isAuthenticated) {+ return (+ <Navigate+ to={buildLoginRedirectUrl(location.pathname, location.search, location.hash)}+ replace+ />+ );+ }+ return (+ <Page>+ <p className="text-text-secondary text-sm">+ {localize('com_ui_code_setup_account', { 0: user?.email ?? user?.name ?? user?.id ?? '' })}+ </p>+ {user?.id != null && attemptId != null ? (+ <Review key={`${user.id}:${attemptId}`} userId={user.id} attemptId={attemptId} />+ ) : (+ <Alert variant="error">{localize('com_ui_code_setup_unavailable')}</Alert>+ )}+ </Page>+ );+}diff --git a/client/src/components/Code/__tests__/Setup.spec.tsx b/client/src/components/Code/__tests__/Setup.spec.tsxnew file mode 100644index 0000000000..818f34bfc6--- /dev/null+++ b/client/src/components/Code/__tests__/Setup.spec.tsx@@ -0,0 +1,427 @@+/* eslint-disable i18next/no-literal-string */+import React from 'react';+import { AxiosError } from 'axios';+import { RecoilRoot } from 'recoil';+import { ToastProvider } from '@librechat/client';+import { createMemoryRouter, RouterProvider } from 'react-router-dom';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import {+ dataService,+ DynamicQueryKeys,+ QueryKeys,+ TERMS_NOT_ACCEPTED_CODE,+} from 'librechat-data-provider';+import type { CodeSetupAttempt } from 'librechat-data-provider';+import type { AxiosResponse } from 'axios';+import mockTranslations from '~/locales/en/translation.json';+import { codeSetupRoute } from '~/routes/CodeSetup';+import store from '~/store';++let mockAuth = {+ isAuthReady: true,+ isAuthenticated: true,+ user: { id: 'user-1', email: '[email protected]' },+ logout: jest.fn(),+};++jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => mockAuth }));+jest.mock('~/hooks', () => ({+ useLocalize: () => (key: keyof typeof mockTranslations, options?: { 0?: string }) =>+ mockTranslations[key]?.replace('{{0}}', options?.[0] ?? ''),+}));+// Markdown rendering is unrelated to setup consent. Keep the real terms acceptance modal.+jest.mock(+ '~/components/Chat/Messages/Content/MarkdownLite',+ () =>+ ({ content }: { content: string }) => <p>{content}</p>,+);+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getStartupConfig: jest.fn(),+ getUserTerms: jest.fn(),+ acceptTerms: jest.fn(),+ getCodeSetupAttempt: jest.fn(),+ approveCodeSetupAttempt: jest.fn(),+ denyCodeSetupAttempt: jest.fn(),+ },+ };+});++const initialAttempt: CodeSetupAttempt = {+ version: 1,+ attemptId: 'attempt-1',+ status: 'pending',+ expiresAt: '2030-01-01T00:00:00.000Z',+ verificationCode: '123456',+ machineName: 'Development laptop',+ workspace: { type: 'directory' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: true,+ keyFingerprint: 'a'.repeat(64),+ controlPlanes: [+ { id: 'plane-1', name: 'My control plane' },+ { id: 'plane-2', name: 'Second plane' },+ ],+};++function httpError(status: number, code?: string) {+ return new AxiosError(+ 'private server details must not be rendered',+ undefined,+ undefined,+ undefined,+ {+ status,+ data: { code },+ } as AxiosResponse,+ );+}++function setup({ basename = '/', path = '/code/setup/attempt-1' } = {}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, cacheTime: 0 }, mutations: { retry: false } },+ logger: { log: console.log, warn: console.warn, error: () => undefined },+ });+ const router = createMemoryRouter(+ [+ codeSetupRoute,+ { path: 'login', element: <p>Sign-in page</p> },+ { path: '*', element: <p>Not found</p> },+ ],+ { basename, initialEntries: [`${basename === '/' ? '' : basename}${path}`] },+ );+ const view = render(+ <QueryClientProvider client={queryClient}>+ <RecoilRoot+ initializeState={({ set }) => {+ set(store.queriesEnabled, true);+ set(store.user, mockAuth.user as never);+ }}+ >+ <ToastProvider>+ <RouterProvider router={router} />+ </ToastProvider>+ </RecoilRoot>+ </QueryClientProvider>,+ );+ return { ...view, router, queryClient };+}++beforeEach(() => {+ jest.clearAllMocks();+ mockAuth = {+ isAuthReady: true,+ isAuthenticated: true,+ user: { id: 'user-1', email: '[email protected]' },+ logout: jest.fn(),+ };+ jest.mocked(dataService.getStartupConfig).mockResolvedValue({ interface: {} } as never);+ jest.mocked(dataService.getCodeSetupAttempt).mockResolvedValue(initialAttempt);+});++it('shows an accessible loading state without starting a decision', () => {+ jest.mocked(dataService.getCodeSetupAttempt).mockReturnValue(new Promise(() => undefined));+ setup();+ expect(screen.getByRole('status')).toHaveTextContent(mockTranslations.com_ui_code_setup_loading);+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+ expect(dataService.denyCodeSetupAttempt).not.toHaveBeenCalled();+});++it('shows the signed-in account and immutable consent details without automatically approving', async () => {+ setup();+ expect(await screen.findByText(initialAttempt.machineName)).toBeInTheDocument();+ expect(screen.getByText('Signed in as [email protected]')).toBeInTheDocument();+ expect(screen.getByText(initialAttempt.verificationCode)).toBeInTheDocument();+ expect(screen.getByText(initialAttempt.keyFingerprint)).toBeInTheDocument();+ expect(screen.getByText(mockTranslations.com_ui_code_setup_directory)).toBeInTheDocument();+ expect(document.querySelector('time')).toHaveAttribute('datetime', initialAttempt.expiresAt);+ expect(screen.getByText(mockTranslations.com_ui_code_setup_command_warning)).toBeInTheDocument();+ expect(screen.getByText(mockTranslations.com_ui_code_setup_trust_warning)).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeDisabled();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+ expect(dataService.denyCodeSetupAttempt).not.toHaveBeenCalled();+});++it('only approves the chosen authorized plane after an explicit click and reconciles the result', async () => {+ const approved: CodeSetupAttempt = {+ ...initialAttempt,+ status: 'provisioning',+ controlPlaneId: 'plane-2',+ };+ jest.mocked(dataService.approveCodeSetupAttempt).mockImplementation(async () => {+ jest.mocked(dataService.getCodeSetupAttempt).mockResolvedValue(approved);+ return approved;+ });+ const { queryClient } = setup();+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');+ fireEvent.click(await screen.findByRole('radio', { name: 'Second plane' }));+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }));+ await waitFor(() =>+ expect(dataService.approveCodeSetupAttempt).toHaveBeenCalledWith('attempt-1', {+ controlPlaneId: 'plane-2',+ }),+ );+ expect(+ await screen.findByText(mockTranslations.com_ui_code_setup_provisioning),+ ).toBeInTheDocument();+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.codeEnvironments]);+ expect(dataService.denyCodeSetupAttempt).not.toHaveBeenCalled();+});++it('sends denial only after clicking Deny, without requiring a plane', async () => {+ const denied: CodeSetupAttempt = { ...initialAttempt, status: 'denied' };+ jest.mocked(dataService.denyCodeSetupAttempt).mockImplementation(async () => {+ jest.mocked(dataService.getCodeSetupAttempt).mockResolvedValue(denied);+ return denied;+ });+ setup();+ fireEvent.click(+ await screen.findByRole('button', { name: mockTranslations.com_ui_code_setup_deny }),+ );+ await waitFor(() => expect(dataService.denyCodeSetupAttempt).toHaveBeenCalledWith('attempt-1'));+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_denied)).toBeInTheDocument();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});++it('disables both actions while a decision is pending', async () => {+ jest.mocked(dataService.approveCodeSetupAttempt).mockReturnValue(new Promise(() => undefined));+ setup();+ fireEvent.click(await screen.findByRole('radio', { name: 'My control plane' }));+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }));+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_saving)).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_deny }),+ ).toBeDisabled();+});++it.each([+ ['provisioning', 'com_ui_code_setup_provisioning'],+ ['approved', 'com_ui_code_setup_approved'],+ ['completed', 'com_ui_code_setup_completed'],+ ['denied', 'com_ui_code_setup_denied'],+ ['cancelled', 'com_ui_code_setup_cancelled'],+ ['expired', 'com_ui_code_setup_expired'],+ ['failed', 'com_ui_code_setup_failed'],+] as const)('shows %s without offering approval or denial', async (status, key) => {+ jest.mocked(dataService.getCodeSetupAttempt).mockResolvedValue({ ...initialAttempt, status });+ setup();+ expect(await screen.findByText(mockTranslations[key])).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_deny }),+ ).not.toBeInTheDocument();+});++it('offers only an explicit retry for a retryable failure', async () => {+ jest.mocked(dataService.getCodeSetupAttempt).mockResolvedValue({+ ...initialAttempt,+ status: 'failed',+ failure: { code: 'provider_unavailable', retryable: true },+ });+ setup();+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_retryable)).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeDisabled();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});++it('does not offer actions for an expired pending request', async () => {+ jest+ .mocked(dataService.getCodeSetupAttempt)+ .mockResolvedValue({ ...initialAttempt, expiresAt: '2000-01-01T00:00:00.000Z' });+ setup();+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_expired)).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).not.toBeInTheDocument();+});++it.each([403, 404, 410])(+ 'does not disclose the request on a wrong-user or unavailable %s response',+ async (status) => {+ jest.mocked(dataService.getCodeSetupAttempt).mockRejectedValue(httpError(status));+ setup();+ expect(+ await screen.findByText(mockTranslations.com_ui_code_setup_unavailable),+ ).toBeInTheDocument();+ expect(screen.queryByText(initialAttempt.machineName)).not.toBeInTheDocument();+ expect(screen.queryByText(/private server details/)).not.toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).not.toBeInTheDocument();+ },+);++it('retries a read failure without retrying a mutation', async () => {+ jest+ .mocked(dataService.getCodeSetupAttempt)+ .mockRejectedValueOnce(httpError(503))+ .mockResolvedValue(initialAttempt);+ setup();+ expect(+ await screen.findByText(mockTranslations.com_ui_code_setup_load_failed),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_retry }));+ expect(await screen.findByText(initialAttempt.machineName)).toBeInTheDocument();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});++it('reconciles a lost approval response before offering another decision', async () => {+ jest.mocked(dataService.approveCodeSetupAttempt).mockImplementation(async () => {+ jest+ .mocked(dataService.getCodeSetupAttempt)+ .mockResolvedValue({ ...initialAttempt, status: 'provisioning' });+ throw httpError(503);+ });+ setup();+ fireEvent.click(await screen.findByRole('radio', { name: 'My control plane' }));+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }));+ expect(+ await screen.findByText(mockTranslations.com_ui_code_setup_provisioning),+ ).toBeInTheDocument();+ expect(dataService.approveCodeSetupAttempt).toHaveBeenCalledTimes(1);+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).not.toBeInTheDocument();+});++it('does not allow approval without an authorized plane, but still allows denial', async () => {+ jest+ .mocked(dataService.getCodeSetupAttempt)+ .mockResolvedValue({ ...initialAttempt, controlPlanes: [] });+ setup();+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_no_planes)).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_deny }),+ ).toBeEnabled();+});++it('uses account-scoped cache keys', async () => {+ const { queryClient } = setup();+ expect(await screen.findByText(initialAttempt.machineName)).toBeInTheDocument();+ expect(+ queryClient.getQueryData(DynamicQueryKeys.codeSetupAttempt('attempt-1', 'user-1')),+ ).toEqual(initialAttempt);+ expect(+ queryClient.getQueryData(DynamicQueryKeys.codeSetupAttempt('attempt-1', 'other-user')),+ ).toBeUndefined();+});++it('waits for normal auth readiness and does not fetch or approve early', () => {+ mockAuth.isAuthReady = false;+ setup();+ expect(screen.getByRole('status')).toHaveTextContent(mockTranslations.com_ui_code_setup_loading);+ expect(dataService.getCodeSetupAttempt).not.toHaveBeenCalled();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});++it('protects the exact setup route and preserves its destination under a basename', async () => {+ mockAuth.isAuthenticated = false;+ const { router } = setup({ basename: '/librechat' });+ await screen.findByText('Sign-in page');+ expect(router.state.location.pathname).toBe('/librechat/login');+ expect(new URLSearchParams(router.state.location.search).get('redirect_to')).toBe(+ '/code/setup/attempt-1',+ );+ expect(dataService.getCodeSetupAttempt).not.toHaveBeenCalled();+});++it.each(['/code/setup/attempt-1/extra', '/other/code/setup/attempt-1', '/code/setup'])(+ 'does not match the non-exact path %s',+ async (path) => {+ setup({ path });+ expect(await screen.findByText('Not found')).toBeInTheDocument();+ expect(dataService.getCodeSetupAttempt).not.toHaveBeenCalled();+ },+);++it('requires terms acceptance before setup and never treats acceptance as approval', async () => {+ jest.mocked(dataService.getStartupConfig).mockResolvedValue({+ interface: { termsOfService: { modalAcceptance: true, modalContent: 'Required terms' } },+ } as never);+ jest.mocked(dataService.getUserTerms).mockResolvedValue({ termsAccepted: false } as never);+ jest+ .mocked(dataService.acceptTerms)+ .mockResolvedValue({ termsAcceptedAt: '2026-10-22T00:00:00.000Z' } as never);+ setup();+ expect(await screen.findByRole('dialog')).toBeInTheDocument();+ expect(dataService.getCodeSetupAttempt).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_accept }));+ expect(await screen.findByText(initialAttempt.machineName)).toBeInTheDocument();+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});++it('reopens terms when a decision is refused after a terms reset', async () => {+ jest.mocked(dataService.getStartupConfig).mockResolvedValue({+ interface: { termsOfService: { modalAcceptance: true, modalContent: 'Updated terms' } },+ } as never);+ jest+ .mocked(dataService.getUserTerms)+ .mockResolvedValueOnce({ termsAccepted: true } as never)+ .mockResolvedValue({ termsAccepted: false } as never);+ jest+ .mocked(dataService.approveCodeSetupAttempt)+ .mockRejectedValue(httpError(403, TERMS_NOT_ACCEPTED_CODE));+ setup();+ fireEvent.click(await screen.findByRole('radio', { name: 'My control plane' }));+ fireEvent.click(screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }));+ expect(await screen.findByRole('dialog')).toBeInTheDocument();+ expect(dataService.approveCodeSetupAttempt).toHaveBeenCalledTimes(1);+});++it('expires at the original deadline without extending it during reads', async () => {+ jest.useFakeTimers();+ try {+ const expiresAt = new Date(Date.now() + 5_000).toISOString();+ jest+ .mocked(dataService.getCodeSetupAttempt)+ .mockResolvedValue({ ...initialAttempt, expiresAt });+ setup();+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_pending)).toBeInTheDocument();+ await act(async () => {+ jest.advanceTimersByTime(5_000);+ });+ expect(await screen.findByText(mockTranslations.com_ui_code_setup_expired)).toBeInTheDocument();+ expect(document.querySelector('time')).toHaveAttribute('datetime', expiresAt);+ expect(+ screen.queryByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).not.toBeInTheDocument();+ } finally {+ jest.useRealTimers();+ }+});++it('disables a selected plane when it is no longer authorized', async () => {+ const { queryClient } = setup();+ fireEvent.click(await screen.findByRole('radio', { name: 'My control plane' }));+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeEnabled();+ queryClient.setQueryData(DynamicQueryKeys.codeSetupAttempt('attempt-1', 'user-1'), {+ ...initialAttempt,+ controlPlanes: [],+ });+ await waitFor(() =>+ expect(+ screen.getByRole('button', { name: mockTranslations.com_ui_code_setup_approve }),+ ).toBeDisabled(),+ );+ expect(dataService.approveCodeSetupAttempt).not.toHaveBeenCalled();+});diff --git a/client/src/components/ui/TermsAndConditionsModal.tsx b/client/src/components/ui/TermsAndConditionsModal.tsxindex 5bfce84606..37f5e1f9e5 100644--- a/client/src/components/ui/TermsAndConditionsModal.tsx+++ b/client/src/components/ui/TermsAndConditionsModal.tsx@@ -29,7 +29,7 @@ const TermsAndConditionsModal = ({onOpenChange(false);},onError: () => {- showToast({ message: 'Failed to accept terms' });+ showToast({ message: localize('com_ui_terms_accept_failed'), status: 'error' });},});diff --git a/client/src/data-provider/CodeSetup.ts b/client/src/data-provider/CodeSetup.tsnew file mode 100644index 0000000000..f33df917e4--- /dev/null+++ b/client/src/data-provider/CodeSetup.ts@@ -0,0 +1,68 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';+import type { CodeSetupApprovalRequest, CodeSetupAttempt } from 'librechat-data-provider';+import { reopenTermsOnRefusal } from '~/utils/terms';++export function useCodeSetupAttemptQuery(attemptId: string, userId: string, enabled: boolean) {+ const queryClient = useQueryClient();+ return useQuery<CodeSetupAttempt, unknown>(+ DynamicQueryKeys.codeSetupAttempt(attemptId, userId),+ () => dataService.getCodeSetupAttempt(attemptId),+ {+ enabled,+ cacheTime: 0,+ retry: false,+ refetchInterval: (data, query) =>+ query.state.error == null &&+ data != null &&+ ['pending', 'provisioning', 'approved'].includes(data.status) &&+ (data.status !== 'pending' || Date.parse(data.expiresAt) > Date.now())+ ? 2_000+ : false,+ refetchIntervalInBackground: false,+ onError: (error) => {+ const data = (error as { response?: { data?: unknown } })?.response?.data;+ reopenTermsOnRefusal(queryClient, data);+ },+ },+ );+}++export function useCodeSetupDecisionMutation(+ attemptId: string,+ userId: string,+ decision: 'approve' | 'deny',+) {+ const queryClient = useQueryClient();+ const queryKey = DynamicQueryKeys.codeSetupAttempt(attemptId, userId);+ return useMutation<CodeSetupAttempt, unknown, CodeSetupApprovalRequest | undefined>({+ mutationKey: [+ decision === 'approve' ? MutationKeys.approveCodeSetup : MutationKeys.denyCodeSetup,+ userId,+ attemptId,+ ],+ mutationFn: (payload) => {+ if (decision === 'deny') {+ return dataService.denyCodeSetupAttempt(attemptId);+ }+ if (payload == null) {+ throw new Error('Code setup approval requires a control plane');+ }+ return dataService.approveCodeSetupAttempt(attemptId, payload);+ },+ retry: false,+ onMutate: () => queryClient.cancelQueries(queryKey),+ onSuccess: async (data) => {+ await queryClient.cancelQueries(queryKey);+ queryClient.setQueryData(queryKey, data);+ void queryClient.invalidateQueries([QueryKeys.codeEnvironments]);+ void queryClient.invalidateQueries([QueryKeys.endpoints]);+ },+ onError: (error) => {+ const data = (error as { response?: { data?: unknown } })?.response?.data;+ reopenTermsOnRefusal(queryClient, data);+ },+ // A lost mutation response is not a rejected decision. Reconcile before offering an action.+ onSettled: () => queryClient.invalidateQueries(queryKey),+ });+}diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsxindex 7271c2281b..53c6be209e 100644--- a/client/src/hooks/AuthContext.tsx+++ b/client/src/hooks/AuthContext.tsx@@ -179,11 +179,13 @@ const AuthContextProvider = ({* setup route finish the previous user's enrollment and take the tab as them.*/clearTwoFactorSetupToken();- if (twoFASetupRequired) {+ if (twoFASetupRequired || twoFAPending) {const redirectTo = new URLSearchParams(window.location.search).get('redirect_to');if (redirectTo) {persistRedirectToSession(redirectTo);}+ }+ if (twoFASetupRequired) {persistTwoFactorSetupToken(tempToken ?? '');navigate('/login/2fa/setup', { replace: true });return;diff --git a/client/src/hooks/__tests__/AuthContext.spec.tsx b/client/src/hooks/__tests__/AuthContext.spec.tsxindex 039fdd7271..80d9d9c093 100644--- a/client/src/hooks/__tests__/AuthContext.spec.tsx+++ b/client/src/hooks/__tests__/AuthContext.spec.tsx@@ -1271,3 +1271,91 @@ describe('AuthContextProvider: read-aloud cache at every session end', () => {expect(getCachedTTSAudio('departing')).toBeDefined();});});++describe('AuthContextProvider: browser setup destination', () => {+ const destination = '/code/setup/browser-attempt';+ const authenticated = { token: 'auth-token', user: { id: 'setup-user', role: 'USER' } };++ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ sessionStorage.clear();+ clearTwoFactorSetupToken();+ capturedAuthContext = undefined;+ window.history.replaceState({}, '', `/login?redirect_to=${encodeURIComponent(destination)}`);+ });++ afterEach(() => {+ jest.useRealTimers();+ sessionStorage.clear();+ clearTwoFactorSetupToken();+ mockApiBaseUrl.mockReturnValue('');+ window.history.replaceState({}, '', '/');+ });++ it('returns password sign-in to the setup without approving it', () => {+ renderProvider();+ act(() => mockCapturedLoginOptions.onSuccess(authenticated));+ act(() => jest.advanceTimersByTime(100));+ expect(mockNavigate).toHaveBeenLastCalledWith(destination, { replace: true });+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();+ });++ it('retains the destination through the normal 2FA challenge', () => {+ renderProvider();+ act(() => mockCapturedLoginOptions.onSuccess({ twoFAPending: true, tempToken: 'challenge' }));+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(destination);+ window.history.replaceState({}, '', '/login/2fa?tempToken=challenge');+ act(() =>+ capturedAuthContext?.completeAuthentication(authenticated.token, authenticated.user as never),+ );+ expect(mockNavigate).toHaveBeenLastCalledWith(destination, { replace: true });+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();+ });++ it('retains the destination through mandatory 2FA enrollment and reload', () => {+ const first = renderProvider();+ act(() =>+ mockCapturedLoginOptions.onSuccess({ twoFASetupRequired: true, tempToken: 'enrollment' }),+ );+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(destination);+ first.unmount();+ window.history.replaceState({}, '', '/login/2fa/setup');+ renderProvider();+ act(() =>+ capturedAuthContext?.completeAuthentication(authenticated.token, authenticated.user as never),+ );+ expect(mockNavigate).toHaveBeenLastCalledWith(destination, { replace: true });+ });++ it.each(['OAuth', 'OIDC'])('returns %s silent refresh to the stored setup destination', () => {+ sessionStorage.setItem(SESSION_KEY, destination);+ window.history.replaceState({}, '', '/');+ renderProviderLive();+ const options = mockRefreshMutate.mock.calls[0][1] as { onSuccess: (data: unknown) => void };+ act(() => options.onSuccess(authenticated));+ act(() => jest.advanceTimersByTime(100));+ expect(mockNavigate).toHaveBeenLastCalledWith(destination, { replace: true });+ expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();+ });++ it('keeps the exact setup destination when refreshing under a basename', () => {+ mockApiBaseUrl.mockReturnValue('/librechat');+ window.history.replaceState({}, '', `/librechat${destination}`);+ renderProviderLive();+ const options = mockRefreshMutate.mock.calls[0][1] as { onSuccess: (data: unknown) => void };+ act(() => options.onSuccess(authenticated));+ act(() => jest.advanceTimersByTime(100));+ expect(mockNavigate).toHaveBeenLastCalledWith(destination, { replace: true });+ });++ it('preserves the setup destination through refresh-enforced enrollment under a basename', () => {+ mockApiBaseUrl.mockReturnValue('/librechat');+ window.history.replaceState({}, '', `/librechat${destination}`);+ renderProviderLive();+ const options = mockRefreshMutate.mock.calls[0][1] as { onSuccess: (data: unknown) => void };+ act(() => options.onSuccess({ twoFASetupRequired: true, tempToken: 'enrollment' }));+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(destination);+ expect(mockNavigate).toHaveBeenLastCalledWith('/login/2fa/setup', { replace: true });+ });+});diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex bed8f9dd72..df36d52e6e 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -3677,5 +3677,40 @@"com_ui_analytics_consent_label": "Analytics consent","com_ui_analytics_consent_message": "This site can use Google Tag Manager to measure how it is used. Analytics stay off unless you allow them, and you can change this later in Settings.","com_ui_analytics_consent_setting": "Allow analytics",- "com_ui_analytics_consent_setting_description": "Lets this site load Google Tag Manager. Turning this off takes full effect after you reload the page."+ "com_ui_analytics_consent_setting_description": "Lets this site load Google Tag Manager. Turning this off takes full effect after you reload the page.",+ "com_ui_code_setup_title": "Approve Machine Setup",+ "com_ui_code_setup_account": "Signed in as {{0}}",+ "com_ui_code_setup_loading": "Loading setup details…",+ "com_ui_code_setup_pending": "Review this request. Nothing is approved until you choose Approve setup.",+ "com_ui_code_setup_provisioning": "Provisioning the approved setup. Keep the setup command running on your machine.",+ "com_ui_code_setup_approved": "Setup approved. Waiting for your machine to finish.",+ "com_ui_code_setup_completed": "Setup completed. This does not mean the worker is online or the workspace is ready. Check its status before use.",+ "com_ui_code_setup_denied": "Setup denied. This request cannot be approved.",+ "com_ui_code_setup_cancelled": "Setup cancelled. Start a new setup from your machine if needed.",+ "com_ui_code_setup_expired": "This setup request expired. Start a new setup from your machine.",+ "com_ui_code_setup_failed": "Setup failed and cannot be retried. Start a new setup from your machine.",+ "com_ui_code_setup_retryable": "Setup failed. Review the details and explicitly approve to retry before this request expires.",+ "com_ui_code_setup_terms": "Accept the terms and conditions before reviewing this setup.",+ "com_ui_code_setup_load_failed": "Could not load setup details. Retry to check the current state.",+ "com_ui_code_setup_unavailable": "This setup request is unavailable for this account. Check the link and signed-in account, or start a new setup from your machine.",+ "com_ui_code_setup_action_failed": "Could not confirm your decision. The current setup state has been checked. Retry only if an action is still available.",+ "com_ui_code_setup_machine": "Machine name",+ "com_ui_code_setup_code": "Verification code",+ "com_ui_code_setup_fingerprint": "Public key fingerprint (SHA-256, DER SPKI)",+ "com_ui_code_setup_workspace": "Workspace",+ "com_ui_code_setup_private": "Private workspace",+ "com_ui_code_setup_directory": "Directory workspace (local path not shared)",+ "com_ui_code_setup_expires": "Request expires",+ "com_ui_code_setup_writes": "Workspace file writes",+ "com_ui_code_setup_commands": "Workspace commands",+ "com_ui_code_setup_plane": "Authorized control plane",+ "com_ui_code_setup_plane_unavailable": "The selected control plane is no longer available.",+ "com_ui_code_setup_no_planes": "No authorized control planes are available. You can deny this request.",+ "com_ui_code_setup_verify": "Only approve a setup you started. Compare the verification code and public key fingerprint with those shown on your machine.",+ "com_ui_code_setup_command_warning": "Commands can modify files independently of the workspace file-write setting. Disabling file writes does not make commands read-only.",+ "com_ui_code_setup_trust_warning": "Pairing is not host trust and does not grant tool approvals. Those checks remain separate.",+ "com_ui_code_setup_approve": "Approve setup",+ "com_ui_code_setup_deny": "Deny setup",+ "com_ui_code_setup_saving": "Saving your decision…",+ "com_ui_terms_accept_failed": "Could not accept the terms. Please try again."}diff --git a/client/src/routes/CodeSetup.tsx b/client/src/routes/CodeSetup.tsxnew file mode 100644index 0000000000..a870455264--- /dev/null+++ b/client/src/routes/CodeSetup.tsx@@ -0,0 +1,7 @@+import CodeSetup from '~/components/Code/Setup';++export const codeSetupRoute = {+ path: 'code/setup/:attemptId',+ caseSensitive: true,+ element: <CodeSetup />,+};diff --git a/client/src/routes/index.tsx b/client/src/routes/index.tsxindex 3373c92358..7fac97dbb2 100644--- a/client/src/routes/index.tsx+++ b/client/src/routes/index.tsx@@ -14,6 +14,7 @@ import { importWithRecovery } from '~/lib/assets/lazy';import RouteErrorBoundary from './RouteErrorBoundary';import StartupLayout from './Layouts/Startup';import MarketplaceRoute from './Marketplace';+import { codeSetupRoute } from './CodeSetup';import LoginLayout from './Layouts/Login';import dashboardRoutes from './Dashboard';import WithRum from '~/lib/rum/WithRum';@@ -129,6 +130,7 @@ export const router = createBrowserRouter(],},dashboardRoutes,+ codeSetupRoute,{path: '/',element: <Root />,diff --git a/e2e/specs/mock/scenarios/two-factor-deep-link.spec.ts b/e2e/specs/mock/scenarios/two-factor-deep-link.spec.tsindex 602d04231e..c7e0b46f62 100644--- a/e2e/specs/mock/scenarios/two-factor-deep-link.spec.ts+++ b/e2e/specs/mock/scenarios/two-factor-deep-link.spec.ts@@ -1,12 +1,10 @@import { expect, test } from '@playwright/test';+import type { CodeSetupAttempt } from 'librechat-data-provider';import type { Page, Route } from '@playwright/test';/**- * An ordinary (already enrolled) 2FA sign-in parks its destination in session storage when the- * login screen mounts, swaps the document to `/` once the challenge is verified, and rebuilds- * the session through the silent refresh. The destination has to survive that document swap and- * be consumed by the sign-in that carried it, and the sign-in itself must never depend on the- * store being writable at all.+ * Ordinary 2FA completes in the auth context. Safe destinations survive an unavailable store+ * and are consumed once, without a document reload or an implicit machine approval.*//** A non-default destination: reaching it proves the deep link outlived the whole challenge.@@ -219,10 +217,7 @@ test.describe('ordinary 2FA challenge · deep links', () => {await mockChallengeAuth(page);await page.addInitScript(() => {Object.defineProperty(window, 'sessionStorage', {- /** Configurable because the CI-mode build's storage polyfill replaces a broken- * sessionStorage with its own in-memory shim rather than crashing on a frozen- * property. The shim is per-document, so the challenge's document swap still- * empties it and the landing contract is identical either way. */+ /** The app may replace unavailable storage with its in-document fallback. */configurable: true,get() {throw new DOMException('Storage is blocked in this context', 'SecurityError');@@ -231,14 +226,91 @@ test.describe('ordinary 2FA challenge · deep links', () => {});await page.goto(`/login?redirect_to=${encodeURIComponent(DEEP_LINK)}`);- /** The store being unwritable must cost the destination, never the sign-in itself. */+ /** Neither the destination nor sign-in depends on writable session storage. */await expect(page.getByRole('textbox', { name: 'Email' })).toBeVisible({ timeout: 15000 });await signInThroughChallenge(page);+ await expectAuthenticatedShell(page);+ await expect(page).toHaveURL(DEEP_LINK_PATTERN);+ });++ test('an unsafe destination falls back locally @scenario:2fa-unsafe-destination-stays-local', async ({+ page,+ }) => {+ await mockChallengeAuth(page);+ await page.goto(`/login?redirect_to=${encodeURIComponent('//attacker.invalid')}`);+ await signInThroughChallenge(page);await expectAuthenticatedShell(page);await expect(page).toHaveURL(DEFAULT_PATTERN);});+ for (const blockedStorage of [false, true]) {+ test(`machine confirmation requires an explicit decision after 2FA, blocked storage=${blockedStorage} @scenario:2fa-machine-confirmation-${blockedStorage}`, async ({+ page,+ }) => {+ test.setTimeout(90000);+ await mockChallengeAuth(page);+ if (blockedStorage) {+ await page.addInitScript(() => {+ Object.defineProperty(window, 'sessionStorage', {+ configurable: true,+ get() {+ throw new DOMException('Storage blocked', 'SecurityError');+ },+ });+ });+ }+ const attemptId = 'A'.repeat(43);+ const destination = `/code/setup/${attemptId}`;+ const attempt: CodeSetupAttempt = {+ version: 1,+ attemptId,+ status: 'pending',+ expiresAt: new Date(Date.now() + 600000).toISOString(),+ verificationCode: 'A1B2C3-D4E5F6',+ machineName: '2FA test workstation',+ workspace: { type: 'private' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: false,+ keyFingerprint: 'a'.repeat(64),+ controlPlanes: [{ id: 'personal', name: 'Test personal plane' }],+ };+ let decisions = 0;+ page.on('request', (request) => {+ if (+ request.method() === 'POST' &&+ new URL(request.url()).pathname.startsWith('/api/code-environments/setup/')+ )+ decisions++;+ });+ await page.route(`**/api/code-environments/setup/${attemptId}`, (route) =>+ json(route, attempt),+ );+ await page.route(`**/api/code-environments/setup/${attemptId}/approve`, async (route) => {+ expect(route.request().postDataJSON()).toEqual({ controlPlaneId: 'personal' });+ attempt.status = 'approved';+ attempt.controlPlaneId = 'personal';+ await json(route, attempt);+ });+ await page.goto(destination);+ await expect(page.getByRole('textbox', { name: 'Email' })).toBeVisible({ timeout: 15000 });+ await signInThroughChallenge(page);+ await expect(page).toHaveURL(new RegExp(`${destination}$`));+ await expect(page.getByRole('heading', { name: 'Approve Machine Setup' })).toBeVisible();+ await expect(page.getByText(attempt.machineName, { exact: true })).toBeVisible();+ await expect(page.getByText(ENROLLED_USER.email, { exact: false })).toBeVisible();+ await expect(page.getByText(attempt.verificationCode, { exact: true })).toBeVisible();+ expect(decisions).toBe(0);+ await page.getByRole('radio', { name: 'Test personal plane', exact: true }).check();+ expect(decisions).toBe(0);+ await page.getByRole('button', { name: 'Approve setup', exact: true }).click();+ await expect(+ page.getByText('Setup approved. Waiting for your machine to finish.', { exact: true }),+ ).toBeVisible();+ expect(decisions).toBe(1);+ });+ }+test('a consumed destination does not misdirect the next sign-in in the tab @scenario:2fa-destination-consumed-once-across-signins', async ({page,}) => {diff --git a/eslint.config.mjs b/eslint.config.mjsindex 6385ae062e..5d21742aa8 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -58,6 +58,7 @@ const chatLiteralAttributes = {export default [{ignores: [+ 'vendor/code/**/*','client/dist/**/*','client/public/**/*','client/coverage/**/*',diff --git a/package-lock.json b/package-lock.jsonindex 6f53a8d149..706c0373a1 100644--- a/package-lock.json+++ b/package-lock.json@@ -9846,6 +9846,10 @@"resolved": "packages/client","link": true},+ "node_modules/@librechat/code": {+ "resolved": "vendor/code",+ "link": true+ },"node_modules/@librechat/data-schemas": {"resolved": "packages/data-schemas","link": true@@ -40733,6 +40737,7 @@"dependencies": {"@langchain/langgraph-checkpoint": "^1.1.2","@langchain/langgraph-checkpoint-mongodb": "^1.4.0",+ "@librechat/code": "file:../../vendor/code","@simplewebauthn/server": "^13.3.2","cluster-key-slot": "^1.1.2","croner": "^10.0.1",@@ -44360,6 +44365,11 @@"peerDependencies": {"winston": "^3"}+ },+ "vendor/code": {+ "name": "@librechat/code",+ "version": "0.1.0-librechat.a3207a75",+ "license": "Apache-2.0"}}}diff --git a/packages/api/jest.config.mjs b/packages/api/jest.config.mjsindex 93f44872e3..175226a1b4 100644--- a/packages/api/jest.config.mjs+++ b/packages/api/jest.config.mjs@@ -1,6 +1,7 @@import { maxWorkers, workerIdleMemoryLimit } from '../../config/jest.workers.cjs';const esModules = [+ '@librechat/code','@langchain/langgraph','@langchain/langgraph-checkpoint','@langchain/langgraph-sdk',diff --git a/packages/api/package.json b/packages/api/package.jsonindex cbc5b31a2b..d514866f01 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -179,6 +179,7 @@"helmet": "^8.3.0","protobufjs": "^7.6.5","proxy-from-env": "^2.1.0",- "re2js": "^2.8.6"+ "re2js": "^2.8.6",+ "@librechat/code": "file:../../vendor/code"}}diff --git a/packages/api/src/auth/codeapi.ts b/packages/api/src/auth/codeapi.tsindex 08048f7714..675c4f33dd 100644--- a/packages/api/src/auth/codeapi.ts+++ b/packages/api/src/auth/codeapi.ts@@ -248,14 +248,19 @@ function resolveTenantId(user: CodeApiUserContext): string | undefined {return resolveSingleTenantId();}-export function getCodeApiTenantId(req: ServerRequest): string {- const tenantId = resolveTenantId(resolveUser(req));+export function getCodeApiTenantIdForUser(user: { tenantId?: string }): string {+ const tenantId = resolveTenantId(user);if (!tenantId) {throw new Error('Code API JWT auth requires tenant context');}return tenantId;}+export function getCodeApiTenantId(req: ServerRequest): string {+ const user = resolveUser(req);+ return getCodeApiTenantIdForUser({ tenantId: stringifyClaimValue(user.tenantId) });+}+function isManagedCodeApiJwtMode(): boolean {const provider = process.env.CODEAPI_AUTH_PROVIDER;return provider === 'librechat-jwt' || provider === 'both';diff --git a/packages/api/src/code/environments.ts b/packages/api/src/code/environments.tsindex 897bc7c777..c3a860a5bd 100644--- a/packages/api/src/code/environments.ts+++ b/packages/api/src/code/environments.ts@@ -8,6 +8,10 @@ import {ResourceType,isSecureCodeEnvironmentControlURL,} from 'librechat-data-provider';+import type {+ CodeEnvironmentSetupBinding,+ CodeEnvironmentSetupRecord,+} from '@librechat/data-schemas';import type { CodeEnvironmentUserSettings } from 'librechat-data-provider';import type { ResolvedPrincipal } from '~/types/principal';import { AccessControlService } from '~/acl/accessControlService';@@ -43,6 +47,15 @@ export type CodeEnvironmentRegistration = {};};+/** Retry identity for browser setup. Every stage supplies the same complete binding. */+export type CodeEnvironmentSetupInput = {+ actor: { userId: string };+ environment: CodeEnvironmentRegistration;+ setupAttemptId: string;+ requestHash: string;+ maxOwned?: number;+};+export type AccessibleCodeEnvironmentConfiguration = {id: string;name: string;@@ -176,6 +189,9 @@ export function createCodeEnvironmentRegistry(mongoose: typeof import('mongoose'),options: CodeEnvironmentRegistryOptions = {},): {+ reserveSetup: (params: CodeEnvironmentSetupInput) => Promise<CodeEnvironmentSummary>;+ completeSetup: (params: CodeEnvironmentSetupInput) => Promise<CodeEnvironmentSummary>;+ discardSetup: (params: CodeEnvironmentSetupInput) => Promise<void>;register: (params: {actor: CodeEnvironmentPrincipalContext;environment: CodeEnvironmentRegistration;@@ -243,6 +259,98 @@ export function createCodeEnvironmentRegistry(return environmentIds;}+ function setupBinding({+ actor,+ environment: input,+ setupAttemptId,+ requestHash,+ maxOwned,+ }: CodeEnvironmentSetupInput): CodeEnvironmentSetupBinding {+ if (+ !/^[A-Za-z0-9_-]{1,128}$/.test(setupAttemptId) ||+ !/^[a-f0-9]{64}$/.test(requestHash) ||+ !Types.ObjectId.isValid(actor.userId)+ ) {+ throw new CodeEnvironmentValidationError('Browser setup registry identity is invalid');+ }+ if (maxOwned != null && (!Number.isSafeInteger(maxOwned) || maxOwned < 1))+ throw new CodeEnvironmentValidationError('Browser setup owner limit is invalid');+ const environment = normalizeRegistration(input);+ return {+ setupAttemptId,+ requestHash,+ ownerId: actor.userId,+ environmentId: environment.id,+ name: environment.name,+ type: environment.type,+ baseURL: environment.baseURL,+ controlPlaneId: environment.controlPlaneId,+ workerId: environment.workerId,+ revocationTokenEnv: environment.revocationTokenEnv,+ workerPrincipal: environment.workerPrincipal,+ };+ }++ function setupSummary(record: CodeEnvironmentSetupRecord): CodeEnvironmentSummary {+ return {+ resourceId: record.resourceId,+ id: record.id,+ name: record.name,+ type: record.type,+ canEdit: true,+ canDelete: true,+ };+ }++ async function reserveSetup(params: CodeEnvironmentSetupInput): Promise<CodeEnvironmentSummary> {+ const reserved = await methods.reserveSetupEnvironment(setupBinding(params), params.maxOwned);+ if (reserved == null) throw new CodeEnvironmentLimitError();+ return setupSummary(reserved);+ }++ async function completeSetup(params: CodeEnvironmentSetupInput): Promise<CodeEnvironmentSummary> {+ const binding = setupBinding(params);+ const reserved = await methods.findSetupEnvironment(binding);+ if (reserved == null)+ throw new CodeEnvironmentValidationError('Browser setup reservation is unavailable');+ if (!reserved.pending) {+ // A completed replay must not restore an ownership grant that was subsequently revoked.+ const allowed = await access.checkPermission({+ userId: params.actor.userId,+ resourceType: ResourceType.CODE_ENVIRONMENT,+ resourceId: reserved.resourceId,+ requiredPermission: PermissionBits.DELETE,+ });+ if (!allowed)+ throw new CodeEnvironmentValidationError('Browser setup ownership is unavailable');+ return setupSummary(reserved);+ }+ const permission = await access.grantPermission({+ principalType: PrincipalType.USER,+ principalId: params.actor.userId,+ resourceType: ResourceType.CODE_ENVIRONMENT,+ resourceId: reserved.resourceId,+ accessRoleId: AccessRoleIds.CODE_ENVIRONMENT_OWNER,+ grantedBy: params.actor.userId,+ });+ if (permission == null) throw new Error('Unable to grant code environment ownership');+ // Do not roll back setup reservations. The durable pending row is the retry journal.+ await invalidateAccessibleConfigurations();+ return setupSummary(await methods.completeSetupEnvironment(binding, reserved.resourceId));+ }++ async function discardSetup(params: CodeEnvironmentSetupInput): Promise<void> {+ const binding = setupBinding(params);+ const discarded = await methods.beginDiscardSetupEnvironment(binding);+ if (discarded == null) return;+ await access.removeAllPermissions({+ resourceType: ResourceType.CODE_ENVIRONMENT,+ resourceId: discarded.resourceId,+ });+ await invalidateAccessibleConfigurations();+ await methods.finishDiscardSetupEnvironment(binding, discarded.resourceId);+ }+async function register({actor,environment: input,@@ -615,6 +723,9 @@ export function createCodeEnvironmentRegistry(}return {+ reserveSetup,+ completeSetup,+ discardSetup,register,markRevocationPending,listAccessible,diff --git a/packages/api/src/code/index.ts b/packages/api/src/code/index.tsindex 76dbe1c34d..7ee2b2a5a8 100644--- a/packages/api/src/code/index.ts+++ b/packages/api/src/code/index.ts@@ -13,3 +13,4 @@ export * from './errors';export * from './instructions';export * from './targets';export * from './agent';+export { createCodeSetupRouter } from './setup/router';diff --git a/packages/api/src/code/lifecycle.ts b/packages/api/src/code/lifecycle.tsindex a63f903217..6d59a29a86 100644--- a/packages/api/src/code/lifecycle.ts+++ b/packages/api/src/code/lifecycle.ts@@ -138,6 +138,7 @@ export async function reconcileCodeEnvironmentLifecycle({}const staleRegistration = new Date(Date.now() - REGISTRATION_STALE_MS);const registrationCandidates = await CodeEnvironment.find({+ setupAttemptId: { $exists: false },registrationPendingAt: { $lte: staleRegistration },$and: [{diff --git a/packages/api/src/code/setup.registry.integration.spec.ts b/packages/api/src/code/setup.registry.integration.spec.tsnew file mode 100644index 0000000000..e009757919--- /dev/null+++ b/packages/api/src/code/setup.registry.integration.spec.ts@@ -0,0 +1,262 @@+import mongoose, { Types } from 'mongoose';+import { ResourceType } from 'librechat-data-provider';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createMethods, createModels, tenantStorage } from '@librechat/data-schemas';+import type { CodeEnvironmentSetupInput } from './environments';+import { AccessControlService } from '~/acl/accessControlService';+import { createCodeEnvironmentRegistry } from './environments';++function input(id: string, ownerId: string): CodeEnvironmentSetupInput {+ return {+ actor: { userId: ownerId },+ setupAttemptId: `attempt-${id}`,+ requestHash: 'a'.repeat(64),+ maxOwned: 1,+ environment: {+ id,+ name: 'Setup Machine',+ type: 'attached',+ baseURL: 'https://code.example.com',+ controlPlaneId: 'setup-plane',+ workerId: `worker-${id}`,+ revocationTokenEnv: 'CODE_API_TOKEN',+ workerPrincipal: { type: 'user', id: ownerId },+ },+ };+}++describe('staged browser setup registry', () => {+ let mongo: MongoMemoryServer;+ beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await Promise.all(Object.values(mongoose.models).map((model) => model.init()));+ });+ beforeEach(async () => {+ await Promise.all(+ Object.values(mongoose.models).map((model) => model.collection.deleteMany({})),+ );+ await mongoose.connection.db!.collection('code_environment_tombstones').deleteMany({});+ await createMethods(mongoose).seedDefaultRoles();+ });+ afterAll(async () => {+ await mongoose.disconnect();+ await mongo.stop();+ });++ test('explicitly enforces owner-slot uniqueness when automatic index creation is disabled', async () => {+ const model = mongoose.models.CodeEnvironment;+ await model.collection.dropIndex('createdBy_1_ownerSlot_1_tenantId_1');+ const previous = mongoose.get('autoIndex');+ mongoose.set('autoIndex', false);+ try {+ const ownerId = new Types.ObjectId().toHexString();+ const outcomes = await Promise.allSettled(+ Array.from({ length: 8 }, (_, index) =>+ createCodeEnvironmentRegistry(mongoose).reserveSetup(input(`no-auto-${index}`, ownerId)),+ ),+ );+ expect(outcomes.filter((outcome) => outcome.status === 'fulfilled')).toHaveLength(1);+ expect(await model.countDocuments({ createdBy: ownerId })).toBe(1);+ const indexes = await model.collection.indexes();+ expect(+ indexes.some(+ (entry) => entry.unique && entry.key.createdBy === 1 && entry.key.ownerSlot === 1,+ ),+ ).toBe(true);+ } finally {+ mongoose.set('autoIndex', previous);+ }+ });++ test('reservation stays hidden and replays before owner capacity checks', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input('capacity', ownerId);+ const reserved = await registry.reserveSetup(params);+ await expect(createCodeEnvironmentRegistry(mongoose).reserveSetup(params)).resolves.toEqual(+ reserved,+ );+ await expect(registry.listAccessible({ userId: ownerId })).resolves.toEqual([]);+ await expect(registry.reserveSetup(input('second-machine', ownerId))).rejects.toThrow('limit');+ expect(await mongoose.models.CodeEnvironment.countDocuments({ createdBy: ownerId })).toBe(1);+ const completed = await registry.completeSetup(params);+ expect(completed).toEqual(reserved);+ await expect(registry.completeSetup(params)).resolves.toEqual(completed);+ await expect(registry.listAccessible({ userId: ownerId })).resolves.toEqual([completed]);+ });++ test('ACL failure persists the pending reservation and retry repairs the grant at full capacity', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input('acl-failure', ownerId);+ const reserved = await registry.reserveSetup(params);+ const grant = jest+ .spyOn(AccessControlService.prototype, 'grantPermission')+ .mockRejectedValueOnce(new Error('injected database outage'));+ await expect(registry.completeSetup(params)).rejects.toThrow('injected database outage');+ expect(+ await mongoose.models.CodeEnvironment.findById(reserved.resourceId).lean(),+ ).toMatchObject({+ setupAttemptId: params.setupAttemptId,+ setupRequestHash: params.requestHash,+ registrationPendingAt: expect.any(Date),+ });+ await expect(registry.listAccessible({ userId: ownerId })).resolves.toEqual([]);+ await expect(registry.reserveSetup(params)).resolves.toEqual(reserved);+ await expect(registry.completeSetup(params)).resolves.toEqual(reserved);+ expect(grant).toHaveBeenCalledTimes(2);+ expect(+ await mongoose.models.AclEntry.countDocuments({+ resourceType: ResourceType.CODE_ENVIRONMENT,+ resourceId: reserved.resourceId,+ }),+ ).toBe(1);+ });++ test('a grant followed by cache failure stays hidden and the retry does not duplicate ACLs', async () => {+ const ownerId = new Types.ObjectId().toString();+ const cache = {+ get: jest.fn(async () => undefined),+ set: jest.fn().mockRejectedValueOnce(new Error('cache outage')).mockResolvedValue(true),+ };+ const registry = createCodeEnvironmentRegistry(mongoose, { configurationCache: cache });+ const params = input('cache-failure', ownerId);+ const reserved = await registry.reserveSetup(params);+ await expect(registry.completeSetup(params)).rejects.toThrow('cache outage');+ await expect(registry.listAccessible({ userId: ownerId })).resolves.toEqual([]);+ await registry.completeSetup(params);+ expect(await mongoose.models.AclEntry.countDocuments({ resourceId: reserved.resourceId })).toBe(+ 1,+ );+ });++ test.each([+ 'owner',+ 'attempt',+ 'hash',+ 'plane',+ 'url',+ 'worker',+ 'principal',+ 'name',+ 'token',+ ] as const)('replays and compensation require the complete %s binding', async (field) => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input(`binding-${field}`, ownerId);+ const reserved = await registry.reserveSetup(params);+ const changed: CodeEnvironmentSetupInput = {+ ...params,+ actor: { ...params.actor },+ environment: { ...params.environment },+ };+ if (field === 'owner') changed.actor.userId = new Types.ObjectId().toString();+ if (field === 'attempt') changed.setupAttemptId = 'different-attempt';+ if (field === 'hash') changed.requestHash = 'b'.repeat(64);+ if (field === 'plane') changed.environment.controlPlaneId = 'another-plane';+ if (field === 'url') changed.environment.baseURL = 'https://another.example.com';+ if (field === 'worker') changed.environment.workerId = 'another-worker';+ if (field === 'principal')+ changed.environment.workerPrincipal = { type: 'user', id: new Types.ObjectId().toString() };+ if (field === 'name') changed.environment.name = 'Renamed Machine';+ if (field === 'token') changed.environment.revocationTokenEnv = 'ANOTHER_TOKEN';+ await expect(registry.reserveSetup(changed)).rejects.toThrow('binding');+ await expect(registry.completeSetup(changed)).rejects.toThrow('binding');+ await expect(registry.discardSetup(changed)).rejects.toThrow('binding');+ expect(await mongoose.models.CodeEnvironment.findById(reserved.resourceId)).not.toBeNull();+ });++ test('parallel setup attempts cannot exceed owner slots and a retired slot uses a fresh ACL resource', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const first = input('parallel-one', ownerId);+ const second = input('parallel-two', ownerId);+ const results = await Promise.allSettled([+ registry.reserveSetup(first),+ registry.reserveSetup(second),+ ]);+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);+ expect(await mongoose.models.CodeEnvironment.countDocuments({ createdBy: ownerId })).toBe(1);+ const winner = results[0].status === 'fulfilled' ? first : second;+ const old = await registry.completeSetup(winner);+ await registry.discardSetup(winner);+ const replacement = await registry.reserveSetup(input('replacement', ownerId));+ expect(replacement.resourceId).not.toBe(old.resourceId);+ await registry.discardSetup(winner);+ expect(await mongoose.models.CodeEnvironment.findById(replacement.resourceId)).not.toBeNull();+ });++ test('discard survives ACL failure, is idempotent, and never resurrects a retired worker', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input('discard', ownerId);+ const reserved = await registry.reserveSetup(params);+ await registry.completeSetup(params);+ const remove = jest+ .spyOn(AccessControlService.prototype, 'removeAllPermissions')+ .mockRejectedValueOnce(new Error('ACL cleanup outage'));+ await expect(registry.discardSetup(params)).rejects.toThrow('ACL cleanup outage');+ await expect(registry.listAccessible({ userId: ownerId })).resolves.toEqual([]);+ await expect(registry.completeSetup(params)).rejects.toThrow('binding');+ await registry.discardSetup(params);+ await registry.discardSetup(params);+ expect(remove).toHaveBeenCalledTimes(3);+ expect(await mongoose.models.CodeEnvironment.findById(reserved.resourceId)).toBeNull();+ expect(await mongoose.models.AclEntry.countDocuments({ resourceId: reserved.resourceId })).toBe(+ 0,+ );+ await expect(registry.reserveSetup(params)).rejects.toThrow('binding');+ });++ test('a completed replay does not restore a subsequently revoked ownership ACL', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input('revoked', ownerId);+ const reserved = await registry.reserveSetup(params);+ await registry.completeSetup(params);+ await mongoose.models.AclEntry.deleteMany({ resourceId: reserved.resourceId });+ await expect(registry.completeSetup(params)).rejects.toThrow('ownership');+ expect(await mongoose.models.AclEntry.countDocuments({ resourceId: reserved.resourceId })).toBe(+ 0,+ );+ });++ test('tenant context is part of reservation and compensation identity', async () => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input('tenant-scoped', ownerId);+ const reserved = await tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ registry.reserveSetup(params),+ );+ await tenantStorage.run({ tenantId: 'tenant-b' }, async () => registry.discardSetup(params));+ const found = await tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ registry.reserveSetup(params),+ );+ expect(found).toEqual(reserved);+ });+ test.each(['deleteCodeEnvironmentById', 'deleteUserCodeEnvironments'] as const)(+ 'generic %s preserves exact identity for later browser compensation',+ async (method) => {+ const ownerId = new Types.ObjectId().toString();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const params = input(`generic-${method}`, ownerId);+ const reserved = await registry.reserveSetup(params);+ await registry.completeSetup(params);+ const methods = createMethods(mongoose);+ if (method === 'deleteCodeEnvironmentById')+ await methods.deleteCodeEnvironmentById(reserved.resourceId);+ else await methods.deleteUserCodeEnvironments(ownerId);+ expect(await mongoose.models.CodeEnvironment.findById(reserved.resourceId)).toBeNull();+ await expect(registry.discardSetup(params)).resolves.toBeUndefined();+ expect(+ await mongoose.models.AclEntry.countDocuments({ resourceId: reserved.resourceId }),+ ).toBe(0);+ await expect(registry.reserveSetup(params)).rejects.toThrow('binding');+ const rebound = { ...params, environment: { ...params.environment, id: 'rebound-machine' } };+ await expect(registry.reserveSetup(rebound)).rejects.toThrow('binding');+ await expect(registry.discardSetup(rebound)).rejects.toThrow('binding');+ },+ );+});diff --git a/packages/api/src/code/setup/bridge.spec.ts b/packages/api/src/code/setup/bridge.spec.tsnew file mode 100644index 0000000000..365e6026b4--- /dev/null+++ b/packages/api/src/code/setup/bridge.spec.ts@@ -0,0 +1,112 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto';+import {+ hashBrowserEnrollmentRequest,+ isBrowserEnrollmentApproval,+ isBrowserEnrollmentStatusRequest,+ isBrowserEnrollmentRedemption,+ signBrowserEnrollmentRedemption,+} from '@librechat/code/browser-enrollment';+import type { BrowserEnrollmentApproval } from '@librechat/code/browser-enrollment';+import { createSetupBridge, setupRedemptionContract } from './bridge';++function approval(): BrowserEnrollmentApproval {+ const publicKey = generateKeyPairSync('ed25519')+ .publicKey.export({ type: 'spki', format: 'pem' })+ .toString();+ const request = {+ version: 1 as const,+ instance: 'https://chat.example.test/base',+ attemptId: randomBytes(32).toString('base64url'),+ createdAt: new Date().toISOString(),+ publicKey,+ machineName: 'A machine',+ workspace: { type: 'private' as const },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: false,+ };+ return {+ protocolVersion: 1,+ operation: 'enrollment.redeem',+ serverId: 'https://code.example.test',+ instance: request.instance,+ attemptId: request.attemptId,+ requestHash: hashBrowserEnrollmentRequest(request),+ workerId: 'stable-worker',+ expiresAt: new Date(Date.now() + 600_000).toISOString(),+ publicKey,+ binding: { tenantId: 'legacy', principal: { type: 'user', id: 'owner-one' } },+ };+}++test('the local server dependency is the unmodified merged protocol, not a mutable or unpublished reference', () => {+ const root = path.resolve(__dirname, '../../../../../vendor/code');+ const source = fs.readFileSync(path.join(root, 'browser-enrollment-protocol.ts'));+ const metadata = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));+ expect(metadata.librechatUpstream.commit).toBe('a3207a75c8327ba1c9526eff8b06f3588f3739ed');+ expect(createHash('sha256').update(source).digest('hex')).toBe(+ '1ecf23023f7cf482eb140dc327b2400331f18d1c50f04ba037afca6186b97a99',+ );+});++test('the administrator transport uses strict flat approval, status, and redemption projections', async () => {+ const approved = approval();+ const fetchImpl = jest.fn(+ async (url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {+ expect(init?.headers).toEqual(+ expect.objectContaining({ Authorization: 'Bearer server-only' }),+ );+ expect(init?.redirect).toBe('error');+ const body: unknown = JSON.parse(String(init?.body));+ if (String(url).endsWith('/status')) {+ expect(isBrowserEnrollmentStatusRequest(body)).toBe(true);+ expect(body).toEqual({ protocolVersion: 1, ...setupRedemptionContract(approved) });+ return Response.json({+ protocolVersion: 1,+ status: 'completed',+ workerId: approved.workerId,+ });+ }+ if (String(url).endsWith('/redeem')) {+ expect(isBrowserEnrollmentRedemption(body)).toBe(true);+ return Response.json({}, { status: 409 });+ }+ expect(isBrowserEnrollmentApproval(body)).toBe(true);+ expect(body).toEqual(approved);+ return Response.json(approved);+ },+ );+ const bridge = createSetupBridge(fetchImpl);+ await bridge.issue('https://code.example.test/v1', 'server-only', approved);+ await expect(+ bridge.status('https://code.example.test/v1', 'server-only', approved),+ ).resolves.toBe('completed');+ const key = generateKeyPairSync('ed25519')+ .privateKey.export({ type: 'pkcs8', format: 'pem' })+ .toString();+ const signature = signBrowserEnrollmentRedemption(key, approved);+ await expect(+ bridge.redeem('https://code.example.test/v1', 'server-only', approved, signature),+ ).rejects.toMatchObject({ status: 409 });+});++test('unsupported capabilities, changed server identities, and oversized provider responses fail closed', async () => {+ const fetchImpl = jest+ .fn()+ .mockResolvedValueOnce(Response.json({ browserEnrollmentVersion: 2 }))+ .mockResolvedValueOnce(+ Response.json({ browserEnrollmentVersion: 1, serverId: 'https://other.example.test' }),+ )+ .mockResolvedValueOnce(new Response('x'.repeat(16 * 1024 + 1)));+ const bridge = createSetupBridge(fetchImpl);+ await expect(+ bridge.capabilities('https://code.example.test/v1', 'server-only'),+ ).rejects.toMatchObject({ status: 502 });+ await expect(+ bridge.capabilities('https://code.example.test/v1', 'server-only'),+ ).rejects.toMatchObject({ status: 502 });+ await expect(+ bridge.status('https://code.example.test/v1', 'server-only', approval()),+ ).rejects.toMatchObject({ status: 502 });+});diff --git a/packages/api/src/code/setup/bridge.ts b/packages/api/src/code/setup/bridge.tsnew file mode 100644index 0000000000..ef99d4dab9--- /dev/null+++ b/packages/api/src/code/setup/bridge.ts@@ -0,0 +1,182 @@+import {+ isBrowserEnrollmentApproval,+ isBrowserEnrollmentStatusRequest,+ isBrowserEnrollmentRedemption,+} from '@librechat/code/browser-enrollment';+import type {+ BrowserEnrollmentApproval,+ BrowserEnrollmentRedemptionContract,+} from '@librechat/code/browser-enrollment';+import type { CodeBridgeFetch } from '../bridge';++export type SetupCredential = {+ protocolVersion: 1;+ workerId: string;+ credential: string;+ expiresAt: string;+};++export class SetupBridgeError extends Error {+ constructor(public readonly status: number) {+ super('Code API enrollment is unavailable');+ }+}++async function boundedJson(response: Response): Promise<unknown> {+ const reader = response.body?.getReader();+ if (reader == null) throw new SetupBridgeError(502);+ const chunks: Uint8Array[] = [];+ let bytes = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ bytes += value.byteLength;+ if (bytes > 16 * 1024) throw new SetupBridgeError(502);+ chunks.push(value);+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;+ } catch {+ throw new SetupBridgeError(502);+ } finally {+ await reader.cancel().catch(() => undefined);+ reader.releaseLock();+ }+}++function record(value: unknown): value is Record<string, unknown> {+ return value != null && typeof value === 'object' && !Array.isArray(value);+}++/** Only this projection crosses the strict Code API status/redemption boundary. */+export function setupRedemptionContract(+ approval: BrowserEnrollmentRedemptionContract,+): BrowserEnrollmentRedemptionContract {+ return {+ operation: 'enrollment.redeem',+ serverId: approval.serverId,+ instance: approval.instance,+ attemptId: approval.attemptId,+ requestHash: approval.requestHash,+ workerId: approval.workerId,+ expiresAt: approval.expiresAt,+ };+}++export function createSetupBridge(fetchImpl: CodeBridgeFetch = fetch) {+ async function request(+ baseURL: string,+ token: string,+ path: string,+ body?: object,+ ): Promise<unknown> {+ try {+ const response = await fetchImpl(`${baseURL}/bridge/enrollments${path}`, {+ method: body == null ? 'GET' : 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body: body == null ? undefined : JSON.stringify(body),+ redirect: 'error',+ signal: AbortSignal.timeout(10_000),+ });+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ throw new SetupBridgeError(response.status);+ }+ return await boundedJson(response);+ } catch (error) {+ if (error instanceof SetupBridgeError) throw error;+ throw new SetupBridgeError(503);+ }+ }++ return {+ async capabilities(baseURL: string, token: string): Promise<string> {+ const payload = await request(baseURL, token, '/capabilities');+ if (+ !record(payload) ||+ payload.browserEnrollmentVersion !== 1 ||+ typeof payload.serverId !== 'string'+ )+ throw new SetupBridgeError(502);+ const server = new URL(payload.serverId);+ if (+ server.protocol !== 'https:' ||+ server.origin !== payload.serverId ||+ server.origin !== new URL(baseURL).origin+ )+ throw new SetupBridgeError(502);+ return payload.serverId;+ },+ async issue(+ baseURL: string,+ token: string,+ approval: BrowserEnrollmentApproval,+ ): Promise<void> {+ if (!isBrowserEnrollmentApproval(approval)) throw new SetupBridgeError(502);+ const payload = await request(baseURL, token, '', approval);+ if (+ !isBrowserEnrollmentApproval(payload) ||+ JSON.stringify(setupRedemptionContract(payload)) !==+ JSON.stringify(setupRedemptionContract(approval)) ||+ payload.publicKey !== approval.publicKey ||+ payload.binding.tenantId !== approval.binding.tenantId ||+ payload.binding.principal.type !== approval.binding.principal.type ||+ payload.binding.principal.id !== approval.binding.principal.id+ )+ throw new SetupBridgeError(502);+ },+ async status(+ baseURL: string,+ token: string,+ approval: BrowserEnrollmentRedemptionContract,+ ): Promise<'pending' | 'completed' | 'revoked' | 'unknown'> {+ const body = { protocolVersion: 1 as const, ...setupRedemptionContract(approval) };+ if (!isBrowserEnrollmentStatusRequest(body)) throw new SetupBridgeError(502);+ let payload: unknown;+ try {+ payload = await request(baseURL, token, '/status', body);+ } catch (error) {+ if (error instanceof SetupBridgeError && error.status === 409) return 'unknown';+ throw error;+ }+ if (+ !record(payload) ||+ payload.protocolVersion !== 1 ||+ payload.workerId !== approval.workerId ||+ !['pending', 'completed', 'revoked'].includes(String(payload.status))+ )+ throw new SetupBridgeError(502);+ return payload.status as 'pending' | 'completed' | 'revoked';+ },+ async redeem(+ baseURL: string,+ token: string,+ approval: BrowserEnrollmentRedemptionContract,+ signature: string,+ ): Promise<SetupCredential> {+ const body = { protocolVersion: 1 as const, ...setupRedemptionContract(approval), signature };+ if (!isBrowserEnrollmentRedemption(body)) throw new SetupBridgeError(502);+ const payload = await request(baseURL, token, '/redeem', body);+ if (+ !record(payload) ||+ payload.protocolVersion !== 1 ||+ payload.workerId !== approval.workerId ||+ typeof payload.credential !== 'string' ||+ payload.credential.length < 32 ||+ payload.credential.length > 4096 ||+ typeof payload.expiresAt !== 'string' ||+ !Number.isFinite(Date.parse(payload.expiresAt)) ||+ Date.parse(payload.expiresAt) <= Date.now()+ )+ throw new SetupBridgeError(502);+ return {+ protocolVersion: 1,+ workerId: approval.workerId,+ credential: payload.credential,+ expiresAt: payload.expiresAt,+ };+ },+ };+}++export type SetupBridge = ReturnType<typeof createSetupBridge>;diff --git a/packages/api/src/code/setup/compatibility.integration.spec.ts b/packages/api/src/code/setup/compatibility.integration.spec.tsnew file mode 100644index 0000000000..7b35e4ab68--- /dev/null+++ b/packages/api/src/code/setup/compatibility.integration.spec.ts@@ -0,0 +1,421 @@+import fs from 'node:fs';+import os from 'node:os';+import Redis from 'ioredis';+import path from 'node:path';+import express from 'express';+import { Agent } from 'undici';+import mongoose from 'mongoose';+import { createServer } from 'node:https';+import { spawn, execFileSync } from 'node:child_process';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createServer as createHttpServer } from 'node:http';+import { generateKeyPairSync, randomBytes } from 'node:crypto';+import { createBrowserSetupBackend, createMethods, createModels } from '@librechat/data-schemas';+import type { BrowserSetupSession, AppConfig } from '@librechat/data-schemas';+import type { Server } from 'node:http';+import type { Router } from 'express';+import { createCodeEnvironmentRegistry } from '../environments';+import { createSameOriginGuard } from '~/middleware/origin';+import { createCodeSetupRouter } from './router';++const upstreamCommit = 'a3207a75c8327ba1c9526eff8b06f3588f3739ed';+const upstreamRoot = process.env.CODE_SETUP_UPSTREAM;+const describeCompatibility = upstreamRoot == null ? describe.skip : describe;++function listen(server: Server): Promise<string> {+ return new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ const address = server.address();+ if (address == null || typeof address === 'string') {+ reject(new Error('Expected a disposable TCP listener'));+ return;+ }+ resolve(`127.0.0.1:${address.port}`);+ });+ });+}++function close(server: Server): Promise<void> {+ return new Promise((resolve, reject) => {+ server.closeAllConnections();+ server.close((error) => (error ? reject(error) : resolve()));+ });+}++describeCompatibility(+ 'merged browser setup CLI with disposable Code API and LibreChat authorities',+ () => {+ let mongo: MongoMemoryServer;+ let redis: Redis;+ let directory: string;+ let certificate: Buffer;+ let privateKey: Buffer;+ const originalEnvironment = {+ CODEAPI_JWT_ENABLED: process.env.CODEAPI_JWT_ENABLED,+ CODEAPI_JWT_PRIVATE_KEY: process.env.CODEAPI_JWT_PRIVATE_KEY,+ CODE_SETUP_COMPAT_ADMIN: process.env.CODE_SETUP_COMPAT_ADMIN,+ };++ beforeAll(async () => {+ if (upstreamRoot == null) throw new Error('The pinned upstream fixture is required');+ const fixtureCommit = execFileSync('git', ['rev-parse', 'HEAD'], {+ cwd: upstreamRoot,+ encoding: 'utf8',+ }).trim();+ if (fixtureCommit !== upstreamCommit)+ throw new Error('The upstream fixture must match the merged protocol commit');+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'librechat-enrollment-'));+ fs.chmodSync(directory, 0o700);+ execFileSync(+ 'openssl',+ [+ 'req',+ '-x509',+ '-newkey',+ 'rsa:2048',+ '-nodes',+ '-days',+ '1',+ '-subj',+ '/CN=127.0.0.1',+ '-addext',+ 'subjectAltName=IP:127.0.0.1',+ '-keyout',+ path.join(directory, 'tls.key'),+ '-out',+ path.join(directory, 'tls.crt'),+ ],+ { stdio: 'ignore' },+ );+ certificate = fs.readFileSync(path.join(directory, 'tls.crt'));+ privateKey = fs.readFileSync(path.join(directory, 'tls.key'));+ fs.chmodSync(path.join(directory, 'tls.key'), 0o600);+ const signing = generateKeyPairSync('ed25519');+ process.env.CODEAPI_JWT_ENABLED = 'true';+ process.env.CODEAPI_JWT_PRIVATE_KEY = signing.privateKey+ .export({ type: 'pkcs8', format: 'pem' })+ .toString();+ process.env.CODE_SETUP_COMPAT_ADMIN = randomBytes(32).toString('base64url');+ const redisUrl = process.env.CODE_SETUP_REDIS_URI;+ if (redisUrl == null || new URL(redisUrl).pathname !== '/15') {+ throw new Error('Compatibility tests require the disposable CI Redis database 15');+ }+ redis = new Redis(redisUrl);+ await redis.ping();+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await Promise.all(Object.values(mongoose.models).map((model) => model.init()));+ }, 60_000);++ beforeEach(async () => {+ await redis.flushdb();+ await mongoose.connection.dropDatabase();+ await createMethods(mongoose).seedDefaultRoles();+ });++ afterAll(async () => {+ await mongoose.disconnect();+ await mongo?.stop();+ redis?.disconnect();+ for (const [key, value] of Object.entries(originalEnvironment)) {+ if (value == null) delete process.env[key];+ else process.env[key] = value;+ }+ if (directory != null) fs.rmSync(directory, { recursive: true, force: true });+ });++ test.each(['normal', 'lost-issuance', 'lost-redemption'] as const)(+ '%s completes the exact CLI command and preserves its existing profile on retry',+ async (scenario) => {+ if (upstreamRoot == null) throw new Error('The pinned upstream fixture is required');+ const { createBridgeRouter } = jest.requireActual(+ path.join(upstreamRoot, 'service/src/bridge/router.ts'),+ ) as {+ createBridgeRouter: (options: {+ store: object;+ pairings: object;+ authMode: 'paired';+ adminToken: string;+ allowDynamicWorkers: boolean;+ }) => Router;+ };+ const { RedisBridgePairingStore } = jest.requireActual(+ path.join(upstreamRoot, 'service/src/bridge/pairing.ts'),+ ) as {+ RedisBridgePairingStore: new (+ client: Redis,+ pairingTtl: number,+ credentialTtl: number,+ skew: number,+ namespace: string,+ options: { serverId: string },+ ) => object;+ };+ const { RedisBridgeStore } = jest.requireActual(+ path.join(upstreamRoot, 'service/src/bridge/store.ts'),+ ) as {+ RedisBridgeStore: new (client: Redis) => object;+ };+ const codeApp = express();+ codeApp.use(express.json());+ const codeServer = createServer({ key: privateKey, cert: certificate }, codeApp);+ const codeOrigin = `https://${await listen(codeServer)}`;+ codeApp.use(+ '/v1/bridge',+ createBridgeRouter({+ store: new RedisBridgeStore(redis),+ pairings: new RedisBridgePairingStore(redis, 600, 900, 5_000, '', {+ serverId: codeOrigin,+ }),+ authMode: 'paired',+ adminToken: process.env.CODE_SETUP_COMPAT_ADMIN!,+ allowDynamicWorkers: true,+ }),+ );+ const user = await mongoose.models.User.create({+ name: 'Compatibility owner',+ email: `${scenario}@example.test`,+ provider: 'local',+ role: 'USER',+ emailVerified: true,+ termsAccepted: true,+ });+ const userId = user._id.toString();+ const browserToken = randomBytes(32).toString('base64url');+ const lifetime = new AbortController();+ const app = express();+ app.use(express.json());+ const server = createHttpServer(app);+ const instance = `http://${await listen(server)}`;+ const settings = {+ enabled: true,+ instance,+ maxPending: 8,+ maxPerIp: 8,+ requestsPerMinute: 1200,+ requestsPerIpMinute: 120,+ proofWindowMs: 60_000,+ maxProofsPerAttempt: 1024,+ reconcileIntervalMs: 10_000,+ retentionMs: 86_400_000,+ };+ const config = {+ endpoints: {+ agents: {+ statefulCodeSessions: {+ allowedEnvironments: ['user'],+ principalWorkers: { enabled: true, maxPerUser: 1, browserSetup: settings },+ environments: [+ {+ id: 'personal',+ name: 'Disposable Code API',+ type: 'attached',+ owner: 'deployment',+ baseURL: `${codeOrigin}/v1`,+ pairing: { tokenEnv: 'CODE_SETUP_COMPAT_ADMIN', allowPrincipalWorkers: true },+ },+ ],+ },+ },+ },+ } as AppConfig;+ // Authentication is a fixture boundary here; login and explicit confirmation have browser E2E coverage.+ const replica = () =>+ createCodeSetupRouter({+ backend: createBrowserSetupBackend(mongoose),+ signal: lifetime.signal,+ getAppConfig: async () => config,+ registry: () => createCodeEnvironmentRegistry(mongoose),+ requireJwtAuth: (req, res, next) => {+ if (req.headers.authorization !== `Bearer ${browserToken}`) {+ res.sendStatus(401);+ return;+ }+ Object.assign(req, { user: { id: userId } });+ next();+ },+ checkBan: (_req, _res, next) => next(),+ requireSameOrigin: createSameOriginGuard({ trustedOrigins: [instance] }),+ banStore: { get: async () => undefined },+ });+ let activeReplica = replica();+ app.use('/api/code-environments/setup', (req, res, next) => activeReplica(req, res, next));+ const tls = new Agent({ connect: { ca: certificate } });+ const realFetch = globalThis.fetch;+ let loseIssue = scenario === 'lost-issuance';+ let loseRedemption = scenario === 'lost-redemption';+ const upstreamFetch = jest+ .spyOn(globalThis, 'fetch')+ .mockImplementation(async (input, init) => {+ const url = String(input);+ const options = { ...init, ...(url.startsWith(codeOrigin) ? { dispatcher: tls } : {}) };+ const response = await realFetch(input, options);+ const lose =+ response.ok &&+ ((loseIssue && url === `${codeOrigin}/v1/bridge/enrollments`) ||+ (loseRedemption && url === `${codeOrigin}/v1/bridge/enrollments/redeem`));+ if (lose) {+ loseIssue = false;+ loseRedemption = false;+ await response.body?.cancel();+ throw new Error('Disposable transport lost an already committed response');+ }+ return response;+ });+ const profile = path.join(directory, `${scenario}.json`);+ const cli = path.join(upstreamRoot, 'packages/code/dist/cli.js');+ const children = new Set<ReturnType<typeof spawn>>();+ function runCli(): Promise<{ code: number | null; stdout: string; stderr: string }> {+ return new Promise((resolve, reject) => {+ const child = spawn(+ process.execPath,+ [+ cli,+ 'setup',+ '--instance',+ instance,+ '--machine-name',+ 'Compatibility VM',+ '--profile',+ profile,+ '--non-interactive',+ '--default-workspace',+ '--no-browser',+ ],+ {+ env: { ...process.env, NODE_EXTRA_CA_CERTS: path.join(directory, 'tls.crt') },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ children.add(child);+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (data: Buffer) => {+ stdout = (stdout + data.toString()).slice(-8192);+ });+ child.stderr.on('data', (data: Buffer) => {+ stderr = (stderr + data.toString()).slice(-8192);+ });+ child.once('error', reject);+ child.once('exit', (code) => {+ children.delete(child);+ resolve({ code, stdout, stderr });+ });+ });+ }+ async function browser(pathname: string, body?: object): Promise<Response> {+ return await realFetch(`${instance}${pathname}`, {+ method: body == null ? 'GET' : 'POST',+ headers: {+ Authorization: `Bearer ${browserToken}`,+ Origin: instance,+ 'Content-Type': 'application/json',+ },+ ...(body == null ? {} : { body: JSON.stringify(body) }),+ signal: AbortSignal.timeout(15_000),+ });+ }+ try {+ const first = runCli();+ const backend = createBrowserSetupBackend(mongoose);+ let pending: BrowserSetupSession | undefined;+ for (let index = 0; index < 150 && pending == null; index++) {+ const rows = await mongoose.connection+ .collection<BrowserSetupSession>('browser_setup_sessions')+ .find({})+ .limit(1)+ .toArray();+ pending = rows[0];+ if (pending == null) await new Promise((resolve) => setTimeout(resolve, 100));+ }+ if (pending == null) {+ const result = await first;+ throw new Error(+ `Merged CLI did not create a setup session (exit ${result.code}); storage ownership must remain enforced`,+ );+ }+ const setupPath = `/api/code-environments/setup/${pending.attemptId}`;+ const inspect = await browser(setupPath);+ expect(inspect.status).toBe(200);+ const projection = (await inspect.json()) as {+ status: string;+ machineName: string;+ verificationCode: string;+ };+ expect(projection).toMatchObject({+ status: 'pending',+ machineName: 'Compatibility VM',+ verificationCode: pending.verificationCode,+ });+ const planned = JSON.parse(pending.requestCanonical) as Record<string, unknown>;+ expect(planned.workspace).toEqual({ type: 'private' });+ expect(planned).not.toHaveProperty('privateKey');+ expect(planned).not.toHaveProperty('path');+ const decision = await browser(`${setupPath}/approve`, { controlPlaneId: 'personal' });+ expect(decision.status).toBe(scenario === 'lost-issuance' ? 503 : 200);+ if (scenario === 'lost-issuance') {+ activeReplica = replica();+ expect((await browser(setupPath)).status).toBe(200);+ }+ const initial = await first;+ let output = initial.stdout;+ if (scenario === 'lost-redemption') {+ expect(initial.code).toBe(1);+ activeReplica = replica();+ expect((await browser(setupPath)).status).toBe(200);+ const resumed = await runCli();+ expect(resumed.code).toBe(0);+ output += resumed.stdout;+ } else expect(initial.code).toBe(0);+ expect(output).toContain('Machine enrolled. Profile saved.');+ expect(output).toContain('not connected or ready');+ expect(output).toContain(pending.verificationCode);+ const saved = JSON.parse(fs.readFileSync(profile, 'utf8')) as {+ identityPath: string;+ workspace: object;+ allowWorkspaceWrites: boolean;+ allowWorkspaceCommands: boolean;+ };+ expect(saved).toMatchObject({+ version: 1,+ workspace: { type: 'private' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: false,+ });+ const identity = JSON.parse(fs.readFileSync(saved.identityPath, 'utf8')) as {+ workerId: string;+ publicKey: string;+ credential: string;+ };+ expect(identity.workerId).toBe(pending.workerId);+ expect(identity.publicKey).toBe(planned.publicKey);+ expect(identity.credential.length).toBeGreaterThanOrEqual(32);+ expect(fs.statSync(saved.identityPath).mode & 0o777).toBe(0o600);+ const receipt = JSON.parse(+ fs.readFileSync(`${profile}.setup/attempt.json`, 'utf8'),+ ) as Record<string, unknown>;+ expect(receipt.completed).toBe(true);+ expect(receipt).not.toHaveProperty('privateKey');+ expect((await backend.createStore().get(pending.attemptId))?.status).toBe('completed');+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ expect(+ await createCodeEnvironmentRegistry(mongoose).listAccessible({ userId }),+ ).toHaveLength(1);+ const before = fs.readFileSync(saved.identityPath, 'utf8');+ expect((await runCli()).code).toBe(0);+ expect(fs.readFileSync(saved.identityPath, 'utf8')).toBe(before);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ } finally {+ lifetime.abort();+ for (const child of children) child.kill('SIGKILL');+ await Promise.all([close(server), close(codeServer)]);+ await tls.close();+ upstreamFetch.mockRestore();+ }+ },+ 60_000,+ );+ },+);diff --git a/packages/api/src/code/setup/policy.ts b/packages/api/src/code/setup/policy.tsnew file mode 100644index 0000000000..ffb67d6aa7--- /dev/null+++ b/packages/api/src/code/setup/policy.ts@@ -0,0 +1,201 @@+import { runAsSystem, tenantStorage } from '@librechat/data-schemas';+import { normalizeBrowserEnrollmentInstance } from '@librechat/code/browser-enrollment';+import type { AppConfig, BrowserSetupSession, BrowserSetupUser } from '@librechat/data-schemas';+import type { GetAppConfigOptions } from '~/app/service';+import { resolveCodeWorkerEnrollmentLimit } from '../enrollment';+import { isTwoFactorEnrollmentRequired } from '~/auth/twoFactor';+import { getAppConfigOptionsFromUser } from '~/app/service';+import { getCodeApiTenantIdForUser } from '~/auth/codeapi';+import { isEnabled } from '~/utils/common';++export type SetupUser = BrowserSetupUser;+type Sessions = NonNullable<NonNullable<AppConfig['endpoints']>['agents']>['statefulCodeSessions'];+export type SetupPlane = NonNullable<NonNullable<Sessions>['environments']>[number];+export type SetupConfig = NonNullable<+ NonNullable<NonNullable<Sessions>['principalWorkers']>['browserSetup']+>;+export type ExistingSetupPolicy = {+ config: Pick<SetupConfig, 'instance' | 'retentionMs'>;+ planes: SetupPlane[];+ maxOwned: number;+ user?: SetupUser;+ tenantId?: string;+ codeTenantId?: string;+};+export type SetupPolicy = ExistingSetupPolicy & { config: SetupConfig };++export class SetupPolicyError extends Error {+ constructor(+ public readonly code: 'SETUP_UNAVAILABLE' | 'ACCOUNT_UNAVAILABLE' | 'POLICY_WITHDRAWN',+ ) {+ super(code);+ }+}+export interface SetupPolicyDependencies {+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig>;+ getUser: (id: string) => Promise<SetupUser | null>;+ userIsBanned: (id: string) => Promise<boolean>;+ principalAuthEnabled: () => boolean;+ principalAuthReady: () => Promise<void> | void;+}+function sessions(config: AppConfig): Sessions {+ return config.endpoints?.agents?.statefulCodeSessions;+}+function planes(config: AppConfig, existing = false): SetupPlane[] {+ return (+ sessions(config)?.environments?.filter(+ (plane) =>+ plane.type === 'attached' &&+ plane.owner === 'deployment' &&+ plane.pairing?.tokenEnv != null &&+ (existing || plane.pairing.allowPrincipalWorkers === true),+ ) ?? []+ );+}+export function readSetupConfig(config: AppConfig, requireEnabled = true): SetupConfig {+ const settings = sessions(config)?.principalWorkers?.browserSetup;+ if (+ settings == null ||+ (requireEnabled && settings.enabled !== true) ||+ normalizeBrowserEnrollmentInstance(settings.instance) !== settings.instance+ ) {+ throw new SetupPolicyError('SETUP_UNAVAILABLE');+ }+ return settings;+}++/** Identity and authorization are reloaded independently of browser middleware. */+export function createSetupPolicy(deps: SetupPolicyDependencies): {+ deployment: (options?: { existing?: boolean }) => Promise<SetupPolicy>;+ user: (id: string, expectedTenantId?: string) => Promise<SetupPolicy>;+ frozen: (+ session: BrowserSetupSession,+ options?: { completed?: boolean },+ ) => Promise<ExistingSetupPolicy>;+} {+ async function deployment(options: { existing?: boolean } = {}): Promise<SetupPolicy> {+ if (!deps.principalAuthEnabled()) throw new SetupPolicyError('SETUP_UNAVAILABLE');+ const [base] = await Promise.all([+ deps.getAppConfig({ baseOnly: true, failClosed: true, refresh: true }),+ deps.principalAuthReady(),+ ]);+ const config = readSetupConfig(base, !options.existing);+ const maxOwned = resolveCodeWorkerEnrollmentLimit(sessions(base)?.principalWorkers);+ const authorized = planes(base, options.existing);+ if (!options.existing && (maxOwned === 0 || authorized.length === 0))+ throw new SetupPolicyError('SETUP_UNAVAILABLE');+ return { config, planes: authorized, maxOwned };+ }+ async function account(id: string, expectedTenantId?: string): Promise<SetupUser> {+ const [user, banned] = await Promise.all([+ runAsSystem(async () => deps.getUser(id)),+ deps.userIsBanned(id),+ ]);+ if (+ user == null ||+ user.id !== id ||+ user.agentTriggerDeletionStartedAt != null ||+ banned ||+ (user.expiresAt != null && user.expiresAt.getTime() <= Date.now()) ||+ isTwoFactorEnrollmentRequired(user) ||+ (user.provider === 'local' &&+ user.emailVerified !== true &&+ !isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN)) ||+ (expectedTenantId != null && (user.tenantId ?? '') !== expectedTenantId)+ ) {+ throw new SetupPolicyError('ACCOUNT_UNAVAILABLE');+ }+ return user;+ }+ function assertTerms(config: AppConfig, user: SetupUser): void {+ if (+ config.interfaceConfig?.termsOfService?.modalAcceptance === true &&+ user.termsAccepted !== true+ ) {+ throw new SetupPolicyError('POLICY_WITHDRAWN');+ }+ }+ async function user(id: string, expectedTenantId?: string): Promise<SetupPolicy> {+ const owner = await account(id, expectedTenantId);+ return await tenantStorage.run({ tenantId: owner.tenantId, userId: id }, async () => {+ const [base, effective] = await Promise.all([+ deployment(),+ deps.getAppConfig({+ ...getAppConfigOptionsFromUser(owner),+ refresh: true,+ failClosed: true,+ skipRuntimeAugmentation: true,+ }),+ ]);+ assertTerms(effective, owner);+ const settings = sessions(effective)?.principalWorkers;+ const maxOwned = resolveCodeWorkerEnrollmentLimit({ maxPerUser: base.maxOwned }, settings);+ const allowed = new Set(planes(effective).map((plane) => plane.id));+ const authorized = base.planes.filter((plane) => allowed.has(plane.id));+ if (settings?.browserSetup?.enabled === false || maxOwned === 0 || authorized.length === 0)+ throw new SetupPolicyError('POLICY_WITHDRAWN');+ return {+ ...base,+ user: owner,+ maxOwned,+ planes: authorized,+ tenantId: owner.tenantId ?? '',+ codeTenantId: getCodeApiTenantIdForUser(owner),+ };+ });+ }+ async function existing(session: BrowserSetupSession): Promise<ExistingSetupPolicy> {+ const owner = await account(session.ownerId!, session.tenantId);+ if (!deps.principalAuthEnabled()) throw new SetupPolicyError('POLICY_WITHDRAWN');+ return await tenantStorage.run({ tenantId: owner.tenantId, userId: owner.id }, async () => {+ const [base, effective] = await Promise.all([+ deps.getAppConfig({ baseOnly: true, refresh: true, failClosed: true }),+ deps.getAppConfig({+ ...getAppConfigOptionsFromUser(owner),+ refresh: true,+ failClosed: true,+ skipRuntimeAugmentation: true,+ }),+ deps.principalAuthReady(),+ ]);+ assertTerms(effective, owner);+ const allowed = new Set(planes(effective, true).map((plane) => plane.id));+ const authorized = planes(base, true).filter((plane) => allowed.has(plane.id));+ const settings = sessions(base)?.principalWorkers?.browserSetup;+ // Enrollment toggles and capacity govern new trust, not an existing redeemed identity.+ return {+ config: {+ instance: settings?.instance ?? session.approval!.instance,+ retentionMs: settings?.retentionMs ?? 86_400_000,+ },+ planes: authorized,+ maxOwned: 0,+ user: owner,+ tenantId: owner.tenantId ?? '',+ codeTenantId: getCodeApiTenantIdForUser(owner),+ };+ });+ }+ async function frozen(+ session: BrowserSetupSession,+ options: { completed?: boolean } = {},+ ): Promise<ExistingSetupPolicy> {+ if (session.ownerId == null || session.approval == null)+ throw new SetupPolicyError('POLICY_WITHDRAWN');+ const resolved = options.completed+ ? await existing(session)+ : await user(session.ownerId, session.tenantId);+ const plane = resolved.planes.find(({ id }) => id === session.planeId);+ if (+ plane == null ||+ plane.baseURL.replace(/\/+$/, '') !== session.baseURL ||+ plane.pairing?.tokenEnv !== session.tokenEnv ||+ resolved.codeTenantId !== session.approval.binding.tenantId ||+ resolved.config.instance !== session.approval.instance+ )+ throw new SetupPolicyError('POLICY_WITHDRAWN');+ return resolved;+ }+ return { deployment, user, frozen };+}+export type SetupPolicyReader = ReturnType<typeof createSetupPolicy>;diff --git a/packages/api/src/code/setup/router.integration.spec.ts b/packages/api/src/code/setup/router.integration.spec.tsnew file mode 100644index 0000000000..15a1fa6587--- /dev/null+++ b/packages/api/src/code/setup/router.integration.spec.ts@@ -0,0 +1,419 @@+import express from 'express';+import request from 'supertest';+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { generateKeyPairSync, randomBytes } from 'node:crypto';+import { createMethods, createModels, createBrowserSetupBackend } from '@librechat/data-schemas';+import {+ browserSetupRequestHash,+ signBrowserSetupProof,+ isBrowserEnrollmentApproval,+ isBrowserEnrollmentStatusRequest,+ isBrowserEnrollmentRedemption,+ signBrowserEnrollmentRedemption,+} from '@librechat/code/browser-enrollment';+import type {+ BrowserSetupProof,+ BrowserEnrollmentRequest,+ BrowserEnrollmentApproval,+} from '@librechat/code/browser-enrollment';+import type { AppConfig } from '@librechat/data-schemas';+import { createCodeEnvironmentRegistry } from '../environments';+import { createSameOriginGuard } from '~/middleware/origin';+import { createCodeSetupRouter } from './router';++const identity = generateKeyPairSync('ed25519');+const publicKey = identity.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const privateKey = identity.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();+const other = generateKeyPairSync('ed25519');+const otherPrivateKey = other.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();+const instance = 'https://chat.example.test/base';++function config(): AppConfig {+ return {+ endpoints: {+ agents: {+ statefulCodeSessions: {+ principalWorkers: {+ enabled: true,+ maxPerUser: 1,+ browserSetup: {+ enabled: true,+ instance,+ maxPending: 2,+ maxPerIp: 2,+ requestsPerMinute: 1200,+ requestsPerIpMinute: 120,+ proofWindowMs: 60_000,+ maxProofsPerAttempt: 1024,+ reconcileIntervalMs: 10_000,+ retentionMs: 86_400_000,+ },+ },+ environments: [+ {+ id: 'code-api',+ name: 'Code API',+ type: 'attached',+ owner: 'deployment',+ baseURL: 'https://code.example.test/v1',+ pairing: { tokenEnv: 'CODE_SETUP_TEST_ADMIN', allowPrincipalWorkers: true },+ },+ ],+ },+ },+ },+ } as AppConfig;+}++function setupRequest(): BrowserEnrollmentRequest {+ return {+ version: 1,+ instance,+ attemptId: randomBytes(32).toString('base64url'),+ createdAt: new Date().toISOString(),+ publicKey,+ machineName: 'Browser worker',+ workspace: { type: 'private' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: false,+ };+}++function body(+ input: BrowserEnrollmentRequest,+ operation: BrowserSetupProof['operation'] = 'setup.start',+ changes: Partial<BrowserSetupProof> = {},+ signingKey = privateKey,+) {+ const proof: BrowserSetupProof = {+ operation,+ instance: input.instance,+ attemptId: input.attemptId,+ requestHash: browserSetupRequestHash(input),+ timestamp: new Date().toISOString(),+ nonce: randomBytes(32).toString('base64url'),+ ...changes,+ };+ return { request: input, proof, signature: signBrowserSetupProof(signingKey, proof) };+}++describe('browser setup HTTP protocol boundary', () => {+ let mongo: MongoMemoryServer;+ let owner: string;+ let base: AppConfig;+ let support = true;+ let refreshCount = 0;+ const lifetimes: AbortController[] = [];+ let approval: BrowserEnrollmentApproval | undefined;+ let completed = false;+ let credentialExpiresAt: string;+ const previous = {+ jwt: process.env.CODEAPI_JWT_ENABLED,+ key: process.env.CODEAPI_JWT_PRIVATE_KEY,+ token: process.env.CODE_SETUP_TEST_ADMIN,+ };+ beforeAll(async () => {+ process.env.CODEAPI_JWT_ENABLED = 'true';+ process.env.CODEAPI_JWT_PRIVATE_KEY = privateKey;+ process.env.CODE_SETUP_TEST_ADMIN = 'server-only-administrator';+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await Promise.all(Object.values(mongoose.models).map((model) => model.init()));+ });+ beforeEach(async () => {+ await mongoose.connection.dropDatabase();+ await createMethods(mongoose).seedDefaultRoles();+ const user = await mongoose.models.User.create({+ name: 'Signed-in owner',+ email: '[email protected]',+ provider: 'local',+ emailVerified: true,+ termsAccepted: true,+ role: 'USER',+ });+ refreshCount = 0;+ owner = user._id.toString();+ base = config();+ support = true;+ approval = undefined;+ completed = false;+ credentialExpiresAt = new Date(Date.now() + 900_000).toISOString();+ jest.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {+ if (+ init?.redirect !== 'error' ||+ new Headers(init?.headers).get('Authorization') !== 'Bearer server-only-administrator'+ ) {+ throw new Error('Invalid administrator transport');+ }+ if (String(url).endsWith('/capabilities'))+ return Response.json(+ support ? { browserEnrollmentVersion: 1, serverId: 'https://code.example.test' } : {},+ { status: support ? 200 : 404 },+ );+ const payload: unknown = JSON.parse(String(init?.body));+ if (String(url).endsWith('/status')) {+ if (!isBrowserEnrollmentStatusRequest(payload))+ throw new Error('Invalid upstream status request');+ return approval+ ? Response.json({+ protocolVersion: 1,+ workerId: approval.workerId,+ status: completed ? 'completed' : 'pending',+ })+ : Response.json({}, { status: 409 });+ }+ if (String(url).endsWith('/redeem')) {+ if (!isBrowserEnrollmentRedemption(payload)) throw new Error('Invalid upstream redemption');+ completed = true;+ return Response.json({+ protocolVersion: 1,+ workerId: approval!.workerId,+ credential: 'key-bound-credential-that-is-long-enough',+ expiresAt: credentialExpiresAt,+ });+ }+ if (!isBrowserEnrollmentApproval(payload)) throw new Error('invalid upstream approval');+ approval = payload;+ return Response.json(payload);+ });+ });+ afterEach(() => {+ lifetimes.splice(0).forEach((controller) => controller.abort());+ jest.restoreAllMocks();+ });+ afterAll(async () => {+ for (const [name, value] of Object.entries({+ CODEAPI_JWT_ENABLED: previous.jwt,+ CODEAPI_JWT_PRIVATE_KEY: previous.key,+ CODE_SETUP_TEST_ADMIN: previous.token,+ })) {+ if (value == null) delete process.env[name];+ else process.env[name] = value;+ }+ await mongoose.disconnect();+ await mongo.stop();+ });++ function app(options: { registrationUnavailable?: boolean } = {}) {+ const lifetime = new AbortController();+ lifetimes.push(lifetime);+ const backend = createBrowserSetupBackend(mongoose);+ if (options.registrationUnavailable)+ backend.ensureRegistration = async () => {+ throw new Error('Index enforcement unavailable');+ };+ const app = express();+ app.set('trust proxy', 1);+ app.use(express.json());+ app.use(+ '/api/code-environments/setup',+ createCodeSetupRouter({+ backend,+ signal: lifetime.signal,+ getAppConfig: async (options) => {+ if (options.refresh) refreshCount++;+ return base;+ },+ registry: () => createCodeEnvironmentRegistry(mongoose),+ requireJwtAuth: (req, res, next) => {+ if (req.headers.authorization !== 'Bearer browser-session') {+ res.status(401).json({ code: 'AUTH_REQUIRED' });+ return;+ }+ Object.assign(req, { user: { id: owner } });+ next();+ },+ checkBan: (_req, _res, next) => next(),+ requireSameOrigin: createSameOriginGuard({ trustedOrigins: [instance] }),+ banStore: { get: async () => undefined },+ }),+ );+ return app;+ }++ test('real CLI-shaped start and signed completion pass through explicit browser approval only', async () => {+ const first = app();+ const second = app();+ const input = setupRequest();+ const capabilities = await request(first).get('/api/code-environments/setup/capabilities');+ expect(capabilities.status).toBe(200);+ expect(capabilities.body).toEqual({ browserEnrollmentVersion: 1 });+ const initial = await request(first)+ .post('/api/code-environments/setup/start')+ .send(body(input));+ expect(initial.status).toBe(200);+ expect(initial.body.status).toBe('pending');+ expect(initial.body.verificationUrl).toBe(`${instance}/code/setup/${input.attemptId}`);+ const path = `/api/code-environments/setup/${input.attemptId}`;+ expect((await request(first).get(path)).status).toBe(401);+ const inspect = await request(first).get(path).set('Authorization', 'Bearer browser-session');+ expect(inspect.status).toBe(200);+ expect(inspect.body.status).toBe('pending');+ expect(approval).toBeUndefined();+ const crossOrigin = await request(first)+ .post(`${path}/approve`)+ .set('Authorization', 'Bearer browser-session')+ .set('Origin', 'https://attacker.example')+ .send({ controlPlaneId: 'code-api' });+ expect(crossOrigin.status).toBe(403);+ expect(approval).toBeUndefined();+ const approved = await request(first)+ .post(`${path}/approve`)+ .set('Authorization', 'Bearer browser-session')+ .set('Origin', 'https://chat.example.test')+ .send({ controlPlaneId: 'code-api' });+ expect(approved.status).toBe(200);+ expect(approved.body.status).toBe('approved');+ expect(JSON.stringify(approved.body)).not.toMatch(+ /server-only-administrator|credential|binding|codeApiUrl/,+ );+ const complete = {+ ...body(input, 'setup.complete'),+ redemptionSignature: signBrowserEnrollmentRedemption(privateKey, approval!),+ };+ const response = await request(second)+ .post('/api/code-environments/setup/complete')+ .send(complete);+ expect(response.status).toBe(200);+ expect(response.body.status).toBe('completed');+ expect(response.body.credential.workerId).toBe(approval!.workerId);+ expect(+ (+ await request(first)+ .post('/api/code-environments/setup/complete')+ .send({+ ...body(input, 'setup.complete'),+ redemptionSignature: complete.redemptionSignature,+ })+ ).body.credential,+ ).toEqual(response.body.credential);+ });++ test.each([+ 'operation',+ 'audience',+ 'attempt',+ 'hash',+ 'signature',+ 'stale',+ 'future',+ 'nonce',+ ] as const)('rejects a %s mismatch without durable allocation', async (kind) => {+ const server = app();+ const input = setupRequest();+ let value = body(input);+ if (kind === 'operation') value = body(input, 'setup.poll');+ if (kind === 'audience') value = body({ ...input, instance: 'https://other.example.test' });+ if (kind === 'attempt')+ value = body(input, 'setup.start', { attemptId: randomBytes(32).toString('base64url') });+ if (kind === 'hash') value = body(input, 'setup.start', { requestHash: 'f'.repeat(64) });+ if (kind === 'signature') value = body(input, 'setup.start', {}, otherPrivateKey);+ if (kind === 'stale')+ value = body(input, 'setup.start', {+ timestamp: new Date(Date.now() - 61_000).toISOString(),+ });+ if (kind === 'future')+ value = body(input, 'setup.start', {+ timestamp: new Date(Date.now() + 61_000).toISOString(),+ });+ if (kind === 'nonce') value.proof.nonce = 'malformed';+ const response = await request(server).post('/api/code-environments/setup/start').send(value);+ expect([400, 401]).toContain(response.status);+ expect(await mongoose.connection.collection('browser_setup_sessions').countDocuments()).toBe(0);+ });++ test('replay is shared across replicas, identical starts resume, and immutable changes conflict', async () => {+ const first = app();+ const second = app();+ const input = setupRequest();+ const signed = body(input);+ const response = await request(first).post('/api/code-environments/setup/start').send(signed);+ expect(response.status).toBe(200);+ expect(+ (await request(second).post('/api/code-environments/setup/start').send(signed)).status,+ ).toBe(409);+ const resumed = await request(second)+ .post('/api/code-environments/setup/start')+ .send(body(input));+ expect(resumed.body).toEqual(response.body);+ expect(+ (+ await request(second)+ .post('/api/code-environments/setup/start')+ .send(body({ ...input, machineName: 'Changed' }))+ ).status,+ ).toBe(409);+ expect(await mongoose.connection.collection('browser_setup_sessions').countDocuments()).toBe(1);+ });++ test('capability fails closed for policy withdrawal, absent credentials, and unsupported Code API', async () => {+ const server = app();+ support = false;+ expect((await request(server).get('/api/code-environments/setup/capabilities')).status).toBe(+ 503,+ );+ support = true;+ delete process.env.CODE_SETUP_TEST_ADMIN;+ expect((await request(server).get('/api/code-environments/setup/capabilities')).status).toBe(+ 503,+ );+ process.env.CODE_SETUP_TEST_ADMIN = 'server-only-administrator';+ base.endpoints!.agents!.statefulCodeSessions!.principalWorkers!.enabled = false;+ expect((await request(server).get('/api/code-environments/setup/capabilities')).status).toBe(+ 503,+ );+ });++ test('rate-limited and invalid machine requests never trigger a forced configuration reload', async () => {+ const server = app();+ const settings = base.endpoints!.agents!.statefulCodeSessions!.principalWorkers!.browserSetup!;+ settings.requestsPerMinute = 2;+ settings.requestsPerIpMinute = 2;+ expect(+ (await request(server).post('/api/code-environments/setup/start').send({ invalid: true }))+ .status,+ ).toBe(400);+ expect(refreshCount).toBe(0);+ expect((await request(server).get('/api/code-environments/setup/capabilities')).status).toBe(+ 200,+ );+ const admitted = refreshCount;+ expect((await request(server).get('/api/code-environments/setup/capabilities')).status).toBe(+ 429,+ );+ expect(refreshCount).toBe(admitted);+ });++ test('capabilities fail closed when the required unique registration indexes cannot be enforced', async () => {+ const response = await request(app({ registrationUnavailable: true })).get(+ '/api/code-environments/setup/capabilities',+ );+ expect(response.status).toBe(503);+ expect(response.body.browserEnrollmentVersion).toBeUndefined();+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ test('bounded anonymous allocation cannot grow by changing attempt IDs or forwarded IPs', async () => {+ const server = app();+ for (let i = 0; i < 2; i++)+ expect(+ (+ await request(server)+ .post('/api/code-environments/setup/start')+ .set('X-Forwarded-For', `198.51.100.${i + 1}`)+ .send(body(setupRequest()))+ ).status,+ ).toBe(200);+ expect(+ (+ await request(server)+ .post('/api/code-environments/setup/start')+ .set('X-Forwarded-For', '198.51.100.200')+ .send(body(setupRequest()))+ ).status,+ ).toBe(429);+ expect(await mongoose.connection.collection('browser_setup_sessions').countDocuments()).toBe(2);+ });+});diff --git a/packages/api/src/code/setup/router.ts b/packages/api/src/code/setup/router.tsnew file mode 100644index 0000000000..0ab29b1166--- /dev/null+++ b/packages/api/src/code/setup/router.ts@@ -0,0 +1,348 @@+import { Keyv } from 'keyv';+import { Router } from 'express';+import { createHash } from 'node:crypto';+import { runAsSystem } from '@librechat/data-schemas';+import { ViolationTypes } from 'librechat-data-provider';+import {+ isBrowserEnrollmentRequest,+ isBrowserSetupProof,+ isBrowserEnrollmentSignature,+ isBrowserEnrollmentToken,+ hashBrowserEnrollmentRequest,+ canonicalBrowserEnrollmentRequest,+ verifyBrowserSetupProof,+ verifyBrowserEnrollmentRedemption,+} from '@librechat/code/browser-enrollment';+import type {+ BrowserSetupSession,+ BrowserSetupBackend,+ BrowserSetupStore,+} from '@librechat/data-schemas';+import type {+ BrowserSetupProof,+ BrowserEnrollmentRequest,+} from '@librechat/code/browser-enrollment';+import type { RequestHandler, Request, Response } from 'express';+import type { AppConfig } from '@librechat/data-schemas';+import type { SetupRegistry, SetupService } from './service';+import type { GetAppConfigOptions } from '~/app/service';+import type { SetupConfig } from './policy';+import { isCodeApiJwtAuthEnabled, assertCodeApiJwtSigningReady } from '~/auth/codeapi';+import { createSetupPolicy, readSetupConfig, SetupPolicyError } from './policy';+import { readCodeBridgeSecret, revokeCodeBridgeWorker } from '../bridge';+import { createSetupBridge, SetupBridgeError } from './bridge';+import { createSetupService, SetupError } from './service';+import { isEnabled } from '~/utils/common';+import { keyvMongo } from '~/cache';++interface SetupRouterDependencies {+ backend: BrowserSetupBackend;+ signal?: AbortSignal;+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig>;+ registry: () => SetupRegistry;+ requireJwtAuth: RequestHandler;+ requireSameOrigin: RequestHandler;+ checkBan: RequestHandler;+ banStore: { get: (key: string) => Promise<unknown> };+}++type MachineBody = {+ request: BrowserEnrollmentRequest;+ proof: BrowserSetupProof;+ signature: string;+ redemptionSignature?: string;+};++function record(value: unknown): value is Record<string, unknown> {+ return value != null && typeof value === 'object' && !Array.isArray(value);+}++function parseBody(value: unknown, operation: BrowserSetupProof['operation']): MachineBody {+ const keys =+ operation === 'setup.complete'+ ? ['request', 'proof', 'signature', 'redemptionSignature']+ : ['request', 'proof', 'signature'];+ if (+ !record(value) ||+ Object.keys(value).some((key) => !keys.includes(key)) ||+ !isBrowserEnrollmentRequest(value.request) ||+ !isBrowserSetupProof(value.proof) ||+ !isBrowserEnrollmentSignature(value.signature)+ )+ throw new SetupError(400, 'SETUP_PROOF_INVALID');+ const { request, proof, signature } = value;+ if (+ proof.operation !== operation ||+ proof.instance !== request.instance ||+ proof.attemptId !== request.attemptId ||+ proof.requestHash !== hashBrowserEnrollmentRequest(request) ||+ !verifyBrowserSetupProof(request.publicKey, proof, signature)+ )+ throw new SetupError(401, 'SETUP_PROOF_INVALID');+ if (operation === 'setup.complete' && !isBrowserEnrollmentSignature(value.redemptionSignature))+ throw new SetupError(400, 'SETUP_PROOF_INVALID');+ return {+ request,+ proof,+ signature,+ ...(typeof value.redemptionSignature === 'string'+ ? { redemptionSignature: value.redemptionSignature }+ : {}),+ };+}++function sendError(error: unknown, res: Response): void {+ if (res.headersSent) return;+ res.set('Cache-Control', 'no-store');+ if (error instanceof SetupError) {+ if (error.status === 429) res.set('Retry-After', '60');+ res.status(error.status).json({ code: error.code });+ return;+ }+ if (error instanceof SetupPolicyError) {+ res.status(error.code === 'SETUP_UNAVAILABLE' ? 503 : 403).json({ code: error.code });+ return;+ }+ if (error instanceof SetupBridgeError) {+ res.status(503).json({ code: 'SETUP_RETRY_REQUIRED' });+ return;+ }+ res.status(503).json({ code: 'SETUP_RETRY_REQUIRED' });+}++/** Browser routes keep every normal auth gate. Machine proofs never enter that middleware. */+export function createCodeSetupRouter(deps: SetupRouterDependencies): Router {+ const router = Router();+ let banCache: Keyv | undefined;+ let runtime:+ | {+ service: SetupService;+ store: BrowserSetupStore;+ policy: ReturnType<typeof createSetupPolicy>;+ }+ | undefined;+ let nextSweep = 0;+ let sweeping = false;++ function getRuntime(): NonNullable<typeof runtime> {+ if (runtime != null) return runtime;+ const store = deps.backend.createStore();+ const policy = createSetupPolicy({+ getAppConfig: deps.getAppConfig,+ principalAuthEnabled: isCodeApiJwtAuthEnabled,+ principalAuthReady: assertCodeApiJwtSigningReady,+ getUser: deps.backend.getUser,+ userIsBanned: async (id) => {+ if (!isEnabled(process.env.BAN_VIOLATIONS)) return false;+ banCache ??= new Keyv({ store: keyvMongo, namespace: ViolationTypes.BAN, ttl: 0 });+ const [cached, logged] = await Promise.all([banCache.get(id), deps.banStore.get(id)]);+ return [cached, logged].some(+ (value) =>+ value != null &&+ (!record(value) ||+ value.expiresAt == null ||+ !Number.isFinite(Number(value.expiresAt)) ||+ Number(value.expiresAt) > Date.now()),+ );+ },+ });+ const service = createSetupService({+ store,+ policy,+ registry: deps.registry(),+ bridge: createSetupBridge(),+ readSecret: readCodeBridgeSecret,+ revoke: revokeCodeBridgeWorker,+ });+ runtime = { service, store, policy };+ return runtime;+ }++ function boundary(handler: (req: Request, res: Response) => Promise<void>): RequestHandler {+ return (req, res) => {+ res.set('Cache-Control', 'no-store');+ void handler(req, res).catch((error: unknown) => sendError(error, res));+ };+ }++ async function limit(req: Request, config: SetupConfig): Promise<string> {+ // Express resolves the deployment's configured trusted proxy chain. The independent global+ // ceiling bounds allocation even when a deployment permits a client-controlled forwarded IP.+ const ipHash = createHash('sha256')+ .update(req.ip ?? 'unknown')+ .digest('hex');+ const allowed = await getRuntime().store.consumeRequest({+ ipHash,+ now: Date.now(),+ limits: {+ global: config.requestsPerMinute,+ perIp: Math.min(config.requestsPerIpMinute, config.requestsPerMinute),+ windowMs: 60_000,+ },+ });+ if (!allowed) throw new SetupError(429, 'SETUP_RATE_LIMITED');+ return ipHash;+ }++ async function admit(req: Request): Promise<string> {+ const cached = await deps.getAppConfig({ baseOnly: true, failClosed: true });+ return await limit(req, readSetupConfig(cached, false));+ }++ async function machine(+ req: Request,+ operation: BrowserSetupProof['operation'],+ ): Promise<{ session: BrowserSetupSession; body: MachineBody }> {+ const current = getRuntime();+ const ipHash = await admit(req);+ const body = parseBody(req.body, operation);+ let session = await current.store.get(body.request.attemptId);+ const deployment = await current.policy.deployment({ existing: session != null });+ if (+ body.request.instance !== deployment.config.instance ||+ Math.abs(Date.now() - Date.parse(body.proof.timestamp)) > deployment.config.proofWindowMs+ )+ throw new SetupError(401, 'SETUP_PROOF_INVALID');+ if (session == null && operation === 'setup.start') {+ await deps.backend.ensureRegistration();+ if ((await current.service.availablePlanes(deployment)).length === 0)+ throw new SetupError(503, 'SETUP_UNAVAILABLE');+ session = await current.service.start(body.request, ipHash, deployment.config);+ }+ if (session == null) throw new SetupError(404, 'SETUP_NOT_FOUND');+ if (+ session.requestHash !== body.proof.requestHash ||+ session.requestCanonical !== canonicalBrowserEnrollmentRequest(body.request)+ )+ throw new SetupError(409, 'SETUP_CONFLICT');+ if (+ operation === 'setup.complete' &&+ (session.approval == null ||+ !verifyBrowserEnrollmentRedemption(+ body.request.publicKey,+ session.approval,+ body.redemptionSignature!,+ ))+ )+ throw new SetupError(401, 'SETUP_PROOF_INVALID');+ const claimed = await current.store.claimNonce({+ attemptId: session.attemptId,+ requestHash: session.requestHash,+ nonce: body.proof.nonce,+ now: Date.now(),+ expiresAt: Date.parse(body.proof.timestamp) + deployment.config.proofWindowMs + 1,+ maxNonces: 256,+ maxOperations: deployment.config.maxProofsPerAttempt,+ });+ if (claimed !== 'claimed')+ throw new SetupError(+ claimed === 'limited' ? 429 : 409,+ claimed === 'limited' ? 'SETUP_RATE_LIMITED' : 'SETUP_PROOF_REPLAYED',+ );+ return { session, body };+ }++ router.get(+ '/capabilities',+ boundary(async (req, res) => {+ const current = getRuntime();+ await admit(req);+ const policy = await current.policy.deployment();+ await deps.backend.ensureRegistration();+ if ((await current.service.availablePlanes(policy)).length === 0)+ throw new SetupError(503, 'SETUP_UNAVAILABLE');+ res.json({ browserEnrollmentVersion: 1 });+ }),+ );+ for (const action of ['start', 'poll', 'cancel', 'complete'] as const) {+ router.post(+ `/${action}`,+ boundary(async (req, res) => {+ const { session, body } = await machine(req, `setup.${action}`);+ const service = getRuntime().service;+ const outcome =+ action === 'cancel'+ ? await service.cancel(session)+ : await service.advance(+ session,+ action === 'complete' ? body.redemptionSignature : undefined,+ );+ res.json(service.machineResponse(outcome));+ }),+ );+ }++ const browser = Router();+ browser.use(deps.requireJwtAuth, deps.checkBan);+ async function browserSession(+ req: Request,+ ): Promise<{ session: BrowserSetupSession; userId: string }> {+ const attemptId = req.params.attemptId;+ const userId = (req.user as { id?: string } | undefined)?.id;+ if (!userId) throw new SetupError(401, 'AUTH_REQUIRED');+ if (!isBrowserEnrollmentToken(attemptId)) throw new SetupError(404, 'SETUP_NOT_FOUND');+ const session = await getRuntime().store.get(attemptId);+ if (session == null || (session.ownerId != null && session.ownerId !== userId))+ throw new SetupError(404, 'SETUP_NOT_FOUND');+ return { session, userId };+ }+ browser.get(+ '/:attemptId',+ boundary(async (req, res) => {+ const { session, userId } = await browserSession(req);+ res.json(await getRuntime().service.inspect(session, userId));+ }),+ );+ browser.post(+ '/:attemptId/approve',+ deps.requireSameOrigin,+ boundary(async (req, res) => {+ const { session, userId } = await browserSession(req);+ if (+ !record(req.body) ||+ Object.keys(req.body).length !== 1 ||+ typeof req.body.controlPlaneId !== 'string' ||+ req.body.controlPlaneId.length > 128+ )+ throw new SetupError(400, 'SETUP_INVALID_DECISION');+ res.json(await getRuntime().service.approve(session, userId, req.body.controlPlaneId));+ }),+ );+ browser.post(+ '/:attemptId/deny',+ deps.requireSameOrigin,+ boundary(async (req, res) => {+ const { session, userId } = await browserSession(req);+ if (!record(req.body) || Object.keys(req.body).length !== 0)+ throw new SetupError(400, 'SETUP_INVALID_DECISION');+ res.json(await getRuntime().service.deny(session, userId));+ }),+ );+ router.use(browser);++ // The timer only schedules work. Mongo owns intent, deadlines, leases and retry progress.+ const timer = setInterval(() => {+ if (sweeping || !deps.backend.isConnected() || Date.now() < nextSweep) return;+ sweeping = true;+ void runAsSystem(async () => {+ const current = getRuntime();+ // Cleanup must keep running after an operator withdraws the capability.+ let interval = 10_000;+ try {+ interval = (await current.policy.deployment()).config.reconcileIntervalMs;+ } catch {+ /* Frozen cleanup destinations remain server-owned durable intent. */+ }+ nextSweep = Date.now() + interval;+ await current.service.reconcile();+ })+ .catch(() => undefined)+ .finally(() => {+ sweeping = false;+ });+ }, 1_000);+ timer.unref();+ if (deps.signal?.aborted) clearInterval(timer);+ else deps.signal?.addEventListener('abort', () => clearInterval(timer), { once: true });+ return router;+}diff --git a/packages/api/src/code/setup/service.integration.spec.ts b/packages/api/src/code/setup/service.integration.spec.tsnew file mode 100644index 0000000000..1d1a3cbf40--- /dev/null+++ b/packages/api/src/code/setup/service.integration.spec.ts@@ -0,0 +1,508 @@+import mongoose, { Types } from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto';+import { createMethods, createModels, createBrowserSetupStore } from '@librechat/data-schemas';+import {+ browserSetupRequestHash,+ signBrowserEnrollmentRedemption,+ isBrowserEnrollmentApproval,+ isBrowserEnrollmentStatusRequest,+ isBrowserEnrollmentRedemption,+ verifyBrowserEnrollmentRedemption,+} from '@librechat/code/browser-enrollment';+import type {+ BrowserEnrollmentApproval,+ BrowserEnrollmentRequest,+} from '@librechat/code/browser-enrollment';+import type { AppConfig, BrowserSetupSession } from '@librechat/data-schemas';+import type { CodeBridgeFetch } from '../bridge';+import { createCodeEnvironmentRegistry } from '../environments';+import { createSetupService, SetupError } from './service';+import { createSetupPolicy } from './policy';+import { createSetupBridge } from './bridge';++const key = generateKeyPairSync('ed25519');+const publicKey = key.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const privateKey = key.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();+const ownerId = new Types.ObjectId().toHexString();+const strangerId = new Types.ObjectId().toHexString();+const ipHash = createHash('sha256').update('127.0.0.1').digest('hex');++function configuration(): AppConfig {+ return {+ endpoints: {+ agents: {+ statefulCodeSessions: {+ allowedEnvironments: ['user'],+ principalWorkers: {+ enabled: true,+ maxPerUser: 1,+ browserSetup: {+ enabled: true,+ instance: 'https://chat.example.test/base',+ maxPending: 8,+ maxPerIp: 5,+ requestsPerMinute: 1200,+ requestsPerIpMinute: 120,+ proofWindowMs: 60_000,+ maxProofsPerAttempt: 1024,+ reconcileIntervalMs: 10_000,+ retentionMs: 86_400_000,+ },+ },+ environments: [+ {+ id: 'code-api',+ name: 'Personal machines',+ type: 'attached',+ owner: 'deployment',+ baseURL: 'https://code.example.test/v1',+ pairing: { tokenEnv: 'CODE_ADMIN_TOKEN', allowPrincipalWorkers: true },+ },+ ],+ },+ },+ },+ } as AppConfig;+}++/** External service fixture validates the actual shared strict schemas at every boundary. */+function codeApi() {+ let approval: BrowserEnrollmentApproval | undefined;+ let completed = false;+ let revoked = false;+ let issueLost = false;+ let redeemLost = false;+ let unavailable = false;+ let issueCount = 0;+ let redeemCount = 0;+ let revokeCount = 0;+ const credential = {+ protocolVersion: 1 as const,+ workerId: '',+ credential: randomBytes(32).toString('base64url'),+ expiresAt: new Date(Date.now() + 3600_000).toISOString(),+ };+ const fetchImpl: CodeBridgeFetch = async (input, init) => {+ if (unavailable) throw new Error('external outage');+ expect(init?.headers).toEqual(+ expect.objectContaining({ Authorization: 'Bearer administrator-only' }),+ );+ const url = String(input);+ if (url.endsWith('/capabilities'))+ return Response.json({ browserEnrollmentVersion: 1, serverId: 'https://code.example.test' });+ const body: unknown = JSON.parse(String(init?.body));+ if (url.endsWith('/status')) {+ expect(isBrowserEnrollmentStatusRequest(body)).toBe(true);+ if (!approval) return Response.json({ code: 'ENROLLMENT_INVALID' }, { status: 409 });+ let status = 'pending';+ if (completed) status = 'completed';+ if (revoked || (!completed && Date.parse(approval.expiresAt) <= Date.now()))+ status = 'revoked';+ return Response.json({ protocolVersion: 1, workerId: approval.workerId, status });+ }+ if (url.endsWith('/redeem')) {+ expect(isBrowserEnrollmentRedemption(body)).toBe(true);+ if (+ !isBrowserEnrollmentRedemption(body) ||+ !approval ||+ revoked ||+ !verifyBrowserEnrollmentRedemption(approval.publicKey, body, body.signature)+ )+ return Response.json({}, { status: 409 });+ completed = true;+ redeemCount++;+ if (redeemLost) {+ redeemLost = false;+ throw new Error('response lost after redemption');+ }+ return Response.json({ ...credential, workerId: approval.workerId });+ }+ expect(isBrowserEnrollmentApproval(body)).toBe(true);+ if (!isBrowserEnrollmentApproval(body) || revoked) return Response.json({}, { status: 409 });+ if (approval) expect(body).toEqual(approval);+ approval = body;+ issueCount++;+ if (issueLost) {+ issueLost = false;+ throw new Error('response lost after issuance');+ }+ return Response.json(body);+ };+ return {+ fetchImpl,+ loseIssue: () => {+ issueLost = true;+ },+ loseRedeem: () => {+ redeemLost = true;+ },+ outage: (value: boolean) => {+ unavailable = value;+ },+ revoke: async () => {+ revoked = true;+ revokeCount++;+ },+ status: () => ({ approval, completed, revoked, issueCount, redeemCount, revokeCount }),+ };+}++function input(createdAt = new Date().toISOString()): BrowserEnrollmentRequest {+ return {+ version: 1,+ instance: 'https://chat.example.test/base',+ attemptId: randomBytes(32).toString('base64url'),+ createdAt,+ publicKey,+ machineName: 'Development VM',+ workspace: { type: 'directory' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: true,+ };+}++async function fixture() {+ const base = configuration();+ let effective = base;+ const policy = createSetupPolicy({+ getAppConfig: async (options) => (options.baseOnly ? base : effective),+ principalAuthEnabled: () => true,+ principalAuthReady: () => undefined,+ getUser: async (id) => {+ const user = await createMethods(mongoose).getUserById(id);+ return user == null+ ? null+ : {+ id: user._id.toString(),+ provider: user.provider,+ emailVerified: user.emailVerified,+ termsAccepted: user.termsAccepted,+ role: user.role,+ tenantId: user.tenantId,+ };+ },+ userIsBanned: async () => false,+ });+ const external = codeApi();+ const registry = createCodeEnvironmentRegistry(mongoose);+ const make = () => {+ const store = createBrowserSetupStore(mongoose);+ const service = createSetupService({+ store,+ policy,+ registry,+ bridge: createSetupBridge(external.fetchImpl),+ readSecret: () => 'administrator-only',+ revoke: external.revoke,+ });+ return { store, service };+ };+ const { store, service } = make();+ const request = input();+ const config = (await policy.deployment()).config;+ const session = await service.start(request, ipHash, config);+ const latest = async (): Promise<BrowserSetupSession> => (await store.get(session.attemptId))!;+ const signature = async () =>+ signBrowserEnrollmentRedemption(privateKey, (await latest()).approval!);+ return {+ request,+ session,+ config,+ store,+ service,+ registry,+ external,+ latest,+ signature,+ make,+ disableEnrollment: () => {+ base.endpoints!.agents!.statefulCodeSessions!.principalWorkers!.maxPerUser = 0;+ },+ disableBrowserSetup: () => {+ base.endpoints!.agents!.statefulCodeSessions!.principalWorkers!.browserSetup!.enabled = false;+ },+ deleteAccount: async () => {+ await mongoose.models.User.deleteOne({ _id: ownerId });+ },+ changeTenant: async () => {+ await mongoose.models.User.collection.updateOne(+ { _id: new Types.ObjectId(ownerId) },+ { $set: { tenantId: 'other-tenant' } },+ );+ },+ withdraw: () => {+ effective = {+ ...base,+ endpoints: {+ ...base.endpoints,+ agents: {+ ...base.endpoints!.agents,+ statefulCodeSessions: {+ ...base.endpoints!.agents!.statefulCodeSessions!,+ principalWorkers: { enabled: false },+ },+ },+ },+ };+ },+ };+}++describe('browser setup durable lifecycle', () => {+ let mongo: MongoMemoryServer;+ beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await Promise.all(Object.values(mongoose.models).map((model) => model.init()));+ });+ beforeEach(async () => {+ await mongoose.connection.dropDatabase();+ await createMethods(mongoose).seedDefaultRoles();+ await mongoose.models.User.create(+ [ownerId, strangerId].map((id) => ({+ _id: id,+ name: 'Setup owner',+ email: `${id}@example.test`,+ provider: 'local',+ emailVerified: true,+ termsAccepted: true,+ role: 'USER',+ })),+ );+ });+ afterAll(async () => {+ await mongoose.disconnect();+ await mongo.stop();+ });++ test('resumes immutable starts, returns the CLI approval, and idempotently completes the final owner slot', async () => {+ const f = await fixture();+ const second = f.make();+ expect((await second.service.start(f.request, ipHash, f.config)).workerId).toBe(+ f.session.workerId,+ );+ await expect(+ second.service.start({ ...f.request, allowWorkspaceWrites: true }, ipHash, f.config),+ ).rejects.toMatchObject({ code: 'SETUP_CONFLICT' });+ expect(await f.registry.listAccessible({ userId: ownerId })).toEqual([]);+ const confirmation = await f.service.inspect(await f.latest(), ownerId);+ expect(confirmation.status).toBe('pending');+ expect(confirmation.keyFingerprint).toBe(+ createHash('sha256')+ .update(key.publicKey.export({ type: 'spki', format: 'der' }))+ .digest('hex'),+ );+ expect(f.external.status().approval).toBeUndefined();+ const approved = await f.service.approve(await f.latest(), ownerId, 'code-api');+ expect(approved.status).toBe('approved');+ expect(await f.registry.listAccessible({ userId: ownerId })).toEqual([]);+ const outcome = await second.service.advance(await f.latest(), await f.signature());+ const response = second.service.machineResponse(outcome);+ expect(response.status).toBe('completed');+ expect(response.verificationUrl).toBe(+ `${f.request.instance}/code/setup/${f.request.attemptId}`,+ );+ expect(response.expiresAt).toBe(f.session.expiresAt);+ expect(response.approval).toEqual({+ operation: 'enrollment.redeem',+ serverId: 'https://code.example.test',+ instance: f.request.instance,+ attemptId: f.request.attemptId,+ requestHash: browserSetupRequestHash(f.request),+ workerId: f.session.workerId,+ expiresAt: f.session.expiresAt,+ codeApiUrl: 'https://code.example.test/v1',+ });+ const replay = await f.service.advance(await f.latest(), await f.signature());+ expect(replay.credential).toEqual(outcome.credential);+ expect(await f.registry.listAccessible({ userId: ownerId })).toHaveLength(1);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ expect(JSON.stringify(await f.service.inspect(await f.latest(), ownerId))).not.toMatch(+ /administrator-only|credential|codeApiUrl|publicKey|binding/,+ );+ });++ test('lost issuance response resumes the exact operation on another replica without another worker', async () => {+ const f = await fixture();+ f.external.loseIssue();+ await expect(f.service.approve(await f.latest(), ownerId, 'code-api')).rejects.toThrow();+ const before = await f.latest();+ expect(before.status).toBe('provisioning');+ const second = f.make();+ expect((await second.service.advance(before)).session.status).toBe('approved');+ expect(f.external.status().issueCount).toBe(1);+ expect((await f.latest()).approval).toEqual(before.approval);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ });++ test('lost redemption response is completed before cancellation or expiry cleanup can revoke it', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ f.external.loseRedeem();+ await expect(f.service.advance(await f.latest(), await f.signature())).rejects.toThrow();+ expect((await f.latest()).status).toBe('completing');+ const second = f.make();+ expect((await second.service.cancel(await f.latest())).session.status).toBe('completed');+ expect(f.external.status().revoked).toBe(false);+ expect(+ (await second.service.advance(await f.latest(), await f.signature())).credential,+ ).toBeDefined();+ });++ test.each(['deleteAccount', 'withdraw', 'changeTenant'] as const)(+ 'revalidates %s during provisioning and persists compensation',+ async (change) => {+ const f = await fixture();+ f.external.loseIssue();+ await expect(f.service.approve(await f.latest(), ownerId, 'code-api')).rejects.toThrow();+ await f[change]();+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('failed');+ expect(f.external.status().revoked).toBe(true);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(0);+ expect((await f.latest()).progress?.cleanup).toBe(true);+ },+ );++ test('outage retains ambiguous redemption and cleanup intent across process restart', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ f.external.loseRedeem();+ await expect(f.service.advance(await f.latest(), await f.signature())).rejects.toThrow();+ f.external.outage(true);+ await expect(f.make().service.cancel(await f.latest())).rejects.toThrow();+ expect((await f.latest()).purgeAt).toBeUndefined();+ f.external.outage(false);+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('completed');+ expect(f.external.status().revoked).toBe(false);+ });++ test('explicit denial and cancellation do not allocate remote trust or allow later approval', async () => {+ for (const denied of [false, true]) {+ const f = await fixture();+ const result = denied+ ? await f.service.deny(await f.latest(), ownerId)+ : f.service.machineResponse(await f.service.cancel(await f.latest()));+ expect(result.status).toBe(denied ? 'denied' : 'cancelled');+ expect((await f.service.approve(await f.latest(), ownerId, 'code-api')).status).toBe(+ result.status,+ );+ expect(f.external.status().approval).toBeUndefined();+ }+ });++ test('frozen ownership rejects a different user without disclosing request details', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ await expect(f.service.inspect(await f.latest(), strangerId)).rejects.toEqual(+ new SetupError(404, 'SETUP_NOT_FOUND'),+ );+ await expect(f.service.approve(await f.latest(), strangerId, 'code-api')).rejects.toMatchObject(+ { status: 404 },+ );+ });++ test('concurrent approval freezes one binding and allocates one owner slot', async () => {+ const f = await fixture();+ const initial = await f.latest();+ const results = await Promise.all([+ f.service.approve(initial, ownerId, 'code-api'),+ f.make().service.approve(initial, ownerId, 'code-api'),+ ]);+ expect(results.every((value) => ['provisioning', 'approved'].includes(value.status))).toBe(+ true,+ );+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ expect(f.external.status().issueCount).toBe(1);+ expect((await f.latest()).ownerId).toBe(ownerId);+ });++ test('registry commit followed by response loss retries successfully at full capacity', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ const commit = f.registry.completeSetup.bind(f.registry);+ jest.spyOn(f.registry, 'completeSetup').mockImplementationOnce(async (params) => {+ await commit(params);+ throw new Error('registry commit response lost');+ });+ await expect(f.service.advance(await f.latest(), await f.signature())).rejects.toThrow(+ 'registry commit response lost',+ );+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ expect(+ (await f.make().service.advance(await f.latest(), await f.signature())).session.status,+ ).toBe('completed');+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ });++ test('completed enrollment survives ordinary setup expiry without revocation', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ await f.service.advance(await f.latest(), await f.signature());+ const time = Date.now();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(time + 601_000);+ try {+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('completed');+ expect(f.external.status().revoked).toBe(false);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ } finally {+ clock.mockRestore();+ }+ });++ test.each([false, true])(+ 'already revoked enrollment is not revoked again after completion=%s',+ async (completed) => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ if (completed) await f.service.advance(await f.latest(), await f.signature());+ await f.external.revoke();+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('failed');+ expect(f.external.status().revokeCount).toBe(1);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(0);+ },+ );++ test.each(['disableEnrollment', 'disableBrowserSetup'] as const)(+ 'lost redemption remains completed after %s without revocation or another slot',+ async (disable) => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ const approved = (await f.latest()).approval;+ f.external.loseRedeem();+ await expect(f.service.advance(await f.latest(), await f.signature())).rejects.toThrow();+ f[disable]();+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('completed');+ expect(f.external.status().revoked).toBe(false);+ expect((await f.latest()).approval).toEqual(approved);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(1);+ expect((await f.service.inspect(await f.latest(), ownerId)).status).toBe('completed');+ expect(+ (await f.make().service.advance(await f.latest(), await f.signature())).credential,+ ).toBeDefined();+ },+ );++ test('authorization withdrawal after completion deliberately revokes instead of treating it as TTL cleanup', async () => {+ const f = await fixture();+ await f.service.approve(await f.latest(), ownerId, 'code-api');+ await f.service.advance(await f.latest(), await f.signature());+ await f.deleteAccount();+ expect((await f.make().service.advance(await f.latest())).session.status).toBe('failed');+ expect(f.external.status().revoked).toBe(true);+ expect(await mongoose.models.CodeEnvironment.countDocuments()).toBe(0);+ });++ test('stale or far-future creation time cannot allocate or reopen an attempt', async () => {+ const f = await fixture();+ for (const createdAt of [+ new Date(Date.now() - 601_000).toISOString(),+ new Date(Date.now() + 61_000).toISOString(),+ ]) {+ await expect(f.service.start(input(createdAt), ipHash, f.config)).rejects.toMatchObject({+ code: 'SETUP_EXPIRED',+ });+ }+ });+});diff --git a/packages/api/src/code/setup/service.ts b/packages/api/src/code/setup/service.tsnew file mode 100644index 0000000000..6e81af81c4--- /dev/null+++ b/packages/api/src/code/setup/service.ts@@ -0,0 +1,579 @@+import { tenantStorage } from '@librechat/data-schemas';+import { createHash, createPublicKey, randomBytes, randomUUID } from 'node:crypto';+import {+ isBrowserEnrollmentRequest,+ canonicalBrowserEnrollmentRequest,+ verifyBrowserEnrollmentRedemption,+ isBrowserEnrollmentApproval,+} from '@librechat/code/browser-enrollment';+import type {+ BrowserSetupSession,+ BrowserSetupStore,+ BrowserSetupPatch,+} from '@librechat/data-schemas';+import type { BrowserEnrollmentRequest } from '@librechat/code/browser-enrollment';+import type { CodeSetupAttempt } from 'librechat-data-provider';+import type { CodeEnvironmentSetupInput, CodeEnvironmentSummary } from '../environments';+import type { SetupPolicyReader, SetupConfig, ExistingSetupPolicy } from './policy';+import type { SetupBridge, SetupCredential } from './bridge';+import { setupRedemptionContract } from './bridge';+import { SetupPolicyError } from './policy';++export class SetupError extends Error {+ constructor(+ public readonly status: number,+ public readonly code: string,+ ) {+ super(code);+ }+}++export type SetupRegistry = {+ reserveSetup: (input: CodeEnvironmentSetupInput) => Promise<CodeEnvironmentSummary>;+ completeSetup: (input: CodeEnvironmentSetupInput) => Promise<CodeEnvironmentSummary>;+ discardSetup: (input: CodeEnvironmentSetupInput) => Promise<void>;+};++export interface SetupServiceDependencies {+ store: BrowserSetupStore;+ policy: SetupPolicyReader;+ bridge: SetupBridge;+ registry: SetupRegistry;+ readSecret: (name: string) => string | undefined;+ revoke: (input: { baseURL: string; token: string; workerId: string }) => Promise<void>;+ now?: () => number;+}++export type SetupMachineResponse = {+ version: 1;+ status: 'pending' | 'approved' | 'completed' | 'denied' | 'cancelled' | 'expired';+ expiresAt: string;+ verificationUrl: string;+ verificationCode: string;+ approval?: ReturnType<typeof setupRedemptionContract> & { codeApiUrl: string };+ credential?: SetupCredential;+};++type Outcome = { session: BrowserSetupSession; credential?: SetupCredential };++function request(session: BrowserSetupSession): BrowserEnrollmentRequest {+ const value: unknown = JSON.parse(session.requestCanonical);+ if (+ !isBrowserEnrollmentRequest(value) ||+ canonicalBrowserEnrollmentRequest(value) !== session.requestCanonical+ ) {+ throw new SetupError(503, 'SETUP_UNAVAILABLE');+ }+ return value;+}++function terminal(session: BrowserSetupSession): boolean {+ return ['completed', 'denied', 'cancelled', 'expired', 'failed'].includes(session.status);+}++export function createSetupService(deps: SetupServiceDependencies): {+ availablePlanes: (+ policy: ExistingSetupPolicy,+ ) => Promise<Array<{ id: string; name: string; serverId: string }>>;+ start: (+ input: BrowserEnrollmentRequest,+ ipHash: string,+ config: SetupConfig,+ ) => Promise<BrowserSetupSession>;+ inspect: (session: BrowserSetupSession, userId: string) => Promise<CodeSetupAttempt>;+ approve: (+ session: BrowserSetupSession,+ userId: string,+ planeId: string,+ ) => Promise<CodeSetupAttempt>;+ deny: (session: BrowserSetupSession, userId: string) => Promise<CodeSetupAttempt>;+ cancel: (session: BrowserSetupSession) => Promise<Outcome>;+ advance: (session: BrowserSetupSession, redemptionSignature?: string) => Promise<Outcome>;+ machineResponse: (outcome: Outcome) => SetupMachineResponse;+ reconcile: () => Promise<void>;+} {+ const now = deps.now ?? Date.now;++ function token(session: BrowserSetupSession): string {+ const value = session.tokenEnv == null ? undefined : deps.readSecret(session.tokenEnv)?.trim();+ if (!value) throw new SetupError(503, 'SETUP_UNAVAILABLE');+ return value;+ }++ async function availablePlanes(+ policy: ExistingSetupPolicy,+ ): Promise<Array<{ id: string; name: string; serverId: string }>> {+ const results = await Promise.all(+ policy.planes.map(async (plane) => {+ const secret = deps.readSecret(plane.pairing!.tokenEnv)?.trim();+ const baseURL = plane.baseURL.replace(/\/+$/, '');+ if (!secret || new URL(baseURL).protocol !== 'https:') return null;+ try {+ const serverId = await deps.bridge.capabilities(baseURL, secret);+ return { id: plane.id, name: plane.name, serverId };+ } catch {+ return null;+ }+ }),+ );+ return results.filter((value): value is NonNullable<typeof value> => value != null);+ }++ async function start(+ input: BrowserEnrollmentRequest,+ ipHash: string,+ config: SetupConfig,+ ): Promise<BrowserSetupSession> {+ const created = Date.parse(input.createdAt);+ if (created > now() + config.proofWindowMs || created + 600_000 <= now()) {+ throw new SetupError(410, 'SETUP_EXPIRED');+ }+ const canonical = canonicalBrowserEnrollmentRequest(input);+ const result = await deps.store.start({+ session: {+ attemptId: input.attemptId,+ requestCanonical: canonical,+ requestHash: createHash('sha256').update(canonical).digest('hex'),+ createdAt: input.createdAt,+ expiresAt: new Date(created + 600_000).toISOString(),+ verificationCode: `${randomBytes(3).toString('hex').toUpperCase()}-${randomBytes(3).toString('hex').toUpperCase()}`,+ workerId: `code-${randomUUID()}`,+ status: 'pending',+ revision: 0,+ },+ ipHash,+ now: now(),+ limits: {+ global: config.maxPending,+ perIp: Math.min(config.maxPending, config.maxPerIp),+ windowMs: 600_000 + config.proofWindowMs,+ },+ });+ if (result.status === 'conflict') throw new SetupError(409, 'SETUP_CONFLICT');+ if (!('session' in result)) throw new SetupError(429, 'SETUP_RATE_LIMITED');+ return result.session;+ }++ function assertOwner(+ session: BrowserSetupSession,+ userId: string,+ policy: ExistingSetupPolicy,+ ): void {+ if (+ session.ownerId != null &&+ (session.ownerId !== userId || session.tenantId !== policy.tenantId)+ ) {+ throw new SetupError(404, 'SETUP_NOT_FOUND');+ }+ }++ async function project(+ session: BrowserSetupSession,+ policy: ExistingSetupPolicy,+ ): Promise<CodeSetupAttempt> {+ const input = request(session);+ const choices =+ session.status === 'pending'+ ? await availablePlanes(policy)+ : policy.planes.map(({ id, name }) => ({ id, name }));+ let status: CodeSetupAttempt['status'] =+ session.status === 'completing' ? 'provisioning' : session.status;+ if (session.status === 'pending' && Date.parse(session.expiresAt) <= now()) status = 'expired';+ return {+ version: 1,+ attemptId: session.attemptId,+ status,+ expiresAt: session.expiresAt,+ verificationCode: session.verificationCode,+ machineName: input.machineName,+ workspace: input.workspace,+ allowWorkspaceWrites: input.allowWorkspaceWrites,+ allowWorkspaceCommands: input.allowWorkspaceCommands,+ keyFingerprint: createHash('sha256')+ .update(createPublicKey(input.publicKey).export({ type: 'spki', format: 'der' }))+ .digest('hex'),+ controlPlanes: choices.map(({ id, name }) => ({ id, name })),+ ...(session.planeId == null ? {} : { controlPlaneId: session.planeId }),+ ...(session.failureCode+ ? { failure: { code: session.failureCode, retryable: !terminal(session) } }+ : {}),+ };+ }++ async function inspect(session: BrowserSetupSession, userId: string): Promise<CodeSetupAttempt> {+ const policy =+ session.status === 'completed'+ ? await deps.policy.frozen(session, { completed: true })+ : await deps.policy.user(userId);+ assertOwner(session, userId, policy);+ const needsProgress =+ session.status === 'provisioning' ||+ session.status === 'completing' ||+ (session.status === 'pending' && Date.parse(session.expiresAt) <= now()) ||+ (session.stopReason != null && session.progress?.cleanup !== true);+ const current = needsProgress ? (await advance(session)).session : session;+ assertOwner(current, userId, policy);+ return await project(current, policy);+ }++ async function approve(+ session: BrowserSetupSession,+ userId: string,+ planeId: string,+ ): Promise<CodeSetupAttempt> {+ if (session.status === 'completed') return await inspect(session, userId);+ const policy = await deps.policy.user(userId);+ assertOwner(session, userId, policy);+ if (terminal(session)) return await project(session, policy);+ if (session.status !== 'pending') {+ if (session.planeId !== planeId) throw new SetupError(409, 'SETUP_CONFLICT');+ return await project((await advance(session)).session, policy);+ }+ if (Date.parse(session.expiresAt) <= now()) throw new SetupError(410, 'SETUP_EXPIRED');+ const plane = policy.planes.find(({ id }) => id === planeId);+ const supported = (await availablePlanes(policy)).find(({ id }) => id === planeId);+ if (plane == null || supported == null || policy.codeTenantId == null)+ throw new SetupError(403, 'SETUP_POLICY_UNAVAILABLE');+ const input = request(session);+ const approval = {+ protocolVersion: 1 as const,+ operation: 'enrollment.redeem' as const,+ serverId: supported.serverId,+ instance: input.instance,+ attemptId: session.attemptId,+ requestHash: session.requestHash,+ workerId: session.workerId,+ expiresAt: session.expiresAt,+ publicKey: input.publicKey,+ binding: { tenantId: policy.codeTenantId, principal: { type: 'user' as const, id: userId } },+ };+ if (input.instance !== policy.config.instance || !isBrowserEnrollmentApproval(approval))+ throw new SetupError(403, 'SETUP_POLICY_UNAVAILABLE');+ // This CAS is the explicit approval and ownership linearization point, before all effects.+ const frozen = await deps.store.update({+ attemptId: session.attemptId,+ requestHash: session.requestHash,+ revision: session.revision,+ patch: {+ status: 'provisioning',+ ownerId: userId,+ tenantId: policy.tenantId,+ planeId,+ baseURL: plane.baseURL.replace(/\/+$/, ''),+ tokenEnv: plane.pairing!.tokenEnv,+ approval,+ },+ });+ if (frozen == null) {+ const current = await deps.store.get(session.attemptId);+ if (current == null) throw new SetupError(404, 'SETUP_NOT_FOUND');+ assertOwner(current, userId, policy);+ if (current.planeId !== planeId) throw new SetupError(409, 'SETUP_CONFLICT');+ return await project((await advance(current)).session, policy);+ }+ return await project((await advance(frozen)).session, policy);+ }++ async function deny(session: BrowserSetupSession, userId: string): Promise<CodeSetupAttempt> {+ const policy = await deps.policy.user(userId);+ assertOwner(session, userId, policy);+ const stopped = await advance(session, undefined, 'denied', userId, policy.tenantId);+ assertOwner(stopped.session, userId, policy);+ return await project(stopped.session, policy);+ }++ async function cancel(session: BrowserSetupSession): Promise<Outcome> {+ return await advance(session, undefined, 'cancelled');+ }++ function registration(+ session: BrowserSetupSession,+ maxOwned?: number,+ ): CodeEnvironmentSetupInput {+ if (+ session.approval == null ||+ session.ownerId == null ||+ session.baseURL == null ||+ session.planeId == null+ ) {+ throw new SetupError(503, 'SETUP_UNAVAILABLE');+ }+ return {+ actor: { userId: session.ownerId },+ setupAttemptId: session.attemptId,+ requestHash: session.requestHash,+ maxOwned,+ environment: {+ id: session.workerId,+ name: request(session).machineName,+ type: 'attached',+ baseURL: session.baseURL,+ workerId: session.workerId,+ controlPlaneId: session.planeId,+ revocationTokenEnv: session.tokenEnv,+ workerPrincipal: session.approval.binding.principal,+ },+ };+ }++ async function advance(+ initial: BrowserSetupSession,+ redemptionSignature?: string,+ stop?: 'denied' | 'cancelled',+ denyOwner?: string,+ denyTenant?: string,+ ): Promise<Outcome> {+ if (terminal(initial) && initial.status !== 'completed' && initial.progress?.cleanup === true)+ return { session: initial };+ const leaseId = randomUUID();+ let session = await deps.store.claim({+ attemptId: initial.attemptId,+ requestHash: initial.requestHash,+ revision: initial.revision,+ leaseId,+ now: now(),+ leaseMs: 120_000,+ });+ if (session == null) {+ const current = await deps.store.get(initial.attemptId);+ if (current == null) throw new SetupError(404, 'SETUP_NOT_FOUND');+ if (redemptionSignature != null || stop != null) throw new SetupError(409, 'SETUP_BUSY');+ return { session: current };+ }+ const current = (): BrowserSetupSession => session!;+ async function save(patch: BrowserSetupPatch): Promise<void> {+ const value = current();+ const changed = await deps.store.update({+ attemptId: value.attemptId,+ requestHash: value.requestHash,+ revision: value.revision,+ leaseId,+ patch,+ });+ if (changed == null) throw new SetupError(409, 'SETUP_BUSY');+ session = changed;+ }+ async function fence(): Promise<void> {+ const live = await deps.store.get(current().attemptId);+ if (+ live?.leaseId !== leaseId ||+ live.revision !== current().revision ||+ (live.leaseExpiresAt ?? 0) < now() + 15_000+ )+ throw new SetupError(409, 'SETUP_BUSY');+ }+ async function scoped<T>(job: () => Promise<T>): Promise<T> {+ return await tenantStorage.run(+ { tenantId: current().tenantId || undefined, userId: current().ownerId },+ job,+ );+ }+ async function finish(+ status: BrowserSetupSession['status'],+ retentionMs = 86_400_000,+ ): Promise<void> {+ await save({+ status,+ progress: { cleanup: true },+ purgeAt: new Date(now() + retentionMs).toISOString(),+ });+ }+ async function cleanup(+ reason: NonNullable<BrowserSetupSession['stopReason']>,+ alreadyRevoked = false,+ ): Promise<void> {+ await save({ stopReason: reason });+ const value = current();+ if (value.approval != null) {+ await fence();+ // Issuance can have succeeded without a response. Revocation also fences late issuance.+ if (!alreadyRevoked) {+ await deps.revoke({+ baseURL: value.baseURL!,+ token: token(value),+ workerId: value.workerId,+ });+ }+ await fence();+ await scoped(async () => deps.registry.discardSetup(registration(value)));+ }+ await finish(reason === 'withdrawn' ? 'failed' : reason);+ }+ try {+ let value = current();+ if (value.approval == null) {+ if (stop != null || Date.parse(value.expiresAt) <= now()) {+ await save({+ ...(denyOwner == null ? {} : { ownerId: denyOwner, tenantId: denyTenant }),+ stopReason: stop ?? 'expired',+ });+ await finish(stop ?? 'expired');+ }+ return { session: current() };+ }+ await fence();+ const remote = await deps.bridge.status(value.baseURL!, token(value), value.approval!);+ let policy: ExistingSetupPolicy | undefined;+ try {+ policy = await deps.policy.frozen(value, { completed: remote === 'completed' });+ } catch (error) {+ if (!(error instanceof SetupPolicyError)) throw error;+ await save({ stopReason: 'withdrawn', failureCode: error.code });+ }+ value = current();+ // Enrollment, not the setup deadline or a profile acknowledgement, owns completion.+ if (remote === 'completed' && value.stopReason !== 'withdrawn') {+ await fence();+ await scoped(async () => deps.registry.completeSetup(registration(value)));+ await save({ progress: { registryCompleted: true, redemption: true } });+ await finish('completed', policy?.config.retentionMs);+ if (redemptionSignature == null) return { session: current() };+ if (+ !verifyBrowserEnrollmentRedemption(+ request(value).publicKey,+ value.approval!,+ redemptionSignature,+ )+ )+ throw new SetupError(401, 'SETUP_PROOF_INVALID');+ const credential = await deps.bridge.redeem(+ value.baseURL!,+ token(value),+ value.approval!,+ redemptionSignature,+ );+ return { session: current(), credential };+ }+ if (remote === 'revoked') {+ await save({+ failureCode: 'SETUP_REVOKED',+ stopReason:+ value.stopReason ??+ stop ??+ (Date.parse(value.expiresAt) <= now() ? 'expired' : 'withdrawn'),+ });+ // The exact contract is already fenced. A newer manual generation must not be revoked.+ await cleanup(current().stopReason!, true);+ return { session: current() };+ }+ const reason =+ value.stopReason ?? stop ?? (Date.parse(value.expiresAt) <= now() ? 'expired' : undefined);+ if (reason != null) {+ await cleanup(reason);+ return { session: current() };+ }+ if (policy == null) throw new SetupError(503, 'SETUP_UNAVAILABLE');+ await fence();+ await scoped(async () =>+ deps.registry.reserveSetup(registration(current(), policy.maxOwned)),+ );+ await save({ progress: { registryReserved: true } });+ // Recheck current authority after capacity/ACL writes and before remote trust issuance.+ await deps.policy.frozen(current());+ if (remote === 'unknown') {+ if (current().progress?.issued === true)+ throw new SetupError(503, 'SETUP_RECONCILIATION_REQUIRED');+ await fence();+ await deps.bridge.issue(current().baseURL!, token(current()), current().approval!);+ }+ await save({ status: 'approved', progress: { issued: true } });+ if (redemptionSignature == null) return { session: current() };+ value = current();+ if (+ !verifyBrowserEnrollmentRedemption(+ request(value).publicKey,+ value.approval!,+ redemptionSignature,+ )+ )+ throw new SetupError(401, 'SETUP_PROOF_INVALID');+ await deps.policy.frozen(value);+ // Holding the durable lease makes explicit cancellation lose to this completion intent.+ await save({ status: 'completing' });+ await fence();+ const credential = await deps.bridge.redeem(+ value.baseURL!,+ token(value),+ value.approval!,+ redemptionSignature,+ );+ await save({ progress: { redemption: true } });+ // Existing trust still needs current account/tenant/plane authorization, not a new enrollment slot.+ await deps.policy.frozen(current(), { completed: true });+ await fence();+ await scoped(async () => deps.registry.completeSetup(registration(current())));+ await save({ progress: { registryCompleted: true } });+ await finish('completed', policy.config.retentionMs);+ return { session: current(), credential };+ } catch (error) {+ if (error instanceof SetupPolicyError && current().approval != null) {+ await save({ stopReason: 'withdrawn', failureCode: error.code });+ await cleanup('withdrawn');+ return { session: current() };+ }+ if (!(error instanceof SetupError && error.status < 500)) {+ await save({ failureCode: 'SETUP_RETRY_REQUIRED' });+ }+ throw error;+ } finally {+ const value = current();+ await deps.store.release({+ attemptId: value.attemptId,+ requestHash: value.requestHash,+ revision: value.revision,+ leaseId,+ });+ }+ }++ function machineResponse({ session, credential }: Outcome): SetupMachineResponse {+ let status: SetupMachineResponse['status'] = 'pending';+ if (['approved', 'completed', 'denied', 'cancelled', 'expired'].includes(session.status)) {+ status = session.status as SetupMachineResponse['status'];+ } else if (session.status === 'failed') {+ status = 'denied';+ }+ const input = request(session);+ return {+ version: 1,+ status,+ expiresAt: session.expiresAt,+ verificationUrl: `${input.instance}/code/setup/${session.attemptId}`,+ verificationCode: session.verificationCode,+ ...(session.approval == null+ ? {}+ : {+ approval: {+ ...setupRedemptionContract(session.approval),+ codeApiUrl: session.baseURL!,+ },+ }),+ ...(credential == null ? {} : { credential }),+ };+ }++ async function reconcile(): Promise<void> {+ const candidates = await deps.store.listReconcile(25, now());+ for (const candidate of candidates) {+ try {+ await advance(candidate);+ } catch {+ /* Durable intent remains for another replica; no request or provider payload is logged. */+ }+ }+ }++ return {+ availablePlanes,+ start,+ inspect,+ approve,+ deny,+ cancel,+ advance,+ machineResponse,+ reconcile,+ };+}++export type SetupService = ReturnType<typeof createSetupService>;diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 788ef135b1..8aa7b0b4d7 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -50,6 +50,10 @@ export const userPlugins = () => `${BASE_URL}/api/user/plugins`;export const deleteUser = () => `${BASE_URL}/api/user/delete`;export const codeEnvironments = () => `${BASE_URL}/api/code-environments`;+export const codeSetupAttempt = (attemptId: string) =>+ `${codeEnvironments()}/setup/${encodeURIComponent(attemptId)}`;+export const codeSetupApprove = (attemptId: string) => `${codeSetupAttempt(attemptId)}/approve`;+export const codeSetupDeny = (attemptId: string) => `${codeSetupAttempt(attemptId)}/deny`;export const codeEnvironmentPairings = () => `${codeEnvironments()}/pairings`;export const codeEnvironmentById = (id: string) =>`${codeEnvironments()}/${encodeURIComponent(id)}`;diff --git a/packages/data-provider/src/codeSetup.spec.ts b/packages/data-provider/src/codeSetup.spec.tsnew file mode 100644index 0000000000..f99569f60a--- /dev/null+++ b/packages/data-provider/src/codeSetup.spec.ts@@ -0,0 +1,103 @@+import {+ codeSetupAttemptSchema,+ codeSetupApprovalRequestSchema,+ codeSetupDenyRequestSchema,+} from './codeSetup';+import { approveCodeSetupAttempt, denyCodeSetupAttempt, getCodeSetupAttempt } from './data-service';+import * as endpoints from './api-endpoints';+import request from './request';++const attempt = {+ version: 1,+ attemptId: 'attempt-1',+ status: 'pending',+ expiresAt: '2030-01-01T00:00:00.000Z',+ verificationCode: '123456',+ machineName: 'My machine',+ workspace: { type: 'directory' },+ allowWorkspaceWrites: false,+ allowWorkspaceCommands: true,+ keyFingerprint: 'a'.repeat(64),+ controlPlanes: [{ id: 'plane-1', name: 'Control plane' }],+};++describe('browser setup contracts', () => {+ it('projects only serializable browser fields, including no path or credentials', () => {+ const parsed = codeSetupAttemptSchema.parse({+ ...attempt,+ privateKey: 'secret',+ pairingCode: 'secret',+ workerCredential: 'secret',+ workspace: { type: 'directory', path: '/private/directory' },+ controlPlanes: [{ id: 'plane-1', name: 'Control plane', endpoint: 'https://internal' }],+ failure: { code: 'provisioning_failed', retryable: true, message: 'sensitive details' },+ });+ expect(parsed).toEqual({+ ...attempt,+ failure: { code: 'provisioning_failed', retryable: true },+ });+ expect(JSON.parse(JSON.stringify(parsed))).toEqual(parsed);+ });++ it.each(['a'.repeat(63), 'A'.repeat(64), 'SHA256:base64', 'not-a-fingerprint'])(+ 'rejects a fingerprint outside the server SHA-256 DER SPKI hex contract: %s',+ (keyFingerprint) => {+ expect(codeSetupAttemptSchema.safeParse({ ...attempt, keyFingerprint }).success).toBe(false);+ },+ );++ it('rejects unknown versions, states, expiry and workspace kinds', () => {+ for (const override of [+ { version: 2 },+ { status: 'ready' },+ { expiresAt: 'tomorrow' },+ { workspace: { type: 'remote', path: '/local' } },+ ]) {+ expect(codeSetupAttemptSchema.safeParse({ ...attempt, ...override }).success).toBe(false);+ }+ });++ it('only accepts a control-plane approval and an empty denial', () => {+ expect(codeSetupApprovalRequestSchema.parse({ controlPlaneId: 'plane-1' })).toEqual({+ controlPlaneId: 'plane-1',+ });+ expect(+ codeSetupApprovalRequestSchema.safeParse({ controlPlaneId: 'plane-1', approve: true })+ .success,+ ).toBe(false);+ expect(codeSetupApprovalRequestSchema.safeParse({ controlPlaneId: '' }).success).toBe(false);+ expect(codeSetupDenyRequestSchema.parse({})).toEqual({});+ expect(codeSetupDenyRequestSchema.safeParse({ controlPlaneId: 'plane-1' }).success).toBe(false);+ });+});++describe('browser setup transport', () => {+ it('encodes every attempt ID as one URL segment', () => {+ expect(endpoints.codeSetupAttempt('a/b?c#d')).toBe(+ '/api/code-environments/setup/a%2Fb%3Fc%23d',+ );+ expect(endpoints.codeSetupApprove('a/b')).toBe('/api/code-environments/setup/a%2Fb/approve');+ expect(endpoints.codeSetupDeny('a/b')).toBe('/api/code-environments/setup/a%2Fb/deny');+ });++ it('reads and validates the browser projection', async () => {+ const get = jest.spyOn(request, 'get').mockResolvedValue({ ...attempt, credential: 'secret' });+ await expect(getCodeSetupAttempt('attempt-1')).resolves.toEqual(attempt);+ expect(get).toHaveBeenCalledWith('/api/code-environments/setup/attempt-1');+ });++ it('rejects a response belonging to a different setup attempt', async () => {+ jest.spyOn(request, 'get').mockResolvedValue({ ...attempt, attemptId: 'other-attempt' });+ await expect(getCodeSetupAttempt('attempt-1')).rejects.toThrow('does not match');+ });++ it('sends only the explicit approval body and empty denial body', async () => {+ const post = jest.spyOn(request, 'post').mockResolvedValue(attempt);+ await approveCodeSetupAttempt('attempt-1', { controlPlaneId: 'plane-1' });+ expect(post).toHaveBeenCalledWith('/api/code-environments/setup/attempt-1/approve', {+ controlPlaneId: 'plane-1',+ });+ await denyCodeSetupAttempt('attempt-1');+ expect(post).toHaveBeenCalledWith('/api/code-environments/setup/attempt-1/deny', {});+ });+});diff --git a/packages/data-provider/src/codeSetup.ts b/packages/data-provider/src/codeSetup.tsnew file mode 100644index 0000000000..2020147dc2--- /dev/null+++ b/packages/data-provider/src/codeSetup.ts@@ -0,0 +1,46 @@+import { z } from 'zod';++export const codeSetupStatusSchema = z.enum([+ 'pending',+ 'provisioning',+ 'approved',+ 'completed',+ 'denied',+ 'cancelled',+ 'expired',+ 'failed',+]);++export const codeSetupFailureSchema = z.object({+ code: z.string(),+ retryable: z.boolean(),+});++/** Browser projection only. Credentials, endpoints and local paths never belong here. */+export const codeSetupAttemptSchema = z.object({+ version: z.literal(1),+ attemptId: z.string().min(1),+ status: codeSetupStatusSchema,+ expiresAt: z.string().datetime({ offset: true }),+ verificationCode: z.string(),+ machineName: z.string(),+ workspace: z.object({ type: z.enum(['private', 'directory']) }),+ allowWorkspaceWrites: z.boolean(),+ allowWorkspaceCommands: z.boolean(),+ /** Server-computed SHA-256 of the DER SPKI public key, encoded as lowercase hex. */+ keyFingerprint: z.string().regex(/^[a-f0-9]{64}$/),+ controlPlanes: z.array(z.object({ id: z.string().min(1), name: z.string() })),+ controlPlaneId: z.string().optional(),+ failure: codeSetupFailureSchema.optional(),+});++export const codeSetupApprovalRequestSchema = z+ .object({ controlPlaneId: z.string().min(1) })+ .strict();+export const codeSetupDenyRequestSchema = z.object({}).strict();++export type CodeSetupStatus = z.infer<typeof codeSetupStatusSchema>;+export type CodeSetupFailure = z.infer<typeof codeSetupFailureSchema>;+export type CodeSetupAttempt = z.infer<typeof codeSetupAttemptSchema>;+export type CodeSetupApprovalRequest = z.infer<typeof codeSetupApprovalRequestSchema>;+export type CodeSetupDenyRequest = z.infer<typeof codeSetupDenyRequestSchema>;diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex e2e696aa17..8b410829dd 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1731,6 +1731,39 @@ export const agentsEndpointSchema = baseEndpointSchemaenabled: z.boolean().optional(),/** Defaults to five. Zero disables enrollment; existing machines remain usable. */maxPerUser: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),+ browserSetup: z+ .object({+ enabled: z.boolean().optional().default(false),+ /** Canonical public instance URL, including the deployment prefix. */+ instance: z.string().url(),+ maxPending: z.number().int().min(1).max(512).optional().default(128),+ maxPerIp: z.number().int().min(1).max(512).optional().default(5),+ requestsPerMinute: z.number().int().min(1).max(20000).optional().default(1200),+ requestsPerIpMinute: z.number().int().min(1).max(2000).optional().default(120),+ proofWindowMs: z.number().int().min(10000).max(120000).optional().default(60000),+ maxProofsPerAttempt: z+ .number()+ .int()+ .min(320)+ .max(10000)+ .optional()+ .default(1024),+ reconcileIntervalMs: z+ .number()+ .int()+ .min(1000)+ .max(60000)+ .optional()+ .default(10000),+ retentionMs: z+ .number()+ .int()+ .min(600000)+ .max(604800000)+ .optional()+ .default(86400000),+ })+ .optional(),}).optional(),/** Server-only policy letting a conversation's owner move its sealed attached decisiondiff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 2844ce803f..30d11388a0 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -8,9 +8,11 @@ import type {} from './types/traces';import type { TInsightsAccessResponse, TInsightsParams, TInsightsResponse } from './types/insights';import type { ScheduleMCPConsentView, ConfirmScheduleMCPConsent } from './types/scheduleConsent';+import type { CodeSetupAttempt, CodeSetupApprovalRequest } from './codeSetup';import type { TFileConfig } from './file-config';import type * as tl from './types/tools';import type * as t from './types';+import { codeSetupAttemptSchema, codeSetupApprovalRequestSchema } from './codeSetup';import { TOOL_CALL_PREVIEWS_PARAM, TOOL_CALL_PREVIEWS_VERSION } from './previews';import * as permissions from './accessPermissions';import * as endpoints from './api-endpoints';@@ -106,6 +108,38 @@ export function deleteUser(payload?: t.TDeleteUserRequest): Promise<unknown> {return request.deleteWithOptions(endpoints.deleteUser(), { data: payload });}+function parseCodeSetupAttempt(attemptId: string, data: unknown): CodeSetupAttempt {+ const attempt = codeSetupAttemptSchema.parse(data);+ if (attempt.attemptId !== attemptId) {+ throw new Error('Code setup response does not match the requested attempt');+ }+ return attempt;+}++export async function getCodeSetupAttempt(attemptId: string): Promise<CodeSetupAttempt> {+ return parseCodeSetupAttempt(attemptId, await request.get(endpoints.codeSetupAttempt(attemptId)));+}++export async function approveCodeSetupAttempt(+ attemptId: string,+ payload: CodeSetupApprovalRequest,+): Promise<CodeSetupAttempt> {+ return parseCodeSetupAttempt(+ attemptId,+ await request.post(+ endpoints.codeSetupApprove(attemptId),+ codeSetupApprovalRequestSchema.parse(payload),+ ),+ );+}++export async function denyCodeSetupAttempt(attemptId: string): Promise<CodeSetupAttempt> {+ return parseCodeSetupAttempt(+ attemptId,+ await request.post(endpoints.codeSetupDeny(attemptId), {}),+ );+}+export function getCodeEnvironments(): Promise<t.TCodeEnvironmentsResponse> {return request.get(endpoints.codeEnvironments());}diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 77679cbb2c..5df907e1cc 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -109,3 +109,5 @@ export * from './code/workspace';export * from './types/scheduleConsent';export * from './approval';++export * from './codeSetup';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex d2b72a7f9d..b76b0c3951 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -114,6 +114,7 @@ export enum QueryKeys {conversationPullRequest = 'conversationPullRequest',pullRequestConnection = 'pullRequestConnection',codeEnvironments = 'codeEnvironments',+ codeSetupAttempt = 'codeSetupAttempt',agentQueuedTurns = 'agentQueuedTurns',/* Combined Pinned-section display order (favorites + pinned chats) */pinnedOrder = 'pinnedOrder',@@ -121,6 +122,8 @@ export enum QueryKeys {// Dynamic query keys that require parametersexport const DynamicQueryKeys = {+ codeSetupAttempt: (attemptId: string, userId: string) =>+ [QueryKeys.codeSetupAttempt, userId, attemptId] as const,agentFiles: (agentId: string) => ['agentFiles', agentId] as const,projectFiles: (projectId: string) => [QueryKeys.projectFiles, projectId] as const,projectAvailableFiles: (projectId: string) =>@@ -129,6 +132,8 @@ export const DynamicQueryKeys = {} as const;export enum MutationKeys {+ approveCodeSetup = 'approveCodeSetup',+ denyCodeSetup = 'denyCodeSetup',resetToolApprovalGrants = 'resetToolApprovalGrants',subagentControl = 'subagentControl',cancelBackgroundTasks = 'cancelBackgroundTasks',diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.tsindex 38b269be70..dbd5b35728 100644--- a/packages/data-schemas/src/index.ts+++ b/packages/data-schemas/src/index.ts@@ -121,3 +121,7 @@ export {warnOnMissingSearchTokens,} from './migrations';export type { SearchTokenBackfillResult } from './migrations';++export { createBrowserSetupStore, createBrowserSetupBackend } from './methods/browserSetup';+export type * from './types/browserSetup';+export type * from './types/codeEnvironmentSetup';diff --git a/packages/data-schemas/src/methods/browserSetup.integration.spec.ts b/packages/data-schemas/src/methods/browserSetup.integration.spec.tsnew file mode 100644index 0000000000..d456ebaca0--- /dev/null+++ b/packages/data-schemas/src/methods/browserSetup.integration.spec.ts@@ -0,0 +1,497 @@+import mongoose from 'mongoose';+import { createHash } from 'node:crypto';+import { MongoMemoryServer } from 'mongodb-memory-server';+import type { BrowserSetupSession, BrowserSetupStore } from '~/types/browserSetup';+import { createBrowserSetupStore } from './browserSetup';++const now = Date.parse('2026-10-22T10:00:00.000Z');+const limits = { global: 4, perIp: 2, windowMs: 60_000 };+const hash = (input: string): string => createHash('sha256').update(input).digest('hex');+const ipHash = hash('trusted-request-ip');+function session(attemptId: string): BrowserSetupSession {+ const requestCanonical = JSON.stringify({ attemptId, machineName: 'Machine' });+ return {+ attemptId,+ requestCanonical,+ requestHash: hash(requestCanonical),+ createdAt: new Date(now).toISOString(),+ expiresAt: new Date(now + 600_000).toISOString(),+ verificationCode: 'ABCD-1234',+ workerId: `worker-${attemptId}`,+ status: 'pending',+ revision: 0,+ };+}++function persistedSessions() {+ return mongoose.connection.db!.collection<{+ _id: string;+ nonces: Array<{ nonce: string; expiresAt: number }>;+ operations: number;+ deleteAfter?: Date;+ }>('browser_setup_sessions');+}++function allocationBudget() {+ return mongoose.connection.db!.collection<{+ _id: string;+ allocations: Array<{ session: BrowserSetupSession }>;+ }>('browser_setup_budget');+}++function requestBudget() {+ return mongoose.connection.db!.collection<{+ _id: string;+ count: number;+ peers: Record<string, number>;+ }>('browser_setup_requests');+}++describe('durable browser setup store', () => {+ let mongo: MongoMemoryServer;+ let store: BrowserSetupStore;++ beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ });+ beforeEach(async () => {+ await mongoose.connection.dropDatabase();+ store = createBrowserSetupStore(mongoose);+ });+ afterAll(async () => {+ await mongoose.disconnect();+ await mongo.stop();+ });++ test('constructing a store does not launch database work outside an awaited boundary', async () => {+ const createIndex = jest.spyOn(mongoose.mongo.Collection.prototype, 'createIndex');+ try {+ const fresh = createBrowserSetupStore(mongoose);+ expect(createIndex).not.toHaveBeenCalled();+ await fresh.get('missing');+ expect(createIndex).toHaveBeenCalledTimes(2);+ } finally {+ createIndex.mockRestore();+ }+ });++ test('concurrent start preserves the first immutable session and survives factory recreation', async () => {+ const original = session('attempt');+ const results = await Promise.all(+ Array.from({ length: 12 }, (_, index) =>+ store.start({+ session: { ...original, verificationCode: `code-${index}` },+ ipHash,+ now,+ limits,+ }),+ ),+ );+ expect(results.filter((result) => result.status === 'created')).toHaveLength(1);+ const persisted = await createBrowserSetupStore(mongoose).get(original.attemptId);+ expect(persisted).toMatchObject({ ...original, verificationCode: expect.any(String) });+ for (const result of results) {+ expect(['created', 'replay']).toContain(result.status);+ if ('session' in result) expect(result.session).toEqual(persisted);+ }+ const altered = {+ ...original,+ requestCanonical: '{"different":true}',+ requestHash: hash('{"different":true}'),+ };+ await expect(store.start({ session: altered, ipHash, now, limits })).resolves.toEqual({+ status: 'conflict',+ });+ });++ test('CAS and write-once frozen fields reject conflicting owners and immutable patches', async () => {+ const original = session('cas');+ await store.start({ session: original, ipHash, now, limits });+ const race = await Promise.all(+ ['owner-one', 'owner-two'].map((ownerId) =>+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ patch: { ownerId, tenantId: 'tenant-a', status: 'provisioning' },+ }),+ ),+ );+ expect(race.filter(Boolean)).toHaveLength(1);+ const frozen = race.find((entry) => entry != null)!;+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: frozen.revision,+ patch: { tenantId: 'tenant-b' },+ }),+ ).resolves.toBeNull();+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: frozen.revision,+ patch: { ownerId: undefined },+ }),+ ).rejects.toThrow('Invalid frozen');+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: frozen.revision,+ patch: { workerId: 'replacement' } as never,+ }),+ ).rejects.toThrow('Invalid browser setup update');+ });++ test('leases are exclusive, revision-fenced, durable, and reclaimable after expiry', async () => {+ const original = session('lease');+ await store.start({ session: original, ipHash, now, limits });+ const claims = await Promise.all(+ ['lease-a', 'lease-b'].map((leaseId) =>+ store.claim({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ leaseId,+ now,+ leaseMs: 60_000,+ }),+ ),+ );+ expect(claims.filter(Boolean)).toHaveLength(1);+ const claimed = claims.find((entry) => entry != null)!;+ expect(await store.listReconcile(10, now)).toEqual([]);+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: claimed.revision,+ patch: { status: 'provisioning' },+ }),+ ).resolves.toBeNull();+ const next = await createBrowserSetupStore(mongoose).claim({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: claimed.revision,+ leaseId: 'successor',+ now: now + 60_001,+ leaseMs: 60_000,+ });+ expect(next?.revision).toBe(claimed.revision + 1);+ await expect(+ store.release({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: claimed.revision,+ leaseId: claimed.leaseId!,+ }),+ ).resolves.toBeNull();+ expect(+ await store.release({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: next!.revision,+ leaseId: 'successor',+ }),+ ).toMatchObject({ revision: next!.revision + 1 });+ expect(await store.listReconcile(1, now + 60_002)).toHaveLength(0);+ expect(await store.listReconcile(1, now + 600_002)).toHaveLength(1);+ });++ test('nonces are shared, bounded, replay-safe, and operation counts survive nonce pruning', async () => {+ const original = session('nonce');+ await store.start({ session: original, ipHash, now, limits });+ const input = {+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ nonce: 'nonce-a',+ now,+ expiresAt: now + 1000,+ maxNonces: 1,+ maxOperations: 2,+ };+ const results = await Promise.all([+ store.claimNonce(input),+ createBrowserSetupStore(mongoose).claimNonce(input),+ ]);+ expect(results.sort()).toEqual(['claimed', 'replay']);+ await expect(store.claimNonce({ ...input, nonce: 'nonce-b' })).resolves.toBe('limited');+ await expect(+ store.claimNonce({ ...input, nonce: 'nonce-b', now: now + 1001, expiresAt: now + 2000 }),+ ).resolves.toBe('claimed');+ await expect(+ store.claimNonce({ ...input, nonce: 'nonce-c', now: now + 2001, expiresAt: now + 3000 }),+ ).resolves.toBe('limited');+ await expect(store.claimNonce({ ...input, requestHash: hash('wrong') })).resolves.toBe(+ 'missing',+ );+ const persisted = await persistedSessions().findOne({ _id: original.attemptId });+ expect(persisted?.nonces).toHaveLength(1);+ expect(persisted?.operations).toBe(2);+ });++ test('global and per-IP occupancy stay bounded across windows and release only after terminal cleanup', async () => {+ const results = await Promise.all(+ Array.from({ length: 20 }, (_, index) =>+ store.start({+ session: session(`slot-${index}`),+ ipHash: hash(`peer-${index % 3}`),+ now,+ limits,+ }),+ ),+ );+ expect(results.filter((result) => result.status === 'created')).toHaveLength(limits.global);+ const created = results.filter(+ (result): result is Extract<typeof result, { session: BrowserSetupSession }> =>+ 'session' in result,+ );+ const owned = created[0].session;+ await store.update({+ attemptId: owned.attemptId,+ requestHash: owned.requestHash,+ revision: 0,+ patch: { ownerId: 'owner', status: 'provisioning' },+ });+ await expect(+ store.start({ session: session('later'), ipHash, now: now + 86_400_000, limits }),+ ).resolves.toEqual({ status: 'limited' });+ await expect(+ store.update({+ attemptId: owned.attemptId,+ requestHash: owned.requestHash,+ revision: 1,+ patch: { purgeAt: new Date(now).toISOString() },+ }),+ ).rejects.toThrow('Unresolved');+ const unresolved = await persistedSessions().findOne({ _id: owned.attemptId });+ expect(unresolved?.deleteAfter).toBeUndefined();+ await store.update({+ attemptId: owned.attemptId,+ requestHash: owned.requestHash,+ revision: 1,+ patch: {+ status: 'cancelled',+ progress: { cleanup: true },+ purgeAt: new Date(now + 1000).toISOString(),+ },+ });+ await expect(+ store.start({ session: session('later'), ipHash, now: now + 86_400_000, limits }),+ ).resolves.toMatchObject({ status: 'created' });+ const resolved = await persistedSessions().findOne({ _id: owned.attemptId });+ expect(resolved?.deleteAfter).toEqual(new Date(now + 1000));+ expect(await store.listReconcile(2, now + 86_400_000)).toHaveLength(2);+ });++ test('pre-proof request limits atomically bound global and per-IP state', async () => {+ const samePeer = await Promise.all(+ Array.from({ length: 12 }, () => store.consumeRequest({ ipHash, now, limits })),+ );+ expect(samePeer.filter(Boolean)).toHaveLength(limits.perIp);+ const diverse = await Promise.all(+ Array.from({ length: 20 }, (_, index) =>+ store.consumeRequest({ ipHash: hash(`untrusted-${index}`), now, limits }),+ ),+ );+ expect(diverse.filter(Boolean)).toHaveLength(limits.global - limits.perIp);+ const budget = await requestBudget().findOne({ _id: 'global' });+ expect(budget?.count).toBe(limits.global);+ expect(Object.keys(budget?.peers ?? {}).length).toBeLessThanOrEqual(limits.global);+ expect(await requestBudget().countDocuments()).toBe(1);+ expect(+ await createBrowserSetupStore(mongoose).consumeRequest({+ ipHash,+ now: now + limits.windowMs,+ limits,+ }),+ ).toBe(true);+ const reset = await requestBudget().findOne({ _id: 'global' });+ expect(reset?.peers).toEqual({ [ipHash]: 1 });+ });++ test('allocation per-IP bound is atomic under racing starts', async () => {+ const results = await Promise.all(+ Array.from({ length: 12 }, (_, index) =>+ store.start({ session: session(`same-${index}`), ipHash, now, limits }),+ ),+ );+ expect(results.filter((result) => result.status === 'created')).toHaveLength(limits.perIp);+ });+ test('an expired lease holder cannot save even before a successor acquires the lease', async () => {+ const original = session('expired-holder');+ await store.start({ session: original, ipHash, now, limits });+ const claimed = await store.claim({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ leaseId: 'expired',+ now,+ leaseMs: 1,+ });+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: claimed!.revision,+ leaseId: 'expired',+ patch: { status: 'provisioning' },+ }),+ ).resolves.toBeNull();+ });++ test('completed withdrawal disarms TTL until compensation finishes and cannot reopen completion', async () => {+ const original = session('withdrawal');+ const clock = Date.now();+ await store.start({ session: original, ipHash, now, limits });+ const completed = await store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ patch: {+ status: 'completed',+ tenantId: '',+ stopReason: 'expired',+ progress: { cleanup: true },+ purgeAt: new Date(clock + 60_000).toISOString(),+ },+ });+ expect(completed?.tenantId).toBe('');+ expect(await store.listReconcile(10, clock)).toEqual([]);+ const claimed = await store.claim({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: completed!.revision,+ leaseId: 'withdrawal',+ now: clock,+ leaseMs: 60_000,+ });+ const withdrawn = await store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: claimed!.revision,+ leaseId: 'withdrawal',+ patch: { stopReason: 'withdrawn' },+ });+ expect(withdrawn?.progress?.cleanup).toBe(false);+ const persisted = await persistedSessions().findOne({ _id: original.attemptId });+ expect(persisted?.deleteAfter).toBeUndefined();+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: withdrawn!.revision,+ leaseId: 'withdrawal',+ patch: { status: 'approved' },+ }),+ ).resolves.toBeNull();+ await expect(+ store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: withdrawn!.revision,+ leaseId: 'withdrawal',+ patch: { stopReason: 'cancelled' },+ }),+ ).resolves.toBeNull();+ const failed = await store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: withdrawn!.revision,+ leaseId: 'withdrawal',+ patch: {+ status: 'failed',+ progress: { cleanup: true },+ purgeAt: new Date(clock + 120_000).toISOString(),+ },+ });+ await store.release({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: failed!.revision,+ leaseId: 'withdrawal',+ });+ const resolved = await persistedSessions().findOne({ _id: original.attemptId });+ expect(resolved?.deleteAfter).toEqual(new Date(clock + 120_000));+ });++ test('live pending attempts do not starve provisioning, and repeated failures rotate behind other work', async () => {+ const records = [+ session('pending-a'),+ session('pending-b'),+ session('provision-a'),+ session('provision-b'),+ ];+ for (let index = 0; index < records.length; index++)+ await store.start({ session: records[index], ipHash: hash(`fair-${index}`), now, limits });+ for (const original of records.slice(2))+ await store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ patch: { ownerId: 'owner', status: 'provisioning' },+ });+ const first = (await store.listReconcile(1, now))[0];+ expect(first.attemptId.startsWith('provision-')).toBe(true);+ const claimed = await store.claim({+ attemptId: first.attemptId,+ requestHash: first.requestHash,+ revision: first.revision,+ leaseId: 'fairness',+ now,+ leaseMs: 60_000,+ });+ await store.release({+ attemptId: first.attemptId,+ requestHash: first.requestHash,+ revision: claimed!.revision,+ leaseId: 'fairness',+ });+ const second = (await store.listReconcile(1, now + 1))[0];+ expect(second.attemptId.startsWith('provision-')).toBe(true);+ expect(second.attemptId).not.toBe(first.attemptId);+ });+ test('a lost session insert reuses the durable allocation snapshot rather than new retry randomness', async () => {+ const original = session('insert-loss');+ await store.start({ session: original, ipHash, now, limits });+ await persistedSessions().deleteOne({ _id: original.attemptId });+ const recovered = await createBrowserSetupStore(mongoose).start({+ session: { ...original, verificationCode: 'new-code' },+ ipHash,+ now,+ limits,+ });+ expect(recovered).toEqual({ status: 'created', session: original });+ const budget = await allocationBudget().findOne({ _id: 'global' });+ expect(budget?.allocations).toHaveLength(1);+ });++ test('a database outage is an error, never an in-memory success or absence', async () => {+ const original = session('outage');+ await store.start({ session: original, ipHash, now, limits });+ await mongoose.disconnect();+ try {+ await expect(store.get(original.attemptId)).rejects.toThrow();+ } finally {+ await mongoose.connect(mongo.getUri());+ }+ });+ test('reconciliation recovers an abandoned allocation snapshot without a client retry', async () => {+ const original = session('abandoned-insert');+ await store.start({ session: original, ipHash, now, limits });+ await persistedSessions().deleteOne({ _id: original.attemptId });+ const recovered = await createBrowserSetupStore(mongoose).listReconcile(1, now + 600_001);+ expect(recovered).toEqual([original]);+ await store.update({+ attemptId: original.attemptId,+ requestHash: original.requestHash,+ revision: 0,+ patch: { status: 'expired', progress: { cleanup: true } },+ });+ const budget = await allocationBudget().findOne({ _id: 'global' });+ expect(budget?.allocations).toEqual([]);+ });+});diff --git a/packages/data-schemas/src/methods/browserSetup.ts b/packages/data-schemas/src/methods/browserSetup.tsnew file mode 100644index 0000000000..04389e71c6--- /dev/null+++ b/packages/data-schemas/src/methods/browserSetup.ts@@ -0,0 +1,660 @@+import { createHash } from 'node:crypto';+import type { mongo } from 'mongoose';+import type {+ BrowserSetupStore,+ BrowserSetupBackend,+ BrowserSetupSession,+ BrowserSetupStatus,+ BrowserSetupProgress,+ BrowserSetupStartResult,+ BrowserSetupNonceResult,+} from '~/types/browserSetup';+import type { IUser } from '~/types/user';+import { createCodeEnvironmentMethods } from './codeEnvironment';+import { buildIndexWithRetry } from '~/utils/retry';++type SessionDocument = BrowserSetupSession & {+ _id: string;+ nonces: Array<{ nonce: string; expiresAt: number }>;+ operations: number;+ deleteAfter?: Date;+ allocationReleased?: boolean;+ reconciledAt?: number;+};++type Allocation = {+ attemptId: string;+ ipHash: string;+ expiresAt: number;+ session: BrowserSetupSession;+};++type AllocationBudget = { _id: string; allocations: Allocation[] };+type RequestBudget = {+ _id: string;+ expiresAt: number;+ count: number;+ peers: Record<string, number>;+};++function duplicate(error: unknown): boolean {+ return typeof error === 'object' && error != null && 'code' in error && error.code === 11000;+}++function boundedInteger(value: number, max: number): boolean {+ return Number.isSafeInteger(value) && value > 0 && value <= max;+}++function publicSession(document: SessionDocument): BrowserSetupSession {+ const {+ _id,+ nonces: _nonces,+ operations: _operations,+ deleteAfter: _deleteAfter,+ allocationReleased: _allocationReleased,+ reconciledAt: _reconciledAt,+ ...session+ } = document;+ return session;+}++function terminal(status: BrowserSetupStatus): boolean {+ return ['completed', 'denied', 'cancelled', 'expired', 'failed'].includes(status);+}++/** The singleton bounds anonymous allocation state, including distinct attacker-controlled IPs. */+export function createBrowserSetupStore(mongoose: typeof import('mongoose')): BrowserSetupStore {+ const db = mongoose.connection.db;+ if (db == null) throw new Error('MongoDB is not connected');+ const sessions = db.collection<SessionDocument>('browser_setup_sessions');+ const budgets = db.collection<AllocationBudget>('browser_setup_budget');+ const requests = db.collection<RequestBudget>('browser_setup_requests');+ let initialization: Promise<void> | undefined;+ async function initialize(): Promise<void> {+ await buildIndexWithRetry(+ () => sessions.createIndex({ deleteAfter: 1 }, { expireAfterSeconds: 0 }),+ 'browser-setup-ttl',+ );+ await buildIndexWithRetry(+ () => sessions.createIndex({ reconciledAt: 1, expiresAt: 1, _id: 1 }),+ 'browser-setup-reconciliation',+ );+ await Promise.all([+ requests+ .updateOne(+ { _id: 'global' },+ { $setOnInsert: { expiresAt: 0, count: 0, peers: {} } },+ { upsert: true },+ )+ .catch((error: unknown) => {+ if (!duplicate(error)) throw error;+ }),+ budgets+ .updateOne({ _id: 'global' }, { $setOnInsert: { allocations: [] } }, { upsert: true })+ .catch((error: unknown) => {+ if (!duplicate(error)) throw error;+ }),+ ]);+ }+ async function ready(): Promise<void> {+ const current = (initialization ??= initialize());+ try {+ await current;+ } catch (error) {+ if (initialization === current) initialization = undefined;+ throw error;+ }+ }++ async function get(attemptId: string): Promise<BrowserSetupSession | null> {+ await ready();+ const found = await sessions.findOne({ _id: attemptId });+ if (found == null) return null;+ await releaseResolved([found]);+ return publicSession(found);+ }++ async function start({+ session,+ ipHash,+ now,+ limits,+ }: Parameters<BrowserSetupStore['start']>[0]): Promise<BrowserSetupStartResult> {+ if (+ !boundedInteger(limits.global, 512) ||+ !boundedInteger(limits.perIp, 100_000) ||+ !boundedInteger(limits.windowMs, 86_400_000) ||+ !Number.isSafeInteger(now) ||+ !/^[a-f0-9]{64}$/.test(ipHash) ||+ !/^[A-Za-z0-9_-]{1,128}$/.test(session.attemptId) ||+ !/^[a-f0-9]{64}$/.test(session.requestHash) ||+ Buffer.byteLength(session.requestCanonical) > 8192 ||+ createHash('sha256').update(session.requestCanonical).digest('hex') !== session.requestHash ||+ !Number.isFinite(Date.parse(session.createdAt)) ||+ !Number.isFinite(Date.parse(session.expiresAt)) ||+ session.verificationCode.length > 128 ||+ session.workerId.length > 128 ||+ session.status !== 'pending' ||+ session.revision !== 0 ||+ Object.keys(session).some(+ (key) =>+ ![+ 'attemptId',+ 'requestCanonical',+ 'requestHash',+ 'createdAt',+ 'expiresAt',+ 'verificationCode',+ 'workerId',+ 'status',+ 'revision',+ ].includes(key),+ )+ )+ throw new Error('Invalid browser setup allocation');+ await ready();+ const existing = await get(session.attemptId);+ if (existing != null)+ return existing.requestCanonical === session.requestCanonical &&+ existing.requestHash === session.requestHash+ ? { status: 'replay', session: existing }+ : { status: 'conflict' };++ const active = '$allocations';+ const claimed = await budgets.findOneAndUpdate(+ {+ _id: 'global',+ 'allocations.session.attemptId': { $ne: session.attemptId },+ $expr: {+ $and: [+ { $lt: [{ $size: active }, limits.global] },+ {+ $lt: [+ {+ $size: {+ $filter: {+ input: active,+ as: 'entry',+ cond: { $eq: ['$$entry.ipHash', { $literal: ipHash }] },+ },+ },+ },+ limits.perIp,+ ],+ },+ ],+ },+ },+ {+ $push: {+ allocations: {+ attemptId: session.attemptId,+ ipHash,+ expiresAt: now + limits.windowMs,+ session,+ },+ },+ },+ {+ returnDocument: 'after',+ projection: { allocations: { $elemMatch: { 'session.attemptId': session.attemptId } } },+ },+ );+ // A crash after reserving the budget must preserve the first session's random code and expiry.+ const reservation =+ claimed ??+ (await budgets.findOne(+ { _id: 'global', 'allocations.session.attemptId': session.attemptId },+ { projection: { allocations: { $elemMatch: { 'session.attemptId': session.attemptId } } } },+ ));+ const original = reservation?.allocations[0]?.session;+ if (original == null) return { status: 'limited' };+ if (+ original.requestCanonical !== session.requestCanonical ||+ original.requestHash !== session.requestHash+ )+ return { status: 'conflict' };+ let inserted = false;+ try {+ const result = await sessions.updateOne(+ { _id: session.attemptId },+ { $setOnInsert: { ...original, nonces: [], operations: 0 } },+ { upsert: true },+ );+ inserted = result.upsertedCount === 1;+ } catch (error) {+ if (!duplicate(error)) throw error;+ }+ const persisted = await get(session.attemptId);+ if (persisted == null) throw new Error('Browser setup allocation disappeared');+ if (+ persisted.requestCanonical !== session.requestCanonical ||+ persisted.requestHash !== session.requestHash+ )+ return { status: 'conflict' };+ return { status: inserted ? 'created' : 'replay', session: persisted };+ }++ async function update({+ attemptId,+ requestHash,+ revision,+ patch,+ leaseId,+ }: Parameters<BrowserSetupStore['update']>[0]): Promise<BrowserSetupSession | null> {+ await ready();+ const existing = await get(attemptId);+ if (+ existing == null ||+ existing.requestHash !== requestHash ||+ existing.revision !== revision ||+ existing.leaseId !== leaseId+ )+ return null;+ const frozen = ['ownerId', 'tenantId', 'planeId', 'baseURL', 'tokenEnv', 'approval'] as const;+ for (const key of frozen) {+ if (Object.prototype.hasOwnProperty.call(patch, key) && patch[key] == null)+ throw new Error('Invalid frozen browser setup field');+ if (+ patch[key] != null &&+ existing[key] != null &&+ JSON.stringify(patch[key]) !== JSON.stringify(existing[key])+ )+ return null;+ }+ if (+ Object.keys(patch).some(+ (key) =>+ !['status', ...frozen, 'progress', 'failureCode', 'purgeAt', 'stopReason'].includes(key),+ )+ )+ throw new Error('Invalid browser setup update');+ if (+ patch.stopReason != null &&+ existing.stopReason != null &&+ patch.stopReason !== existing.stopReason &&+ patch.stopReason !== 'withdrawn'+ )+ return null;+ for (const key of ['ownerId', 'tenantId', 'planeId', 'baseURL', 'tokenEnv'] as const) {+ const value = patch[key];+ if (+ value != null &&+ (typeof value !== 'string' ||+ (value.length === 0 && key !== 'tenantId') ||+ value.length > (key === 'baseURL' ? 2048 : 256))+ )+ throw new Error('Invalid frozen browser setup field');+ }+ if (patch.tokenEnv != null && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(patch.tokenEnv))+ throw new Error('Invalid browser setup token environment reference');+ if (+ patch.approval != null &&+ (patch.approval.attemptId !== attemptId ||+ patch.approval.requestHash !== requestHash ||+ patch.approval.workerId !== existing.workerId ||+ patch.approval.expiresAt !== existing.expiresAt ||+ Buffer.byteLength(JSON.stringify(patch.approval)) > 8192)+ )+ throw new Error('Invalid browser setup approval binding');+ const statuses = [+ 'pending',+ 'provisioning',+ 'approved',+ 'completing',+ 'completed',+ 'denied',+ 'cancelled',+ 'expired',+ 'failed',+ ];+ if (patch.status != null && !statuses.includes(patch.status))+ throw new Error('Invalid browser setup status');+ if (+ patch.stopReason != null &&+ !['denied', 'cancelled', 'expired', 'withdrawn'].includes(patch.stopReason)+ )+ throw new Error('Invalid browser setup stop reason');+ if (+ patch.progress != null &&+ Object.entries(patch.progress).some(+ ([key, value]) =>+ !['registryReserved', 'registryCompleted', 'issued', 'redemption', 'cleanup'].includes(+ key,+ ) || typeof value !== 'boolean',+ )+ )+ throw new Error('Invalid browser setup progress');+ const status = patch.status ?? existing.status;+ const withdrawn = (patch.stopReason ?? existing.stopReason) === 'withdrawn';+ if (+ terminal(existing.status) &&+ status !== existing.status &&+ !(existing.status === 'completed' && status === 'failed' && withdrawn)+ )+ return null;+ const withdrawing = patch.stopReason === 'withdrawn' && existing.stopReason !== 'withdrawn';+ const progress = {+ ...existing.progress,+ ...(withdrawing ? { cleanup: false } : {}),+ ...patch.progress,+ };+ if (+ Object.entries(existing.progress ?? {}).some(+ ([key, value]) =>+ value === true &&+ patch.progress?.[key as keyof BrowserSetupProgress] === false &&+ !(key === 'cleanup' && withdrawing),+ )+ )+ return null;+ if (patch.failureCode != null && !/^[A-Z][A-Z0-9_]{0,79}$/.test(patch.failureCode))+ throw new Error('Invalid browser setup failure code');+ if (+ patch.purgeAt != null &&+ (!terminal(status) ||+ progress.cleanup !== true ||+ !Number.isFinite(Date.parse(patch.purgeAt)))+ )+ throw new Error('Unresolved browser setup cannot expire from storage');+ const updated = await sessions.findOneAndUpdate(+ {+ _id: attemptId,+ requestHash,+ revision,+ ...(leaseId == null+ ? { leaseId: { $exists: false } }+ : { leaseId, leaseExpiresAt: { $gt: Date.now() } }),+ },+ {+ $set: { ...patch, progress },+ ...(withdrawing ? { $unset: { deleteAfter: '' } } : {}),+ $inc: { revision: 1 },+ },+ { returnDocument: 'after' },+ );+ if (updated == null) return null;+ await releaseResolved([updated]);+ return publicSession(updated);+ }++ async function claimNonce({+ attemptId,+ requestHash,+ nonce,+ now,+ expiresAt,+ maxNonces,+ maxOperations,+ }: Parameters<BrowserSetupStore['claimNonce']>[0]): Promise<BrowserSetupNonceResult> {+ if (+ !boundedInteger(maxNonces, 10_000) ||+ !boundedInteger(maxOperations, 100_000) ||+ !/^[A-Za-z0-9_-]{1,128}$/.test(nonce) ||+ !Number.isSafeInteger(now) ||+ !Number.isSafeInteger(expiresAt) ||+ expiresAt <= now+ )+ throw new Error('Invalid browser setup nonce');+ await ready();+ const claim = async (): Promise<boolean> => {+ const result = await sessions.updateOne(+ {+ _id: attemptId,+ requestHash,+ operations: { $lt: maxOperations },+ nonces: { $not: { $elemMatch: { nonce, expiresAt: { $gt: now } } } },+ [`nonces.${maxNonces - 1}`]: { $exists: false },+ },+ { $push: { nonces: { nonce, expiresAt } }, $inc: { operations: 1 } },+ );+ return result.matchedCount === 1;+ };+ if (await claim()) return 'claimed';+ let found = await sessions.findOne({ _id: attemptId, requestHash });+ if (found == null) return 'missing';+ if (found.nonces.some((entry) => entry.nonce === nonce && entry.expiresAt > now))+ return 'replay';+ if (found.operations >= maxOperations) return 'limited';+ if (found.nonces.some((entry) => entry.expiresAt <= now)) {+ await sessions.updateOne(+ { _id: attemptId, requestHash },+ { $pull: { nonces: { expiresAt: { $lte: now } } } },+ );+ if (await claim()) return 'claimed';+ found = await sessions.findOne({ _id: attemptId, requestHash });+ if (found == null) return 'missing';+ if (found.nonces.some((entry) => entry.nonce === nonce && entry.expiresAt > now))+ return 'replay';+ }+ return 'limited';+ }++ async function consumeRequest({+ ipHash,+ now,+ limits,+ }: Parameters<BrowserSetupStore['consumeRequest']>[0]): Promise<boolean> {+ if (+ !/^[a-f0-9]{64}$/.test(ipHash) ||+ !Number.isSafeInteger(now) ||+ !boundedInteger(limits.global, 100_000) ||+ !boundedInteger(limits.perIp, 100_000) ||+ !boundedInteger(limits.windowMs, 86_400_000)+ )+ throw new Error('Invalid browser setup request budget');+ await ready();+ // The validated hash is a bounded field in one singleton, never a new attacker-owned bucket.+ const peer = `peers.${ipHash}`;+ const increment = async (): Promise<boolean> => {+ const result = await requests.updateOne(+ {+ _id: 'global',+ expiresAt: { $gt: now },+ count: { $lt: limits.global },+ $or: [{ [peer]: { $exists: false } }, { [peer]: { $lt: limits.perIp } }],+ },+ { $inc: { count: 1, [peer]: 1 } },+ );+ return result.matchedCount === 1;+ };+ if (await increment()) return true;+ await requests.updateOne(+ { _id: 'global', expiresAt: { $lte: now } },+ { $set: { expiresAt: now + limits.windowMs, count: 0, peers: {} } },+ );+ return await increment();+ }++ async function claim({+ attemptId,+ requestHash,+ revision,+ leaseId,+ now,+ leaseMs,+ }: Parameters<BrowserSetupStore['claim']>[0]): Promise<BrowserSetupSession | null> {+ if (+ !/^[A-Za-z0-9_-]{1,128}$/.test(leaseId) ||+ !Number.isSafeInteger(now) ||+ !boundedInteger(leaseMs, 300_000)+ )+ throw new Error('Invalid browser setup lease');+ await ready();+ const found = await sessions.findOneAndUpdate(+ {+ _id: attemptId,+ requestHash,+ revision,+ $or: [{ leaseId: { $exists: false } }, { leaseExpiresAt: { $lte: now } }],+ },+ {+ $set: { leaseId, leaseExpiresAt: now + leaseMs, reconciledAt: now },+ $unset: { deleteAfter: '' },+ $inc: { revision: 1 },+ },+ { returnDocument: 'after' },+ );+ return found == null ? null : publicSession(found);+ }++ async function release({+ attemptId,+ requestHash,+ revision,+ leaseId,+ }: Parameters<BrowserSetupStore['release']>[0]): Promise<BrowserSetupSession | null> {+ await ready();+ const found = await sessions.findOneAndUpdate(+ { _id: attemptId, requestHash, revision, leaseId },+ { $unset: { leaseId: '', leaseExpiresAt: '' }, $inc: { revision: 1 } },+ { returnDocument: 'after' },+ );+ if (found == null) return null;+ await releaseResolved([found]);+ return publicSession(found);+ }++ async function writeSessions(+ operations: mongo.AnyBulkWriteOperation<SessionDocument>[],+ ): Promise<void> {+ // Attempt IDs are deployment-global; raw batches use exact IDs and CAS/lease predicates.+ // eslint-disable-next-line no-restricted-syntax+ await sessions.bulkWrite(operations);+ }++ async function restoreAllocations(limit: number): Promise<void> {+ const missing = await budgets+ .aggregate<Allocation>([+ { $match: { _id: 'global' } },+ { $unwind: '$allocations' },+ {+ $lookup: {+ from: sessions.collectionName,+ localField: 'allocations.attemptId',+ foreignField: '_id',+ as: 'persisted',+ },+ },+ { $match: { persisted: { $size: 0 } } },+ { $replaceRoot: { newRoot: '$allocations' } },+ { $limit: limit },+ ])+ .toArray();+ if (missing.length === 0) return;+ await writeSessions(+ missing.map(({ session }) => ({+ updateOne: {+ filter: { _id: session.attemptId },+ update: { $setOnInsert: { ...session, nonces: [], operations: 0 } },+ upsert: true,+ },+ })),+ );+ }++ async function releaseResolved(documents: SessionDocument[]): Promise<void> {+ const resolved = documents.filter(+ (entry) =>+ terminal(entry.status) &&+ entry.leaseId == null &&+ entry.progress?.cleanup === true &&+ (!entry.allocationReleased || (entry.purgeAt != null && entry.deleteAfter == null)),+ );+ if (resolved.length === 0) return;+ await budgets.updateOne(+ { _id: 'global' },+ {+ $pull: {+ allocations: { attemptId: { $in: resolved.map((entry) => entry.attemptId) } },+ },+ },+ );+ // TTL is armed only after occupancy release. A crash before this write remains reconcilable.+ await writeSessions(+ resolved.map((entry) => ({+ updateOne: {+ filter: {+ _id: entry.attemptId,+ revision: entry.revision,+ leaseId: { $exists: false },+ 'progress.cleanup': true,+ },+ update: {+ $set: {+ allocationReleased: true,+ ...(entry.purgeAt == null ? {} : { deleteAfter: new Date(entry.purgeAt) }),+ },+ },+ },+ })),+ );+ }++ async function listReconcile(+ limit: number,+ now: number = Date.now(),+ ): Promise<BrowserSetupSession[]> {+ if (!boundedInteger(limit, 512) || !Number.isSafeInteger(now))+ throw new Error('Invalid browser setup reconciliation limit');+ await ready();+ await restoreAllocations(limit);+ const found = await sessions+ .find({+ $and: [+ {+ $or: [+ { status: { $ne: 'pending' } },+ { expiresAt: { $lte: new Date(now).toISOString() } },+ ],+ },+ {+ $or: [+ { 'progress.cleanup': { $ne: true } },+ { allocationReleased: { $ne: true } },+ { purgeAt: { $exists: true }, deleteAfter: { $exists: false } },+ ],+ },+ { $or: [{ leaseId: { $exists: false } }, { leaseExpiresAt: { $lte: now } }] },+ ],+ })+ .sort({ reconciledAt: 1, expiresAt: 1, _id: 1 })+ .limit(limit)+ .toArray();+ await releaseResolved(found);+ return found.map(publicSession);+ }++ return { start, get, update, claimNonce, consumeRequest, claim, release, listReconcile };+}++export function createBrowserSetupBackend(+ mongoose: typeof import('mongoose'),+): BrowserSetupBackend {+ const methods = createCodeEnvironmentMethods(mongoose);+ return {+ ensureRegistration: methods.ensureSetupEnvironmentIndexes,+ createStore: () => createBrowserSetupStore(mongoose),+ isConnected: () => mongoose.connection.readyState === 1,+ async getUser(id) {+ const user = await mongoose.models.User.findById(id)+ .select(+ '_id tenantId role idOnTheSource provider emailVerified twoFactorEnabled termsAccepted expiresAt agentTriggerDeletionStartedAt',+ )+ .lean<IUser>();+ if (user == null) return null;+ return {+ id: user._id.toString(),+ tenantId: user.tenantId,+ role: user.role,+ idOnTheSource: user.idOnTheSource ?? null,+ provider: user.provider,+ emailVerified: user.emailVerified,+ twoFactorEnabled: user.twoFactorEnabled,+ termsAccepted: user.termsAccepted,+ expiresAt: user.expiresAt,+ agentTriggerDeletionStartedAt: user.agentTriggerDeletionStartedAt,+ };+ },+ };+}diff --git a/packages/data-schemas/src/methods/codeEnvironment.ts b/packages/data-schemas/src/methods/codeEnvironment.tsindex c6d9555dd3..5419224669 100644--- a/packages/data-schemas/src/methods/codeEnvironment.ts+++ b/packages/data-schemas/src/methods/codeEnvironment.ts@@ -3,9 +3,14 @@ import { createHash } from 'crypto';import { ResourceType, MAX_AGENT_CODE_ENVIRONMENT_CHOICES } from 'librechat-data-provider';import type { CodeEnvironmentUserSettings } from 'librechat-data-provider';import type { Model } from 'mongoose';+import type {+ CodeEnvironmentSetupBinding,+ CodeEnvironmentSetupRecord,+} from '~/types/codeEnvironmentSetup';import type { CodeEnvironmentDocument } from '~/types';import type { IAclEntry } from '~/types';import { getTenantId, SYSTEM_TENANT_ID } from '~/config/tenantContext';+import { createIndexesWithRetry } from '~/utils/retry';import logger from '~/config/winston';const CODE_ENVIRONMENT_TOMBSTONES = 'code_environment_tombstones';@@ -18,6 +23,8 @@ type CodeEnvironmentTombstone = {tenantId: string;environmentId: string;deletedAt: Date;+ setupBinding?: string;+ setupResourceId?: string;};function tenantScope(tenantId?: string): string {@@ -31,6 +38,12 @@ function tombstoneId(environmentId: string, tenantId?: string): string {.digest('hex');}+function setupTombstoneId(attemptId: string, tenantId?: string): string {+ return createHash('sha256')+ .update(`librechat-code-environment-setup-tombstone\0${tenantScope(tenantId)}\0${attemptId}`)+ .digest('hex');+}+function tombstones(mongoose: typeof import('mongoose')) {const db = mongoose.connection.db;if (db == null) {@@ -215,9 +228,31 @@ type CreateCodeEnvironmentInput = Pick<CodeEnvironmentDocument,'environmentId' | 'name' | 'type' | 'baseURL' | 'controlPlaneId' | 'createdBy'> &- Pick<Partial<CodeEnvironmentDocument>, 'workerId' | 'revocationTokenEnv' | 'workerPrincipal'>;+ Pick<+ Partial<CodeEnvironmentDocument>,+ 'workerId' | 'revocationTokenEnv' | 'workerPrincipal' | 'setupAttemptId' | 'setupRequestHash'+ >;export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')): {+ ensureSetupEnvironmentIndexes: () => Promise<void>;+ reserveSetupEnvironment: (+ binding: CodeEnvironmentSetupBinding,+ maxOwned?: number,+ ) => Promise<CodeEnvironmentSetupRecord | null>;+ findSetupEnvironment: (+ binding: CodeEnvironmentSetupBinding,+ ) => Promise<CodeEnvironmentSetupRecord | null>;+ completeSetupEnvironment: (+ binding: CodeEnvironmentSetupBinding,+ resourceId: string,+ ) => Promise<CodeEnvironmentSetupRecord>;+ beginDiscardSetupEnvironment: (+ binding: CodeEnvironmentSetupBinding,+ ) => Promise<CodeEnvironmentSetupRecord | null>;+ finishDiscardSetupEnvironment: (+ binding: CodeEnvironmentSetupBinding,+ resourceId: string,+ ) => Promise<void>;createCodeEnvironment: (input: CreateCodeEnvironmentInput) => Promise<CodeEnvironmentDocument>;createCodeEnvironmentWithinOwnerLimit: (input: CreateCodeEnvironmentInput,@@ -250,6 +285,271 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')deleteUserCodeEnvironments: (userId: string | Types.ObjectId) => Promise<number>;} {const model = () => mongoose.models.CodeEnvironment as Model<CodeEnvironmentDocument>;+ let setupIndexInitialization: Promise<void> | undefined;+ async function ensureSetupEnvironmentIndexes(): Promise<void> {+ const current = (setupIndexInitialization ??= createIndexesWithRetry(model()));+ try {+ await current;+ } catch (error) {+ if (setupIndexInitialization === current) setupIndexInitialization = undefined;+ throw error;+ }+ }++ function setupFilter(binding: CodeEnvironmentSetupBinding) {+ return {+ environmentId: binding.environmentId,+ tenantId: tenantScope() === '' ? { $exists: false } : tenantScope(),+ setupAttemptId: binding.setupAttemptId,+ setupRequestHash: binding.requestHash,+ createdBy: new Types.ObjectId(binding.ownerId),+ name: binding.name,+ type: binding.type,+ baseURL: binding.baseURL,+ controlPlaneId: binding.controlPlaneId,+ workerId: binding.workerId ?? { $exists: false },+ revocationTokenEnv: binding.revocationTokenEnv ?? { $exists: false },+ ...(binding.workerPrincipal == null+ ? { workerPrincipal: { $exists: false } }+ : {+ 'workerPrincipal.type': binding.workerPrincipal.type,+ 'workerPrincipal.id': binding.workerPrincipal.id,+ }),+ };+ }++ function setupIdentity(+ binding: CodeEnvironmentSetupBinding,+ tenantId: string = tenantScope(),+ ): string {+ return JSON.stringify([+ tenantId,+ binding.setupAttemptId,+ binding.requestHash,+ binding.ownerId,+ binding.environmentId,+ binding.name,+ binding.type,+ binding.baseURL,+ binding.controlPlaneId,+ binding.workerId ?? null,+ binding.revocationTokenEnv ?? null,+ binding.workerPrincipal?.type ?? null,+ binding.workerPrincipal?.id ?? null,+ ]);+ }++ function rowSetupBinding(environment: CodeEnvironmentDocument): string | undefined {+ if (environment.setupAttemptId == null || environment.setupRequestHash == null)+ return undefined;+ return setupIdentity(+ {+ setupAttemptId: environment.setupAttemptId,+ requestHash: environment.setupRequestHash,+ ownerId: environment.createdBy.toString(),+ environmentId: environment.environmentId,+ name: environment.name,+ type: environment.type,+ baseURL: environment.baseURL,+ controlPlaneId: environment.controlPlaneId,+ workerId: environment.workerId,+ revocationTokenEnv: environment.revocationTokenEnv,+ workerPrincipal: environment.workerPrincipal,+ },+ tenantScope(environment.tenantId),+ );+ }++ async function retireEnvironment(environment: CodeEnvironmentDocument): Promise<void> {+ const setupBinding = rowSetupBinding(environment);+ const metadata =+ setupBinding == null ? {} : { setupBinding, setupResourceId: environment._id.toString() };+ const ids = [tombstoneId(environment.environmentId, environment.tenantId)];+ if (setupBinding != null)+ ids.push(setupTombstoneId(environment.setupAttemptId!, environment.tenantId));+ await Promise.all(+ ids.map(async (_id) =>+ tombstones(mongoose).updateOne(+ {+ _id,+ ...(setupBinding == null+ ? {}+ : { $or: [{ setupBinding: { $exists: false } }, { setupBinding }] }),+ },+ {+ $setOnInsert: {+ tenantId: tenantScope(environment.tenantId),+ environmentId: environment.environmentId,+ deletedAt: new Date(),+ },+ ...(setupBinding == null ? {} : { $set: metadata }),+ },+ { upsert: true },+ ),+ ),+ );+ }++ function retiredSetupFilter(binding: CodeEnvironmentSetupBinding) {+ return {+ _id: { $in: [tombstoneId(binding.environmentId), setupTombstoneId(binding.setupAttemptId)] },+ };+ }++ function setupRecord(environment: CodeEnvironmentDocument): CodeEnvironmentSetupRecord {+ return {+ resourceId: environment._id.toString(),+ id: environment.environmentId,+ name: environment.name,+ type: environment.type,+ pending: environment.registrationPendingAt != null,+ };+ }++ function setupLiveFilter(binding: CodeEnvironmentSetupBinding) {+ return {+ ...setupFilter(binding),+ setupDiscardedAt: { $exists: false },+ deletionStartedAt: { $exists: false },+ deletionCommittedAt: { $exists: false },+ revocationPendingAt: { $exists: false },+ };+ }++ async function findSetupEnvironment(+ binding: CodeEnvironmentSetupBinding,+ ): Promise<CodeEnvironmentSetupRecord | null> {+ const environment = await model()+ .findOne(setupLiveFilter(binding))+ .lean<CodeEnvironmentDocument>();+ if (environment != null) return setupRecord(environment);+ const [collision, retired] = await Promise.all([+ model().exists({+ tenantId: tenantScope() === '' ? { $exists: false } : tenantScope(),+ $or: [{ environmentId: binding.environmentId }, { setupAttemptId: binding.setupAttemptId }],+ }),+ tombstones(mongoose).findOne(retiredSetupFilter(binding)),+ ]);+ if (collision != null || retired != null)+ throw new Error('Browser setup registry binding is unavailable');+ return null;+ }++ async function reserveSetupEnvironment(+ binding: CodeEnvironmentSetupBinding,+ maxOwned?: number,+ ): Promise<CodeEnvironmentSetupRecord | null> {+ await ensureSetupEnvironmentIndexes();+ const replay = await findSetupEnvironment(binding);+ if (replay != null) return replay;+ const input: CreateCodeEnvironmentInput = {+ ...binding,+ createdBy: new Types.ObjectId(binding.ownerId),+ setupRequestHash: binding.requestHash,+ };+ let created: CodeEnvironmentDocument | null;+ try {+ created =+ maxOwned == null+ ? await createCodeEnvironment(input)+ : await createCodeEnvironmentWithinOwnerLimit(input, maxOwned);+ } catch (error) {+ const duplicate =+ typeof error === 'object' && error != null && 'code' in error && error.code === 11000;+ if (!duplicate) throw error;+ const replayed = await findSetupEnvironment(binding);+ if (replayed != null) return replayed;+ throw error;+ }+ if (created == null) return await findSetupEnvironment(binding);+ // A concurrent retirement can win between the initial lookup and insertion.+ if ((await tombstones(mongoose).findOne(retiredSetupFilter(binding))) != null) {+ await model().updateOne(+ { _id: created._id, ...setupFilter(binding) },+ { $set: { setupDiscardedAt: new Date() } },+ );+ throw new Error('Browser setup registry binding is retired');+ }+ return setupRecord(created);+ }++ async function completeSetupEnvironment(+ binding: CodeEnvironmentSetupBinding,+ resourceId: string,+ ): Promise<CodeEnvironmentSetupRecord> {+ const updated = await model()+ .findOneAndUpdate(+ { _id: new Types.ObjectId(resourceId), ...setupLiveFilter(binding) },+ { $unset: { registrationPendingAt: 1, registrationReconcileAfter: 1 } },+ { new: true },+ )+ .lean<CodeEnvironmentDocument>();+ if (updated == null) throw new Error('Browser setup registration could not be committed');+ return setupRecord(updated);+ }++ async function beginDiscardSetupEnvironment(+ binding: CodeEnvironmentSetupBinding,+ ): Promise<CodeEnvironmentSetupRecord | null> {+ const updated = await model()+ .findOneAndUpdate(+ setupFilter(binding),+ { $set: { setupDiscardedAt: new Date(), registrationPendingAt: new Date() } },+ { new: true },+ )+ .lean<CodeEnvironmentDocument>();+ if (updated != null) {+ await retireEnvironment(updated);+ return setupRecord(updated);+ }+ const [collision, retired] = await Promise.all([+ model().exists({+ $or: [{ environmentId: binding.environmentId }, { setupAttemptId: binding.setupAttemptId }],+ tenantId: tenantScope() === '' ? { $exists: false } : tenantScope(),+ }),+ tombstones(mongoose).findOne(retiredSetupFilter(binding)),+ ]);+ if (collision != null || (retired != null && retired.setupBinding !== setupIdentity(binding)))+ throw new Error('Browser setup registry binding does not match');+ // Fence an absent reservation, including compensation racing its first insertion.+ if (retired == null)+ await Promise.all(+ retiredSetupFilter(binding)._id.$in.map(async (_id) =>+ tombstones(mongoose).updateOne(+ { _id },+ {+ $setOnInsert: {+ tenantId: tenantScope(),+ environmentId: binding.environmentId,+ deletedAt: new Date(),+ setupBinding: setupIdentity(binding),+ },+ },+ { upsert: true },+ ),+ ),+ );+ return retired?.setupResourceId == null+ ? null+ : {+ resourceId: retired.setupResourceId,+ id: binding.environmentId,+ name: binding.name,+ type: binding.type,+ pending: true,+ };+ }++ async function finishDiscardSetupEnvironment(+ binding: CodeEnvironmentSetupBinding,+ resourceId: string,+ ): Promise<void> {+ await model().deleteOne({+ _id: new Types.ObjectId(resourceId),+ ...setupFilter(binding),+ setupDiscardedAt: { $exists: true },+ });+ }async function createCodeEnvironment(input: CreateCodeEnvironmentInput,@@ -291,7 +591,10 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')return (await model().create({...input,- _id: ownerSlotId(input.createdBy, ownerSlot),+ _id:+ input.setupAttemptId == null+ ? ownerSlotId(input.createdBy, ownerSlot)+ : new Types.ObjectId(),ownerSlot,registrationPendingAt: new Date(),})@@ -374,22 +677,12 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')): Promise<CodeEnvironmentDocument | null> {const environment = await model().findById(id).lean<CodeEnvironmentDocument>();if (environment == null) return null;- await tombstones(mongoose).updateOne(- { _id: tombstoneId(environment.environmentId, environment.tenantId) },- {- $setOnInsert: {- tenantId: tenantScope(environment.tenantId),- environmentId: environment.environmentId,- deletedAt: new Date(),- },- },- { upsert: true },- );+ await retireEnvironment(environment);return await model().findByIdAndDelete(id).lean<CodeEnvironmentDocument>();}async function discardCodeEnvironmentById(id: string | Types.ObjectId): Promise<void> {- await model().deleteOne({ _id: id });+ await model().deleteOne({ _id: id, setupAttemptId: { $exists: false } });}async function completeCodeEnvironmentRegistration(id: string | Types.ObjectId): Promise<void> {@@ -397,6 +690,7 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose'){_id: id,registrationPendingAt: { $exists: true },+ setupAttemptId: { $exists: false },registrationLeaseId: { $exists: false },},{ $unset: { registrationPendingAt: 1, registrationReconcileAfter: 1 } },@@ -509,17 +803,7 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')await cancelCodeEnvironmentRemoval(candidate._id, claimed.deletionLeaseId);continue;}- await tombstones(mongoose).updateOne(- { _id: tombstoneId(claimed.environmentId, claimed.tenantId) },- {- $setOnInsert: {- tenantId: tenantScope(claimed.tenantId),- environmentId: claimed.environmentId,- deletedAt: new Date(),- },- },- { upsert: true },- );+ await retireEnvironment(claimed);await AclEntry.deleteMany({resourceType: ResourceType.CODE_ENVIRONMENT,resourceId: candidate._id,@@ -534,6 +818,12 @@ export function createCodeEnvironmentMethods(mongoose: typeof import('mongoose')}return {+ ensureSetupEnvironmentIndexes,+ reserveSetupEnvironment,+ findSetupEnvironment,+ completeSetupEnvironment,+ beginDiscardSetupEnvironment,+ finishDiscardSetupEnvironment,createCodeEnvironment,createCodeEnvironmentWithinOwnerLimit,findCodeEnvironmentsByIds,diff --git a/packages/data-schemas/src/schema/codeEnvironment.ts b/packages/data-schemas/src/schema/codeEnvironment.tsindex 7329a59dee..88bc5a0578 100644--- a/packages/data-schemas/src/schema/codeEnvironment.ts+++ b/packages/data-schemas/src/schema/codeEnvironment.ts@@ -60,6 +60,9 @@ const codeEnvironmentSchema: Schema<CodeEnvironmentDocument> = new Schema<CodeEnrequired: true,index: true,},+ setupAttemptId: { type: String },+ setupRequestHash: { type: String },+ setupDiscardedAt: { type: Date },ownerSlot: {type: Number,min: 0,@@ -120,6 +123,14 @@ const codeEnvironmentSchema: Schema<CodeEnvironmentDocument> = new Schema<CodeEn);codeEnvironmentSchema.index({ environmentId: 1, tenantId: 1 }, { unique: true });+codeEnvironmentSchema.index(+ { createdBy: 1, ownerSlot: 1, tenantId: 1 },+ { unique: true, partialFilterExpression: { ownerSlot: { $type: 'number' } } },+);+codeEnvironmentSchema.index(+ { setupAttemptId: 1, tenantId: 1 },+ { unique: true, partialFilterExpression: { setupAttemptId: { $type: 'string' } } },+);codeEnvironmentSchema.index({ updatedAt: -1, _id: 1 });export default codeEnvironmentSchema;diff --git a/packages/data-schemas/src/types/browserSetup.ts b/packages/data-schemas/src/types/browserSetup.tsnew file mode 100644index 0000000000..97fa8e96e8--- /dev/null+++ b/packages/data-schemas/src/types/browserSetup.ts@@ -0,0 +1,148 @@+export type BrowserSetupStatus =+ | 'pending'+ | 'provisioning'+ | 'approved'+ | 'completing'+ | 'completed'+ | 'denied'+ | 'cancelled'+ | 'expired'+ | 'failed';++export type BrowserSetupApproval = {+ protocolVersion: 1;+ operation: 'enrollment.redeem';+ serverId: string;+ instance: string;+ attemptId: string;+ requestHash: string;+ workerId: string;+ expiresAt: string;+ publicKey: string;+ binding: { tenantId: string; principal: { type: 'user'; id: string } };+};++export type BrowserSetupProgress = {+ registryReserved?: boolean;+ registryCompleted?: boolean;+ issued?: boolean;+ redemption?: boolean;+ cleanup?: boolean;+};++export type BrowserSetupSession = {+ attemptId: string;+ requestCanonical: string;+ requestHash: string;+ createdAt: string;+ expiresAt: string;+ verificationCode: string;+ workerId: string;+ status: BrowserSetupStatus;+ revision: number;+ ownerId?: string;+ tenantId?: string;+ planeId?: string;+ baseURL?: string;+ tokenEnv?: string;+ approval?: BrowserSetupApproval;+ progress?: BrowserSetupProgress;+ failureCode?: string;+ stopReason?: 'denied' | 'cancelled' | 'expired' | 'withdrawn';+ leaseId?: string;+ leaseExpiresAt?: number;+ purgeAt?: string;+};++export type BrowserSetupPatch = Partial<+ Pick<+ BrowserSetupSession,+ | 'status'+ | 'ownerId'+ | 'tenantId'+ | 'planeId'+ | 'baseURL'+ | 'tokenEnv'+ | 'approval'+ | 'progress'+ | 'failureCode'+ | 'stopReason'+ | 'purgeAt'+ >+>;++export type BrowserSetupStartResult =+ | { status: 'created'; session: BrowserSetupSession }+ | { status: 'replay'; session: BrowserSetupSession }+ | { status: 'conflict' }+ | { status: 'limited' };++export type BrowserSetupNonceResult = 'claimed' | 'replay' | 'limited' | 'missing';++export type BrowserSetupBudgetLimits = { global: number; perIp: number; windowMs: number };++export type BrowserSetupStore = {+ consumeRequest: (input: {+ ipHash: string;+ now: number;+ limits: BrowserSetupBudgetLimits;+ }) => Promise<boolean>;+ claim: (input: {+ attemptId: string;+ requestHash: string;+ revision: number;+ leaseId: string;+ now: number;+ leaseMs: number;+ }) => Promise<BrowserSetupSession | null>;+ release: (input: {+ attemptId: string;+ requestHash: string;+ revision: number;+ leaseId: string;+ }) => Promise<BrowserSetupSession | null>;+ listReconcile: (limit: number, now?: number) => Promise<BrowserSetupSession[]>;+ start: (input: {+ session: BrowserSetupSession;+ ipHash: string;+ now: number;+ limits: BrowserSetupBudgetLimits;+ }) => Promise<BrowserSetupStartResult>;+ get: (attemptId: string) => Promise<BrowserSetupSession | null>;+ update: (input: {+ attemptId: string;+ requestHash: string;+ revision: number;+ patch: BrowserSetupPatch;+ leaseId?: string;+ }) => Promise<BrowserSetupSession | null>;+ claimNonce: (input: {+ attemptId: string;+ requestHash: string;+ nonce: string;+ now: number;+ expiresAt: number;+ maxNonces: number;+ maxOperations: number;+ }) => Promise<BrowserSetupNonceResult>;+};++export type BrowserSetupUser = {+ id: string;+ tenantId?: string;+ role?: string;+ idOnTheSource?: string | null;+ provider?: string;+ emailVerified?: boolean;+ twoFactorEnabled?: boolean;+ termsAccepted?: boolean;+ agentTriggerDeletionStartedAt?: Date | null;+ expiresAt?: Date;+};++export type BrowserSetupBackend = {+ createStore: () => BrowserSetupStore;+ ensureRegistration: () => Promise<void>;+ getUser: (id: string) => Promise<BrowserSetupUser | null>;+ isConnected: () => boolean;+};diff --git a/packages/data-schemas/src/types/codeEnvironment.ts b/packages/data-schemas/src/types/codeEnvironment.tsindex ab79459fa1..a69c3c24e8 100644--- a/packages/data-schemas/src/types/codeEnvironment.ts+++ b/packages/data-schemas/src/types/codeEnvironment.ts@@ -9,6 +9,9 @@ export type CodeEnvironment = {controlPlaneId: string;createdBy: Types.ObjectId;ownerSlot?: number;+ setupAttemptId?: string;+ setupRequestHash?: string;+ setupDiscardedAt?: Date;pendingAgentReferences?: Array<{reservationId: string;expiresAt: Date;diff --git a/packages/data-schemas/src/types/codeEnvironmentSetup.ts b/packages/data-schemas/src/types/codeEnvironmentSetup.tsnew file mode 100644index 0000000000..9f98473425--- /dev/null+++ b/packages/data-schemas/src/types/codeEnvironmentSetup.ts@@ -0,0 +1,24 @@+export type CodeEnvironmentSetupBinding = {+ setupAttemptId: string;+ requestHash: string;+ ownerId: string;+ environmentId: string;+ name: string;+ type: 'managed' | 'attached';+ baseURL: string;+ controlPlaneId: string;+ workerId?: string;+ revocationTokenEnv?: string;+ workerPrincipal?: {+ type: 'deployment' | 'tenant' | 'user' | 'role' | 'group';+ id: string;+ };+};++export type CodeEnvironmentSetupRecord = {+ resourceId: string;+ id: string;+ name: string;+ type: 'managed' | 'attached';+ pending: boolean;+};diff --git a/vendor/code/LICENSE b/vendor/code/LICENSEnew file mode 100644index 0000000000..d645695673--- /dev/null+++ b/vendor/code/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/vendor/code/browser-enrollment-protocol.js b/vendor/code/browser-enrollment-protocol.jsnew file mode 100644index 0000000000..99e1c7b02e--- /dev/null+++ b/vendor/code/browser-enrollment-protocol.js@@ -0,0 +1,253 @@+import { createHash, createPublicKey, sign, verify } from 'node:crypto';++++++export const BROWSER_ENROLLMENT_PROTOCOL_VERSION = 1 ;+export const BROWSER_ENROLLMENT_MAX_TTL_MS = 10 * 60_000;+export const BROWSER_SETUP_PROOF_DOMAIN = 'librechat-code:browser-setup:v1';+export const BROWSER_ENROLLMENT_REDEMPTION_DOMAIN = 'librechat-code:browser-enrollment-redeem:v1';++++++++++++++++++++++++++++++++++++++++++++++++++++++++++function record(value ) {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function keys(value , names ) {+ return Object.keys(value).length === names.length && names.every(name => Object.prototype.hasOwnProperty.call(value, name));+}++export function isBrowserEnrollmentTimestamp(value ) {+ if (typeof value !== 'string' || value.length !== 24) return false;+ const time = Date.parse(value);+ return Number.isFinite(time) && new Date(time).toISOString() === value;+}++export function isBrowserEnrollmentToken(value ) {+ return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value) &&+ Buffer.from(value, 'base64url').toString('base64url') === value;+}++export function isBrowserEnrollmentSignature(value ) {+ return typeof value === 'string' && /^[A-Za-z0-9_-]{86}$/.test(value) &&+ Buffer.from(value, 'base64url').toString('base64url') === value;+}++export function isBrowserEnrollmentPublicKey(value ) {+ if (typeof value !== 'string' || value.length > 4096 || !value.startsWith('-----BEGIN PUBLIC KEY-----\n')) return false;+ try {+ const key = createPublicKey(value);+ return key.asymmetricKeyType === 'ed25519' && key.export({ type: 'spki', format: 'pem' }) === value;+ } catch {+ return false;+ }+}++export function normalizeBrowserEnrollmentInstance(value ) {+ if (value.length > 2048 || value !== value.trim()) throw new TypeError('Invalid LibreChat instance URL');+ const url = new URL(value);+ if (+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) ||+ url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== ''+ ) {+ throw new TypeError('LibreChat instance requires HTTPS (or loopback HTTP), without credentials, query, or fragment');+ }+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;+}++function instance(value ) {+ try {+ return typeof value === 'string' && normalizeBrowserEnrollmentInstance(value) === value;+ } catch {+ return false;+ }+}++function serverOrigin(value ) {+ if (typeof value !== 'string' || value.length > 256) return false;+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && url.origin === value && instance(value);+ } catch {+ return false;+ }+}++function requestHash(value ) {+ return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);+}++export function isBrowserEnrollmentRequest(value ) {+ return record(value) && keys(value, [+ 'version', 'instance', 'attemptId', 'createdAt', 'publicKey', 'machineName',+ 'workspace', 'allowWorkspaceWrites', 'allowWorkspaceCommands',+ ]) && value.version === 1 && instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) &&+ isBrowserEnrollmentTimestamp(value.createdAt) && isBrowserEnrollmentPublicKey(value.publicKey) &&+ typeof value.machineName === 'string' && /^[A-Za-z0-9][A-Za-z0-9 ._()-]{0,79}$/.test(value.machineName) &&+ value.machineName === value.machineName.trim() && record(value.workspace) && keys(value.workspace, ['type']) &&+ (value.workspace.type === 'private' || value.workspace.type === 'directory') &&+ typeof value.allowWorkspaceWrites === 'boolean' && typeof value.allowWorkspaceCommands === 'boolean';+}++export function canonicalBrowserEnrollmentRequest(input ) {+ if (!isBrowserEnrollmentRequest(input)) throw new TypeError('Invalid browser enrollment request');+ return JSON.stringify({+ version: input.version,+ instance: input.instance,+ attemptId: input.attemptId,+ createdAt: input.createdAt,+ publicKey: input.publicKey,+ machineName: input.machineName,+ workspace: { type: input.workspace.type },+ allowWorkspaceWrites: input.allowWorkspaceWrites,+ allowWorkspaceCommands: input.allowWorkspaceCommands,+ });+}++export function hashBrowserEnrollmentRequest(input ) {+ return createHash('sha256').update(canonicalBrowserEnrollmentRequest(input)).digest('hex');+}++export function isBrowserSetupProof(value ) {+ return record(value) && keys(value, ['operation', 'instance', 'attemptId', 'requestHash', 'timestamp', 'nonce']) &&+ typeof value.operation === 'string' && ['setup.start', 'setup.poll', 'setup.cancel', 'setup.complete'].includes(value.operation) &&+ instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) && requestHash(value.requestHash) &&+ isBrowserEnrollmentTimestamp(value.timestamp) && isBrowserEnrollmentToken(value.nonce);+}++export function canonicalBrowserSetupProof(input ) {+ if (!isBrowserSetupProof(input)) throw new TypeError('Invalid browser setup proof');+ return [BROWSER_SETUP_PROOF_DOMAIN, input.operation, input.instance, input.attemptId,+ input.requestHash, input.timestamp, input.nonce].join('\n');+}++export function isBrowserEnrollmentRedemptionContract(value ) {+ return record(value) && value.operation === 'enrollment.redeem' && serverOrigin(value.serverId) &&+ instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) && requestHash(value.requestHash) &&+ typeof value.workerId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.workerId) &&+ isBrowserEnrollmentTimestamp(value.expiresAt);+}++export function isBrowserEnrollmentBinding(value ) {+ return record(value) && keys(value, ['tenantId', 'principal']) &&+ typeof value.tenantId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.tenantId) &&+ record(value.principal) && keys(value.principal, ['type', 'id']) &&+ typeof value.principal.type === 'string' && ['deployment', 'tenant', 'user', 'role', 'group'].includes(value.principal.type) &&+ typeof value.principal.id === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.principal.id);+}++const CONTRACT_KEYS = ['operation', 'serverId', 'instance', 'attemptId', 'requestHash', 'workerId', 'expiresAt'];++export function isBrowserEnrollmentApproval(value ) {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion', 'publicKey', 'binding']) &&+ value.protocolVersion === 1 && isBrowserEnrollmentPublicKey(value.publicKey) && isBrowserEnrollmentBinding(value.binding);+}++export function isBrowserEnrollmentStatusRequest(value ) {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion']) && value.protocolVersion === 1;+}++export function isBrowserEnrollmentRedemption(value ) {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion', 'signature']) &&+ value.protocolVersion === 1 && isBrowserEnrollmentSignature(value.signature);+}++export function canonicalBrowserEnrollmentRedemption(input ) {+ if (!isBrowserEnrollmentRedemptionContract(input)) throw new TypeError('Invalid browser enrollment redemption');+ return [BROWSER_ENROLLMENT_REDEMPTION_DOMAIN, input.operation, input.serverId, input.instance,+ input.attemptId, input.requestHash, input.workerId, input.expiresAt].join('\n');+}++export function signBrowserSetupProof(privateKey , input ) {+ return sign(null, Buffer.from(canonicalBrowserSetupProof(input)), privateKey).toString('base64url');+}++export function verifyBrowserSetupProof(publicKey , input , signature ) {+ try {+ return isBrowserEnrollmentPublicKey(publicKey) && isBrowserEnrollmentSignature(signature) &&+ verify(null, Buffer.from(canonicalBrowserSetupProof(input)), publicKey, Buffer.from(signature, 'base64url'));+ } catch {+ return false;+ }+}++export function signBrowserEnrollmentRedemption(privateKey , input ) {+ return sign(null, Buffer.from(canonicalBrowserEnrollmentRedemption(input)), privateKey).toString('base64url');+}++export function verifyBrowserEnrollmentRedemption(publicKey , input , signature ) {+ try {+ return isBrowserEnrollmentPublicKey(publicKey) && isBrowserEnrollmentSignature(signature) &&+ verify(null, Buffer.from(canonicalBrowserEnrollmentRedemption(input)), publicKey, Buffer.from(signature, 'base64url'));+ } catch {+ return false;+ }+}++export const browserSetupRequestHash = hashBrowserEnrollmentRequest;+export const canonicalBrowserSetupRequest = canonicalBrowserEnrollmentRequest;+export const canonicalEnrollmentRedemption = canonicalBrowserEnrollmentRedemption;+export const signEnrollmentRedemption = signBrowserEnrollmentRedemption;+export const verifyEnrollmentRedemption = verifyBrowserEnrollmentRedemption;+export const validateBrowserSetupRequest = isBrowserEnrollmentRequest;+export const validateBrowserSetupProof = isBrowserSetupProof;+export const validateEnrollmentRedemption = isBrowserEnrollmentRedemptionContract;diff --git a/vendor/code/browser-enrollment-protocol.ts b/vendor/code/browser-enrollment-protocol.tsnew file mode 100644index 0000000000..ef1c712b8d--- /dev/null+++ b/vendor/code/browser-enrollment-protocol.ts@@ -0,0 +1,253 @@+import { createHash, createPublicKey, sign, verify } from 'node:crypto';++export type BrowserSetupRequest = BrowserEnrollmentRequest;+export type EnrollmentRedemption = BrowserEnrollmentRedemptionContract;+export type EnrollmentApproval = BrowserEnrollmentApproval;++export const BROWSER_ENROLLMENT_PROTOCOL_VERSION = 1 as const;+export const BROWSER_ENROLLMENT_MAX_TTL_MS = 10 * 60_000;+export const BROWSER_SETUP_PROOF_DOMAIN = 'librechat-code:browser-setup:v1';+export const BROWSER_ENROLLMENT_REDEMPTION_DOMAIN = 'librechat-code:browser-enrollment-redeem:v1';++export interface BrowserEnrollmentRequest {+ version: 1;+ instance: string;+ attemptId: string;+ createdAt: string;+ publicKey: string;+ machineName: string;+ workspace: { type: 'private' | 'directory' };+ allowWorkspaceWrites: boolean;+ allowWorkspaceCommands: boolean;+}++export interface BrowserSetupProof {+ operation: 'setup.start' | 'setup.poll' | 'setup.cancel' | 'setup.complete';+ instance: string;+ attemptId: string;+ requestHash: string;+ timestamp: string;+ nonce: string;+}++export interface BrowserEnrollmentRedemptionContract {+ operation: 'enrollment.redeem';+ serverId: string;+ instance: string;+ attemptId: string;+ requestHash: string;+ workerId: string;+ expiresAt: string;+}++export interface BrowserEnrollmentStatusRequest extends BrowserEnrollmentRedemptionContract {+ protocolVersion: 1;+}++export interface BrowserEnrollmentRedemption extends BrowserEnrollmentRedemptionContract {+ protocolVersion: 1;+ signature: string;+}++export interface BrowserEnrollmentBinding {+ tenantId: string;+ principal: { type: 'deployment' | 'tenant' | 'user' | 'role' | 'group'; id: string };+}++export interface BrowserEnrollmentApproval extends BrowserEnrollmentRedemptionContract {+ protocolVersion: 1;+ publicKey: string;+ binding: BrowserEnrollmentBinding;+}++export interface BrowserEnrollmentCapabilities {+ browserEnrollmentVersion: 1;+ serverId: string;+}++function record(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function keys(value: Record<string, unknown>, names: string[]): boolean {+ return Object.keys(value).length === names.length && names.every(name => Object.prototype.hasOwnProperty.call(value, name));+}++export function isBrowserEnrollmentTimestamp(value: unknown): value is string {+ if (typeof value !== 'string' || value.length !== 24) return false;+ const time = Date.parse(value);+ return Number.isFinite(time) && new Date(time).toISOString() === value;+}++export function isBrowserEnrollmentToken(value: unknown): value is string {+ return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value) &&+ Buffer.from(value, 'base64url').toString('base64url') === value;+}++export function isBrowserEnrollmentSignature(value: unknown): value is string {+ return typeof value === 'string' && /^[A-Za-z0-9_-]{86}$/.test(value) &&+ Buffer.from(value, 'base64url').toString('base64url') === value;+}++export function isBrowserEnrollmentPublicKey(value: unknown): value is string {+ if (typeof value !== 'string' || value.length > 4096 || !value.startsWith('-----BEGIN PUBLIC KEY-----\n')) return false;+ try {+ const key = createPublicKey(value);+ return key.asymmetricKeyType === 'ed25519' && key.export({ type: 'spki', format: 'pem' }) === value;+ } catch {+ return false;+ }+}++export function normalizeBrowserEnrollmentInstance(value: string): string {+ if (value.length > 2048 || value !== value.trim()) throw new TypeError('Invalid LibreChat instance URL');+ const url = new URL(value);+ if (+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) ||+ url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== ''+ ) {+ throw new TypeError('LibreChat instance requires HTTPS (or loopback HTTP), without credentials, query, or fragment');+ }+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;+}++function instance(value: unknown): value is string {+ try {+ return typeof value === 'string' && normalizeBrowserEnrollmentInstance(value) === value;+ } catch {+ return false;+ }+}++function serverOrigin(value: unknown): value is string {+ if (typeof value !== 'string' || value.length > 256) return false;+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && url.origin === value && instance(value);+ } catch {+ return false;+ }+}++function requestHash(value: unknown): value is string {+ return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);+}++export function isBrowserEnrollmentRequest(value: unknown): value is BrowserEnrollmentRequest {+ return record(value) && keys(value, [+ 'version', 'instance', 'attemptId', 'createdAt', 'publicKey', 'machineName',+ 'workspace', 'allowWorkspaceWrites', 'allowWorkspaceCommands',+ ]) && value.version === 1 && instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) &&+ isBrowserEnrollmentTimestamp(value.createdAt) && isBrowserEnrollmentPublicKey(value.publicKey) &&+ typeof value.machineName === 'string' && /^[A-Za-z0-9][A-Za-z0-9 ._()-]{0,79}$/.test(value.machineName) &&+ value.machineName === value.machineName.trim() && record(value.workspace) && keys(value.workspace, ['type']) &&+ (value.workspace.type === 'private' || value.workspace.type === 'directory') &&+ typeof value.allowWorkspaceWrites === 'boolean' && typeof value.allowWorkspaceCommands === 'boolean';+}++export function canonicalBrowserEnrollmentRequest(input: BrowserEnrollmentRequest): string {+ if (!isBrowserEnrollmentRequest(input)) throw new TypeError('Invalid browser enrollment request');+ return JSON.stringify({+ version: input.version,+ instance: input.instance,+ attemptId: input.attemptId,+ createdAt: input.createdAt,+ publicKey: input.publicKey,+ machineName: input.machineName,+ workspace: { type: input.workspace.type },+ allowWorkspaceWrites: input.allowWorkspaceWrites,+ allowWorkspaceCommands: input.allowWorkspaceCommands,+ });+}++export function hashBrowserEnrollmentRequest(input: BrowserEnrollmentRequest): string {+ return createHash('sha256').update(canonicalBrowserEnrollmentRequest(input)).digest('hex');+}++export function isBrowserSetupProof(value: unknown): value is BrowserSetupProof {+ return record(value) && keys(value, ['operation', 'instance', 'attemptId', 'requestHash', 'timestamp', 'nonce']) &&+ typeof value.operation === 'string' && ['setup.start', 'setup.poll', 'setup.cancel', 'setup.complete'].includes(value.operation) &&+ instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) && requestHash(value.requestHash) &&+ isBrowserEnrollmentTimestamp(value.timestamp) && isBrowserEnrollmentToken(value.nonce);+}++export function canonicalBrowserSetupProof(input: BrowserSetupProof): string {+ if (!isBrowserSetupProof(input)) throw new TypeError('Invalid browser setup proof');+ return [BROWSER_SETUP_PROOF_DOMAIN, input.operation, input.instance, input.attemptId,+ input.requestHash, input.timestamp, input.nonce].join('\n');+}++export function isBrowserEnrollmentRedemptionContract(value: unknown): value is BrowserEnrollmentRedemptionContract {+ return record(value) && value.operation === 'enrollment.redeem' && serverOrigin(value.serverId) &&+ instance(value.instance) && isBrowserEnrollmentToken(value.attemptId) && requestHash(value.requestHash) &&+ typeof value.workerId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.workerId) &&+ isBrowserEnrollmentTimestamp(value.expiresAt);+}++export function isBrowserEnrollmentBinding(value: unknown): value is BrowserEnrollmentBinding {+ return record(value) && keys(value, ['tenantId', 'principal']) &&+ typeof value.tenantId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.tenantId) &&+ record(value.principal) && keys(value.principal, ['type', 'id']) &&+ typeof value.principal.type === 'string' && ['deployment', 'tenant', 'user', 'role', 'group'].includes(value.principal.type) &&+ typeof value.principal.id === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.principal.id);+}++const CONTRACT_KEYS = ['operation', 'serverId', 'instance', 'attemptId', 'requestHash', 'workerId', 'expiresAt'];++export function isBrowserEnrollmentApproval(value: unknown): value is BrowserEnrollmentApproval {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion', 'publicKey', 'binding']) &&+ value.protocolVersion === 1 && isBrowserEnrollmentPublicKey(value.publicKey) && isBrowserEnrollmentBinding(value.binding);+}++export function isBrowserEnrollmentStatusRequest(value: unknown): value is BrowserEnrollmentStatusRequest {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion']) && value.protocolVersion === 1;+}++export function isBrowserEnrollmentRedemption(value: unknown): value is BrowserEnrollmentRedemption {+ return isBrowserEnrollmentRedemptionContract(value) && record(value) &&+ keys(value, [...CONTRACT_KEYS, 'protocolVersion', 'signature']) &&+ value.protocolVersion === 1 && isBrowserEnrollmentSignature(value.signature);+}++export function canonicalBrowserEnrollmentRedemption(input: BrowserEnrollmentRedemptionContract): string {+ if (!isBrowserEnrollmentRedemptionContract(input)) throw new TypeError('Invalid browser enrollment redemption');+ return [BROWSER_ENROLLMENT_REDEMPTION_DOMAIN, input.operation, input.serverId, input.instance,+ input.attemptId, input.requestHash, input.workerId, input.expiresAt].join('\n');+}++export function signBrowserSetupProof(privateKey: string, input: BrowserSetupProof): string {+ return sign(null, Buffer.from(canonicalBrowserSetupProof(input)), privateKey).toString('base64url');+}++export function verifyBrowserSetupProof(publicKey: string, input: BrowserSetupProof, signature: string): boolean {+ try {+ return isBrowserEnrollmentPublicKey(publicKey) && isBrowserEnrollmentSignature(signature) &&+ verify(null, Buffer.from(canonicalBrowserSetupProof(input)), publicKey, Buffer.from(signature, 'base64url'));+ } catch {+ return false;+ }+}++export function signBrowserEnrollmentRedemption(privateKey: string, input: BrowserEnrollmentRedemptionContract): string {+ return sign(null, Buffer.from(canonicalBrowserEnrollmentRedemption(input)), privateKey).toString('base64url');+}++export function verifyBrowserEnrollmentRedemption(publicKey: string, input: BrowserEnrollmentRedemptionContract, signature: string): boolean {+ try {+ return isBrowserEnrollmentPublicKey(publicKey) && isBrowserEnrollmentSignature(signature) &&+ verify(null, Buffer.from(canonicalBrowserEnrollmentRedemption(input)), publicKey, Buffer.from(signature, 'base64url'));+ } catch {+ return false;+ }+}++export const browserSetupRequestHash = hashBrowserEnrollmentRequest;+export const canonicalBrowserSetupRequest = canonicalBrowserEnrollmentRequest;+export const canonicalEnrollmentRedemption = canonicalBrowserEnrollmentRedemption;+export const signEnrollmentRedemption = signBrowserEnrollmentRedemption;+export const verifyEnrollmentRedemption = verifyBrowserEnrollmentRedemption;+export const validateBrowserSetupRequest = isBrowserEnrollmentRequest;+export const validateBrowserSetupProof = isBrowserSetupProof;+export const validateEnrollmentRedemption = isBrowserEnrollmentRedemptionContract;diff --git a/vendor/code/generate.mjs b/vendor/code/generate.mjsnew file mode 100644index 0000000000..35fd38bab6--- /dev/null+++ b/vendor/code/generate.mjs@@ -0,0 +1,12 @@+import fs from 'node:fs';+import { createHash } from 'node:crypto';+import { stripTypeScriptTypes } from 'node:module';++const sourceUrl = new URL('./browser-enrollment-protocol.ts', import.meta.url);+const metadata = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8'));+const source = fs.readFileSync(sourceUrl, 'utf8');+if (createHash('sha256').update(source).digest('hex') !== metadata.librechatUpstream.sha256) {+ throw new Error('Pinned upstream protocol integrity check failed');+}+const javascript = stripTypeScriptTypes(source).replace(/[ \t]+$/gm, '');+fs.writeFileSync(new URL('./browser-enrollment-protocol.js', import.meta.url), javascript);diff --git a/vendor/code/package.json b/vendor/code/package.jsonnew file mode 100644index 0000000000..6afa14a7f0--- /dev/null+++ b/vendor/code/package.json@@ -0,0 +1,22 @@+{+ "name": "@librechat/code",+ "version": "0.1.0-librechat.a3207a75",+ "private": true,+ "type": "module",+ "license": "Apache-2.0",+ "exports": {+ "./browser-enrollment": {+ "types": "./browser-enrollment-protocol.ts",+ "default": "./browser-enrollment-protocol.js"+ }+ },+ "librechatUpstream": {+ "repository": "https://github.com/LibreChat-AI/code-interpreter",+ "commit": "a3207a75c8327ba1c9526eff8b06f3588f3739ed",+ "path": "packages/code/src/browser-enrollment-protocol.ts",+ "sha256": "1ecf23023f7cf482eb140dc327b2400331f18d1c50f04ba037afca6186b97a99"+ },+ "scripts": {+ "build": "node generate.mjs"+ }+}