Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9fd1cfc07 | ||
|
|
5feca644e2 | ||
|
|
72a5c71fe3 | ||
|
|
31bd2144cf | ||
|
|
8360c518b6 | ||
|
|
bd938fc6c6 | ||
|
|
b6a82bcf8f | ||
|
|
650ad06b15 | ||
|
|
52bcd7de06 | ||
|
|
495340a3b7 | ||
|
|
864c8a7bc7 | ||
|
|
1bcdcfc1e1 | ||
|
|
72700de2f0 | ||
|
|
32acfb52e3 | ||
|
|
3cb0488797 | ||
|
|
43cc8a73bb | ||
|
|
e4c75ffdd1 | ||
|
|
8486223c89 | ||
|
|
fa01f11732 | ||
|
|
6e56f51429 | ||
|
|
e27fb77e5b | ||
|
|
d2ded972bc | ||
|
|
5e9a043837 | ||
|
|
d31f7546bd | ||
|
|
7f0bdb3145 | ||
|
|
523c38b371 | ||
|
|
de8a33d8a3 | ||
|
|
2f2378ab21 | ||
|
|
120c39a197 | ||
|
|
8d2549322a | ||
|
|
c3257d2238 | ||
|
|
87b581388d | ||
|
|
2abc855b9c | ||
|
|
fdbb17da6c | ||
|
|
ec32864a00 | ||
|
|
3e83bc6779 | ||
|
|
39e5a71c7e | ||
|
|
1eb2caecec | ||
|
|
d44146f1fc | ||
|
|
dca8e39e69 | ||
|
|
72b061877a | ||
|
|
5a3aede148 | ||
|
|
4f25c3131a | ||
|
|
512289012c | ||
|
|
3af4415366 | ||
|
|
749784a50c | ||
|
|
26e83d7645 | ||
|
|
662f054658 | ||
|
|
150c5fff4d | ||
|
|
abe59a625c | ||
|
|
14bb1bf35a | ||
|
|
9f6c243327 | ||
|
|
34096ffe12 | ||
|
|
a12198a01f | ||
|
|
4abec9f46a | ||
|
|
7c4c1b676c | ||
|
|
0138889e81 | ||
|
|
9ef8cf46a9 | ||
|
|
4d96ee9e4d | ||
|
|
c4f48f6af5 | ||
|
|
f466b6c2ca | ||
|
|
26591fb2ba | ||
|
|
f54d01289b |
@@ -0,0 +1,16 @@
|
||||
# depcheck configuration.
|
||||
#
|
||||
# ignores: dependencies that are present on purpose but never imported directly,
|
||||
# so depcheck's static scan reports them as a false positive.
|
||||
#
|
||||
# The three @opentelemetry/* entries below are all transitive dependencies of
|
||||
# @opentelemetry/sdk-node, which we DO import and drive (NodeSDK in
|
||||
# packages/api/src/telemetry/sdk.ts). They are pinned at the top level to keep
|
||||
# every otel package on one aligned version (mismatched otel versions break at
|
||||
# runtime). None is imported by name, so depcheck flags them — expected, not
|
||||
# dead. Do NOT remove them (that would unpin the otel version set). Only
|
||||
# @opentelemetry/api is imported directly and stays checked.
|
||||
ignores:
|
||||
- "@opentelemetry/core"
|
||||
- "@opentelemetry/exporter-trace-otlp-http"
|
||||
- "@opentelemetry/sdk-trace-base"
|
||||
+25
-19
@@ -117,6 +117,17 @@ PROXY=
|
||||
# Endpoint: https://api.hanzo.ai/v1
|
||||
HANZO_API_KEY=
|
||||
|
||||
# Canonical Hanzo Cloud agents (/v1/agents). Lets signed-in users run their own
|
||||
# cloud agents from chat via `/agent <name>` or the @mention picker. The chat
|
||||
# backend proxies /v1/chat/agents/cloud/* to this host, forwarding the user's
|
||||
# hanzo.id token server-side (never to the browser); cloud scopes to their org.
|
||||
# Optional: if unset, derived from OPENAI_BASE_URL (its host, minus /v1).
|
||||
# HANZO_CLOUD_URL=https://api.hanzo.ai
|
||||
# A cloud-agent run is a real billable completion; these bound abuse of the proxy.
|
||||
# CLOUD_AGENT_USER_MAX=30 # max cloud-agent requests per user per window
|
||||
# CLOUD_AGENT_WINDOW=1 # rate-limit window, minutes
|
||||
# CLOUD_AGENT_MAX_CONCURRENT=50 # process-wide in-flight ceiling to cloud (503 past it)
|
||||
|
||||
#===================================#
|
||||
# Known Endpoints - chat.yaml #
|
||||
#===================================#
|
||||
@@ -825,31 +836,26 @@ OPENWEATHER_API_KEY=
|
||||
# Hanzo Chat Code Interpreter API #
|
||||
#====================================#
|
||||
|
||||
# https://hanzo.ai/docs/chat/code-interpreter
|
||||
# LIBRECHAT_CODE_API_KEY=your-key
|
||||
# "Run Code" routes through the Hanzo unified backend (api.hanzo.ai/v1/exec),
|
||||
# which executes in a Hanzo sandbox. execute_code POSTs {BASEURL}/exec with
|
||||
# X-API-Key. https://hanzo.ai/docs/chat/code-interpreter
|
||||
# LIBRECHAT_CODE_BASEURL=https://api.hanzo.ai/v1
|
||||
# LIBRECHAT_CODE_API_KEY=your-key # prod: KMS chat-secrets/LIBRECHAT_CODE_API_KEY
|
||||
|
||||
#======================#
|
||||
# Web Search #
|
||||
#======================#
|
||||
|
||||
# Note: All of the following variable names can be customized.
|
||||
# Omit values to allow user to provide them.
|
||||
|
||||
# For more information on configuration values, see:
|
||||
# Web Search routes through the Hanzo unified backend ONLY — no external SaaS.
|
||||
# The searxng provider + firecrawl scraper both point at api.hanzo.ai/v1/websearch
|
||||
# (Hanzo metasearch + Hanzo Crawl). See librechat.yaml `webSearch`.
|
||||
# https://hanzo.ai/docs/chat/features/web_search
|
||||
|
||||
# Search Provider (Required)
|
||||
# SERPER_API_KEY=your_serper_api_key
|
||||
|
||||
# Scraper (Required)
|
||||
# FIRECRAWL_API_KEY=your_firecrawl_api_key
|
||||
# Optional: Custom Firecrawl API URL
|
||||
# FIRECRAWL_API_URL=your_firecrawl_api_url
|
||||
|
||||
# Reranker (Required)
|
||||
# JINA_API_KEY=your_jina_api_key
|
||||
# or
|
||||
# COHERE_API_KEY=your_cohere_api_key
|
||||
# SEARXNG_INSTANCE_URL=https://api.hanzo.ai/v1/websearch
|
||||
# FIRECRAWL_API_URL=https://api.hanzo.ai/v1/websearch
|
||||
# WEBSEARCH_API_KEY=your-key # prod: KMS chat-secrets/WEBSEARCH_API_KEY
|
||||
#
|
||||
# Do NOT set SERPER_API_KEY / TAVILY_API_KEY / JINA_API_KEY / COHERE_API_KEY:
|
||||
# external providers are intentionally disabled (one way, unified backend).
|
||||
|
||||
#======================#
|
||||
# MCP Configuration #
|
||||
|
||||
+13
-3
@@ -5,9 +5,19 @@
|
||||
OPENAI_API_KEY=sk-hanzo-your-api-key-here
|
||||
OPENAI_BASE_URL=https://api.hanzo.ai/v1
|
||||
|
||||
# Runtime Execution (Code Interpreter)
|
||||
CODE_EXECUTION_ENDPOINT=https://api.hanzo.ai/v1/execute
|
||||
RUNTIME_API_KEY=${OPENAI_API_KEY}
|
||||
# Code Interpreter ("Run Code") — Hanzo unified backend.
|
||||
# LibreChat's execute_code tool POSTs {LIBRECHAT_CODE_BASEURL}/exec with header
|
||||
# X-API-Key. cloud-api serves /v1/exec (-> sandboxed executor). The key is
|
||||
# KMS-sourced (chat-secrets/LIBRECHAT_CODE_API_KEY). These are the ONLY vars
|
||||
# LibreChat reads — the old CODE_EXECUTION_ENDPOINT/RUNTIME_API_KEY were dead.
|
||||
LIBRECHAT_CODE_BASEURL=https://api.hanzo.ai/v1
|
||||
LIBRECHAT_CODE_API_KEY=set-in-KMS-chat-secrets
|
||||
|
||||
# Web Search — Hanzo unified backend (searxng + firecrawl compat over Hanzo
|
||||
# search + crawl). See librechat.yaml `webSearch`. One shared service key.
|
||||
SEARXNG_INSTANCE_URL=https://api.hanzo.ai/v1/websearch
|
||||
FIRECRAWL_API_URL=https://api.hanzo.ai/v1/websearch
|
||||
WEBSEARCH_API_KEY=set-in-KMS-chat-secrets
|
||||
|
||||
# ====== BRANDING ======
|
||||
APP_TITLE=Hanzo Chat
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="640" viewBox="0 0 1280 640" role="img" aria-label="chat">
|
||||
<rect width="1280" height="640" fill="#0A0A0A"/>
|
||||
<svg x="96" y="215" width="210" height="210" viewBox="0 0 67 67"><path d="M22.21 67V44.6369H0V67H22.21Z" fill="#fff"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z" fill="#fff"/><path d="M22.21 0H0V22.3184H22.21V0Z" fill="#fff"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z" fill="#fff"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z" fill="#fff"/></svg>
|
||||
<text x="378" y="276" font-family="Inter,system-ui,-apple-system,sans-serif" font-size="78" font-weight="800" letter-spacing="-2" fill="#ffffff">chat</text>
|
||||
<text x="378" y="322" font-family="Inter,system-ui,sans-serif" font-size="30" fill="#ffffff" opacity=".66">AI chat with MCP integration and multi-provider support</text>
|
||||
<rect x="378" y="338" width="806" height="3" rx="1.5" fill="#ffffff" opacity=".9"/>
|
||||
<text x="378" y="390" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">github.com/hanzoai</text>
|
||||
<text x="1184" y="390" text-anchor="end" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">hanzo.ai</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -21,6 +21,9 @@ jobs:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
env:
|
||||
CI: true
|
||||
# pnpm run frontend builds packages/api (rollup, ~5 GiB peak) + the client;
|
||||
# the default ~2 GiB heap OOMs. Match the review workflows' heap knob.
|
||||
NODE_OPTIONS: '--max-old-space-size=${{ secrets.NODE_MAX_OLD_SPACE_SIZE || 6144 }}'
|
||||
NODE_ENV: CI
|
||||
SEARCH: false
|
||||
MONGO_URI: mongodb://localhost:27017/librechat-test
|
||||
|
||||
@@ -119,30 +119,31 @@ jobs:
|
||||
echo "unused_keys=[]" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# Post via github-script (Octokit + the built-in token) rather than the gh
|
||||
# CLI: gh is not installed on the self-hosted ARC runners, so `gh api` here
|
||||
# exits 127. The job already grants `pull-requests: write`.
|
||||
- name: Post verified comment on PR
|
||||
if: env.unused_keys != '[]'
|
||||
run: |
|
||||
PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
|
||||
|
||||
# Format the unused keys list as checkboxes for easy manual checking.
|
||||
FILTERED_KEYS=$(echo "$unused_keys" | jq -r '.[]' | grep -v '^\s*$' | sed 's/^/- [ ] `/;s/$/`/' )
|
||||
|
||||
COMMENT_BODY=$(cat <<EOF
|
||||
### 🚨 Unused i18next Keys Detected
|
||||
|
||||
The following translation keys are defined in \`translation.json\` but are **not used** in the codebase:
|
||||
|
||||
$FILTERED_KEYS
|
||||
|
||||
⚠️ **Please remove these unused keys to keep the translation files clean.**
|
||||
EOF
|
||||
)
|
||||
|
||||
gh api "repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" \
|
||||
-f body="$COMMENT_BODY" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const keys = JSON.parse(process.env.unused_keys || '[]').filter(Boolean);
|
||||
const list = keys.map((k) => `- [ ] \`${k}\``).join('\n');
|
||||
const body = [
|
||||
'### 🚨 Unused i18next Keys Detected',
|
||||
'',
|
||||
'The following translation keys are defined in `translation.json` but are **not used** in the codebase:',
|
||||
'',
|
||||
list,
|
||||
'',
|
||||
'⚠️ **Please remove these unused keys to keep the translation files clean.**',
|
||||
].join('\n');
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body,
|
||||
});
|
||||
|
||||
- name: Fail workflow if unused keys found
|
||||
if: env.unused_keys != '[]'
|
||||
|
||||
@@ -16,6 +16,6 @@ jobs:
|
||||
service: chat
|
||||
image: ghcr.io/hanzoai/chat
|
||||
port: "3080"
|
||||
health-path: /api/health
|
||||
health-path: /health
|
||||
e2e-dir: e2e
|
||||
secrets: inherit
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
name: LiteLLM Linting
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install openai==1.81.0
|
||||
poetry install --with dev
|
||||
pip install openai==1.81.0
|
||||
|
||||
|
||||
|
||||
- name: Run Black formatting
|
||||
run: |
|
||||
cd litellm
|
||||
poetry run black .
|
||||
cd ..
|
||||
|
||||
- name: Run Ruff linting
|
||||
run: |
|
||||
cd litellm
|
||||
poetry run ruff check .
|
||||
cd ..
|
||||
|
||||
- name: Run MyPy type checking
|
||||
run: |
|
||||
cd litellm
|
||||
poetry run mypy . --ignore-missing-imports
|
||||
cd ..
|
||||
|
||||
- name: Check for circular imports
|
||||
run: |
|
||||
cd litellm
|
||||
poetry run python ../tests/documentation_tests/test_circular_imports.py
|
||||
cd ..
|
||||
|
||||
- name: Check import safety
|
||||
run: |
|
||||
poetry run python -c "from litellm import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1)
|
||||
@@ -10,6 +10,12 @@ jobs:
|
||||
test:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
|
||||
# The packages/api rollup build peaks ~5 GiB RSS and OOMs at Node's default
|
||||
# ~2 GiB old-space heap. Match the heap the review workflows already use
|
||||
# (well under the 8 GiB runner limit). One knob, same expression everywhere.
|
||||
env:
|
||||
NODE_OPTIONS: '--max-old-space-size=${{ secrets.NODE_MAX_OLD_SPACE_SIZE || 6144 }}'
|
||||
|
||||
services:
|
||||
mongodb:
|
||||
image: mongo:7
|
||||
@@ -66,5 +72,15 @@ jobs:
|
||||
MEILI_HOST: http://localhost:7700
|
||||
MEILI_MASTER_KEY: test_master_key
|
||||
|
||||
# Gate against tests-without-implementation drift in the MCP connection/
|
||||
# transport layer (proxy, response-size caps, WS SSRF, allowedAddresses).
|
||||
# These suites live in packages/api and were never run by this workflow —
|
||||
# which is how the connection.ts port drifted from its byte-identical tests.
|
||||
# A future half-port now fails here loudly.
|
||||
- name: Run MCP connection/transport tests
|
||||
run: cd packages/api && pnpm run test:transport
|
||||
env:
|
||||
NODE_ENV: test
|
||||
|
||||
- name: Run client tests
|
||||
run: pnpm run test:client
|
||||
@@ -248,35 +248,35 @@ jobs:
|
||||
cd ..
|
||||
fi
|
||||
|
||||
# Post via github-script (Octokit + the built-in token) rather than the gh
|
||||
# CLI: gh is not installed on the self-hosted ARC runners, so `gh api` here
|
||||
# exits 127. The job already grants `pull-requests: write`.
|
||||
- name: Post comment on PR if unused dependencies are found
|
||||
if: env.ROOT_UNUSED != '' || env.CLIENT_UNUSED != '' || env.API_UNUSED != ''
|
||||
run: |
|
||||
PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
|
||||
|
||||
ROOT_LIST=$(echo "$ROOT_UNUSED" | awk '{print "- `" $0 "`"}')
|
||||
CLIENT_LIST=$(echo "$CLIENT_UNUSED" | awk '{print "- `" $0 "`"}')
|
||||
API_LIST=$(echo "$API_UNUSED" | awk '{print "- `" $0 "`"}')
|
||||
|
||||
COMMENT_BODY=$(cat <<EOF
|
||||
### 🚨 Unused NPM Packages Detected
|
||||
|
||||
The following **unused dependencies** were found:
|
||||
|
||||
$(if [[ ! -z "$ROOT_UNUSED" ]]; then echo "#### 📂 Root \`package.json\`"; echo ""; echo "$ROOT_LIST"; echo ""; fi)
|
||||
|
||||
$(if [[ ! -z "$CLIENT_UNUSED" ]]; then echo "#### 📂 Client \`client/package.json\`"; echo ""; echo "$CLIENT_LIST"; echo ""; fi)
|
||||
|
||||
$(if [[ ! -z "$API_UNUSED" ]]; then echo "#### 📂 API \`api/package.json\`"; echo ""; echo "$API_LIST"; echo ""; fi)
|
||||
|
||||
⚠️ **Please remove these unused dependencies to keep your project clean.**
|
||||
EOF
|
||||
)
|
||||
|
||||
gh api "repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" \
|
||||
-f body="$COMMENT_BODY" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const section = (title, val) => {
|
||||
const items = (val || '').split('\n').map((s) => s.trim()).filter(Boolean);
|
||||
if (!items.length) return '';
|
||||
return `#### 📂 ${title}\n\n${items.map((i) => `- \`${i}\``).join('\n')}\n`;
|
||||
};
|
||||
const body = [
|
||||
'### 🚨 Unused NPM Packages Detected',
|
||||
'',
|
||||
'The following **unused dependencies** were found:',
|
||||
'',
|
||||
section('Root `package.json`', process.env.ROOT_UNUSED),
|
||||
section('Client `client/package.json`', process.env.CLIENT_UNUSED),
|
||||
section('API `api/package.json`', process.env.API_UNUSED),
|
||||
'⚠️ **Please remove these unused dependencies to keep your project clean.**',
|
||||
].filter(Boolean).join('\n');
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body,
|
||||
});
|
||||
|
||||
- name: Fail workflow if unused dependencies found
|
||||
if: env.ROOT_UNUSED != '' || env.CLIENT_UNUSED != '' || env.API_UNUSED != ''
|
||||
|
||||
+13
-2
@@ -1,7 +1,9 @@
|
||||
# v0.8.3-rc1
|
||||
|
||||
# Base node image
|
||||
FROM node:20-alpine AS node
|
||||
# Base node image — Hanzo Node 24 (Alpine) base: node:sqlite (DatabaseSync) is
|
||||
# built in and native better-sqlite3 compiles (build-base + python3 + g++ baked
|
||||
# in), so the CHAT_STORE_SQLITE document store runs. Node 20 lacked node:sqlite.
|
||||
FROM ghcr.io/hanzoai/nodejs:v24.18.0 AS node
|
||||
|
||||
# Install jemalloc
|
||||
RUN apk add --no-cache jemalloc
|
||||
@@ -42,6 +44,15 @@ RUN \
|
||||
|
||||
COPY --chown=node:node . .
|
||||
|
||||
# Bake the Umami analytics website id into the Vite build so the index.html
|
||||
# %VITE_ANALYTICS_SITE_ID% placeholder is substituted at build time. Vite's HTML
|
||||
# env replacement (loadEnv, envPrefix includes VITE_) picks this up from process.env.
|
||||
# Without it the tracker POSTs a literal "%VITE_ANALYTICS_SITE_ID%" as the website
|
||||
# id and analytics.hanzo.ai/api/send answers 400. Public site identifier (it appears
|
||||
# in the served HTML), safe to default here; override with --build-arg if needed.
|
||||
ARG VITE_ANALYTICS_SITE_ID=2f72b944-f1f8-4d2d-8f6c-26063bde0d1a
|
||||
ENV VITE_ANALYTICS_SITE_ID=$VITE_ANALYTICS_SITE_ID
|
||||
|
||||
RUN \
|
||||
# React client build with configurable memory
|
||||
NODE_OPTIONS="--max-old-space-size=${NODE_MAX_OLD_SPACE_SIZE}" pnpm run frontend; \
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
ARG NODE_MAX_OLD_SPACE_SIZE=6144
|
||||
|
||||
# Base for all builds
|
||||
FROM node:20-alpine AS base-min
|
||||
FROM ghcr.io/hanzoai/nodejs:v24.18.0 AS base-min
|
||||
# Install jemalloc
|
||||
RUN apk add --no-cache jemalloc
|
||||
# Set environment variable to use jemalloc
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
# Build: docker build -f Dockerfile.static -t ghcr.io/hanzoai/chat:latest .
|
||||
# Run: docker run -p 3080:3080 ghcr.io/hanzoai/chat:latest
|
||||
|
||||
FROM node:22-alpine
|
||||
FROM ghcr.io/hanzoai/nodejs:v24.18.0
|
||||
|
||||
RUN npm install -g serve@14
|
||||
|
||||
|
||||
@@ -92,32 +92,210 @@ CREDS_KEY= CREDS_IV= # Credential encryption
|
||||
|
||||
## Guest Chat (anonymous preview)
|
||||
|
||||
Off by default (`ALLOW_GUEST_CHAT=false`). When enabled, unauthenticated
|
||||
visitors get a per-IP free quota (`GUEST_MESSAGE_MAX`, default 3) on the free
|
||||
Off by default (`ALLOW_GUEST_CHAT=false`). When enabled, the landing IS the chat
|
||||
composer (ChatGPT-style): an unauthenticated visitor renders the real chat view —
|
||||
composer, starter cards, model picker — WITHOUT logging in, scoped to the free
|
||||
Zen model (`GUEST_MODEL`, default `zen3-nano`) via the `Hanzo` custom endpoint
|
||||
(`api.hanzo.ai`). Exhausting the quota returns `402 {type:'GUEST_LIMIT'}` and
|
||||
the client opens the existing OpenID/hanzo.id login.
|
||||
(`api.hanzo.ai`). Prod uses `GUEST_MESSAGE_MAX=2`. Exhausting the quota returns
|
||||
`402 {type:'GUEST_LIMIT'}` and the client opens the existing OpenID/hanzo.id login.
|
||||
|
||||
Client render path (guest === chat, not a marketing gate):
|
||||
- `AuthContext` auto-acquires a guest token when `startupConfig.allowGuestChat`
|
||||
is true (`silentRefresh` fallback + a dedicated effect closing the config race);
|
||||
sets `isGuest=true`, `isAuthenticated=false`. `useAuthRedirect` keeps guests on
|
||||
the chat surface (only truly anonymous, non-guest, non-guest-enabled users go to
|
||||
`/login`). `Root` shows the chat shell for `isAuthenticated || isGuest`.
|
||||
- `ChatRoute` renders `ChatView` for `canChat = isAuthenticated || isGuest`; the
|
||||
`/v1/chat/models` + `/v1/chat/endpoints` queries run for guests (both routes use
|
||||
`requireGuestOrJwtAuth` and return the guest-scoped single-model config), and the
|
||||
roles gate treats a guest as loaded (guests have no agent access). Files:
|
||||
`client/src/routes/{ChatRoute,useAuthRedirect}.tsx`, `hooks/useGuestAuth.ts`,
|
||||
`hooks/AuthContext.tsx`, `components/Auth/GuestLimitDialog.tsx`.
|
||||
|
||||
Security model (fail-closed, server-enforced):
|
||||
- `POST /api/auth/guest` issues a short-lived guest JWT (`{guest:true}`,
|
||||
per-token random id) signed with `JWT_SECRET`. Rate-limited per IP.
|
||||
- `POST /v1/chat/auth/guest` issues a short-lived guest JWT (`{guest:true}`,
|
||||
per-token random id) signed with `JWT_SECRET`. Rate-limited per IP
|
||||
(`guestTokenLimiter`, `GUEST_TOKEN_MAX`/`GUEST_TOKEN_WINDOW`) so tokens can't be
|
||||
spam-minted.
|
||||
- `requireGuestOrJwtAuth` (chat-completion route ONLY) accepts guest tokens;
|
||||
the standard `jwt` strategy rejects them everywhere else (no DB user), so
|
||||
every other route stays closed. `enforceGuestScope` pins endpoint+model and
|
||||
strips agents/tools/files/spec/preset. `guestMessageLimiter` (reuses the
|
||||
Redis `limiterCache`) enforces the per-IP quota.
|
||||
strips agents/tools/files/spec/preset. Guests always use the shared, capped
|
||||
`HANZO_API_KEY` (per-user `hk-` billing is skipped for `guest` principals).
|
||||
- `guestMessageLimiter` enforces the quota against the REAL client IP
|
||||
(`utils/guestClientIp` → Cloudflare `CF-Connecting-IP`, falls back to `req.ip`),
|
||||
NOT the token — clearing cookies / incognito / minting a fresh token does NOT
|
||||
reset it. Backed by the shared Redis `limiterCache` so it holds across replicas.
|
||||
`USE_REDIS=true` is MANDATORY (a memory store would let a visitor round-robin
|
||||
pods to multiply their quota).
|
||||
- Key files: `api/server/services/guestConfig.js`,
|
||||
`api/server/controllers/auth/GuestController.js`,
|
||||
`api/server/middleware/{requireGuestOrJwtAuth,enforceGuestScope}.js`,
|
||||
`api/server/middleware/limiters/{guestLimiters,guestMessageLimiter}.js`,
|
||||
router wiring in `api/server/routes/agents/index.js`. Client:
|
||||
`client/src/hooks/useGuestAuth.ts`, `AuthContext.tsx`,
|
||||
`components/Auth/GuestLimitDialog.tsx`.
|
||||
`api/server/utils/guestClientIp.js`,
|
||||
router wiring in `api/server/routes/agents/index.js`.
|
||||
- Env: `ALLOW_GUEST_CHAT`, `GUEST_MESSAGE_MAX`, `GUEST_ENDPOINT`, `GUEST_MODEL`,
|
||||
`GUEST_TOKEN_EXPIRY`, `GUEST_TOKEN_MAX`, `GUEST_TOKEN_WINDOW`. Requires
|
||||
`HANZO_API_KEY` (the free publishable gateway key) and `USE_REDIS` for the
|
||||
shared per-IP quota across replicas.
|
||||
|
||||
## Cloud Agents (canonical /v1/agents)
|
||||
|
||||
Chat can RUN a user's canonical Hanzo Cloud agents (cloud `/v1/agents`, the ONE
|
||||
production agent registry) from the thread — alongside the LibreChat-legacy local
|
||||
agent builder, which is untouched.
|
||||
|
||||
- Two surfaces, ONE run path: the `/agent <name> [prompt]` slash command and the
|
||||
@mention picker (cloud agents appear as a `cloudAgent` type). Both funnel
|
||||
through `useRunCloudAgent` → `POST /v1/chat/agents/cloud/:name/run`. The @mention /
|
||||
`/agent` picker arms `/agent <name> ` in the composer; submit is intercepted in
|
||||
`ChatForm` (`parseAgentCommand`) and dispatched to the run path.
|
||||
- Server proxy + auth (token never reaches the browser): the chat backend reads
|
||||
the user's hanzo.id token from the server-side session
|
||||
(`req.session.openidTokens.idToken`, then `accessToken`, then the httpOnly
|
||||
cookies) and forwards it as `Authorization: Bearer` to cloud. Cloud's
|
||||
`SanitizeIdentity` (HIP-0026) validates it and pins `X-Org-Id` from the `owner`
|
||||
claim, so a user only ever reaches their OWN org's agents — chat never asserts
|
||||
an org. `requireJwtAuth` gates the proxy (guests rejected); missing token →
|
||||
honest 401, never a service-token fallback (fail-secure). Agent name is
|
||||
validated against cloud's handle grammar (traversal/SSRF guard); it is NOT an
|
||||
open proxy (three fixed endpoints). Principal guard: the on-behalf-of decision
|
||||
keys off the VALIDATED principal (`req.user.provider==='openid'`), not the
|
||||
mutable `token_provider` refresh-strategy cookie, so a local user (who never
|
||||
carries a hanzo.id token) can't run under a stale OpenID session. EVERY
|
||||
forwarded token — id_token preferred, access_token fallback, from session or
|
||||
the httpOnly cookie — must pass `isForwardableToken`: a decodable JWT whose
|
||||
`sub` EQUALS `req.user.openidId` (binding MANDATORY — absent `openidId`/`sub`
|
||||
or a mismatch ⇒ no forward, no fail-open) and is unexpired. Decode-only is
|
||||
sound because cloud does the authoritative JWKS validation over the SAME claims,
|
||||
so it runs as exactly that `sub`; the gate only ever removes a token. An
|
||||
unbindable/expired/foreign token yields an honest 401, never a fabricated or
|
||||
wrong-principal run.
|
||||
- id_token persistence is DECOUPLED from the refresh strategy: OIDC login ALWAYS
|
||||
persists the on-behalf-of BEARER (id_token + access_token) to
|
||||
`req.session.openidTokens` (server-side only), regardless of
|
||||
`OPENID_REUSE_TOKENS`. It does NOT persist the OIDC refresh credential in the
|
||||
decoupled default — the session refreshes via the local JWT cookie, so
|
||||
`session.openidTokens.refreshToken` is written ONLY in REUSE mode (where
|
||||
`refreshController`/`logoutController` read it). That keeps login, refresh AND
|
||||
logout on the local-JWT path byte-identical to a non-OpenID login; that flag
|
||||
SOLELY gates whether `/v1/chat/auth/refresh` performs the OIDC refresh-grant.
|
||||
The ~1h id_token is used while valid; durable refresh (hanzo.id/Casdoor OIDC
|
||||
refresh or an RFC-8693 token-exchange from the chat session) is a tracked
|
||||
FOLLOW-UP — the login-breaking refresh-grant is NOT enabled here.
|
||||
- Abuse limits (a run is a real billable completion): a per-user rate limiter
|
||||
(`cloudAgentLimiter`, `CLOUD_AGENT_USER_MAX`/`CLOUD_AGENT_WINDOW`) guards the
|
||||
whole `/cloud` router; the client caps input by UTF-8 **bytes** (128 KiB), caps
|
||||
the buffered response (4 MiB → 502), and sheds load past a process-wide in-flight
|
||||
ceiling (`CLOUD_AGENT_MAX_CONCURRENT`, 503).
|
||||
- Key files: backend `api/server/services/CloudAgentsClient.js`,
|
||||
`api/server/routes/agents/cloud.js` (mounted `/cloud` in
|
||||
`api/server/routes/agents/index.js`); data layer
|
||||
`packages/data-provider/src/{types/cloudAgents.ts,api-endpoints.ts,data-service.ts}`;
|
||||
client `client/src/hooks/Agents/useRunCloudAgent.ts`,
|
||||
`client/src/utils/agentCommand.ts`,
|
||||
`client/src/components/Chat/Input/AgentsCommand.tsx`, and the @mention wiring in
|
||||
`client/src/hooks/Input/useMentions.ts` + `Mention.tsx`.
|
||||
- Env: `HANZO_CLOUD_URL` (optional; falls back to the `OPENAI_BASE_URL` host).
|
||||
- Convergence path (later): chat's LibreChat-legacy `/v1/chat/agents` CRUD should
|
||||
converge onto cloud `/v1/agents`; this step only ADDS cloud-agent RUN.
|
||||
|
||||
## Unified cloud architecture (2026-07) — investigate-before-ripping map
|
||||
|
||||
hanzo.chat is the **chat view** of the Hanzo AI cloud (sibling to hanzo.app =
|
||||
builder, console = admin). This section is the honest map of what is ALREADY
|
||||
unified onto the Go backend (`api.hanzo.ai/v1`) vs the one real seam that is not.
|
||||
Verified by full call-graph + route-table trace; do NOT rip blind.
|
||||
|
||||
### What already routes through the Go backend `api.hanzo.ai/v1` (no shadow LLM)
|
||||
|
||||
- **Chat completions**: client `useSSE` → `POST /v1/chat/agents/chat/Hanzo` (all
|
||||
chat, incl. plain-model, goes through the agents framework) → custom-endpoint
|
||||
resolver (`packages/api/src/endpoints/custom/initialize.ts`) reads
|
||||
`HANZO_API_KEY` + literal `baseURL https://api.hanzo.ai/v1` from the loaded
|
||||
config → LangChain OpenAI client → **`POST https://api.hanzo.ai/v1/chat/completions`**
|
||||
(SSE stream, resumable via `GenerationJobManager`). Per-user `hk-` key +
|
||||
per-org Commerce debit; fail-closed 402. THIS is the one inference path.
|
||||
- **Code interpreter** → `LIBRECHAT_CODE_BASEURL` = cloud `/v1/exec`.
|
||||
- **Web search** → `webSearch` block (searxng+firecrawl contracts) = cloud
|
||||
`/v1/websearch`.
|
||||
- **Cloud agents** → `POST /v1/chat/agents/cloud/:name/run` server-proxies to cloud
|
||||
`/v1/agents` with the user's hanzo.id bearer (see "Cloud Agents" section).
|
||||
- **Model list**: curated **zen-only** (`fetch:false`) in the loaded config —
|
||||
NO raw upstream names (brand policy). Authoritative prod list lives in the
|
||||
`chat-config` ConfigMap (`universe infra/k8s/chat/configmap.yaml`); repo
|
||||
`librechat.yaml` mirrors it (one way).
|
||||
|
||||
### DEAD residue — do NOT treat as a live backend
|
||||
|
||||
- `config.yaml` (LiteLLM `model_list`/`litellm_params`), `docker/Dockerfile.{simple,dev,custom_ui}`
|
||||
(`CMD litellm`), `deploy/migrations/*` (`LiteLLM_*` Prisma tables),
|
||||
`CONTRIBUTING.md` (upstream LiteLLM's), `scripts/cleanup-{litellm,hanzo-chat}.sh`:
|
||||
all **unreferenced** by any compose/k8s/helm/Dockerfile.multi. Prod runs
|
||||
`node server/index.js` and hits `api.hanzo.ai/v1` directly — NO local litellm
|
||||
sidecar. This is upstream merge residue; safe to delete in a dedicated sweep.
|
||||
|
||||
### The ONE real parallel store (FLAG — needs a Go-backend home)
|
||||
|
||||
LibreChat's Express backend owns, in **MongoDB** (`HanzoChat` DB), all of:
|
||||
`convos`, `messages`, `presets`, `prompts`/`promptGroups`, `users`, `balances`/
|
||||
`transactions`, `files`, `sessions` (refresh-token hashes), plus agents/assistants/
|
||||
memory/RBAC. Schemas: `packages/data-schemas/src/schema/*`. This is the shadow
|
||||
store that is NOT on the Go backend.
|
||||
|
||||
- The Go backend (`hanzoai/ai`, mounted at bare `/v1/*` in cloud) DOES have a
|
||||
persistence home, but under **casibase names** (`/v1/get-chats`, `/v1/get-chat`,
|
||||
`/v1/add-chat`, `/v1/get-messages`, `/v1/add-message`, `/v1/get-usages`) — a
|
||||
different schema/shape than LibreChat's Mongo.
|
||||
- The canonical OpenAPI repo has `chat/openapi.yaml` describing the INTENDED
|
||||
LibreChat-shaped REST surface (`/v1/chat/convos`, `/v1/chat/messages`,
|
||||
`/v1/chat/presets`, `/v1/chat/balance`, `/v1/chat/auth/*`) — but the Go binary
|
||||
**does not implement it yet**, and `ai/openapi.yaml` under-documents the real
|
||||
casibase routes.
|
||||
- To truly kill the parallel store WITHOUT breaking live chat: the Go backend
|
||||
(or Base) must implement `chat/openapi.yaml` (conversations/messages/presets),
|
||||
then repoint chat's data layer at it behind a flag and dual-write during
|
||||
cutover. Until then Mongo stays (ripping it = data loss + dead chat).
|
||||
**Coordinate with the openapi agent** (canonical spec + SDK regen).
|
||||
|
||||
### IAM-native auth (HIP-0111) — federated to hanzo.id, LIVE
|
||||
|
||||
- **Prod (backend-proxied)**: LibreChat passport `openid-client` strategy,
|
||||
OIDC **discovery** from `${OPENID_ISSUER}` = `https://hanzo.id`
|
||||
(`/.well-known/openid-configuration`; discovery fetched via in-cluster
|
||||
`iam.hanzo.svc` to dodge the CF hairpin), client_id **`hanzo-chat`**, callback
|
||||
`/oauth/openid/callback`. Local email/password is OFF in prod
|
||||
(`ALLOW_EMAIL_LOGIN=false`, `ALLOW_REGISTRATION=false`); social OIDC only.
|
||||
Files: `api/strategies/openidStrategy.js`, `api/server/socialLogins.js`,
|
||||
`api/server/routes/oauth.js`. This IS IAM-native (federated), just not the
|
||||
console `@hanzo/iam-js-sdk` shape.
|
||||
- **Static/IAM SPA mode** (`Dockerfile.static`, not the live prod deploy): browser
|
||||
`@hanzo/iam` `BrowserIamSdk` PKCE straight to hanzo.id
|
||||
(`client/src/utils/iam.ts`, `OAuthCallback.tsx`). ⚠️ INCONSISTENCY: uses
|
||||
client_id **`app-chat`** while prod uses `hanzo-chat` — align to `hanzo-chat`.
|
||||
`@hanzo/iam` is pinned `^0.4.0` (HIP-0111 wants ≥0.11.0); this path is dormant.
|
||||
|
||||
### One brand system, but pick the RIGHT one for a Tailwind app
|
||||
|
||||
`@hanzo/ui` and `@hanzo/gui` are **two different, non-overlapping** design systems:
|
||||
- **`@hanzo/ui`** = shadcn/ui + Tailwind + Radix (multi-framework). chat is
|
||||
Vite + React 18 + Tailwind, so THIS is the correct shared lib. Already used:
|
||||
`client/src/components/Nav/HanzoHeader.tsx` mounts `@hanzo/ui/navigation`
|
||||
`HanzoHeader` for cross-app chrome. Monochrome rebrand already done (grey ramp,
|
||||
H mark, favicon = hanzo.app set).
|
||||
- **`@hanzo/gui`** = a **Tamagui** fork (Next.js 15 / React 19, RN-web) — console's
|
||||
stack. Forcing it into the Vite/React18 LibreChat client = a ground-up rewrite
|
||||
of a live product; NOT done. Unify by widening `@hanzo/ui` adoption + matching
|
||||
console's monochrome tokens, NOT by swapping component frameworks.
|
||||
|
||||
### Config filename caveat
|
||||
|
||||
`loadCustomConfig.js` defaults to **`chat.yaml`** (`CONFIG_PATH || <root>/chat.yaml`).
|
||||
Prod sets `CONFIG_PATH=/app/chat.yaml` (ConfigMap mount). Repo ships
|
||||
`librechat.yaml` (reference); a deploy that doesn't set `CONFIG_PATH` to it (or
|
||||
provide `chat.yaml`) falls back to the built-in `openAI` endpoint. `OPENAI_BASE_URL`
|
||||
in `compose.prod.yml` is inert here (built-in openAI reads `OPENAI_REVERSE_PROXY`).
|
||||
|
||||
## Internal Package Names
|
||||
|
||||
These are kept as-is from upstream (npm deps, not worth renaming):
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<p align="center"><img src=".github/hero.svg" alt="chat" width="880"></p>
|
||||
|
||||
# Hanzo AI Chat
|
||||
|
||||
AI-powered chat platform with enterprise features, using Hanzo's cloud API or local deployment.
|
||||
|
||||
@@ -49,7 +49,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
4. Add a \`type\` attribute to specify the type of content the artifact represents. Assign one of the following values to the \`type\` attribute:
|
||||
- HTML: "text/html"
|
||||
- The user interface can render single file HTML pages placed within the artifact tags. HTML, JS, and CSS should be in a single file when using the \`text/html\` type.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- The only place external scripts can be imported from is https://cdnjs.cloudflare.com
|
||||
- Mermaid Diagrams: "application/vnd.mermaid"
|
||||
- The user interface will render Mermaid diagrams placed within the artifact tags.
|
||||
@@ -63,7 +63,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
- The assistant can use prebuilt components from the \`shadcn/ui\` library after it is imported: \`import { Alert, AlertDescription, AlertTitle, AlertDialog, AlertDialogAction } from '/components/ui/alert';\`. If using components from the shadcn/ui library, the assistant mentions this to the user and offers to help them install the components if necessary.
|
||||
- Components MUST be imported from \`/components/ui/name\` and NOT from \`/components/name\` or \`@/components/ui/name\`.
|
||||
- NO OTHER LIBRARIES (e.g. zod, hookform) ARE INSTALLED OR ABLE TO BE IMPORTED.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- If you are unable to follow the above requirements for any reason, don't use artifacts and use regular code blocks instead, which will not attempt to render the component.
|
||||
5. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...".
|
||||
6. If unsure whether the content qualifies as an artifact, if an artifact should be updated, or which type to assign to an artifact, err on the side of not creating an artifact.
|
||||
@@ -162,7 +162,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
4. Add a \`type\` attribute to specify the type of content the artifact represents. Assign one of the following values to the \`type\` attribute:
|
||||
- HTML: "text/html"
|
||||
- The user interface can render single file HTML pages placed within the artifact tags. HTML, JS, and CSS should be in a single file when using the \`text/html\` type.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- The only place external scripts can be imported from is https://cdnjs.cloudflare.com
|
||||
- SVG: "image/svg+xml"
|
||||
- The user interface will render the Scalable Vector Graphics (SVG) image within the artifact tags.
|
||||
@@ -186,7 +186,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
- The assistant can use prebuilt components from the \`shadcn/ui\` library after it is imported: \`import { Alert, AlertDescription, AlertTitle, AlertDialog, AlertDialogAction } from '/components/ui/alert';\`. If using components from the shadcn/ui library, the assistant mentions this to the user and offers to help them install the components if necessary.
|
||||
- Components MUST be imported from \`/components/ui/name\` and NOT from \`/components/name\` or \`@/components/ui/name\`.
|
||||
- NO OTHER LIBRARIES (e.g. zod, hookform) ARE INSTALLED OR ABLE TO BE IMPORTED.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- When iterating on code, ensure that the code is complete and functional without any snippets, placeholders, or ellipses.
|
||||
- If you are unable to follow the above requirements for any reason, don't use artifacts and use regular code blocks instead, which will not attempt to render the component.
|
||||
5. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...".
|
||||
@@ -367,7 +367,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
4. Add a \`type\` attribute to specify the type of content the artifact represents. Assign one of the following values to the \`type\` attribute:
|
||||
- HTML: "text/html"
|
||||
- The user interface can render single file HTML pages placed within the artifact tags. HTML, JS, and CSS should be in a single file when using the \`text/html\` type.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- The only place external scripts can be imported from is https://cdnjs.cloudflare.com
|
||||
- SVG: "image/svg+xml"
|
||||
- The user interface will render the Scalable Vector Graphics (SVG) image within the artifact tags.
|
||||
@@ -391,7 +391,7 @@ Artifacts are for substantial, self-contained content that users might modify or
|
||||
- The assistant can use prebuilt components from the \`shadcn/ui\` library after it is imported: \`import { Alert, AlertDescription, AlertTitle, AlertDialog, AlertDialogAction } from '/components/ui/alert';\`. If using components from the shadcn/ui library, the assistant mentions this to the user and offers to help them install the components if necessary.
|
||||
- Components MUST be imported from \`/components/ui/name\` and NOT from \`/components/name\` or \`@/components/ui/name\`.
|
||||
- NO OTHER LIBRARIES (e.g. zod, hookform) ARE INSTALLED OR ABLE TO BE IMPORTED.
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/api/placeholder/400/320" alt="placeholder" />\`
|
||||
- Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so \`<img src="/v1/chat/placeholder/400/320" alt="placeholder" />\`
|
||||
- When iterating on code, ensure that the code is complete and functional without any snippets, placeholders, or ellipses.
|
||||
- If you are unable to follow the above requirements for any reason, don't use artifacts and use regular code blocks instead, which will not attempt to render the component.
|
||||
5. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...".
|
||||
|
||||
@@ -143,16 +143,26 @@ class DALLE3 extends Tool {
|
||||
throw new Error('Missing required field: prompt');
|
||||
}
|
||||
|
||||
// Model is configurable (DALLE3_MODEL) so this tool drives the Hanzo image
|
||||
// family (e.g. zen3-image) through the same OpenAI /images/generations shape.
|
||||
// `quality` and `style` are DALL-E-3-only knobs — send them ONLY for a dall-e
|
||||
// model so a non-DALL-E backend never sees a parameter it may reject.
|
||||
const model = process.env.DALLE3_MODEL || 'dall-e-3';
|
||||
const isDallE = model.startsWith('dall-e');
|
||||
const genParams = {
|
||||
model,
|
||||
size,
|
||||
prompt: this.replaceUnwantedChars(prompt),
|
||||
n: 1,
|
||||
};
|
||||
if (isDallE) {
|
||||
genParams.quality = quality;
|
||||
genParams.style = style;
|
||||
}
|
||||
|
||||
let resp;
|
||||
try {
|
||||
resp = await this.openai.images.generate({
|
||||
model: 'dall-e-3',
|
||||
quality,
|
||||
style,
|
||||
size,
|
||||
prompt: this.replaceUnwantedChars(prompt),
|
||||
n: 1,
|
||||
});
|
||||
resp = await this.openai.images.generate(genParams);
|
||||
} catch (error) {
|
||||
logger.error('[DALL-E-3] Problem generating the image:', error);
|
||||
return this
|
||||
|
||||
@@ -12,6 +12,8 @@ const {
|
||||
loadWebSearchAuth,
|
||||
buildImageToolContext,
|
||||
buildWebSearchContext,
|
||||
resolveHanzoCloudKey,
|
||||
isHanzoPerUserKeyEnabled,
|
||||
} = require('@hanzochat/api');
|
||||
const { getMCPServersRegistry } = require('~/config');
|
||||
const {
|
||||
@@ -232,7 +234,30 @@ const loadTools = async ({
|
||||
const requestedTools = {};
|
||||
|
||||
if (functions === true) {
|
||||
toolConstructors.dalle = DALLE3;
|
||||
// dalle (image generation) drives the Hanzo image family via a PER-USER hk-
|
||||
// key so generation is metered to the signed-in user — mirroring the chat
|
||||
// per-user key path in custom/initialize.ts. A guest keeps the shared env
|
||||
// key; an authenticated user whose key cannot be resolved FAILS CLOSED
|
||||
// (throws) rather than silently billing the shared org. (Custom constructors
|
||||
// take precedence over the generic toolConstructors path in the loop below.)
|
||||
customConstructors.dalle = async () => {
|
||||
const authFields = getAuthFields('dalle');
|
||||
const authValues = await loadAuthValues({ userId: user, authFields });
|
||||
const billingUser = options.req?.user;
|
||||
const isAuthenticatedUser = Boolean(
|
||||
billingUser && !billingUser.guest && billingUser.email,
|
||||
);
|
||||
if (isHanzoPerUserKeyEnabled() && isAuthenticatedUser) {
|
||||
const perUserKey = await resolveHanzoCloudKey(billingUser);
|
||||
if (!perUserKey) {
|
||||
throw new Error(
|
||||
'Your Hanzo Cloud account is not linked for billing yet. Please sign out and back in, then claim your starter credit at https://billing.hanzo.ai',
|
||||
);
|
||||
}
|
||||
authValues.DALLE3_API_KEY = perUserKey;
|
||||
}
|
||||
return new DALLE3({ ...imageGenOptions, ...authValues, userId: user });
|
||||
};
|
||||
}
|
||||
|
||||
/** @type {ImageGenOptions} */
|
||||
|
||||
+15
-3
@@ -5,9 +5,11 @@ const { logger } = require('@librechat/data-schemas');
|
||||
const mongoose = require('mongoose');
|
||||
const MONGO_URI = process.env.MONGO_URI;
|
||||
|
||||
if (!MONGO_URI) {
|
||||
throw new Error('Please define the MONGO_URI environment variable');
|
||||
}
|
||||
// MONGO_URI is intentionally optional: in SQLite-only mode (every collection
|
||||
// served from CHAT_STORE_SQLITE, chat-docdb deleted) there is no Mongo to
|
||||
// connect to. connectDb() below handles the unset case by skipping the
|
||||
// connection rather than failing boot. When MONGO_URI IS set (default and the
|
||||
// dual-write migration window) the connection is required as before.
|
||||
/** The maximum number of connections in the connection pool. */
|
||||
const maxPoolSize = parseInt(process.env.MONGO_MAX_POOL_SIZE) || undefined;
|
||||
/** The minimum number of connections in the connection pool. */
|
||||
@@ -45,6 +47,16 @@ mongoose.connection.on('error', (err) => {
|
||||
});
|
||||
|
||||
async function connectDb() {
|
||||
if (!MONGO_URI) {
|
||||
// SQLite-only mode: skip Mongo entirely. Disable command buffering so any
|
||||
// stray mongoose query (e.g. Meili indexSync, which still references
|
||||
// mongoose.models directly) fails fast and is swallowed by its caller
|
||||
// instead of hanging forever on a pool that will never connect.
|
||||
mongoose.set('bufferCommands', false);
|
||||
logger.info('[connectDb] MONGO_URI unset — SQLite-only mode, skipping MongoDB connection');
|
||||
return null;
|
||||
}
|
||||
|
||||
if (cached.conn && cached.conn?._readyState === 1) {
|
||||
return cached.conn;
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"keep": {
|
||||
"days": true,
|
||||
"amount": 14
|
||||
},
|
||||
"auditLog": "/Users/z/work/hanzo/chat/api/logs/.124163c776d287793643ac0e08ac1d35d67ad894-audit.json",
|
||||
"files": [
|
||||
{
|
||||
"date": 1771557162318,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/meiliSync-2026-02-19.log",
|
||||
"hash": "a54018af15e4552979b0e91a2379ef40b95019fe56fe70074bb13f91952d908f"
|
||||
}
|
||||
],
|
||||
"hashType": "sha256"
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"keep": {
|
||||
"days": true,
|
||||
"amount": 14
|
||||
},
|
||||
"auditLog": "/Users/z/work/hanzo/chat/api/logs/.35252977fe148e605b7b92f19cd71e590a6f0a53-audit.json",
|
||||
"files": [
|
||||
{
|
||||
"date": 1771557162297,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/error-2026-02-19.log",
|
||||
"hash": "63688154da6c0a28cba1e30ddeef3eb867682460096d9b007dcfd2ddc25202b0"
|
||||
}
|
||||
],
|
||||
"hashType": "sha256"
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
{
|
||||
"keep": {
|
||||
"days": true,
|
||||
"amount": 14
|
||||
},
|
||||
"auditLog": "/Users/z/work/hanzo/chat/api/logs/.5a07238e142f72f47174c381d68b979f0f4a60b3-audit.json",
|
||||
"files": [
|
||||
{
|
||||
"date": 1750474453457,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-20.log",
|
||||
"hash": "696c5dfed20dbc87cd7113adb058ad5df3e53b93b9fc24840b7e236724ac4823"
|
||||
},
|
||||
{
|
||||
"date": 1750715218180,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-23.log",
|
||||
"hash": "c802b606c51329d1d65fe6c877dff02200e4d57e6565de3697ce4d8938bd8366"
|
||||
},
|
||||
{
|
||||
"date": 1750883760400,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-25.log",
|
||||
"hash": "202106c1ae63bd10f256f9249f6f32e20e495b9ca7f5ab7844f6dff28716805a"
|
||||
},
|
||||
{
|
||||
"date": 1750950599470,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-26.log",
|
||||
"hash": "e5f73d742f92938cef296a5c97cf8bb7f4e3db0198b8bc53bb0eee3ddf0f1e84"
|
||||
},
|
||||
{
|
||||
"date": 1751049961804,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-27.log",
|
||||
"hash": "15a471f383c1ea303252a3b35f88e44cc4bd1905666617dc9afc4b415d3ddac9"
|
||||
},
|
||||
{
|
||||
"date": 1751124937592,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-06-28.log",
|
||||
"hash": "77a7dd41fff34914a5ce25239c9fd77fafb8c3617a7a118550af69fbcc577643"
|
||||
},
|
||||
{
|
||||
"date": 1751599940774,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/debug-2025-07-03.log",
|
||||
"hash": "c86e337d49f3edad24952270eb6bebba4588201f1e14eab31b2482ee0c68be00"
|
||||
}
|
||||
],
|
||||
"hashType": "sha256"
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"keep": {
|
||||
"days": true,
|
||||
"amount": 14
|
||||
},
|
||||
"auditLog": "/Users/z/work/hanzo/chat/api/logs/.b5a17c43715e8a0a84a729c6012dc1ba16b1828b-audit.json",
|
||||
"files": [
|
||||
{
|
||||
"date": 1750954055845,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/meiliSync-2025-06-26.log",
|
||||
"hash": "980f8267840afde6278855f4218760f010a3fb215aa86ef5bb69dc08bb4b1b50"
|
||||
},
|
||||
{
|
||||
"date": 1751049961800,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/meiliSync-2025-06-27.log",
|
||||
"hash": "cebe79495cabf77d359dbcd3168502d3a5c4d8993e1bed0663fa40d850ccf6d5"
|
||||
},
|
||||
{
|
||||
"date": 1751124937590,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/meiliSync-2025-06-28.log",
|
||||
"hash": "bb29a81af67a7fce02315648194ef210ef2ad3c89e7083220d9a63103dc762cc"
|
||||
},
|
||||
{
|
||||
"date": 1751599940771,
|
||||
"name": "/Users/z/work/hanzo/chat/api/logs/meiliSync-2025-07-03.log",
|
||||
"hash": "9b454a63526db0eb56a27269fd38a86ac3d35dba85338ae89c91ea9895d467cb"
|
||||
}
|
||||
],
|
||||
"hashType": "sha256"
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
2025-06-25T20:37:18.651Z info: [Optional] Redis not initialized.
|
||||
2025-06-25T20:37:20.168Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-25T20:39:50.405Z info: [Optional] Redis not initialized.
|
||||
2025-06-25T20:39:51.070Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-25T20:40:07.114Z info: [Optional] Redis not initialized.
|
||||
2025-06-25T20:40:07.770Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-25T20:40:53.234Z info: [Optional] Redis not initialized.
|
||||
2025-06-25T20:40:53.905Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
@@ -1,115 +0,0 @@
|
||||
2025-06-26T15:10:34.209Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T15:10:35.166Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T16:21:35.171Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T16:21:36.574Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T16:22:06.626Z error: connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T16:23:03.561Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T16:23:04.255Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T16:23:04.300Z info: Connected to MongoDB
|
||||
2025-06-26T16:23:04.301Z info: [indexSync] Starting index synchronization check...
|
||||
2025-06-26T16:23:04.420Z error: Invalid custom config file at /Users/z/work/hanzo/chat/chat.yaml:
|
||||
{
|
||||
"issues": [
|
||||
{
|
||||
"code": "unrecognized_keys",
|
||||
"keys": [
|
||||
"ag... [truncated]
|
||||
2025-06-26T16:23:04.420Z debug: Web search serperApiKey: Using environment variable SERPER_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:23:04.420Z debug: Web search firecrawlApiKey: Using environment variable FIRECRAWL_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:23:04.420Z debug: Web search firecrawlApiUrl: Using environment variable FIRECRAWL_API_URL (not set in environment, user provided value)
|
||||
2025-06-26T16:23:04.421Z debug: Web search jinaApiKey: Using environment variable JINA_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:23:04.421Z debug: Web search cohereApiKey: Using environment variable COHERE_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:23:04.421Z warn: Default value for CREDS_KEY is being used.
|
||||
2025-06-26T16:23:04.421Z warn: Default value for CREDS_IV is being used.
|
||||
2025-06-26T16:23:04.421Z warn: Default value for JWT_SECRET is being used.
|
||||
2025-06-26T16:23:04.421Z warn: Default value for JWT_REFRESH_SECRET is being used.
|
||||
2025-06-26T16:23:04.421Z info: Please replace any default secret values.
|
||||
2025-06-26T16:23:04.421Z info:
|
||||
|
||||
For your convenience, use this tool to generate your own secret values:
|
||||
https://www.hanzo.ai/toolkit/creds_generator
|
||||
|
||||
|
||||
2025-06-26T16:23:04.421Z warn: RAG API is either not running or not reachable at undefined, you may experience errors with file uploads.
|
||||
2025-06-26T16:23:04.429Z info: No changes needed for 'USER' role permissions
|
||||
2025-06-26T16:23:04.431Z info: No changes needed for 'ADMIN' role permissions
|
||||
2025-06-26T16:23:04.431Z info: Turnstile is DISABLED (no siteKey provided).
|
||||
2025-06-26T16:24:16.068Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T16:24:17.688Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T16:24:17.756Z info: Connected to MongoDB
|
||||
2025-06-26T16:24:17.757Z info: [indexSync] Starting index synchronization check...
|
||||
2025-06-26T16:24:17.811Z error: Invalid custom config file at /Users/z/work/hanzo/chat/chat.yaml:
|
||||
{
|
||||
"issues": [
|
||||
{
|
||||
"code": "unrecognized_keys",
|
||||
"keys": [
|
||||
"ag... [truncated]
|
||||
2025-06-26T16:24:17.812Z debug: Web search serperApiKey: Using environment variable SERPER_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:24:17.812Z debug: Web search firecrawlApiKey: Using environment variable FIRECRAWL_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:24:17.812Z debug: Web search firecrawlApiUrl: Using environment variable FIRECRAWL_API_URL (not set in environment, user provided value)
|
||||
2025-06-26T16:24:17.812Z debug: Web search jinaApiKey: Using environment variable JINA_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:24:17.812Z debug: Web search cohereApiKey: Using environment variable COHERE_API_KEY (not set in environment, user provided value)
|
||||
2025-06-26T16:24:17.812Z warn: Default value for CREDS_KEY is being used.
|
||||
2025-06-26T16:24:17.812Z warn: Default value for CREDS_IV is being used.
|
||||
2025-06-26T16:24:17.812Z warn: Default value for JWT_SECRET is being used.
|
||||
2025-06-26T16:24:17.812Z warn: Default value for JWT_REFRESH_SECRET is being used.
|
||||
2025-06-26T16:24:17.812Z info: Please replace any default secret values.
|
||||
2025-06-26T16:24:17.812Z info:
|
||||
|
||||
For your convenience, use this tool to generate your own secret values:
|
||||
https://www.hanzo.ai/toolkit/creds_generator
|
||||
|
||||
|
||||
2025-06-26T16:24:17.812Z warn: RAG API is either not running or not reachable at undefined, you may experience errors with file uploads.
|
||||
2025-06-26T16:24:17.823Z info: No changes needed for 'USER' role permissions
|
||||
2025-06-26T16:24:17.825Z info: No changes needed for 'ADMIN' role permissions
|
||||
2025-06-26T16:24:17.825Z info: Turnstile is DISABLED (no siteKey provided).
|
||||
2025-06-26T16:24:17.832Z info: Server listening at http://localhost:3080
|
||||
2025-06-26T16:24:18.010Z debug: [MEILI_SYNC:meili-index-sync] Creating initial flow state
|
||||
2025-06-26T16:24:18.020Z info: [indexSync] Messages are fully synced: 0/0
|
||||
2025-06-26T16:24:18.023Z info: [indexSync] Conversations are fully synced: 0/0
|
||||
2025-06-26T16:24:18.024Z debug: [indexSync] No sync was needed
|
||||
2025-06-26T16:24:37.105Z error: invalid signature
|
||||
2025-06-26T17:16:21.631Z info: Cleaning up FlowStateManager intervals...
|
||||
2025-06-26T17:28:31.428Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T19:16:07.812Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T19:16:09.408Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T19:16:39.465Z error: connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T19:28:57.619Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T19:28:58.798Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:18:29.425Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:18:30.678Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:19:00.734Z error: getaddrinfo ENOTFOUND mongodb
|
||||
2025-06-26T21:20:04.085Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:20:04.788Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:20:34.832Z error: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T21:35:21.338Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:35:22.746Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:35:52.803Z error: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T21:39:16.497Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:39:17.655Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:39:47.696Z error: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T21:43:04.982Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:06.587Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:07.208Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:07.990Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:09.790Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:10.572Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:12.993Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:14.084Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:16.627Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:17.383Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:19.449Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:20.212Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:34.812Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:43:36.179Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-26T21:43:50.258Z error: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017
|
||||
2025-06-26T21:44:17.565Z info: [Optional] Redis not initialized.
|
||||
2025-06-26T21:44:18.322Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-27T03:16:07.463Z info: [Optional] Redis not initialized.
|
||||
2025-06-27T03:16:08.973Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-27T03:16:17.650Z debug: [indexSync] Clearing sync timeouts before exiting...
|
||||
2025-06-27T03:19:09.423Z info: [Optional] Redis not initialized.
|
||||
2025-06-27T03:19:10.741Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-27T03:19:15.742Z debug: [indexSync] Clearing sync timeouts before exiting...
|
||||
@@ -1,3 +0,0 @@
|
||||
2025-06-27T18:46:02.321Z info: [Optional] Redis not initialized.
|
||||
2025-06-27T18:46:03.818Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-27T18:46:23.237Z debug: [indexSync] Clearing sync timeouts before exiting...
|
||||
@@ -1,3 +0,0 @@
|
||||
2025-06-28T15:35:37.951Z info: [Optional] Redis not initialized.
|
||||
2025-06-28T15:35:39.502Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-06-28T15:36:09.559Z error: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017
|
||||
@@ -1,3 +0,0 @@
|
||||
2025-07-04T03:32:21.282Z info: [Optional] Redis not initialized.
|
||||
2025-07-04T03:32:22.739Z info: [Optional] IoRedis not initialized for rate limiters.
|
||||
2025-07-04T03:32:40.543Z debug: [indexSync] Clearing sync timeouts before exiting...
|
||||
@@ -1,4 +0,0 @@
|
||||
{"level":"error","message":"[mongoMeili] Error checking index convos: fetch failed","name":"MeiliSearchCommunicationError","stack":"MeiliSearchCommunicationError: fetch failed\n at node:internal/deps/undici/undici:13510:13\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)"}
|
||||
{"level":"error","message":"[mongoMeili] Error checking index messages: fetch failed","name":"MeiliSearchCommunicationError","stack":"MeiliSearchCommunicationError: fetch failed\n at node:internal/deps/undici/undici:13510:13\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)"}
|
||||
{"level":"error","message":"[mongoMeili] Error checking index convos: fetch failed","name":"MeiliSearchCommunicationError","stack":"MeiliSearchCommunicationError: fetch failed\n at node:internal/deps/undici/undici:13510:13\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)"}
|
||||
{"level":"error","message":"[mongoMeili] Error checking index messages: fetch failed","name":"MeiliSearchCommunicationError","stack":"MeiliSearchCommunicationError: fetch failed\n at node:internal/deps/undici/undici:13510:13\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)"}
|
||||
@@ -1,4 +0,0 @@
|
||||
{"level":"debug","message":"[mongoMeili] Index convos already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index convos already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index messages already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index messages already exists"}
|
||||
@@ -1,4 +0,0 @@
|
||||
{"level":"debug","message":"[mongoMeili] Index messages already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index convos already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index messages already exists"}
|
||||
{"level":"debug","message":"[mongoMeili] Index convos already exists"}
|
||||
@@ -2189,13 +2189,13 @@ describe('models/Agent', () => {
|
||||
const actions = [
|
||||
{
|
||||
action_id: '123',
|
||||
metadata: { version: '1.0', endpoints: ['GET /api/test'], schema: { type: 'object' } },
|
||||
metadata: { version: '1.0', endpoints: ['GET /v1/chat/test'], schema: { type: 'object' } },
|
||||
},
|
||||
{
|
||||
action_id: '456',
|
||||
metadata: {
|
||||
version: '2.0',
|
||||
endpoints: ['POST /api/example'],
|
||||
endpoints: ['POST /v1/chat/example'],
|
||||
schema: { type: 'string' },
|
||||
},
|
||||
},
|
||||
@@ -2212,10 +2212,10 @@ describe('models/Agent', () => {
|
||||
test('should generate different hashes for different action metadata', async () => {
|
||||
const actionIds = ['test.com_action_123'];
|
||||
const actions1 = [
|
||||
{ action_id: '123', metadata: { version: '1.0', endpoints: ['GET /api/test'] } },
|
||||
{ action_id: '123', metadata: { version: '1.0', endpoints: ['GET /v1/chat/test'] } },
|
||||
];
|
||||
const actions2 = [
|
||||
{ action_id: '123', metadata: { version: '2.0', endpoints: ['GET /api/test'] } },
|
||||
{ action_id: '123', metadata: { version: '2.0', endpoints: ['GET /v1/chat/test'] } },
|
||||
];
|
||||
|
||||
const hash1 = await generateActionMetadataHash(actionIds, actions1);
|
||||
@@ -2284,8 +2284,8 @@ describe('models/Agent', () => {
|
||||
},
|
||||
},
|
||||
endpoints: [
|
||||
{ path: '/api/test', method: 'GET', params: ['id'] },
|
||||
{ path: '/api/create', method: 'POST', body: true },
|
||||
{ path: '/v1/chat/test', method: 'GET', params: ['id'] },
|
||||
{ path: '/v1/chat/create', method: 'POST', body: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
+7
-2
@@ -1,6 +1,5 @@
|
||||
const {
|
||||
CacheKeys,
|
||||
SystemRoles,
|
||||
roleDefaults,
|
||||
permissionsSchema,
|
||||
removeNullishValues,
|
||||
@@ -31,7 +30,13 @@ const getRoleByName = async function (roleName, fieldsToSelect = null) {
|
||||
}
|
||||
let role = await query.lean().exec();
|
||||
|
||||
if (!role && SystemRoles[roleName]) {
|
||||
// Only self-heal a missing system role when we actually hold its canonical
|
||||
// defaults. Keying on SystemRoles[roleName] (enum membership) alone let a
|
||||
// role that exists in the enum but lacks a roleDefaults entry (e.g. GUEST)
|
||||
// fall into `new Role(undefined).save()` -> "name is required" -> every
|
||||
// generation for that role died. roleDefaults[roleName] always carries a
|
||||
// name, so this guard makes the nameless create structurally impossible.
|
||||
if (!role && roleDefaults[roleName]) {
|
||||
role = await new Role(roleDefaults[roleName]).save();
|
||||
await cache.set(roleName, role);
|
||||
return role.toObject();
|
||||
|
||||
@@ -214,6 +214,14 @@ async function createTransaction(_txData) {
|
||||
incrementValue,
|
||||
});
|
||||
|
||||
// NB: chat records NO debit to Commerce here. The single debit for an AI spend
|
||||
// is the cloud gateway's (api.hanzo.ai): every authenticated request forwards
|
||||
// the user's own hk- key and the gateway debits that key's Commerce balance
|
||||
// (per-user, fail-closed, 402 when empty). A second debit from chat would
|
||||
// double-charge — the incident that removed the write in recordCollectedUsage
|
||||
// (packages/api usage.ts). This local Transaction/Balance is the in-app usage
|
||||
// ledger only; in prod the balance gate is off (chat.yaml balance.enabled=false).
|
||||
|
||||
return {
|
||||
rate: transaction.rate,
|
||||
user: transaction.user.toString(),
|
||||
|
||||
@@ -45,7 +45,7 @@ const validateResourceType = (resourceType) => {
|
||||
|
||||
/**
|
||||
* Bulk update permissions for a resource (grant, update, remove)
|
||||
* @route PUT /api/{resourceType}/{resourceId}/permissions
|
||||
* @route PUT /v1/chat/{resourceType}/{resourceId}/permissions
|
||||
* @param {Object} req - Express request object
|
||||
* @param {Object} req.params - Route parameters
|
||||
* @param {string} req.params.resourceType - Resource type (e.g., 'agent')
|
||||
@@ -178,7 +178,7 @@ const updateResourcePermissions = async (req, res) => {
|
||||
/**
|
||||
* Get principals with their permission roles for a resource (UI-friendly format)
|
||||
* Uses efficient aggregation pipeline to join User/Group data in single query
|
||||
* @route GET /api/permissions/{resourceType}/{resourceId}
|
||||
* @route GET /v1/chat/permissions/{resourceType}/{resourceId}
|
||||
*/
|
||||
const getResourcePermissions = async (req, res) => {
|
||||
try {
|
||||
@@ -311,7 +311,7 @@ const getResourcePermissions = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Get available roles for a resource type
|
||||
* @route GET /api/{resourceType}/roles
|
||||
* @route GET /v1/chat/{resourceType}/roles
|
||||
*/
|
||||
const getResourceRoles = async (req, res) => {
|
||||
try {
|
||||
@@ -339,7 +339,7 @@ const getResourceRoles = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Get user's effective permission bitmask for a resource
|
||||
* @route GET /api/{resourceType}/{resourceId}/effective
|
||||
* @route GET /v1/chat/{resourceType}/{resourceId}/effective
|
||||
*/
|
||||
const getUserEffectivePermissions = async (req, res) => {
|
||||
try {
|
||||
@@ -370,7 +370,7 @@ const getUserEffectivePermissions = async (req, res) => {
|
||||
/**
|
||||
* Search for users and groups to grant permissions
|
||||
* Supports hybrid local database + Entra ID search when configured
|
||||
* @route GET /api/permissions/search-principals
|
||||
* @route GET /v1/chat/permissions/search-principals
|
||||
*/
|
||||
const searchPrincipals = async (req, res) => {
|
||||
try {
|
||||
@@ -487,7 +487,7 @@ const searchPrincipals = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Get user's effective permissions for all accessible resources of a type
|
||||
* @route GET /api/permissions/{resourceType}/effective/all
|
||||
* @route GET /v1/chat/permissions/{resourceType}/effective/all
|
||||
*/
|
||||
const getAllEffectivePermissions = async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -60,7 +60,7 @@ describe('guest bootstrap controllers', () => {
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
describe('GET /api/endpoints', () => {
|
||||
describe('GET /v1/chat/endpoints', () => {
|
||||
it('returns ONLY the guest endpoint, no DB/config read', async () => {
|
||||
const req = guestReq();
|
||||
const res = mockRes();
|
||||
@@ -80,7 +80,7 @@ describe('guest bootstrap controllers', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/models', () => {
|
||||
describe('GET /v1/chat/models', () => {
|
||||
it('returns ONLY the single guest model under the guest endpoint', async () => {
|
||||
const req = guestReq();
|
||||
const res = mockRes();
|
||||
|
||||
@@ -15,6 +15,7 @@ const {
|
||||
getBalanceConfig,
|
||||
getProviderConfig,
|
||||
omitTitleOptions,
|
||||
wrapHanzoGatewayFetch,
|
||||
memoryInstructions,
|
||||
applyContextToAgent,
|
||||
createTokenCounter,
|
||||
@@ -940,7 +941,7 @@ class AgentClient extends BaseClient {
|
||||
}
|
||||
|
||||
/** Skip token spending if aborted - the abort handler (abortMiddleware.js) handles it
|
||||
This prevents double-spending when user aborts via `/api/agents/chat/abort` */
|
||||
This prevents double-spending when user aborts via `/v1/chat/agents/chat/abort` */
|
||||
const wasAborted = abortController?.signal?.aborted;
|
||||
if (!wasAborted) {
|
||||
await this.recordCollectedUsage({
|
||||
@@ -1069,6 +1070,22 @@ class AgentClient extends BaseClient {
|
||||
clientOptions.configuration = options.configOptions;
|
||||
}
|
||||
|
||||
// Envelope-safety for the title path (parity with agent runs). The Hanzo Cloud
|
||||
// gateway answers some failures with HTTP 200 + a JSON error-envelope
|
||||
// ({status:"error", msg}) that carries no `choices`. Left raw, the OpenAI client
|
||||
// parses the 200 to `undefined` and #titleConvo crashes on
|
||||
// `reading 'message'` — so no title is ever written. Wrap the title client's
|
||||
// fetch exactly as `initializeCustom` does for agent runs, so the envelope
|
||||
// becomes a clean, catchable error the outer try/catch skips gracefully.
|
||||
// Response-only + idempotent (a re-wrap sees a 402, not a 200 envelope), so
|
||||
// per-user hk- billing and normal completions are untouched.
|
||||
if (
|
||||
clientOptions.configuration &&
|
||||
/(?:^|\.)hanzo\.ai(?::|\/|$)/i.test(clientOptions.configuration.baseURL ?? '')
|
||||
) {
|
||||
clientOptions.configuration.fetch = wrapHanzoGatewayFetch(clientOptions.configuration.fetch);
|
||||
}
|
||||
|
||||
if (clientOptions.maxTokens != null) {
|
||||
delete clientOptions.maxTokens;
|
||||
}
|
||||
@@ -1085,6 +1102,16 @@ class AgentClient extends BaseClient {
|
||||
),
|
||||
);
|
||||
|
||||
// Force the title generation onto the STREAMING (SSE) path. The Hanzo Cloud
|
||||
// gateway's non-streaming (`stream:false`) chat.completion body — though a
|
||||
// valid `{choices:[{message}]}` — is parsed to ZERO generations by the pinned
|
||||
// langchain ChatOpenAI, so `invoke()` then throws
|
||||
// `Cannot read properties of undefined (reading 'message')` and NO title is
|
||||
// ever written. The streaming path (which every agent RUN already uses, hence
|
||||
// generation works) parses the same gateway correctly. `streaming` is stripped
|
||||
// by `omitTitleOptions` above, so it must be (re)set here, after the filter.
|
||||
clientOptions.streaming = true;
|
||||
|
||||
if (
|
||||
provider === Providers.GOOGLE &&
|
||||
(endpointConfig?.titleMethod === TitleMethod.FUNCTIONS ||
|
||||
|
||||
@@ -7,7 +7,11 @@ const {
|
||||
generateAdminExchangeCode,
|
||||
} = require('@hanzochat/api');
|
||||
const { syncUserEntraGroupMemberships } = require('~/server/services/PermissionService');
|
||||
const { setAuthTokens, setOpenIDAuthTokens } = require('~/server/services/AuthService');
|
||||
const {
|
||||
setAuthTokens,
|
||||
setOpenIDAuthTokens,
|
||||
persistOpenIDTokensToSession,
|
||||
} = require('~/server/services/AuthService');
|
||||
const getLogStores = require('~/cache/getLogStores');
|
||||
const { checkBan } = require('~/server/middleware');
|
||||
const { generateToken } = require('~/models');
|
||||
@@ -56,13 +60,32 @@ function createOAuthHandler(redirectUri = domains.client) {
|
||||
}
|
||||
|
||||
/** Standard OAuth flow - set cookies and redirect */
|
||||
if (
|
||||
req.user &&
|
||||
req.user.provider == 'openid' &&
|
||||
isEnabled(process.env.OPENID_REUSE_TOKENS) === true
|
||||
) {
|
||||
await syncUserEntraGroupMemberships(req.user, req.user.tokenset.access_token);
|
||||
setOpenIDAuthTokens(req.user.tokenset, req, res, req.user._id.toString());
|
||||
if (req.user && req.user.provider == 'openid') {
|
||||
if (isEnabled(process.env.OPENID_REUSE_TOKENS) === true) {
|
||||
/**
|
||||
* REUSE path: the OIDC tokenset drives BOTH the app auth token and the
|
||||
* refresh grant (`/v1/chat/auth/refresh` performs an OIDC refresh). Unchanged.
|
||||
* setOpenIDAuthTokens already persists the id_token to the session.
|
||||
*/
|
||||
await syncUserEntraGroupMemberships(req.user, req.user.tokenset.access_token);
|
||||
setOpenIDAuthTokens(req.user.tokenset, req, res, req.user._id.toString());
|
||||
} else {
|
||||
/**
|
||||
* Decoupled path (the live default, REUSE disabled). Keep refresh on the
|
||||
* local-JWT path so login/refresh cookies stay byte-identical, but ALSO
|
||||
* persist the id_token server-side so downstream on-behalf-of cloud calls
|
||||
* (POST /v1/chat/agents/cloud/:name/run -> cloud /v1/agents) can run as this
|
||||
* hanzo.id principal. OPENID_REUSE_TOKENS still SOLELY gates the OIDC
|
||||
* refresh-grant; it no longer gates id_token persistence.
|
||||
*/
|
||||
await setAuthTokens(req.user._id, res);
|
||||
try {
|
||||
persistOpenIDTokensToSession(req, req.user.tokenset);
|
||||
} catch (persistErr) {
|
||||
/** On-behalf-of is best-effort; NEVER let it break the login redirect. */
|
||||
logger.warn('[OAuth] Failed to persist OpenID tokens for on-behalf-of:', persistErr);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await setAuthTokens(req.user._id, res);
|
||||
}
|
||||
|
||||
@@ -5,10 +5,11 @@ const mockGenerateAdminExchangeCode = jest.fn();
|
||||
const mockSyncUserEntraGroupMemberships = jest.fn();
|
||||
const mockSetAuthTokens = jest.fn();
|
||||
const mockSetOpenIDAuthTokens = jest.fn();
|
||||
const mockPersistOpenIDTokensToSession = jest.fn();
|
||||
const mockGetLogStores = jest.fn();
|
||||
const mockCheckBan = jest.fn();
|
||||
const mockGenerateToken = jest.fn();
|
||||
const mockLogger = { info: jest.fn(), error: jest.fn() };
|
||||
const mockLogger = { info: jest.fn(), error: jest.fn(), warn: jest.fn() };
|
||||
|
||||
jest.mock('librechat-data-provider', () => ({
|
||||
CacheKeys: { ADMIN_OAUTH_EXCHANGE: 'admin-oauth-exchange' },
|
||||
@@ -33,6 +34,7 @@ jest.mock('~/server/services/PermissionService', () => ({
|
||||
jest.mock('~/server/services/AuthService', () => ({
|
||||
setAuthTokens: (...args) => mockSetAuthTokens(...args),
|
||||
setOpenIDAuthTokens: (...args) => mockSetOpenIDAuthTokens(...args),
|
||||
persistOpenIDTokensToSession: (...args) => mockPersistOpenIDTokensToSession(...args),
|
||||
}));
|
||||
|
||||
jest.mock(
|
||||
@@ -148,4 +150,87 @@ describe('createOAuthHandler', () => {
|
||||
expect(mockSetAuthTokens).not.toHaveBeenCalled();
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The decouple: id_token persistence for downstream on-behalf-of is split from
|
||||
// the refresh strategy. OPENID_REUSE_TOKENS still SOLELY gates the OIDC
|
||||
// refresh-grant; it no longer gates whether the id_token is persisted.
|
||||
describe('standard OpenID flow — id_token persistence decouple', () => {
|
||||
beforeEach(() => {
|
||||
/** Not an admin cross-origin redirect — exercise the cookie/session path. */
|
||||
mockIsAdminPanelRedirect.mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('REUSE_TOKENS=false: keeps local-JWT refresh AND persists the id_token to session', async () => {
|
||||
process.env.OPENID_REUSE_TOKENS = 'false';
|
||||
const handler = createOAuthHandler('http://localhost:3080');
|
||||
const req = buildReq();
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
/** Refresh stays on the local-JWT path — login/refresh cookies unchanged. */
|
||||
expect(mockSetAuthTokens).toHaveBeenCalledWith(req.user._id, res);
|
||||
/** id_token IS persisted for on-behalf-of, regardless of REUSE_TOKENS. */
|
||||
expect(mockPersistOpenIDTokensToSession).toHaveBeenCalledWith(req, req.user.tokenset);
|
||||
/** The OIDC-reuse writer (which flips refresh to the OIDC grant) is NOT used. */
|
||||
expect(mockSetOpenIDAuthTokens).not.toHaveBeenCalled();
|
||||
expect(res.redirect).toHaveBeenCalledWith('http://localhost:3080');
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('REUSE_TOKENS=true: uses the OIDC writer (refresh path unchanged); no separate persist call', async () => {
|
||||
process.env.OPENID_REUSE_TOKENS = 'true';
|
||||
const handler = createOAuthHandler('http://localhost:3080');
|
||||
const req = buildReq();
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
expect(mockSyncUserEntraGroupMemberships).toHaveBeenCalledWith(
|
||||
req.user,
|
||||
'openid-access-token',
|
||||
);
|
||||
expect(mockSetOpenIDAuthTokens).toHaveBeenCalledWith(req.user.tokenset, req, res, 'user-123');
|
||||
/** setOpenIDAuthTokens already persists the id_token; no separate call. */
|
||||
expect(mockPersistOpenIDTokensToSession).not.toHaveBeenCalled();
|
||||
expect(mockSetAuthTokens).not.toHaveBeenCalled();
|
||||
expect(res.redirect).toHaveBeenCalledWith('http://localhost:3080');
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('local user: setAuthTokens only, never persists an OpenID token', async () => {
|
||||
process.env.OPENID_REUSE_TOKENS = 'false';
|
||||
const handler = createOAuthHandler('http://localhost:3080');
|
||||
const req = buildReq({ user: { _id: 'local-1', provider: 'local', email: 'l@example.com' } });
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
expect(mockSetAuthTokens).toHaveBeenCalledWith('local-1', res);
|
||||
expect(mockPersistOpenIDTokensToSession).not.toHaveBeenCalled();
|
||||
expect(mockSetOpenIDAuthTokens).not.toHaveBeenCalled();
|
||||
expect(res.redirect).toHaveBeenCalledWith('http://localhost:3080');
|
||||
});
|
||||
|
||||
it('login redirect survives a persistence failure (login is paramount)', async () => {
|
||||
process.env.OPENID_REUSE_TOKENS = 'false';
|
||||
mockPersistOpenIDTokensToSession.mockImplementation(() => {
|
||||
throw new Error('session store down');
|
||||
});
|
||||
const handler = createOAuthHandler('http://localhost:3080');
|
||||
const req = buildReq();
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
/** The redirect still happens; the error is swallowed (best-effort). */
|
||||
expect(mockSetAuthTokens).toHaveBeenCalledWith(req.user._id, res);
|
||||
expect(res.redirect).toHaveBeenCalledWith('http://localhost:3080');
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -172,7 +172,7 @@ const getMCPTools = async (req, res) => {
|
||||
};
|
||||
/**
|
||||
* Get all MCP servers with permissions
|
||||
* @route GET /api/mcp/servers
|
||||
* @route GET /v1/chat/mcp/servers
|
||||
*/
|
||||
const getMCPServersList = async (req, res) => {
|
||||
try {
|
||||
@@ -193,7 +193,7 @@ const getMCPServersList = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Create MCP server
|
||||
* @route POST /api/mcp/servers
|
||||
* @route POST /v1/chat/mcp/servers
|
||||
*/
|
||||
const createMCPServerController = async (req, res) => {
|
||||
try {
|
||||
@@ -252,7 +252,7 @@ const getMCPServerById = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Update MCP server
|
||||
* @route PATCH /api/mcp/servers/:serverName
|
||||
* @route PATCH /v1/chat/mcp/servers/:serverName
|
||||
*/
|
||||
const updateMCPServerController = async (req, res) => {
|
||||
try {
|
||||
@@ -287,7 +287,7 @@ const updateMCPServerController = async (req, res) => {
|
||||
|
||||
/**
|
||||
* Delete MCP server
|
||||
* @route DELETE /api/mcp/servers/:serverName
|
||||
* @route DELETE /v1/chat/mcp/servers/:serverName
|
||||
*/
|
||||
const deleteMCPServerController = async (req, res) => {
|
||||
try {
|
||||
|
||||
+26
-26
@@ -296,33 +296,33 @@ if (cluster.isMaster) {
|
||||
|
||||
/** Routes */
|
||||
app.use('/oauth', routes.oauth);
|
||||
app.use('/api/auth', routes.auth);
|
||||
app.use('/api/actions', routes.actions);
|
||||
app.use('/api/keys', routes.keys);
|
||||
app.use('/api/api-keys', routes.apiKeys);
|
||||
app.use('/api/user', routes.user);
|
||||
app.use('/api/search', routes.search);
|
||||
app.use('/api/messages', routes.messages);
|
||||
app.use('/api/convos', routes.convos);
|
||||
app.use('/api/presets', routes.presets);
|
||||
app.use('/api/prompts', routes.prompts);
|
||||
app.use('/api/categories', routes.categories);
|
||||
app.use('/api/endpoints', routes.endpoints);
|
||||
app.use('/api/balance', routes.balance);
|
||||
app.use('/api/models', routes.models);
|
||||
app.use('/api/plugins', routes.plugins);
|
||||
app.use('/api/config', routes.config);
|
||||
app.use('/api/assistants', routes.assistants);
|
||||
app.use('/api/files', await routes.files.initialize());
|
||||
app.use('/v1/chat/auth', routes.auth);
|
||||
app.use('/v1/chat/actions', routes.actions);
|
||||
app.use('/v1/chat/keys', routes.keys);
|
||||
app.use('/v1/chat/api-keys', routes.apiKeys);
|
||||
app.use('/v1/chat/user', routes.user);
|
||||
app.use('/v1/chat/search', routes.search);
|
||||
app.use('/v1/chat/messages', routes.messages);
|
||||
app.use('/v1/chat/convos', routes.convos);
|
||||
app.use('/v1/chat/presets', routes.presets);
|
||||
app.use('/v1/chat/prompts', routes.prompts);
|
||||
app.use('/v1/chat/categories', routes.categories);
|
||||
app.use('/v1/chat/endpoints', routes.endpoints);
|
||||
app.use('/v1/chat/balance', routes.balance);
|
||||
app.use('/v1/chat/models', routes.models);
|
||||
app.use('/v1/chat/plugins', routes.plugins);
|
||||
app.use('/v1/chat/config', routes.config);
|
||||
app.use('/v1/chat/assistants', routes.assistants);
|
||||
app.use('/v1/chat/files', await routes.files.initialize());
|
||||
app.use('/images/', createValidateImageRequest(appConfig.secureImageLinks), routes.staticRoute);
|
||||
app.use('/api/share', routes.share);
|
||||
app.use('/api/roles', routes.roles);
|
||||
app.use('/api/agents', routes.agents);
|
||||
app.use('/api/banner', routes.banner);
|
||||
app.use('/api/memories', routes.memories);
|
||||
app.use('/api/permissions', routes.accessPermissions);
|
||||
app.use('/api/tags', routes.tags);
|
||||
app.use('/api/mcp', routes.mcp);
|
||||
app.use('/v1/chat/share', routes.share);
|
||||
app.use('/v1/chat/roles', routes.roles);
|
||||
app.use('/v1/chat/agents', routes.agents);
|
||||
app.use('/v1/chat/banner', routes.banner);
|
||||
app.use('/v1/chat/memories', routes.memories);
|
||||
app.use('/v1/chat/permissions', routes.accessPermissions);
|
||||
app.use('/v1/chat/tags', routes.tags);
|
||||
app.use('/v1/chat/mcp', routes.mcp);
|
||||
|
||||
/** Error handler */
|
||||
app.use(ErrorController);
|
||||
|
||||
+26
-26
@@ -174,34 +174,34 @@ const startServer = async () => {
|
||||
|
||||
app.use('/oauth', routes.oauth);
|
||||
/* API Endpoints */
|
||||
app.use('/api/auth', routes.auth);
|
||||
app.use('/api/admin', routes.adminAuth);
|
||||
app.use('/api/actions', routes.actions);
|
||||
app.use('/api/keys', routes.keys);
|
||||
app.use('/api/api-keys', routes.apiKeys);
|
||||
app.use('/api/user', routes.user);
|
||||
app.use('/api/search', routes.search);
|
||||
app.use('/api/messages', routes.messages);
|
||||
app.use('/api/convos', routes.convos);
|
||||
app.use('/api/presets', routes.presets);
|
||||
app.use('/api/prompts', routes.prompts);
|
||||
app.use('/api/categories', routes.categories);
|
||||
app.use('/api/endpoints', routes.endpoints);
|
||||
app.use('/api/balance', routes.balance);
|
||||
app.use('/api/models', routes.models);
|
||||
app.use('/api/config', routes.config);
|
||||
app.use('/api/assistants', routes.assistants);
|
||||
app.use('/api/files', await routes.files.initialize());
|
||||
app.use('/v1/chat/auth', routes.auth);
|
||||
app.use('/v1/chat/admin', routes.adminAuth);
|
||||
app.use('/v1/chat/actions', routes.actions);
|
||||
app.use('/v1/chat/keys', routes.keys);
|
||||
app.use('/v1/chat/api-keys', routes.apiKeys);
|
||||
app.use('/v1/chat/user', routes.user);
|
||||
app.use('/v1/chat/search', routes.search);
|
||||
app.use('/v1/chat/messages', routes.messages);
|
||||
app.use('/v1/chat/convos', routes.convos);
|
||||
app.use('/v1/chat/presets', routes.presets);
|
||||
app.use('/v1/chat/prompts', routes.prompts);
|
||||
app.use('/v1/chat/categories', routes.categories);
|
||||
app.use('/v1/chat/endpoints', routes.endpoints);
|
||||
app.use('/v1/chat/balance', routes.balance);
|
||||
app.use('/v1/chat/models', routes.models);
|
||||
app.use('/v1/chat/config', routes.config);
|
||||
app.use('/v1/chat/assistants', routes.assistants);
|
||||
app.use('/v1/chat/files', await routes.files.initialize());
|
||||
app.use('/images/', createValidateImageRequest(appConfig.secureImageLinks), routes.staticRoute);
|
||||
app.use('/api/share', routes.share);
|
||||
app.use('/api/roles', routes.roles);
|
||||
app.use('/api/agents', routes.agents);
|
||||
app.use('/api/banner', routes.banner);
|
||||
app.use('/api/memories', routes.memories);
|
||||
app.use('/api/permissions', routes.accessPermissions);
|
||||
app.use('/v1/chat/share', routes.share);
|
||||
app.use('/v1/chat/roles', routes.roles);
|
||||
app.use('/v1/chat/agents', routes.agents);
|
||||
app.use('/v1/chat/banner', routes.banner);
|
||||
app.use('/v1/chat/memories', routes.memories);
|
||||
app.use('/v1/chat/permissions', routes.accessPermissions);
|
||||
|
||||
app.use('/api/tags', routes.tags);
|
||||
app.use('/api/mcp', routes.mcp);
|
||||
app.use('/v1/chat/tags', routes.tags);
|
||||
app.use('/v1/chat/mcp', routes.mcp);
|
||||
|
||||
app.use(ErrorController);
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ describe('Server Configuration', () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await request(app).post('/api/auth/login').send({
|
||||
const response = await request(app).post('/v1/chat/auth/login').send({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
});
|
||||
|
||||
@@ -22,6 +22,8 @@ jest.mock('librechat-data-provider', () => ({
|
||||
|
||||
jest.mock('~/server/utils', () => ({
|
||||
removePorts: (req) => req.headers['x-test-ip'] || req.ip,
|
||||
guestClientIp: (req) =>
|
||||
req.headers['cf-connecting-ip'] || req.headers['x-test-ip'] || req.ip,
|
||||
}));
|
||||
|
||||
jest.mock('../requireJwtAuth', () =>
|
||||
@@ -70,7 +72,7 @@ const buildRouter = () => {
|
||||
const buildApp = () => {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/agents', buildRouter());
|
||||
app.use('/v1/chat/agents', buildRouter());
|
||||
return app;
|
||||
};
|
||||
|
||||
@@ -94,7 +96,7 @@ describe('guest chat middleware chain', () => {
|
||||
|
||||
it('lets a guest reach the completion route, pinned to the free endpoint/model', async () => {
|
||||
const res = await request(buildApp())
|
||||
.post('/api/agents/chat')
|
||||
.post('/v1/chat/agents/chat')
|
||||
.set('Authorization', `Bearer ${guestToken()}`)
|
||||
.set('x-test-ip', '10.1.0.1')
|
||||
.send({ endpoint: 'Hanzo', model: 'zen3-nano', text: 'hi' });
|
||||
@@ -107,7 +109,7 @@ describe('guest chat middleware chain', () => {
|
||||
const ip = '10.1.0.2';
|
||||
const send = () =>
|
||||
request(app)
|
||||
.post('/api/agents/chat')
|
||||
.post('/v1/chat/agents/chat')
|
||||
.set('Authorization', `Bearer ${guestToken()}`)
|
||||
.set('x-test-ip', ip)
|
||||
.send({ endpoint: 'Hanzo', model: 'zen3-nano', text: 'hi' });
|
||||
@@ -121,7 +123,7 @@ describe('guest chat middleware chain', () => {
|
||||
|
||||
it('routes reserved /chat/abort to the JWT-only handler, not the guest router', async () => {
|
||||
const res = await request(buildApp())
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.set('Authorization', `Bearer ${guestToken()}`)
|
||||
.set('x-test-ip', '10.1.0.3')
|
||||
.send({ streamId: 'x' });
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Regression: a logged-in user in "My Agents" with no agent created/selected
|
||||
* could type "hi" and get `400 {message:'agent_id is required in request body'}`.
|
||||
*
|
||||
* A missing agent_id on the agents endpoint is an ad-hoc (ephemeral) chat, not an
|
||||
* error. This hermetic test locks the access-middleware fix point (no MongoDB /
|
||||
* winston): canAccessAgentFromBody skips the per-agent ACL and calls next().
|
||||
* The downstream build-options fix point is covered by
|
||||
* ../../services/Endpoints/agents/build.spec.js.
|
||||
*/
|
||||
|
||||
// Mock externals so neither winston (data-schemas) nor MongoDB (~/models/Agent) load.
|
||||
jest.mock('@librechat/data-schemas', () => ({ logger: { error: jest.fn(), debug: jest.fn() } }));
|
||||
|
||||
jest.mock('librechat-data-provider', () => ({
|
||||
Constants: { EPHEMERAL_AGENT_ID: 'ephemeral' },
|
||||
ResourceType: { AGENT: 'agent' },
|
||||
// Real predicate semantics (mirrors packages/data-provider/src):
|
||||
isAgentsEndpoint: (endpoint) => endpoint === 'agents',
|
||||
isEphemeralAgentId: (agentId) => !agentId?.startsWith?.('agent_'),
|
||||
}));
|
||||
|
||||
const mockCanAccessResource = jest.fn(() => (req, res, next) => {
|
||||
req.__aclChecked = true;
|
||||
return next();
|
||||
});
|
||||
jest.mock('./canAccessResource', () => ({ canAccessResource: mockCanAccessResource }));
|
||||
|
||||
jest.mock('~/models/Agent', () => ({ getAgent: jest.fn() }));
|
||||
|
||||
const { canAccessAgentFromBody } = require('./canAccessAgentFromBody');
|
||||
|
||||
const makeReqRes = (body) => {
|
||||
const req = { body, params: {} };
|
||||
const res = {
|
||||
status: jest.fn().mockReturnThis(),
|
||||
json: jest.fn().mockReturnThis(),
|
||||
};
|
||||
const next = jest.fn();
|
||||
return { req, res, next };
|
||||
};
|
||||
|
||||
describe('agent_id missing → ephemeral fallback (no 400)', () => {
|
||||
const mw = canAccessAgentFromBody({ requiredPermission: 1 });
|
||||
|
||||
test('agents endpoint with NO agent_id proceeds without a 400', async () => {
|
||||
const { req, res, next } = makeReqRes({ endpoint: 'agents', text: 'hi' });
|
||||
await mw(req, res, next);
|
||||
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(mockCanAccessResource).not.toHaveBeenCalled(); // no per-agent ACL for ephemeral
|
||||
});
|
||||
|
||||
test('non-agents endpoint with no agent_id proceeds (ephemeral)', async () => {
|
||||
const { req, res, next } = makeReqRes({ endpoint: 'openAI', text: 'hi' });
|
||||
await mw(req, res, next);
|
||||
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('explicit ephemeral id proceeds', async () => {
|
||||
const { req, res, next } = makeReqRes({ endpoint: 'agents', agent_id: 'ephemeral_primary' });
|
||||
await mw(req, res, next);
|
||||
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('a real agent_id still runs the per-agent ACL check', async () => {
|
||||
const { req, res, next } = makeReqRes({ endpoint: 'agents', agent_id: 'agent_abc123' });
|
||||
await mw(req, res, next);
|
||||
|
||||
// The middleware builds the ACL check with the real agent id as resourceIdParam,
|
||||
// then runs it (which here calls next via the mock).
|
||||
expect(mockCanAccessResource).toHaveBeenCalledTimes(1);
|
||||
expect(mockCanAccessResource.mock.calls[0][0]).toMatchObject({ resourceType: 'agent' });
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -60,15 +60,11 @@ const canAccessAgentFromBody = (options) => {
|
||||
agentId = Constants.EPHEMERAL_AGENT_ID;
|
||||
}
|
||||
|
||||
if (!agentId) {
|
||||
return res.status(400).json({
|
||||
error: 'Bad Request',
|
||||
message: 'agent_id is required in request body',
|
||||
});
|
||||
}
|
||||
|
||||
// Skip permission checks for ephemeral agents
|
||||
// Real agent IDs always start with "agent_", so anything else is ephemeral
|
||||
// A missing agent_id on the agents endpoint is an ad-hoc (ephemeral) chat,
|
||||
// not an error: "type a message and get a reply" must work before the user
|
||||
// has created or selected an agent. Ephemeral agents carry no per-agent ACL,
|
||||
// so skip the permission check and fall through to plain chat. A missing id
|
||||
// is ephemeral by the canonical predicate (isEphemeralAgentId(undefined) === true).
|
||||
if (isEphemeralAgentId(agentId)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -104,13 +104,15 @@ describe('canAccessAgentFromBody middleware', () => {
|
||||
});
|
||||
|
||||
describe('primary agent checks', () => {
|
||||
test('returns 400 when agent_id is missing on agents endpoint', async () => {
|
||||
test('proceeds (ephemeral fallback) when agent_id is missing on agents endpoint', async () => {
|
||||
// No agent created/selected yet → ad-hoc chat. "Type hi and get a reply"
|
||||
// must work out of the box; a missing id is ephemeral, not a 400.
|
||||
req.body.agent_id = undefined;
|
||||
const middleware = canAccessAgentFromBody({ requiredPermission: 1 });
|
||||
await middleware(req, res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('proceeds for ephemeral primary agent without addedConvo', async () => {
|
||||
|
||||
@@ -46,7 +46,7 @@ const buildEndpointOption = require('./buildEndpointOption');
|
||||
const createReq = (body, config = {}) => ({
|
||||
body,
|
||||
config,
|
||||
baseUrl: '/api/chat',
|
||||
baseUrl: '/v1/chat/chat',
|
||||
});
|
||||
|
||||
const createRes = () => ({
|
||||
|
||||
@@ -26,7 +26,7 @@ const banResponse = async (req, res) => {
|
||||
const { baseUrl, originalUrl } = req;
|
||||
if (!ua.browser.name) {
|
||||
return res.status(403).json({ message });
|
||||
} else if (baseUrl === '/api/agents' && originalUrl.startsWith('/api/agents/chat')) {
|
||||
} else if (baseUrl === '/v1/chat/agents' && originalUrl.startsWith('/v1/chat/agents/chat')) {
|
||||
return await denyRequest(req, res, { type: ViolationTypes.BAN });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const { limiterCache } = require('@hanzochat/api');
|
||||
const { ViolationTypes } = require('librechat-data-provider');
|
||||
const logViolation = require('~/cache/logViolation');
|
||||
|
||||
/**
|
||||
* Per-user rate limiter for the cloud-agents proxy (`/v1/chat/agents/cloud/*`). A run
|
||||
* is a real, billable cloud chat completion that holds an upstream socket for up
|
||||
* to 30s, yet it bypasses the message limiters that guard the sibling completion
|
||||
* path. This caps a signed-in user to CLOUD_AGENT_USER_MAX requests per window so
|
||||
* a loop cannot degrade the shared backend or run up denial-of-wallet cost.
|
||||
* Keyed by user id (the route is JWT-only; guests never reach it).
|
||||
*/
|
||||
const {
|
||||
CLOUD_AGENT_USER_MAX = 30,
|
||||
CLOUD_AGENT_WINDOW = 1,
|
||||
CLOUD_AGENT_VIOLATION_SCORE: score,
|
||||
} = process.env;
|
||||
|
||||
const windowMs = CLOUD_AGENT_WINDOW * 60 * 1000;
|
||||
const max = Number(CLOUD_AGENT_USER_MAX);
|
||||
|
||||
const handler = async (req, res) => {
|
||||
const type = ViolationTypes.TOOL_CALL_LIMIT;
|
||||
const errorMessage = {
|
||||
type,
|
||||
max,
|
||||
limiter: 'user',
|
||||
windowInMinutes: windowMs / 60000,
|
||||
};
|
||||
|
||||
await logViolation(req, res, type, errorMessage, score);
|
||||
res.status(429).json({ message: 'Too many cloud agent requests. Try again later.' });
|
||||
};
|
||||
|
||||
const cloudAgentLimiter = rateLimit({
|
||||
windowMs,
|
||||
max,
|
||||
handler,
|
||||
keyGenerator: (req) => req.user?.id,
|
||||
store: limiterCache('cloud_agent_limiter'),
|
||||
});
|
||||
|
||||
module.exports = cloudAgentLimiter;
|
||||
@@ -1,8 +1,14 @@
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const { limiterCache } = require('@hanzochat/api');
|
||||
const { removePorts } = require('~/server/utils');
|
||||
const { guestClientIp } = require('~/server/utils');
|
||||
|
||||
const { GUEST_TOKEN_WINDOW = 60, GUEST_TOKEN_MAX = 20 } = process.env;
|
||||
const parsePositiveInt = (value, fallback) => {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
};
|
||||
|
||||
const GUEST_TOKEN_WINDOW = parsePositiveInt(process.env.GUEST_TOKEN_WINDOW, 60);
|
||||
const GUEST_TOKEN_MAX = parsePositiveInt(process.env.GUEST_TOKEN_MAX, 20);
|
||||
|
||||
const windowMs = GUEST_TOKEN_WINDOW * 60 * 1000;
|
||||
const max = GUEST_TOKEN_MAX;
|
||||
@@ -16,12 +22,19 @@ const handler = (req, res) => {
|
||||
|
||||
/**
|
||||
* Per-IP rate limiter for guest token issuance.
|
||||
*
|
||||
* Caps how many guest tokens a single client IP can mint per window so nobody can
|
||||
* spam-mint tokens (a DoS / quota-probe vector). Keyed on the REAL client IP
|
||||
* (`guestClientIp` → Cloudflare `CF-Connecting-IP`) and backed by the shared
|
||||
* Redis `limiterCache` so the cap holds across replicas. Note this is defense in
|
||||
* depth only: even unlimited tokens cannot multiply the message quota, which is
|
||||
* itself keyed per-IP (see `guestMessageLimiter`).
|
||||
*/
|
||||
const guestTokenLimiter = rateLimit({
|
||||
windowMs,
|
||||
max,
|
||||
handler,
|
||||
keyGenerator: removePorts,
|
||||
keyGenerator: guestClientIp,
|
||||
store: limiterCache('guest_token_limiter'),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const { limiterCache } = require('@hanzochat/api');
|
||||
const { removePorts } = require('~/server/utils');
|
||||
const { guestClientIp } = require('~/server/utils');
|
||||
const { getGuestConfig } = require('~/server/services/guestConfig');
|
||||
|
||||
const GUEST_LIMIT_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
@@ -16,7 +16,11 @@ const handler = (req, res) => {
|
||||
* Per-IP quota limiter for anonymous guest chat completions.
|
||||
*
|
||||
* Reuses the shared Redis-backed `limiterCache` infrastructure (same store as the
|
||||
* message limiters). It only counts requests made by an authenticated guest
|
||||
* message limiters), so the count is shared across replicas — a guest cannot
|
||||
* multiply their quota by round-robining pods. The key is the REAL client IP
|
||||
* (`guestClientIp` → Cloudflare `CF-Connecting-IP`), NOT the guest token, so
|
||||
* clearing cookies, opening incognito, or minting a fresh guest token does not
|
||||
* reset the count. It only counts requests made by an authenticated guest
|
||||
* principal; logged-in users skip the counter entirely. On exhaustion it returns
|
||||
* a `402 { type: 'GUEST_LIMIT' }` signal the client maps to the login gate.
|
||||
*/
|
||||
@@ -24,7 +28,7 @@ const guestMessageLimiter = rateLimit({
|
||||
windowMs: GUEST_LIMIT_WINDOW_MS,
|
||||
max: () => getGuestConfig().messageMax,
|
||||
handler,
|
||||
keyGenerator: removePorts,
|
||||
keyGenerator: guestClientIp,
|
||||
skip: (req) => req.user?.guest !== true,
|
||||
store: limiterCache('guest_message_limiter'),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ jest.mock('@hanzochat/api', () => ({
|
||||
|
||||
jest.mock('~/server/utils', () => ({
|
||||
removePorts: (req) => req.headers['x-test-ip'] || req.ip,
|
||||
guestClientIp: (req) =>
|
||||
req.headers['cf-connecting-ip'] || req.headers['x-test-ip'] || req.ip,
|
||||
}));
|
||||
|
||||
jest.mock('~/server/services/guestConfig', () => ({
|
||||
|
||||
@@ -9,6 +9,7 @@ const uploadLimiters = require('./uploadLimiters');
|
||||
const forkLimiters = require('./forkLimiters');
|
||||
const registerLimiter = require('./registerLimiter');
|
||||
const toolCallLimiter = require('./toolCallLimiter');
|
||||
const cloudAgentLimiter = require('./cloudAgentLimiter');
|
||||
const messageLimiters = require('./messageLimiters');
|
||||
const verifyEmailLimiter = require('./verifyEmailLimiter');
|
||||
const resetPasswordLimiter = require('./resetPasswordLimiter');
|
||||
@@ -23,6 +24,7 @@ module.exports = {
|
||||
guestMessageLimiter,
|
||||
registerLimiter,
|
||||
toolCallLimiter,
|
||||
cloudAgentLimiter,
|
||||
createTTSLimiters,
|
||||
createSTTLimiters,
|
||||
verifyEmailLimiter,
|
||||
|
||||
@@ -36,7 +36,7 @@ function createApp(user) {
|
||||
next();
|
||||
});
|
||||
}
|
||||
app.use('/api/config', configRoute);
|
||||
app.use('/v1/chat/config', configRoute);
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ afterEach(() => {
|
||||
delete process.env.RUM_ENVIRONMENT;
|
||||
});
|
||||
|
||||
describe('GET /api/config RUM config', () => {
|
||||
describe('GET /v1/chat/config RUM config', () => {
|
||||
it('includes public-token RUM config when enabled with valid env', async () => {
|
||||
mockGetAppConfig.mockResolvedValue(baseAppConfig);
|
||||
process.env.RUM_ENABLED = 'true';
|
||||
@@ -82,7 +82,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_ENVIRONMENT = 'test';
|
||||
const app = createApp(null);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body.rum).toEqual({
|
||||
provider: 'hyperdx',
|
||||
@@ -107,7 +107,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_PUBLIC_TOKEN = 'public-token';
|
||||
const app = createApp(null);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body).not.toHaveProperty('rum');
|
||||
});
|
||||
@@ -119,12 +119,12 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_PROXY_TARGET_URL = 'http://otel-collector:4318';
|
||||
const app = createApp(mockUser);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body.rum).toEqual({
|
||||
provider: 'hyperdx',
|
||||
enabled: true,
|
||||
url: '/api/rum',
|
||||
url: '/v1/chat/rum',
|
||||
serviceName: 'librechat-web',
|
||||
authMode: 'proxy',
|
||||
consoleCapture: false,
|
||||
@@ -139,7 +139,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_AUTH_MODE = 'proxy';
|
||||
const app = createApp(mockUser);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body).not.toHaveProperty('rum');
|
||||
});
|
||||
@@ -151,7 +151,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_PUBLIC_TOKEN = 'public-token';
|
||||
const app = createApp(null);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body).not.toHaveProperty('rum');
|
||||
});
|
||||
@@ -163,7 +163,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_PUBLIC_TOKEN = 'public-token';
|
||||
const app = createApp(null);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body.rum?.url).toBe('http://[::1]:4318');
|
||||
});
|
||||
@@ -175,7 +175,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_AUTH_MODE = 'userJwt';
|
||||
const app = createApp(mockUser);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body).not.toHaveProperty('rum');
|
||||
});
|
||||
@@ -187,7 +187,7 @@ describe('GET /api/config RUM config', () => {
|
||||
process.env.RUM_AUTH_MODE = 'userJwt';
|
||||
const app = createApp(null);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.body).not.toHaveProperty('rum');
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ const configRoute = require('../config');
|
||||
// file deepcode ignore UseCsurfForExpress/test: test
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
app.use('/api/config', configRoute);
|
||||
app.use('/v1/chat/config', configRoute);
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.APP_TITLE;
|
||||
|
||||
@@ -39,7 +39,7 @@ jest.mock('multer', () => require(MOCKS).multerLib());
|
||||
jest.mock('~/server/services/Endpoints/azureAssistants', () => require(MOCKS).assistantEndpoint());
|
||||
jest.mock('~/server/services/Endpoints/assistants', () => require(MOCKS).assistantEndpoint());
|
||||
|
||||
describe('POST /api/convos/duplicate - Rate Limiting', () => {
|
||||
describe('POST /v1/chat/convos/duplicate - Rate Limiting', () => {
|
||||
let app;
|
||||
let duplicateConversation;
|
||||
const savedEnv = {};
|
||||
@@ -73,7 +73,7 @@ describe('POST /api/convos/duplicate - Rate Limiting', () => {
|
||||
req.user = { id: 'rate-limit-test-user' };
|
||||
next();
|
||||
});
|
||||
app.use('/api/convos', convosRouter);
|
||||
app.use('/v1/chat/convos', convosRouter);
|
||||
});
|
||||
|
||||
duplicateConversation.mockResolvedValue({
|
||||
@@ -95,13 +95,13 @@ describe('POST /api/convos/duplicate - Rate Limiting', () => {
|
||||
|
||||
for (let i = 0; i < userMax; i++) {
|
||||
const res = await request(app)
|
||||
.post('/api/convos/duplicate')
|
||||
.post('/v1/chat/convos/duplicate')
|
||||
.send({ conversationId: 'conv-123' });
|
||||
expect(res.status).toBe(201);
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/convos/duplicate')
|
||||
.post('/v1/chat/convos/duplicate')
|
||||
.send({ conversationId: 'conv-123' });
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body.message).toMatch(/too many/i);
|
||||
@@ -122,13 +122,13 @@ describe('POST /api/convos/duplicate - Rate Limiting', () => {
|
||||
|
||||
for (let i = 0; i < ipMax; i++) {
|
||||
const res = await request(app)
|
||||
.post('/api/convos/duplicate')
|
||||
.post('/v1/chat/convos/duplicate')
|
||||
.send({ conversationId: 'conv-123' });
|
||||
expect(res.status).toBe(201);
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/convos/duplicate')
|
||||
.post('/v1/chat/convos/duplicate')
|
||||
.send({ conversationId: 'conv-123' });
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body.message).toMatch(/too many/i);
|
||||
|
||||
@@ -124,7 +124,7 @@ describe('Convos Routes', () => {
|
||||
next();
|
||||
});
|
||||
|
||||
app.use('/api/convos', convosRouter);
|
||||
app.use('/v1/chat/convos', convosRouter);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -145,7 +145,7 @@ describe('Convos Routes', () => {
|
||||
deletedCount: 3,
|
||||
});
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body).toEqual(mockDbResponse);
|
||||
@@ -176,7 +176,7 @@ describe('Convos Routes', () => {
|
||||
deletedCount: 0,
|
||||
});
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deleteAllSharedLinks).toHaveBeenCalledWith('test-user-123');
|
||||
@@ -186,7 +186,7 @@ describe('Convos Routes', () => {
|
||||
const errorMessage = 'Database connection error';
|
||||
deleteConvos.mockRejectedValue(new Error(errorMessage));
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.text).toBe('Error clearing conversations');
|
||||
@@ -200,7 +200,7 @@ describe('Convos Routes', () => {
|
||||
deleteConvos.mockResolvedValue({ deletedCount: 5 });
|
||||
deleteToolCalls.mockRejectedValue(new Error('Tool calls deletion failed'));
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.text).toBe('Error clearing conversations');
|
||||
@@ -211,7 +211,7 @@ describe('Convos Routes', () => {
|
||||
deleteToolCalls.mockResolvedValue({ deletedCount: 10 });
|
||||
deleteAllSharedLinks.mockRejectedValue(new Error('Shared links deletion failed'));
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.text).toBe('Error clearing conversations');
|
||||
@@ -223,7 +223,7 @@ describe('Convos Routes', () => {
|
||||
deleteToolCalls.mockResolvedValue({ deletedCount: 5 });
|
||||
deleteAllSharedLinks.mockResolvedValue({ deletedCount: 2 });
|
||||
|
||||
let response = await request(app).delete('/api/convos/all');
|
||||
let response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deleteAllSharedLinks).toHaveBeenCalledWith('test-user-123');
|
||||
@@ -237,13 +237,13 @@ describe('Convos Routes', () => {
|
||||
req.user = { id: 'test-user-456' };
|
||||
next();
|
||||
});
|
||||
app2.use('/api/convos', require('../convos'));
|
||||
app2.use('/v1/chat/convos', require('../convos'));
|
||||
|
||||
deleteConvos.mockResolvedValue({ deletedCount: 7 });
|
||||
deleteToolCalls.mockResolvedValue({ deletedCount: 12 });
|
||||
deleteAllSharedLinks.mockResolvedValue({ deletedCount: 4 });
|
||||
|
||||
response = await request(app2).delete('/api/convos/all');
|
||||
response = await request(app2).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deleteAllSharedLinks).toHaveBeenCalledWith('test-user-456');
|
||||
@@ -267,7 +267,7 @@ describe('Convos Routes', () => {
|
||||
return Promise.resolve({ deletedCount: 3 });
|
||||
});
|
||||
|
||||
await request(app).delete('/api/convos/all');
|
||||
await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
/** Verify all three functions were called */
|
||||
expect(executionOrder).toEqual(['deleteConvos', 'deleteToolCalls', 'deleteAllSharedLinks']);
|
||||
@@ -286,7 +286,7 @@ describe('Convos Routes', () => {
|
||||
deleteToolCalls.mockResolvedValue(mockToolCallsDeleted);
|
||||
deleteAllSharedLinks.mockResolvedValue(mockSharedLinksDeleted);
|
||||
|
||||
const response = await request(app).delete('/api/convos/all');
|
||||
const response = await request(app).delete('/v1/chat/convos/all');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
|
||||
@@ -314,7 +314,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -341,7 +341,7 @@ describe('Convos Routes', () => {
|
||||
deleteToolCalls.mockResolvedValue({ deletedCount: 0 });
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
source: 'button',
|
||||
@@ -363,7 +363,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -375,7 +375,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 400 when no parameters provided', async () => {
|
||||
const response = await request(app).delete('/api/convos').send({
|
||||
const response = await request(app).delete('/v1/chat/convos').send({
|
||||
arg: {},
|
||||
});
|
||||
|
||||
@@ -386,7 +386,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 400 when request body is empty (DoS prevention)', async () => {
|
||||
const response = await request(app).delete('/api/convos').send({});
|
||||
const response = await request(app).delete('/v1/chat/convos').send({});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body).toEqual({ error: 'no parameters provided' });
|
||||
@@ -394,7 +394,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 400 when arg is null (DoS prevention)', async () => {
|
||||
const response = await request(app).delete('/api/convos').send({ arg: null });
|
||||
const response = await request(app).delete('/v1/chat/convos').send({ arg: null });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body).toEqual({ error: 'no parameters provided' });
|
||||
@@ -402,7 +402,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 400 when arg is undefined (DoS prevention)', async () => {
|
||||
const response = await request(app).delete('/api/convos').send({ arg: undefined });
|
||||
const response = await request(app).delete('/v1/chat/convos').send({ arg: undefined });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body).toEqual({ error: 'no parameters provided' });
|
||||
@@ -411,7 +411,7 @@ describe('Convos Routes', () => {
|
||||
|
||||
it('should return 400 when request body is null (DoS prevention)', async () => {
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('null');
|
||||
|
||||
@@ -427,7 +427,7 @@ describe('Convos Routes', () => {
|
||||
deleteConvoSharedLink.mockRejectedValue(new Error('Failed to delete shared links'));
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -458,7 +458,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -479,7 +479,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/api/convos')
|
||||
.delete('/v1/chat/convos')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -509,7 +509,7 @@ describe('Convos Routes', () => {
|
||||
saveConvo.mockResolvedValue(mockArchivedConvo);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -522,7 +522,7 @@ describe('Convos Routes', () => {
|
||||
expect(saveConvo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ user: { id: 'test-user-123' } }),
|
||||
{ conversationId: mockConversationId, isArchived: true },
|
||||
{ context: `POST /api/convos/archive ${mockConversationId}` },
|
||||
{ context: `POST /v1/chat/convos/archive ${mockConversationId}` },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -538,7 +538,7 @@ describe('Convos Routes', () => {
|
||||
saveConvo.mockResolvedValue(mockUnarchivedConvo);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -551,13 +551,13 @@ describe('Convos Routes', () => {
|
||||
expect(saveConvo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ user: { id: 'test-user-123' } }),
|
||||
{ conversationId: mockConversationId, isArchived: false },
|
||||
{ context: `POST /api/convos/archive ${mockConversationId}` },
|
||||
{ context: `POST /v1/chat/convos/archive ${mockConversationId}` },
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 400 when conversationId is missing', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
isArchived: true,
|
||||
@@ -571,7 +571,7 @@ describe('Convos Routes', () => {
|
||||
|
||||
it('should return 400 when isArchived is not a boolean', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: 'conv-123',
|
||||
@@ -586,7 +586,7 @@ describe('Convos Routes', () => {
|
||||
|
||||
it('should return 400 when isArchived is undefined', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: 'conv-123',
|
||||
@@ -603,7 +603,7 @@ describe('Convos Routes', () => {
|
||||
saveConvo.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/convos/archive')
|
||||
.post('/v1/chat/convos/archive')
|
||||
.send({
|
||||
arg: {
|
||||
conversationId: mockConversationId,
|
||||
@@ -619,7 +619,7 @@ describe('Convos Routes', () => {
|
||||
});
|
||||
|
||||
it('should handle empty arg object', async () => {
|
||||
const response = await request(app).post('/api/convos/archive').send({
|
||||
const response = await request(app).post('/v1/chat/convos/archive').send({
|
||||
arg: {},
|
||||
});
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ function createApp(user) {
|
||||
router.get('/:principalType/:principalId', handlers.getPrincipalGrants);
|
||||
router.post('/', handlers.assignGrant);
|
||||
router.delete('/:principalType/:principalId/:capability', handlers.revokeGrant);
|
||||
app.use('/api/admin/grants', router);
|
||||
app.use('/v1/chat/admin/grants', router);
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -96,7 +96,7 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
|
||||
it('GET / returns seeded admin grants', async () => {
|
||||
const app = createApp(adminUser);
|
||||
const res = await request(app).get('/api/admin/grants').expect(200);
|
||||
const res = await request(app).get('/v1/chat/admin/grants').expect(200);
|
||||
|
||||
expect(res.body).toHaveProperty('grants');
|
||||
expect(res.body).toHaveProperty('total');
|
||||
@@ -107,7 +107,7 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
|
||||
it('GET /effective returns capabilities for admin', async () => {
|
||||
const app = createApp(adminUser);
|
||||
const res = await request(app).get('/api/admin/grants/effective').expect(200);
|
||||
const res = await request(app).get('/v1/chat/admin/grants/effective').expect(200);
|
||||
|
||||
expect(res.body).toHaveProperty('capabilities');
|
||||
expect(res.body.capabilities).toContain('access:admin');
|
||||
@@ -119,7 +119,7 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
|
||||
// Assign
|
||||
const assignRes = await request(app)
|
||||
.post('/api/admin/grants')
|
||||
.post('/v1/chat/admin/grants')
|
||||
.send({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.USER,
|
||||
@@ -135,19 +135,19 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
|
||||
// Verify via GET
|
||||
const getRes = await request(app)
|
||||
.get(`/api/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}`)
|
||||
.get(`/v1/chat/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}`)
|
||||
.expect(200);
|
||||
|
||||
expect(getRes.body.grants.some((g) => g.capability === 'read:users')).toBe(true);
|
||||
|
||||
// Revoke
|
||||
await request(app)
|
||||
.delete(`/api/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}/read:users`)
|
||||
.delete(`/v1/chat/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}/read:users`)
|
||||
.expect(200);
|
||||
|
||||
// Verify revoked
|
||||
const afterRes = await request(app)
|
||||
.get(`/api/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}`)
|
||||
.get(`/v1/chat/admin/grants/${PrincipalType.ROLE}/${SystemRoles.USER}`)
|
||||
.expect(200);
|
||||
|
||||
expect(afterRes.body.grants.some((g) => g.capability === 'read:users')).toBe(false);
|
||||
@@ -157,7 +157,7 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
const app = createApp(adminUser);
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/admin/grants')
|
||||
.post('/v1/chat/admin/grants')
|
||||
.send({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: 'nonexistent-role',
|
||||
@@ -172,7 +172,7 @@ describe('Admin Grants Routes — Integration', () => {
|
||||
const app = createApp(undefined);
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/admin/grants')
|
||||
.post('/v1/chat/admin/grants')
|
||||
.send({
|
||||
principalType: PrincipalType.ROLE,
|
||||
principalId: SystemRoles.USER,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* Proves:
|
||||
* - a guest token on a JWT-only route returns a clean 401 (NOT 500/CastError),
|
||||
* - /api/endpoints, /api/user, /api/convos return guest-scoped data,
|
||||
* - /v1/chat/endpoints, /v1/chat/user, /v1/chat/convos return guest-scoped data,
|
||||
* - a non-bootstrap protected route still 401s for a guest.
|
||||
*/
|
||||
|
||||
@@ -52,19 +52,19 @@ const buildApp = () => {
|
||||
passport.use(jwtLogin());
|
||||
|
||||
// Bootstrap (guest-aware) routes.
|
||||
app.get('/api/endpoints', requireGuestOrJwtAuth, (req, res) => {
|
||||
app.get('/v1/chat/endpoints', requireGuestOrJwtAuth, (req, res) => {
|
||||
if (req.user?.guest === true) {
|
||||
return res.send(JSON.stringify(buildGuestEndpointsConfig()));
|
||||
}
|
||||
return res.send(JSON.stringify({ openAI: {}, Hanzo: {} }));
|
||||
});
|
||||
app.get('/api/user', requireGuestOrJwtAuth, (req, res) => {
|
||||
app.get('/v1/chat/user', requireGuestOrJwtAuth, (req, res) => {
|
||||
if (req.user?.guest === true) {
|
||||
return res.status(200).send(buildGuestUser(req.user));
|
||||
}
|
||||
return res.status(200).send(req.user);
|
||||
});
|
||||
app.get('/api/convos', requireGuestOrJwtAuth, (req, res) => {
|
||||
app.get('/v1/chat/convos', requireGuestOrJwtAuth, (req, res) => {
|
||||
if (req.user?.guest === true) {
|
||||
return res.status(200).json({ conversations: [], nextCursor: null });
|
||||
}
|
||||
@@ -72,7 +72,7 @@ const buildApp = () => {
|
||||
});
|
||||
|
||||
// Non-bootstrap protected route (JWT-only): must reject guests.
|
||||
app.get('/api/prompts', requireJwtAuth, (req, res) => res.status(200).json({ ok: true }));
|
||||
app.get('/v1/chat/prompts', requireJwtAuth, (req, res) => res.status(200).json({ ok: true }));
|
||||
|
||||
return app;
|
||||
};
|
||||
@@ -91,9 +91,9 @@ describe('guest bootstrap auth chain (integration)', () => {
|
||||
|
||||
afterEach(() => jest.clearAllMocks());
|
||||
|
||||
it('GET /api/endpoints → 200 with ONLY the guest endpoint', async () => {
|
||||
it('GET /v1/chat/endpoints → 200 with ONLY the guest endpoint', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/endpoints')
|
||||
.get('/v1/chat/endpoints')
|
||||
.set('Authorization', `Bearer ${guestToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
const body = JSON.parse(res.text);
|
||||
@@ -101,36 +101,36 @@ describe('guest bootstrap auth chain (integration)', () => {
|
||||
expect(getUserById).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('GET /api/user → 200 ephemeral guest principal (no email, no DB lookup)', async () => {
|
||||
const res = await request(app).get('/api/user').set('Authorization', `Bearer ${guestToken}`);
|
||||
it('GET /v1/chat/user → 200 ephemeral guest principal (no email, no DB lookup)', async () => {
|
||||
const res = await request(app).get('/v1/chat/user').set('Authorization', `Bearer ${guestToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ id: 'guest_abc-123', role: 'GUEST', guest: true });
|
||||
expect(res.body).not.toHaveProperty('email');
|
||||
expect(getUserById).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('GET /api/convos → 200 empty list for a guest', async () => {
|
||||
const res = await request(app).get('/api/convos').set('Authorization', `Bearer ${guestToken}`);
|
||||
it('GET /v1/chat/convos → 200 empty list for a guest', async () => {
|
||||
const res = await request(app).get('/v1/chat/convos').set('Authorization', `Bearer ${guestToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ conversations: [], nextCursor: null });
|
||||
});
|
||||
|
||||
it('GET /api/prompts (JWT-only) → clean 401 for a guest, NEVER 500/CastError', async () => {
|
||||
const res = await request(app).get('/api/prompts').set('Authorization', `Bearer ${guestToken}`);
|
||||
it('GET /v1/chat/prompts (JWT-only) → clean 401 for a guest, NEVER 500/CastError', async () => {
|
||||
const res = await request(app).get('/v1/chat/prompts').set('Authorization', `Bearer ${guestToken}`);
|
||||
expect(res.status).toBe(401);
|
||||
// The guest id must never reach getUserById (that is what caused the CastError → 500).
|
||||
expect(getUserById).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('GET /api/prompts → clean 401 for a real-but-missing user (no 500)', async () => {
|
||||
it('GET /v1/chat/prompts → clean 401 for a real-but-missing user (no 500)', async () => {
|
||||
const realToken = jwt.sign({ id: '64b2f0c0c0c0c0c0c0c0c0c0' }, JWT_SECRET);
|
||||
const res = await request(app).get('/api/prompts').set('Authorization', `Bearer ${realToken}`);
|
||||
const res = await request(app).get('/v1/chat/prompts').set('Authorization', `Bearer ${realToken}`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(getUserById).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('GET /api/prompts → 401 with no token (fail closed)', async () => {
|
||||
const res = await request(app).get('/api/prompts');
|
||||
it('GET /v1/chat/prompts → 401 with no token (fail closed)', async () => {
|
||||
const res = await request(app).get('/v1/chat/prompts');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('Keys Routes', () => {
|
||||
next();
|
||||
});
|
||||
|
||||
app.use('/api/keys', keysRouter);
|
||||
app.use('/v1/chat/keys', keysRouter);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -40,7 +40,7 @@ describe('Keys Routes', () => {
|
||||
updateUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app)
|
||||
.put('/api/keys')
|
||||
.put('/v1/chat/keys')
|
||||
.send({ name: 'openAI', value: 'sk-test-key-123', expiresAt: '2026-12-31' });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
@@ -56,7 +56,7 @@ describe('Keys Routes', () => {
|
||||
it('should not allow userId override via request body (IDOR prevention)', async () => {
|
||||
updateUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app).put('/api/keys').send({
|
||||
const response = await request(app).put('/v1/chat/keys').send({
|
||||
userId: 'attacker-injected-id',
|
||||
name: 'openAI',
|
||||
value: 'sk-attacker-key',
|
||||
@@ -74,7 +74,7 @@ describe('Keys Routes', () => {
|
||||
it('should ignore extraneous fields from request body', async () => {
|
||||
updateUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app).put('/api/keys').send({
|
||||
const response = await request(app).put('/v1/chat/keys').send({
|
||||
name: 'openAI',
|
||||
value: 'sk-test-key',
|
||||
expiresAt: '2026-12-31',
|
||||
@@ -96,7 +96,7 @@ describe('Keys Routes', () => {
|
||||
updateUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app)
|
||||
.put('/api/keys')
|
||||
.put('/v1/chat/keys')
|
||||
.send({ name: 'anthropic', value: 'sk-ant-key' });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
@@ -110,7 +110,7 @@ describe('Keys Routes', () => {
|
||||
|
||||
it('should return 400 when request body is null', async () => {
|
||||
const response = await request(app)
|
||||
.put('/api/keys')
|
||||
.put('/v1/chat/keys')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('null');
|
||||
|
||||
@@ -123,7 +123,7 @@ describe('Keys Routes', () => {
|
||||
it('should delete a user key by name', async () => {
|
||||
deleteUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app).delete('/api/keys/openAI');
|
||||
const response = await request(app).delete('/v1/chat/keys/openAI');
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(deleteUserKey).toHaveBeenCalledWith({
|
||||
@@ -138,7 +138,7 @@ describe('Keys Routes', () => {
|
||||
it('should delete all keys when all=true', async () => {
|
||||
deleteUserKey.mockResolvedValue({});
|
||||
|
||||
const response = await request(app).delete('/api/keys?all=true');
|
||||
const response = await request(app).delete('/v1/chat/keys?all=true');
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(deleteUserKey).toHaveBeenCalledWith({
|
||||
@@ -148,7 +148,7 @@ describe('Keys Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 400 when all query param is not true', async () => {
|
||||
const response = await request(app).delete('/api/keys');
|
||||
const response = await request(app).delete('/v1/chat/keys');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body).toEqual({ error: 'Specify either all=true to delete.' });
|
||||
@@ -161,7 +161,7 @@ describe('Keys Routes', () => {
|
||||
const mockExpiry = { expiresAt: '2026-12-31' };
|
||||
getUserKeyExpiry.mockResolvedValue(mockExpiry);
|
||||
|
||||
const response = await request(app).get('/api/keys?name=openAI');
|
||||
const response = await request(app).get('/v1/chat/keys?name=openAI');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(mockExpiry);
|
||||
|
||||
@@ -12,7 +12,7 @@ jest.mock('@hanzochat/api', () => ({
|
||||
const app = express();
|
||||
|
||||
// Mock the route handler
|
||||
app.get('/api/config', (req, res) => {
|
||||
app.get('/v1/chat/config', (req, res) => {
|
||||
const ldapConfig = getLdapConfig();
|
||||
res.json({ ldap: ldapConfig });
|
||||
});
|
||||
@@ -26,7 +26,7 @@ describe('LDAP Config Tests', () => {
|
||||
getLdapConfig.mockReturnValue({ enabled: true, username: true });
|
||||
isEnabled.mockReturnValue(true);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body.ldap).toEqual({
|
||||
@@ -39,7 +39,7 @@ describe('LDAP Config Tests', () => {
|
||||
getLdapConfig.mockReturnValue({ enabled: true });
|
||||
isEnabled.mockReturnValue(false);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body.ldap).toEqual({
|
||||
@@ -50,7 +50,7 @@ describe('LDAP Config Tests', () => {
|
||||
it('should not return LDAP config when LDAP is not enabled', async () => {
|
||||
getLdapConfig.mockReturnValue(undefined);
|
||||
|
||||
const response = await request(app).get('/api/config');
|
||||
const response = await request(app).get('/v1/chat/config');
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body.ldap).toBeUndefined();
|
||||
|
||||
@@ -147,7 +147,7 @@ describe('MCP Routes', () => {
|
||||
next();
|
||||
});
|
||||
|
||||
app.use('/api/mcp', mcpRouter);
|
||||
app.use('/v1/chat/mcp', mcpRouter);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -182,7 +182,7 @@ describe('MCP Routes', () => {
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'test-user-id',
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -199,7 +199,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 403 when userId does not match authenticated user', async () => {
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'different-user-id',
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -216,7 +216,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'test-user-id',
|
||||
flowId: 'non-existent-flow-id',
|
||||
});
|
||||
@@ -237,7 +237,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'test-user-id',
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -254,7 +254,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'test-user-id',
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -274,7 +274,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/initiate').query({
|
||||
userId: 'test-user-id',
|
||||
flowId: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -289,7 +289,7 @@ describe('MCP Routes', () => {
|
||||
const { getLogStores } = require('~/cache');
|
||||
|
||||
it('should redirect to error page when OAuth error is received', async () => {
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/callback').query({
|
||||
error: 'access_denied',
|
||||
state: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -300,7 +300,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
|
||||
it('should redirect to error page when code is missing', async () => {
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/callback').query({
|
||||
state: 'test-user-id:test-server',
|
||||
});
|
||||
const basePath = getBasePath();
|
||||
@@ -310,7 +310,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
|
||||
it('should redirect to error page when state is missing', async () => {
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/callback').query({
|
||||
code: 'test-auth-code',
|
||||
});
|
||||
const basePath = getBasePath();
|
||||
@@ -320,7 +320,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
|
||||
it('should redirect to error page when CSRF cookie is missing', async () => {
|
||||
const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/oauth/callback').query({
|
||||
code: 'test-auth-code',
|
||||
state: 'test-user-id:test-server',
|
||||
});
|
||||
@@ -335,7 +335,7 @@ describe('MCP Routes', () => {
|
||||
it('should redirect to error page when CSRF cookie does not match state', async () => {
|
||||
const csrfToken = generateTestCsrfToken('different-flow-id');
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -355,7 +355,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -419,7 +419,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -464,7 +464,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -506,7 +506,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -558,7 +558,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -606,7 +606,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -671,7 +671,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -718,7 +718,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.get('/v1/chat/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.query({
|
||||
code: 'test-auth-code',
|
||||
@@ -751,7 +751,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/tokens/test-user-id:flow-123');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/tokens/test-user-id:flow-123');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -769,16 +769,16 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).get('/api/mcp/oauth/tokens/test-flow-id');
|
||||
const response = await request(unauthApp).get('/v1/chat/mcp/oauth/tokens/test-flow-id');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
});
|
||||
|
||||
it('should return 403 when user tries to access flow they do not own', async () => {
|
||||
const response = await request(app).get('/api/mcp/oauth/tokens/other-user-id:flow-123');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/tokens/other-user-id:flow-123');
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.body).toEqual({ error: 'Access denied' });
|
||||
@@ -793,7 +793,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get(
|
||||
'/api/mcp/oauth/tokens/test-user-id:non-existent-flow',
|
||||
'/v1/chat/mcp/oauth/tokens/test-user-id:non-existent-flow',
|
||||
);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
@@ -811,7 +811,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/tokens/test-user-id:pending-flow');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/tokens/test-user-id:pending-flow');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body).toEqual({ error: 'Flow not completed' });
|
||||
@@ -822,7 +822,7 @@ describe('MCP Routes', () => {
|
||||
throw new Error('Database connection failed');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/tokens/test-user-id:error-flow');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/tokens/test-user-id:error-flow');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to get tokens' });
|
||||
@@ -843,7 +843,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/status/test-user-id:test-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/status/test-user-id:test-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -855,7 +855,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
|
||||
it('should return 403 when flowId does not match authenticated user', async () => {
|
||||
const response = await request(app).get('/api/mcp/oauth/status/other-user-id:test-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/status/other-user-id:test-server');
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.body).toEqual({ error: 'Access denied' });
|
||||
@@ -869,7 +869,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/status/test-user-id:non-existent');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/status/test-user-id:non-existent');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({ error: 'Flow not found' });
|
||||
@@ -883,7 +883,7 @@ describe('MCP Routes', () => {
|
||||
getLogStores.mockReturnValue({});
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/oauth/status/test-user-id:error-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/oauth/status/test-user-id:error-server');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to get flow status' });
|
||||
@@ -906,7 +906,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
MCPOAuthHandler.generateFlowId.mockReturnValue('test-user-id:test-server');
|
||||
|
||||
const response = await request(app).post('/api/mcp/oauth/cancel/test-server');
|
||||
const response = await request(app).post('/v1/chat/mcp/oauth/cancel/test-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -930,7 +930,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
MCPOAuthHandler.generateFlowId.mockReturnValue('test-user-id:test-server');
|
||||
|
||||
const response = await request(app).post('/api/mcp/oauth/cancel/test-server');
|
||||
const response = await request(app).post('/v1/chat/mcp/oauth/cancel/test-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -949,7 +949,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
|
||||
MCPOAuthHandler.generateFlowId.mockReturnValue('test-user-id:test-server');
|
||||
|
||||
const response = await request(app).post('/api/mcp/oauth/cancel/test-server');
|
||||
const response = await request(app).post('/v1/chat/mcp/oauth/cancel/test-server');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to cancel OAuth flow' });
|
||||
@@ -962,9 +962,9 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).post('/api/mcp/oauth/cancel/test-server');
|
||||
const response = await request(unauthApp).post('/v1/chat/mcp/oauth/cancel/test-server');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
@@ -984,7 +984,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getFlowStateManager.mockReturnValue({});
|
||||
require('~/cache').getLogStores.mockReturnValue({});
|
||||
|
||||
const response = await request(app).post('/api/mcp/non-existent-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/non-existent-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1018,7 +1018,7 @@ describe('MCP Routes', () => {
|
||||
oauthUrl: 'https://oauth.example.com/auth',
|
||||
});
|
||||
|
||||
const response = await request(app).post('/api/mcp/oauth-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/oauth-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1043,7 +1043,7 @@ describe('MCP Routes', () => {
|
||||
require('~/cache').getLogStores.mockReturnValue({});
|
||||
require('~/server/services/Tools/mcp').reinitMCPServer.mockResolvedValue(null);
|
||||
|
||||
const response = await request(app).post('/api/mcp/error-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/error-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1061,7 +1061,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
|
||||
const response = await request(app).post('/api/mcp/test-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/test-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Internal server error' });
|
||||
@@ -1074,9 +1074,9 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).post('/api/mcp/test-server/reinitialize');
|
||||
const response = await request(unauthApp).post('/v1/chat/mcp/test-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
@@ -1116,7 +1116,7 @@ describe('MCP Routes', () => {
|
||||
oauthUrl: null,
|
||||
});
|
||||
|
||||
const response = await request(app).post('/api/mcp/test-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/test-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1174,7 +1174,7 @@ describe('MCP Routes', () => {
|
||||
oauthUrl: null,
|
||||
});
|
||||
|
||||
const response = await request(app).post('/api/mcp/test-server/reinitialize');
|
||||
const response = await request(app).post('/v1/chat/mcp/test-server/reinitialize');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.success).toBe(true);
|
||||
@@ -1212,7 +1212,7 @@ describe('MCP Routes', () => {
|
||||
requiresOAuth: true,
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1236,7 +1236,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 404 when MCP config is not found', async () => {
|
||||
getMCPSetupData.mockRejectedValue(new Error('MCP config not found'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({ error: 'MCP config not found' });
|
||||
@@ -1245,7 +1245,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 500 when connection status check fails', async () => {
|
||||
getMCPSetupData.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to get connection status' });
|
||||
@@ -1258,9 +1258,9 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).get('/api/mcp/connection/status');
|
||||
const response = await request(unauthApp).get('/v1/chat/mcp/connection/status');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
@@ -1287,7 +1287,7 @@ describe('MCP Routes', () => {
|
||||
requiresOAuth: true,
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status/oauth-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status/oauth-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1308,7 +1308,7 @@ describe('MCP Routes', () => {
|
||||
oauthServers: [],
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status/non-existent-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status/non-existent-server');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1319,7 +1319,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 404 when MCP config is not found', async () => {
|
||||
getMCPSetupData.mockRejectedValue(new Error('MCP config not found'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status/test-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status/test-server');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({ error: 'MCP config not found' });
|
||||
@@ -1328,7 +1328,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 500 when connection status check fails', async () => {
|
||||
getMCPSetupData.mockRejectedValue(new Error('Database connection failed'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/connection/status/test-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/connection/status/test-server');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to get connection status' });
|
||||
@@ -1341,9 +1341,9 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).get('/api/mcp/connection/status/test-server');
|
||||
const response = await request(unauthApp).get('/v1/chat/mcp/connection/status/test-server');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
@@ -1366,7 +1366,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
getUserPluginAuthValue.mockResolvedValueOnce('some-api-key-value').mockResolvedValueOnce('');
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/auth-values');
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1387,7 +1387,7 @@ describe('MCP Routes', () => {
|
||||
mockRegistryInstance.getServerConfig.mockResolvedValue(null);
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/non-existent-server/auth-values');
|
||||
const response = await request(app).get('/v1/chat/mcp/non-existent-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1406,7 +1406,7 @@ describe('MCP Routes', () => {
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
getUserPluginAuthValue.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/auth-values');
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1426,7 +1426,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/auth-values');
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Failed to check auth value flags' });
|
||||
@@ -1440,7 +1440,7 @@ describe('MCP Routes', () => {
|
||||
});
|
||||
require('~/config').getMCPManager.mockReturnValue(mockMcpManager);
|
||||
|
||||
const response = await request(app).get('/api/mcp/test-server/auth-values');
|
||||
const response = await request(app).get('/v1/chat/mcp/test-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1453,9 +1453,9 @@ describe('MCP Routes', () => {
|
||||
it('should return 401 when user is not authenticated in auth-values endpoint', async () => {
|
||||
const appWithoutAuth = express();
|
||||
appWithoutAuth.use(express.json());
|
||||
appWithoutAuth.use('/api/mcp', mcpRouter);
|
||||
appWithoutAuth.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(appWithoutAuth).get('/api/mcp/test-server/auth-values');
|
||||
const response = await request(appWithoutAuth).get('/v1/chat/mcp/test-server/auth-values');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ error: 'User not authenticated' });
|
||||
@@ -1502,7 +1502,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get(`/api/mcp/test-server/oauth/callback?code=test-code&state=${flowId}`)
|
||||
.get(`/v1/chat/mcp/test-server/oauth/callback?code=test-code&state=${flowId}`)
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.expect(302);
|
||||
|
||||
@@ -1556,7 +1556,7 @@ describe('MCP Routes', () => {
|
||||
const csrfToken = generateTestCsrfToken(flowId);
|
||||
|
||||
const response = await request(app)
|
||||
.get(`/api/mcp/test-server/oauth/callback?code=test-code&state=${flowId}`)
|
||||
.get(`/v1/chat/mcp/test-server/oauth/callback?code=test-code&state=${flowId}`)
|
||||
.set('Cookie', [`oauth_csrf=${csrfToken}`])
|
||||
.expect(302);
|
||||
|
||||
@@ -1583,7 +1583,7 @@ describe('MCP Routes', () => {
|
||||
|
||||
mockRegistryInstance.getAllServerConfigs.mockResolvedValue(mockServerConfigs);
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(mockServerConfigs);
|
||||
@@ -1593,7 +1593,7 @@ describe('MCP Routes', () => {
|
||||
it('should return empty object when no servers are configured', async () => {
|
||||
mockRegistryInstance.getAllServerConfigs.mockResolvedValue({});
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({});
|
||||
@@ -1606,9 +1606,9 @@ describe('MCP Routes', () => {
|
||||
req.user = null;
|
||||
next();
|
||||
});
|
||||
unauthApp.use('/api/mcp', mcpRouter);
|
||||
unauthApp.use('/v1/chat/mcp', mcpRouter);
|
||||
|
||||
const response = await request(unauthApp).get('/api/mcp/servers');
|
||||
const response = await request(unauthApp).get('/v1/chat/mcp/servers');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.body).toEqual({ message: 'Unauthorized' });
|
||||
@@ -1617,7 +1617,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 500 when server config retrieval fails', async () => {
|
||||
mockRegistryInstance.getAllServerConfigs.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Database error' });
|
||||
@@ -1638,7 +1638,7 @@ describe('MCP Routes', () => {
|
||||
config: validConfig,
|
||||
});
|
||||
|
||||
const response = await request(app).post('/api/mcp/servers').send({ config: validConfig });
|
||||
const response = await request(app).post('/v1/chat/mcp/servers').send({ config: validConfig });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body).toEqual({
|
||||
@@ -1664,7 +1664,7 @@ describe('MCP Routes', () => {
|
||||
title: 'Test Stdio Server',
|
||||
};
|
||||
|
||||
const response = await request(app).post('/api/mcp/servers').send({ config: stdioConfig });
|
||||
const response = await request(app).post('/v1/chat/mcp/servers').send({ config: stdioConfig });
|
||||
|
||||
// Stdio transport is not allowed via API - only admins can configure it via YAML
|
||||
expect(response.status).toBe(400);
|
||||
@@ -1678,7 +1678,7 @@ describe('MCP Routes', () => {
|
||||
title: 'Invalid Server',
|
||||
};
|
||||
|
||||
const response = await request(app).post('/api/mcp/servers').send({ config: invalidConfig });
|
||||
const response = await request(app).post('/v1/chat/mcp/servers').send({ config: invalidConfig });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body.message).toBe('Invalid configuration');
|
||||
@@ -1692,7 +1692,7 @@ describe('MCP Routes', () => {
|
||||
title: 'Invalid Protocol Server',
|
||||
};
|
||||
|
||||
const response = await request(app).post('/api/mcp/servers').send({ config: invalidConfig });
|
||||
const response = await request(app).post('/v1/chat/mcp/servers').send({ config: invalidConfig });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body.message).toBe('Invalid configuration');
|
||||
@@ -1707,7 +1707,7 @@ describe('MCP Routes', () => {
|
||||
|
||||
mockRegistryInstance.addServer.mockRejectedValue(new Error('Database connection failed'));
|
||||
|
||||
const response = await request(app).post('/api/mcp/servers').send({ config: validConfig });
|
||||
const response = await request(app).post('/v1/chat/mcp/servers').send({ config: validConfig });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ message: 'Database connection failed' });
|
||||
@@ -1724,7 +1724,7 @@ describe('MCP Routes', () => {
|
||||
|
||||
mockRegistryInstance.getServerConfig.mockResolvedValue(mockConfig);
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers/test-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers/test-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(mockConfig);
|
||||
@@ -1737,7 +1737,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 404 when server not found', async () => {
|
||||
mockRegistryInstance.getServerConfig.mockResolvedValue(null);
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers/non-existent-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers/non-existent-server');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({ message: 'MCP server not found' });
|
||||
@@ -1746,7 +1746,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 500 when registry throws error', async () => {
|
||||
mockRegistryInstance.getServerConfig.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app).get('/api/mcp/servers/error-server');
|
||||
const response = await request(app).get('/v1/chat/mcp/servers/error-server');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ message: 'Database error' });
|
||||
@@ -1765,7 +1765,7 @@ describe('MCP Routes', () => {
|
||||
mockRegistryInstance.updateServer.mockResolvedValue(updatedConfig);
|
||||
|
||||
const response = await request(app)
|
||||
.patch('/api/mcp/servers/test-server')
|
||||
.patch('/v1/chat/mcp/servers/test-server')
|
||||
.send({ config: updatedConfig });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -1789,7 +1789,7 @@ describe('MCP Routes', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch('/api/mcp/servers/test-server')
|
||||
.patch('/v1/chat/mcp/servers/test-server')
|
||||
.send({ config: invalidConfig });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
@@ -1807,7 +1807,7 @@ describe('MCP Routes', () => {
|
||||
mockRegistryInstance.updateServer.mockRejectedValue(new Error('Update failed'));
|
||||
|
||||
const response = await request(app)
|
||||
.patch('/api/mcp/servers/test-server')
|
||||
.patch('/v1/chat/mcp/servers/test-server')
|
||||
.send({ config: validConfig });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
@@ -1819,7 +1819,7 @@ describe('MCP Routes', () => {
|
||||
it('should delete server successfully', async () => {
|
||||
mockRegistryInstance.removeServer.mockResolvedValue(undefined);
|
||||
|
||||
const response = await request(app).delete('/api/mcp/servers/test-server');
|
||||
const response = await request(app).delete('/v1/chat/mcp/servers/test-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ message: 'MCP server deleted successfully' });
|
||||
@@ -1833,7 +1833,7 @@ describe('MCP Routes', () => {
|
||||
it('should return 500 when registry throws error', async () => {
|
||||
mockRegistryInstance.removeServer.mockRejectedValue(new Error('Deletion failed'));
|
||||
|
||||
const response = await request(app).delete('/api/mcp/servers/error-server');
|
||||
const response = await request(app).delete('/v1/chat/mcp/servers/error-server');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ message: 'Deletion failed' });
|
||||
|
||||
@@ -155,7 +155,7 @@ describe('DELETE /:conversationId/:messageId – route handler', () => {
|
||||
req.user = { id: authenticatedUserId };
|
||||
next();
|
||||
});
|
||||
app.use('/api/messages', messagesRouter);
|
||||
app.use('/v1/chat/messages', messagesRouter);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -165,7 +165,7 @@ describe('DELETE /:conversationId/:messageId – route handler', () => {
|
||||
it('should pass user and conversationId in the deleteMessages filter', async () => {
|
||||
deleteMessages.mockResolvedValue({ deletedCount: 1 });
|
||||
|
||||
await request(app).delete('/api/messages/convo-1/msg-1');
|
||||
await request(app).delete('/v1/chat/messages/convo-1/msg-1');
|
||||
|
||||
expect(deleteMessages).toHaveBeenCalledTimes(1);
|
||||
expect(deleteMessages).toHaveBeenCalledWith({
|
||||
@@ -178,7 +178,7 @@ describe('DELETE /:conversationId/:messageId – route handler', () => {
|
||||
it('should return 204 on successful deletion', async () => {
|
||||
deleteMessages.mockResolvedValue({ deletedCount: 1 });
|
||||
|
||||
const response = await request(app).delete('/api/messages/convo-1/msg-owned');
|
||||
const response = await request(app).delete('/v1/chat/messages/convo-1/msg-owned');
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(deleteMessages).toHaveBeenCalledWith({
|
||||
@@ -191,7 +191,7 @@ describe('DELETE /:conversationId/:messageId – route handler', () => {
|
||||
it('should return 500 when deleteMessages throws', async () => {
|
||||
deleteMessages.mockRejectedValue(new Error('DB failure'));
|
||||
|
||||
const response = await request(app).delete('/api/messages/convo-1/msg-1');
|
||||
const response = await request(app).delete('/v1/chat/messages/convo-1/msg-1');
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: 'Internal server error' });
|
||||
@@ -213,7 +213,7 @@ describe('message route conversation ownership filters', () => {
|
||||
req.user = { id: authenticatedUserId };
|
||||
next();
|
||||
});
|
||||
app.use('/api/messages', messagesRouter);
|
||||
app.use('/v1/chat/messages', messagesRouter);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -233,7 +233,7 @@ describe('message route conversation ownership filters', () => {
|
||||
saveMessage.mockResolvedValue(savedMessage);
|
||||
saveConvo.mockResolvedValue({ conversationId: urlConversationId });
|
||||
|
||||
const response = await request(app).post(`/api/messages/${urlConversationId}`).send({
|
||||
const response = await request(app).post(`/v1/chat/messages/${urlConversationId}`).send({
|
||||
messageId: savedMessage.messageId,
|
||||
conversationId: bodyConversationId,
|
||||
text: savedMessage.text,
|
||||
@@ -248,20 +248,20 @@ describe('message route conversation ownership filters', () => {
|
||||
text: savedMessage.text,
|
||||
user: authenticatedUserId,
|
||||
}),
|
||||
{ context: 'POST /api/messages/:conversationId' },
|
||||
{ context: 'POST /v1/chat/messages/:conversationId' },
|
||||
);
|
||||
expect(saveMessage.mock.calls[0][1].conversationId).not.toBe(bodyConversationId);
|
||||
expect(saveConvo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: authenticatedUserId }),
|
||||
savedMessage,
|
||||
{ context: 'POST /api/messages/:conversationId' },
|
||||
{ context: 'POST /v1/chat/messages/:conversationId' },
|
||||
);
|
||||
});
|
||||
|
||||
it('should filter conversation message reads by authenticated user', async () => {
|
||||
getMessages.mockResolvedValue([{ messageId: 'message-1', conversationId: 'convo-1' }]);
|
||||
|
||||
const response = await request(app).get('/api/messages/convo-1');
|
||||
const response = await request(app).get('/v1/chat/messages/convo-1');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(getMessages).toHaveBeenCalledWith(
|
||||
@@ -273,7 +273,7 @@ describe('message route conversation ownership filters', () => {
|
||||
it('should filter single message reads by authenticated user', async () => {
|
||||
getMessages.mockResolvedValue([{ messageId: 'message-1', conversationId: 'convo-1' }]);
|
||||
|
||||
const response = await request(app).get('/api/messages/convo-1/message-1');
|
||||
const response = await request(app).get('/v1/chat/messages/convo-1/message-1');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(getMessages).toHaveBeenCalledWith(
|
||||
|
||||
@@ -28,7 +28,7 @@ function createApp(user) {
|
||||
req.user = user;
|
||||
next();
|
||||
});
|
||||
app.use('/api/roles', rolesRouter);
|
||||
app.use('/v1/chat/roles', rolesRouter);
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -48,12 +48,12 @@ beforeEach(() => {
|
||||
mockGetRoleByName.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
describe('GET /v1/chat/roles/:roleName — isOwnRole authorization', () => {
|
||||
it('allows a custom role user to fetch their own role', async () => {
|
||||
mockGetRoleByName.mockResolvedValue(staffRole);
|
||||
const app = createApp({ id: 'u1', role: 'STAFF' });
|
||||
|
||||
const res = await request(app).get('/api/roles/STAFF');
|
||||
const res = await request(app).get('/v1/chat/roles/STAFF');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.name).toBe('STAFF');
|
||||
@@ -63,7 +63,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
it('returns 403 when a custom role user requests a different custom role', async () => {
|
||||
const app = createApp({ id: 'u1', role: 'STAFF' });
|
||||
|
||||
const res = await request(app).get('/api/roles/MANAGER');
|
||||
const res = await request(app).get('/v1/chat/roles/MANAGER');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(mockGetRoleByName).not.toHaveBeenCalled();
|
||||
@@ -72,7 +72,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
it('returns 403 when a custom role user requests ADMIN', async () => {
|
||||
const app = createApp({ id: 'u1', role: 'STAFF' });
|
||||
|
||||
const res = await request(app).get('/api/roles/ADMIN');
|
||||
const res = await request(app).get('/v1/chat/roles/ADMIN');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(mockGetRoleByName).not.toHaveBeenCalled();
|
||||
@@ -82,7 +82,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
mockGetRoleByName.mockResolvedValue(userRole);
|
||||
const app = createApp({ id: 'u1', role: SystemRoles.USER });
|
||||
|
||||
const res = await request(app).get(`/api/roles/${SystemRoles.USER}`);
|
||||
const res = await request(app).get(`/v1/chat/roles/${SystemRoles.USER}`);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
@@ -90,7 +90,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
it('returns 403 when USER requests the ADMIN role', async () => {
|
||||
const app = createApp({ id: 'u1', role: SystemRoles.USER });
|
||||
|
||||
const res = await request(app).get(`/api/roles/${SystemRoles.ADMIN}`);
|
||||
const res = await request(app).get(`/v1/chat/roles/${SystemRoles.ADMIN}`);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
@@ -100,7 +100,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
mockGetRoleByName.mockResolvedValue(adminRole);
|
||||
const app = createApp({ id: 'u1', role: SystemRoles.ADMIN });
|
||||
|
||||
const res = await request(app).get(`/api/roles/${SystemRoles.ADMIN}`);
|
||||
const res = await request(app).get(`/v1/chat/roles/${SystemRoles.ADMIN}`);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
@@ -110,7 +110,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
mockGetRoleByName.mockResolvedValue(staffRole);
|
||||
const app = createApp({ id: 'u1', role: SystemRoles.USER });
|
||||
|
||||
const res = await request(app).get('/api/roles/STAFF');
|
||||
const res = await request(app).get('/v1/chat/roles/STAFF');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.name).toBe('STAFF');
|
||||
@@ -120,7 +120,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
mockGetRoleByName.mockResolvedValue(null);
|
||||
const app = createApp({ id: 'u1', role: 'GHOST' });
|
||||
|
||||
const res = await request(app).get('/api/roles/GHOST');
|
||||
const res = await request(app).get('/v1/chat/roles/GHOST');
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
@@ -129,7 +129,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
mockGetRoleByName.mockRejectedValue(new Error('db error'));
|
||||
const app = createApp({ id: 'u1', role: SystemRoles.USER });
|
||||
|
||||
const res = await request(app).get(`/api/roles/${SystemRoles.USER}`);
|
||||
const res = await request(app).get(`/v1/chat/roles/${SystemRoles.USER}`);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
@@ -137,7 +137,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
it('returns 403 for prototype property names like constructor (no prototype pollution)', async () => {
|
||||
const app = createApp({ id: 'u1', role: 'STAFF' });
|
||||
|
||||
const res = await request(app).get('/api/roles/constructor');
|
||||
const res = await request(app).get('/v1/chat/roles/constructor');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(mockGetRoleByName).not.toHaveBeenCalled();
|
||||
@@ -148,7 +148,7 @@ describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
|
||||
const app = createApp({ id: 'u1', role: 'STAFF' });
|
||||
mockGetRoleByName.mockResolvedValue(staffRole);
|
||||
|
||||
const res = await request(app).get('/api/roles/STAFF');
|
||||
const res = await request(app).get('/v1/chat/roles/STAFF');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
@@ -64,7 +64,7 @@ const buildApp = ({ retentionMode = RetentionMode.TEMPORARY } = {}) => {
|
||||
req.config = { interfaceConfig: { retentionMode } };
|
||||
next();
|
||||
});
|
||||
app.use('/api/share', shareRouter);
|
||||
app.use('/v1/chat/share', shareRouter);
|
||||
return app;
|
||||
};
|
||||
|
||||
@@ -78,7 +78,7 @@ describe('share routes retention', () => {
|
||||
createSharedLink.mockResolvedValue({ shareId: 'share-123' });
|
||||
|
||||
const response = await request(buildApp())
|
||||
.post('/api/share/convo-123')
|
||||
.post('/v1/chat/share/convo-123')
|
||||
.send({ targetMessageId: 'msg-123' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -113,7 +113,7 @@ describe('share routes retention', () => {
|
||||
createSharedLink.mockResolvedValue({ shareId: 'share-123' });
|
||||
|
||||
const response = await request(buildApp())
|
||||
.post('/api/share/convo-123')
|
||||
.post('/v1/chat/share/convo-123')
|
||||
.send({ targetMessageId: 'msg-123' });
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
@@ -125,7 +125,7 @@ describe('share routes retention', () => {
|
||||
createSharedLink.mockResolvedValue({ shareId: 'share-123' });
|
||||
|
||||
const response = await request(buildApp({ retentionMode: RetentionMode.ALL }))
|
||||
.post('/api/share/convo-123')
|
||||
.post('/v1/chat/share/convo-123')
|
||||
.send({ targetMessageId: 'msg-123' });
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
@@ -137,7 +137,7 @@ describe('share routes retention', () => {
|
||||
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp()).patch('/api/share/share-123');
|
||||
const response = await request(buildApp()).patch('/v1/chat/share/share-123');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mongoose.models.SharedLink.findOne).toHaveBeenCalledWith(
|
||||
@@ -169,7 +169,7 @@ describe('share routes retention', () => {
|
||||
mockGetSharedLinkExpiration.mockResolvedValue(expiredExpiration);
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp()).patch('/api/share/share-123');
|
||||
const response = await request(buildApp()).patch('/v1/chat/share/share-123');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(updateSharedLink).not.toHaveBeenCalled();
|
||||
@@ -181,7 +181,7 @@ describe('share routes retention', () => {
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp({ retentionMode: RetentionMode.ALL })).patch(
|
||||
'/api/share/share-123',
|
||||
'/v1/chat/share/share-123',
|
||||
);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
@@ -197,7 +197,7 @@ describe('share routes retention', () => {
|
||||
mockGetSharedLinkExpiration.mockResolvedValue(null);
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp()).patch('/api/share/share-123');
|
||||
const response = await request(buildApp()).patch('/v1/chat/share/share-123');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(updateSharedLink).toHaveBeenCalledWith('user-123', 'share-123', undefined, null);
|
||||
@@ -208,7 +208,7 @@ describe('share routes retention', () => {
|
||||
mockGetSharedLinkExpiration.mockResolvedValue(undefined);
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp()).patch('/api/share/share-123');
|
||||
const response = await request(buildApp()).patch('/v1/chat/share/share-123');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(updateSharedLink).toHaveBeenCalledWith('user-123', 'share-123', undefined, undefined);
|
||||
@@ -223,7 +223,7 @@ describe('share routes retention', () => {
|
||||
});
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
|
||||
|
||||
const response = await request(buildApp()).patch('/api/share/share-123');
|
||||
const response = await request(buildApp()).patch('/v1/chat/share/share-123');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
@@ -239,7 +239,7 @@ describe('share routes retention', () => {
|
||||
updateSharedLink.mockResolvedValue({ shareId: 'share-456', targetMessageId: 'msg-456' });
|
||||
|
||||
const response = await request(buildApp())
|
||||
.patch('/api/share/share-123')
|
||||
.patch('/v1/chat/share/share-123')
|
||||
.send({ targetMessageId: 'msg-456' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -253,7 +253,7 @@ describe('share routes retention', () => {
|
||||
|
||||
it('rejects non-string target message updates', async () => {
|
||||
const response = await request(buildApp())
|
||||
.patch('/api/share/share-123')
|
||||
.patch('/v1/chat/share/share-123')
|
||||
.send({ targetMessageId: 123 });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
|
||||
@@ -22,17 +22,17 @@ router.use(uaParser);
|
||||
|
||||
/**
|
||||
* Generic routes for resource permissions
|
||||
* Pattern: /api/permissions/{resourceType}/{resourceId}
|
||||
* Pattern: /v1/chat/permissions/{resourceType}/{resourceId}
|
||||
*/
|
||||
|
||||
/**
|
||||
* GET /api/permissions/search-principals
|
||||
* GET /v1/chat/permissions/search-principals
|
||||
* Search for users and groups to grant permissions
|
||||
*/
|
||||
router.get('/search-principals', checkPeoplePickerAccess, searchPrincipals);
|
||||
|
||||
/**
|
||||
* GET /api/permissions/{resourceType}/roles
|
||||
* GET /v1/chat/permissions/{resourceType}/roles
|
||||
* Get available roles for a resource type
|
||||
*/
|
||||
router.get('/:resourceType/roles', getResourceRoles);
|
||||
@@ -84,7 +84,7 @@ const checkResourcePermissionAccess = (requiredPermission) => (req, res, next) =
|
||||
};
|
||||
|
||||
/**
|
||||
* GET /api/permissions/{resourceType}/{resourceId}
|
||||
* GET /v1/chat/permissions/{resourceType}/{resourceId}
|
||||
* Get all permissions for a specific resource
|
||||
* SECURITY: Requires SHARE permission to view resource permissions
|
||||
*/
|
||||
@@ -95,7 +95,7 @@ router.get(
|
||||
);
|
||||
|
||||
/**
|
||||
* PUT /api/permissions/{resourceType}/{resourceId}
|
||||
* PUT /v1/chat/permissions/{resourceType}/{resourceId}
|
||||
* Bulk update permissions for a specific resource
|
||||
* SECURITY: Requires SHARE permission to modify resource permissions
|
||||
* SECURITY: Requires SHARE_PUBLIC permission to enable public sharing
|
||||
@@ -108,13 +108,13 @@ router.put(
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/permissions/{resourceType}/effective/all
|
||||
* GET /v1/chat/permissions/{resourceType}/effective/all
|
||||
* Get user's effective permissions for all accessible resources of a type
|
||||
*/
|
||||
router.get('/:resourceType/effective/all', getAllEffectivePermissions);
|
||||
|
||||
/**
|
||||
* GET /api/permissions/{resourceType}/{resourceId}/effective
|
||||
* GET /v1/chat/permissions/{resourceType}/{resourceId}/effective
|
||||
* Get user's effective permissions for a specific resource
|
||||
*/
|
||||
router.get('/:resourceType/:resourceId/effective', getUserEffectivePermissions);
|
||||
|
||||
@@ -126,7 +126,7 @@ describe('Access permissions share policy', () => {
|
||||
req.user = { id: 'skill-owner', role: SystemRoles.USER };
|
||||
next();
|
||||
});
|
||||
app.use('/api/permissions', accessPermissionsRouter);
|
||||
app.use('/v1/chat/permissions', accessPermissionsRouter);
|
||||
});
|
||||
|
||||
it.each(sharePolicyCases)(
|
||||
@@ -142,7 +142,7 @@ describe('Access permissions share policy', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/api/permissions/${resourceType}/${resourceId}`)
|
||||
.put(`/v1/chat/permissions/${resourceType}/${resourceId}`)
|
||||
.send({ updated: [createUpdatedPrincipal(accessRoleId)], public: false });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
@@ -166,7 +166,7 @@ describe('Access permissions share policy', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/api/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.put(`/v1/chat/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.send({ updated: [createUpdatedPrincipal(AccessRoleIds.SKILL_VIEWER)], public: false });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -178,7 +178,7 @@ describe('Access permissions share policy', () => {
|
||||
hasCapability.mockResolvedValue(true);
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/api/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.put(`/v1/chat/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.send({ updated: [createUpdatedPrincipal(AccessRoleIds.SKILL_VIEWER)], public: false });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -198,7 +198,7 @@ describe('Access permissions share policy', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/api/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.put(`/v1/chat/permissions/${ResourceType.SKILL}/${resourceId}`)
|
||||
.send({ public: true, publicAccessRoleId: AccessRoleIds.SKILL_VIEWER });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
|
||||
@@ -19,7 +19,7 @@ const { getLogStores } = require('~/cache');
|
||||
|
||||
const router = express.Router();
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
const OAUTH_CSRF_COOKIE_PATH = '/api/actions';
|
||||
const OAUTH_CSRF_COOKIE_PATH = '/v1/chat/actions';
|
||||
|
||||
/**
|
||||
* Sets a CSRF cookie binding the action OAuth flow to the current browser session.
|
||||
|
||||
@@ -80,7 +80,7 @@ const EXCHANGE_CODE_PATTERN = /^[a-f0-9]{64}$/i;
|
||||
* This endpoint is called server-to-server by the admin panel.
|
||||
* The code is one-time-use and expires in 30 seconds.
|
||||
*
|
||||
* POST /api/admin/oauth/exchange
|
||||
* POST /v1/chat/admin/oauth/exchange
|
||||
* Body: { code: string }
|
||||
* Response: { token: string, refreshToken: string, user: object }
|
||||
*/
|
||||
|
||||
@@ -134,7 +134,7 @@ describe('admin auth OpenID refresh route', () => {
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
app.use('/v1/chat/admin', adminAuthRouter);
|
||||
|
||||
isEnabled.mockReturnValue(true);
|
||||
getOpenIdConfig.mockReturnValue(openIdConfig);
|
||||
@@ -187,7 +187,7 @@ describe('admin auth OpenID refresh route', () => {
|
||||
Object.assign(process.env, env);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.post('/v1/chat/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-refresh-token' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -211,7 +211,7 @@ describe('admin auth OpenID refresh route', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.post('/v1/chat/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-refresh-token' });
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
@@ -227,7 +227,7 @@ describe('admin auth OpenID refresh route', () => {
|
||||
process.env.OPENID_REFRESH_AUDIENCE = 'https://api.example.com';
|
||||
|
||||
await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.post('/v1/chat/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-refresh-token' });
|
||||
|
||||
expect(logger.debug).toHaveBeenCalledWith('[admin/oauth/refresh] OpenID refresh params', {
|
||||
|
||||
@@ -69,7 +69,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
beforeAll(() => {
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/agents', agentRoutes);
|
||||
app.use('/v1/chat/agents', agentRoutes);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -86,7 +86,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
@@ -112,7 +112,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -135,7 +135,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -163,7 +163,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -189,7 +189,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -224,7 +224,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
mockSaveMessage.mockResolvedValue();
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -271,7 +271,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
mockSaveMessage.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: jobStreamId });
|
||||
|
||||
// Should still return success even if save fails
|
||||
@@ -289,7 +289,7 @@ describe('Agent Abort Endpoint', () => {
|
||||
mockGenerationJobManager.getActiveJobIdsForUser.mockResolvedValue([]);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/agents/chat/abort')
|
||||
.post('/v1/chat/agents/chat/abort')
|
||||
.send({ conversationId: 'non-existent-job' });
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
jest.mock('@librechat/data-schemas', () => ({
|
||||
logger: { debug: jest.fn(), error: jest.fn(), info: jest.fn(), warn: jest.fn() },
|
||||
}));
|
||||
|
||||
// The proxy keys the on-behalf-of decision off the VALIDATED principal
|
||||
// (`req.user.provider`), not a cookie. requireJwtAuth is exercised elsewhere;
|
||||
// here it simply installs the principal under test so the token-resolution +
|
||||
// honest-error logic is isolated. Set `mockPrincipal` per test (the `mock`
|
||||
// prefix is required for a jest.mock factory to reference it).
|
||||
let mockPrincipal;
|
||||
jest.mock('~/server/middleware', () => ({
|
||||
requireJwtAuth: (req, _res, next) => {
|
||||
req.user = mockPrincipal;
|
||||
next();
|
||||
},
|
||||
// Rate limiter is exercised in its own layer; here it is a pass-through so the
|
||||
// proxy logic (token resolution, honest errors, name guard) is under test.
|
||||
cloudAgentLimiter: (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
const mockClient = {
|
||||
list: jest.fn(),
|
||||
get: jest.fn(),
|
||||
run: jest.fn(),
|
||||
};
|
||||
jest.mock('~/server/services/CloudAgentsClient', () => ({
|
||||
getCloudAgentsClient: jest.fn(() => mockClient),
|
||||
// Boundary name validation in the route uses the real grammar.
|
||||
AGENT_NAME_RE: /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,
|
||||
}));
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const { getCloudAgentsClient } = require('~/server/services/CloudAgentsClient');
|
||||
const cloudRouter = require('../cloud');
|
||||
|
||||
const OPENID_SUB = 'sub-abc-123';
|
||||
const OPENID_USER = { id: 'u_openid', provider: 'openid', openidId: OPENID_SUB };
|
||||
const LOCAL_USER = { id: 'u_local', provider: 'local' };
|
||||
|
||||
/**
|
||||
* Mint a decodable id_token. The signature is irrelevant to the proxy — it
|
||||
* decode-only checks `exp` + `sub`; cloud performs the authoritative JWKS
|
||||
* validation. So a throwaway secret is exactly right here.
|
||||
*/
|
||||
function mintIdToken({ sub = OPENID_SUB, exp = Math.floor(Date.now() / 1000) + 3600 } = {}) {
|
||||
return jwt.sign({ sub, exp }, 'test-only-not-verified');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an app whose session carries (or omits) the OpenID tokens the proxy
|
||||
* forwards to cloud. The authenticated principal is `mockPrincipal` (default: an
|
||||
* OpenID user); `cookie` models the httpOnly no-session fallback.
|
||||
*/
|
||||
function buildApp(session, cookie) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.session = session;
|
||||
if (cookie != null && req.headers.cookie == null) {
|
||||
req.headers.cookie = cookie;
|
||||
}
|
||||
next();
|
||||
});
|
||||
app.use('/v1/chat/agents/cloud', cloudRouter);
|
||||
return app;
|
||||
}
|
||||
|
||||
const VALID_ID = mintIdToken();
|
||||
const withToken = { openidTokens: { idToken: VALID_ID, accessToken: 'ACC' } };
|
||||
|
||||
describe('cloud agents proxy route', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockPrincipal = OPENID_USER;
|
||||
getCloudAgentsClient.mockReturnValue(mockClient);
|
||||
});
|
||||
|
||||
describe('token handling (no leak, fail-secure)', () => {
|
||||
it('401s when the openid principal has no hanzo.id session token', async () => {
|
||||
const res = await request(buildApp({})).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forwards the session id_token (never the browser) to cloud', async () => {
|
||||
mockClient.list.mockResolvedValue({ agents: [{ name: 'researcher' }] });
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockClient.list).toHaveBeenCalledWith(VALID_ID);
|
||||
expect(res.body).toEqual({ agents: [{ name: 'researcher' }], enabled: true });
|
||||
});
|
||||
|
||||
it('falls back to a principal-bound access_token JWT when there is no id_token', async () => {
|
||||
mockClient.list.mockResolvedValue({ agents: [] });
|
||||
// hanzo.id issues JWT access tokens too; the fallback stays principal-bound.
|
||||
const accJwt = mintIdToken();
|
||||
const app = buildApp({ openidTokens: { accessToken: accJwt } });
|
||||
await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(mockClient.list).toHaveBeenCalledWith(accJwt);
|
||||
});
|
||||
|
||||
it('401s (never forwards) an opaque access_token that cannot be principal-bound', async () => {
|
||||
// A non-JWT access_token has no `sub` to bind against — fail-secure, do not
|
||||
// forward. (This is the path a selective `openid_access_token` cookie
|
||||
// injection would take; the binding requirement closes it.)
|
||||
const app = buildApp({ openidTokens: { accessToken: 'OPAQUE_NO_BINDING' } });
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('401s (never forwards) an access_token JWT that names a different principal', async () => {
|
||||
const foreignAcc = mintIdToken({ sub: 'sub-someone-else' });
|
||||
const app = buildApp({ openidTokens: { accessToken: foreignAcc } });
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reads the httpOnly openid_id_token cookie when the session is empty', async () => {
|
||||
mockClient.list.mockResolvedValue({ agents: [] });
|
||||
const app = buildApp({}, `openid_id_token=${VALID_ID}`);
|
||||
await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(mockClient.list).toHaveBeenCalledWith(VALID_ID);
|
||||
});
|
||||
});
|
||||
|
||||
describe('honest expiry + principal binding (never a fabricated session)', () => {
|
||||
it('honest 401 when the id_token is past its own exp (no forward)', async () => {
|
||||
const expired = mintIdToken({ exp: Math.floor(Date.now() / 1000) - 60 });
|
||||
const app = buildApp({ openidTokens: { idToken: expired } });
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('honest 401 when the id_token names a different principal (sub mismatch)', async () => {
|
||||
const foreign = mintIdToken({ sub: 'sub-someone-else' });
|
||||
const app = buildApp({ openidTokens: { idToken: foreign } });
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('honest 401 when the id_token is not a decodable JWT', async () => {
|
||||
const app = buildApp({ openidTokens: { idToken: 'not-a-jwt' } });
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('principal guard (no confused deputy)', () => {
|
||||
it('401s and forwards nothing for a LOCAL principal, even with a valid openid session', async () => {
|
||||
// A local-JWT user whose browser still holds a valid prior openid session.
|
||||
// Forwarding those tokens would run as the wrong principal — deny at the
|
||||
// identity layer (req.user.provider), independent of any cookie.
|
||||
mockPrincipal = LOCAL_USER;
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('401s for a principal that carries no provider', async () => {
|
||||
mockPrincipal = { id: 'u_unknown' };
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('401s for an openid principal with no openidId to bind against (no fail-open)', async () => {
|
||||
// provider==='openid' but the record has no openidId: the binding cannot be
|
||||
// asserted, so NO token is forwarded — even one whose sub would have matched
|
||||
// a normal user. Fail-secure closes the null-binding gap.
|
||||
mockPrincipal = { id: 'u_openid_no_sub', provider: 'openid' };
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('401s when a foreign id_token is injected via cookie with an empty session (confused-deputy denied)', async () => {
|
||||
// Attacker pairs their own openid app-token (req.user) with a victim's
|
||||
// id_token in the openid_id_token cookie and an empty session. The sub
|
||||
// binding rejects it — the forwarded principal can only ever be req.user.
|
||||
const foreign = mintIdToken({ sub: 'victim-sub-xyz' });
|
||||
const app = buildApp({}, `openid_id_token=${foreign}`);
|
||||
const res = await request(app).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockClient.list).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('disabled deployment', () => {
|
||||
it('returns an empty, disabled list when cloud agents are not configured', async () => {
|
||||
getCloudAgentsClient.mockReturnValue(null);
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ agents: [], enabled: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('run', () => {
|
||||
it('forwards {input} and returns the RunResult', async () => {
|
||||
mockClient.run.mockResolvedValue({ id: 'run_1', status: 'ok', output: 'done' });
|
||||
const res = await request(buildApp(withToken))
|
||||
.post('/v1/chat/agents/cloud/researcher/run')
|
||||
.send({ input: 'summarize' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockClient.run).toHaveBeenCalledWith(VALID_ID, 'researcher', 'summarize');
|
||||
expect(res.body.output).toBe('done');
|
||||
});
|
||||
|
||||
it('surfaces an upstream error body with its status (honest failure)', async () => {
|
||||
const err = Object.assign(new Error('bad gateway'), {
|
||||
status: 502,
|
||||
body: { status: 'error', error: 'model down' },
|
||||
});
|
||||
mockClient.run.mockRejectedValue(err);
|
||||
const res = await request(buildApp(withToken))
|
||||
.post('/v1/chat/agents/cloud/researcher/run')
|
||||
.send({ input: 'x' });
|
||||
expect(res.status).toBe(502);
|
||||
expect(res.body).toEqual({ status: 'error', error: 'model down' });
|
||||
});
|
||||
|
||||
it('maps a client-side validation error (bad name) to 400', async () => {
|
||||
const err = Object.assign(new Error('invalid agent name'), { status: 400 });
|
||||
mockClient.run.mockRejectedValue(err);
|
||||
const res = await request(buildApp(withToken))
|
||||
.post('/v1/chat/agents/cloud/researcher/run')
|
||||
.send({ input: 'x' });
|
||||
// simulate the client rejecting after the boundary let a valid name through
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boundary name validation (traversal / injection guard)', () => {
|
||||
// Each decodes (per Express) to a value outside cloud's handle grammar; the
|
||||
// route must reject at the boundary BEFORE constructing any client call.
|
||||
const smuggles = [
|
||||
'..%2Fetc', // -> ../etc
|
||||
'%2e%2e%2fadmin', // -> ../admin
|
||||
'..%5Cevil', // -> ..\evil
|
||||
'a%00b', // -> null byte
|
||||
'a%0dHost', // -> CR injection
|
||||
'a%20b', // -> space
|
||||
];
|
||||
for (const name of smuggles) {
|
||||
it(`rejects "${name}" with 400 and never calls the client`, async () => {
|
||||
const res = await request(buildApp(withToken))
|
||||
.post(`/v1/chat/agents/cloud/${name}/run`)
|
||||
.send({ input: 'x' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockClient.run).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
|
||||
it('rejects a bad name on GET /:name too', async () => {
|
||||
const res = await request(buildApp(withToken)).get('/v1/chat/agents/cloud/..%2Fetc');
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockClient.get).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -411,7 +411,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
// Mount the responses routes
|
||||
const responsesRoutes = require('~/server/routes/agents/responses');
|
||||
app.use('/api/agents/v1/responses', responsesRoutes);
|
||||
app.use('/v1/chat/agents/v1/responses', responsesRoutes);
|
||||
|
||||
// Create test user
|
||||
testUser = await User.create({
|
||||
@@ -531,7 +531,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
describe('basic-response', () => {
|
||||
it('should return a valid ResponseResource for a simple text request', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -570,7 +570,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
describe('streaming-response', () => {
|
||||
it('should return valid SSE streaming events', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -642,7 +642,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
it('should emit valid event types per Open Responses spec', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -679,7 +679,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
it('should include logprobs array in output_text events', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -736,7 +736,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
// gets merged into the system prompt, or we test with a simple user message
|
||||
// that instructs the behavior.
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -762,7 +762,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
describe('multi-turn', () => {
|
||||
it('should handle multi-turn conversation history', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: testAgent.id,
|
||||
input: [
|
||||
@@ -802,7 +802,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
describe('string-input', () => {
|
||||
it('should accept simple string input', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: testAgent.id,
|
||||
input: 'Hello!',
|
||||
});
|
||||
@@ -822,7 +822,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
describe('Extended Thinking', () => {
|
||||
it('should return reasoning output when thinking is enabled', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: thinkingAgent.id,
|
||||
input: [
|
||||
@@ -863,7 +863,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
it('should stream reasoning events when thinking is enabled', async () => {
|
||||
const response = await authRequest()
|
||||
.post('/api/agents/v1/responses')
|
||||
.post('/v1/chat/agents/v1/responses')
|
||||
.send({
|
||||
model: thinkingAgent.id,
|
||||
input: [
|
||||
@@ -938,7 +938,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
describe('Schema Validation', () => {
|
||||
it('should include all required fields in response', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: testAgent.id,
|
||||
input: 'Test',
|
||||
});
|
||||
@@ -984,7 +984,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should have valid message item structure', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: testAgent.id,
|
||||
input: 'Hello',
|
||||
});
|
||||
@@ -1034,7 +1034,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
describe('Response Storage', () => {
|
||||
it('should store response when store: true and retrieve it', async () => {
|
||||
// Create a stored response
|
||||
const createResponse = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const createResponse = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: testAgent.id,
|
||||
input: 'Remember this: The answer is 42.',
|
||||
store: true,
|
||||
@@ -1050,7 +1050,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Retrieve the stored response
|
||||
const getResponseResult = await authRequest().get(`/api/agents/v1/responses/${responseId}`);
|
||||
const getResponseResult = await authRequest().get(`/v1/chat/agents/v1/responses/${responseId}`);
|
||||
|
||||
// Note: The response might be stored under conversationId, not responseId
|
||||
// If we get 404, that's expected behavior for now since we store by conversationId
|
||||
@@ -1062,7 +1062,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should return 404 for non-existent response', async () => {
|
||||
const response = await authRequest().get('/api/agents/v1/responses/resp_nonexistent123');
|
||||
const response = await authRequest().get('/v1/chat/agents/v1/responses/resp_nonexistent123');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body.error).toBeDefined();
|
||||
@@ -1075,7 +1075,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should return error for missing model', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
input: 'Hello',
|
||||
});
|
||||
|
||||
@@ -1084,7 +1084,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should return error for missing input', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: testAgent.id,
|
||||
});
|
||||
|
||||
@@ -1093,7 +1093,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should return error for non-existent agent', async () => {
|
||||
const response = await authRequest().post('/api/agents/v1/responses').send({
|
||||
const response = await authRequest().post('/v1/chat/agents/v1/responses').send({
|
||||
model: 'agent_nonexistent123456789',
|
||||
input: 'Hello',
|
||||
});
|
||||
@@ -1109,7 +1109,7 @@ describeWithApiKey('Open Responses API Integration Tests', () => {
|
||||
|
||||
describe('GET /v1/responses/models', () => {
|
||||
it('should list available agents as models', async () => {
|
||||
const response = await authRequest().get('/api/agents/v1/responses/models');
|
||||
const response = await authRequest().get('/v1/chat/agents/v1/responses/models');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.object).toBe('list');
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
const cookies = require('cookie');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const express = require('express');
|
||||
const { logger } = require('@librechat/data-schemas');
|
||||
const { requireJwtAuth, cloudAgentLimiter } = require('~/server/middleware');
|
||||
const { getCloudAgentsClient, AGENT_NAME_RE } = require('~/server/services/CloudAgentsClient');
|
||||
|
||||
/**
|
||||
* Cloud agents router — lets a signed-in chat user RUN their own canonical Hanzo
|
||||
* Cloud agents (`/v1/agents`) from the chat thread. Mounted at `/v1/chat/agents/cloud`.
|
||||
*
|
||||
* GET /v1/chat/agents/cloud list the caller's cloud agents
|
||||
* GET /v1/chat/agents/cloud/:name one agent's detail + recent runs
|
||||
* POST /v1/chat/agents/cloud/:name/run run the agent {input} -> RunResult
|
||||
*
|
||||
* Auth: `requireJwtAuth` gates every route (guests are rejected). The chat
|
||||
* backend then forwards the user's hanzo.id id_token to cloud as a Bearer;
|
||||
* cloud validates it and scopes to the user's org (see CloudAgentsClient). The
|
||||
* token is read from the server-side session and NEVER returned to the browser.
|
||||
*/
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* Is this token safe to forward on-behalf-of `user`? Fail-secure gates, ALL
|
||||
* mandatory — the function only ever REMOVES a token from consideration, never
|
||||
* admits one:
|
||||
* - Decodable JWT: an opaque/garbage token cannot be principal-bound, so it is
|
||||
* never forwarded. hanzo.id — the only cloud IdP — always issues JWTs.
|
||||
* - Principal binding (MANDATORY): the token must NAME the authenticated user
|
||||
* (`sub === user.openidId`). If we cannot ASSERT the binding — no `openidId`
|
||||
* on the principal, no `sub` on the token, or a mismatch — we do NOT forward.
|
||||
* This keeps "forwarded principal == req.user" true by construction, closing
|
||||
* the credential-mixing confused deputy (a session/cookie carrying a
|
||||
* different user's token) with no fail-open when binding data is absent.
|
||||
* - Expiry: never forward a token past its own `exp`.
|
||||
*
|
||||
* Decode-only (no signature verification): cloud performs the authoritative
|
||||
* JWKS + claim validation over the SAME claims, so it runs as exactly this
|
||||
* `sub`. A forged/tampered token gains nothing here — changing `sub` fails the
|
||||
* binding; an intact `sub` is rejected by cloud on signature.
|
||||
*
|
||||
* @param {string|undefined} token
|
||||
* @param {{openidId?: string}} user
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isForwardableToken(token, user) {
|
||||
if (!token || !user?.openidId) {
|
||||
return false;
|
||||
}
|
||||
const claims = jwt.decode(token);
|
||||
if (!claims || typeof claims !== 'object') {
|
||||
return false;
|
||||
}
|
||||
if (claims.sub !== user.openidId) {
|
||||
return false;
|
||||
}
|
||||
if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the caller's hanzo.id bearer for the on-behalf-of call to cloud.
|
||||
*
|
||||
* Keyed off the VALIDATED principal (`req.user.provider === 'openid'` — the
|
||||
* authoritative DB user loaded by requireJwtAuth), NOT any cookie. A local user
|
||||
* never carries a hanzo.id token, so a stale OpenID session left in the browser
|
||||
* can never be forwarded under a local identity — the confused deputy is denied
|
||||
* at the identity layer.
|
||||
*
|
||||
* EVERY candidate — session first, then the httpOnly no-session cookie fallback;
|
||||
* id_token preferred, access_token second — must pass `isForwardableToken`:
|
||||
* principal-bound to req.user and unexpired. Returns null — for an honest 401,
|
||||
* never a wrong-principal, expired, unbound, or fabricated call — otherwise.
|
||||
*
|
||||
* @param {import('express').Request} req
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function getUserCloudBearer(req) {
|
||||
if (req.user?.provider !== 'openid') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = req.headers.cookie ? cookies.parse(req.headers.cookie) : {};
|
||||
const session = req.session?.openidTokens;
|
||||
|
||||
const idToken = session?.idToken || parsed.openid_id_token;
|
||||
if (isForwardableToken(idToken, req.user)) {
|
||||
return idToken;
|
||||
}
|
||||
/**
|
||||
* access_token fallback (rare: the session/cookie carries no id_token).
|
||||
* hanzo.id issues JWT access tokens too, so this stays principal-bound; an
|
||||
* opaque or foreign access_token fails the gate and is never forwarded.
|
||||
*/
|
||||
const accessToken = session?.accessToken || parsed.openid_access_token;
|
||||
if (isForwardableToken(accessToken, req.user)) {
|
||||
return accessToken;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
router.use(requireJwtAuth);
|
||||
|
||||
/**
|
||||
* Per-user rate limit. A run is a real, billable cloud completion holding an
|
||||
* upstream socket; without this it escapes the throttle that guards the sibling
|
||||
* chat-completion path. Applies to every cloud route (list/get/run) so no proxy
|
||||
* op can be looped to degrade the shared backend. Runs after requireJwtAuth so
|
||||
* the limiter keys on a real user id.
|
||||
*/
|
||||
router.use(cloudAgentLimiter);
|
||||
|
||||
/**
|
||||
* Validate the :name path segment at the HTTP boundary — the same cloud handle
|
||||
* grammar the client enforces, applied here so a malformed/decoded name
|
||||
* (traversal, null byte, CRLF, backslash) is rejected before any client call is
|
||||
* even constructed. Defense at the boundary, not only in the client.
|
||||
*/
|
||||
router.param('name', (req, res, next, name) => {
|
||||
if (!AGENT_NAME_RE.test((name ?? '').toString().trim())) {
|
||||
return res.status(400).json({ error: 'invalid agent name' });
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
/**
|
||||
* Map a CloudAgentsClient error to an HTTP response. Upstream failures that
|
||||
* carry a run body (cloud's 502 with a recorded error run) are passed through so
|
||||
* the client can render the honest failure; everything else is normalized.
|
||||
* @param {import('express').Response} res
|
||||
* @param {Error & {status?: number, body?: any}} err
|
||||
* @param {string} action
|
||||
*/
|
||||
function sendCloudError(res, err, action) {
|
||||
const status = err.status && err.status >= 400 && err.status < 600 ? err.status : 502;
|
||||
if (status >= 500) {
|
||||
logger.warn(`[cloudAgents] ${action} failed`, { status, message: err.message });
|
||||
}
|
||||
if (err.body && typeof err.body === 'object') {
|
||||
return res.status(status).json(err.body);
|
||||
}
|
||||
return res.status(status).json({ error: err.message || 'cloud agents request failed' });
|
||||
}
|
||||
|
||||
/** GET /v1/chat/agents/cloud — list the caller's cloud agents. */
|
||||
router.get('/', async (req, res) => {
|
||||
const client = getCloudAgentsClient();
|
||||
if (!client) {
|
||||
return res.json({ agents: [], enabled: false });
|
||||
}
|
||||
const bearer = getUserCloudBearer(req);
|
||||
if (!bearer) {
|
||||
return res.status(401).json({ error: 'cloud agents require hanzo.id sign-in' });
|
||||
}
|
||||
try {
|
||||
const data = await client.list(bearer);
|
||||
return res.json({ ...data, enabled: true });
|
||||
} catch (err) {
|
||||
return sendCloudError(res, err, 'list');
|
||||
}
|
||||
});
|
||||
|
||||
/** GET /v1/chat/agents/cloud/:name — one agent's detail + recent runs. */
|
||||
router.get('/:name', async (req, res) => {
|
||||
const client = getCloudAgentsClient();
|
||||
if (!client) {
|
||||
return res.status(404).json({ error: 'cloud agents not configured' });
|
||||
}
|
||||
const bearer = getUserCloudBearer(req);
|
||||
if (!bearer) {
|
||||
return res.status(401).json({ error: 'cloud agents require hanzo.id sign-in' });
|
||||
}
|
||||
try {
|
||||
const data = await client.get(bearer, req.params.name);
|
||||
return res.json(data);
|
||||
} catch (err) {
|
||||
return sendCloudError(res, err, 'get');
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /v1/chat/agents/cloud/:name/run — run the agent, return its RunResult. */
|
||||
router.post('/:name/run', async (req, res) => {
|
||||
const client = getCloudAgentsClient();
|
||||
if (!client) {
|
||||
return res.status(404).json({ error: 'cloud agents not configured' });
|
||||
}
|
||||
const bearer = getUserCloudBearer(req);
|
||||
if (!bearer) {
|
||||
return res.status(401).json({ error: 'cloud agents require hanzo.id sign-in' });
|
||||
}
|
||||
try {
|
||||
const run = await client.run(bearer, req.params.name, req.body?.input ?? '');
|
||||
return res.json(run);
|
||||
} catch (err) {
|
||||
return sendCloudError(res, err, 'run');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -16,6 +16,7 @@ const { saveMessage } = require('~/models');
|
||||
const openai = require('./openai');
|
||||
const responses = require('./responses');
|
||||
const { v1 } = require('./v1');
|
||||
const cloud = require('./cloud');
|
||||
const chat = require('./chat');
|
||||
|
||||
const { LIMIT_MESSAGE_IP, LIMIT_MESSAGE_USER } = process.env ?? {};
|
||||
@@ -24,7 +25,7 @@ const router = express.Router();
|
||||
|
||||
/**
|
||||
* Open Responses API routes (API key authentication handled in route file)
|
||||
* Mounted at /agents/v1/responses (full path: /api/agents/v1/responses)
|
||||
* Mounted at /agents/v1/responses (full path: /v1/chat/agents/v1/responses)
|
||||
* NOTE: Must be mounted BEFORE /v1 to avoid being caught by the less specific route
|
||||
* @see https://openresponses.org/specification
|
||||
*/
|
||||
@@ -32,7 +33,7 @@ router.use('/v1/responses', responses);
|
||||
|
||||
/**
|
||||
* OpenAI-compatible API routes (API key authentication handled in route file)
|
||||
* Mounted at /agents/v1 (full path: /api/agents/v1/chat/completions)
|
||||
* Mounted at /agents/v1 (full path: /v1/chat/agents/v1/chat/completions)
|
||||
*/
|
||||
router.use('/v1', openai);
|
||||
|
||||
@@ -98,6 +99,14 @@ router.use(requireJwtAuth);
|
||||
router.use(checkBan);
|
||||
router.use(uaParser);
|
||||
|
||||
/**
|
||||
* Canonical Hanzo Cloud agents (`/v1/agents`). Mounted BEFORE the legacy `/`
|
||||
* (v1) router so `/cloud/*` is not shadowed by v1's `GET /:id`. The cloud router
|
||||
* carries its own `requireJwtAuth` and forwards the user's hanzo.id bearer to
|
||||
* cloud server-side (see cloud.js). Legacy `/v1/chat/agents` CRUD stays untouched.
|
||||
*/
|
||||
router.use('/cloud', cloud);
|
||||
|
||||
router.use('/', v1);
|
||||
|
||||
/**
|
||||
|
||||
@@ -79,18 +79,18 @@ jest.mock('~/server/middleware', () => {
|
||||
|
||||
const authRouter = require('./auth');
|
||||
|
||||
describe('POST /api/auth/cloudfront/refresh', () => {
|
||||
describe('POST /v1/chat/auth/cloudfront/refresh', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/v1/chat/auth', authRouter);
|
||||
});
|
||||
|
||||
it('requires authentication', async () => {
|
||||
await request(app).post('/api/auth/cloudfront/refresh').expect(401);
|
||||
await request(app).post('/v1/chat/auth/cloudfront/refresh').expect(401);
|
||||
|
||||
expect(mockForceRefreshCloudFrontAuthCookies).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -104,7 +104,7 @@ describe('POST /api/auth/cloudfront/refresh', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/auth/cloudfront/refresh')
|
||||
.post('/v1/chat/auth/cloudfront/refresh')
|
||||
.set('Authorization', 'Bearer ok')
|
||||
.expect(404);
|
||||
|
||||
@@ -121,7 +121,7 @@ describe('POST /api/auth/cloudfront/refresh', () => {
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/auth/cloudfront/refresh')
|
||||
.post('/v1/chat/auth/cloudfront/refresh')
|
||||
.set('Authorization', 'Bearer ok')
|
||||
.expect(200);
|
||||
|
||||
@@ -139,7 +139,7 @@ describe('POST /api/auth/cloudfront/refresh', () => {
|
||||
|
||||
it('reuses the auth middleware refresh result instead of minting cookies twice', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/auth/cloudfront/refresh')
|
||||
.post('/v1/chat/auth/cloudfront/refresh')
|
||||
.set('Authorization', 'Bearer ok')
|
||||
.set('x-cloudfront-warmed', 'true')
|
||||
.expect(200);
|
||||
|
||||
@@ -186,7 +186,7 @@ router.post('/archive', validateConvoAccess, async (req, res) => {
|
||||
const dbResponse = await saveConvo(
|
||||
req,
|
||||
{ conversationId, isArchived },
|
||||
{ context: `POST /api/convos/archive ${conversationId}` },
|
||||
{ context: `POST /v1/chat/convos/archive ${conversationId}` },
|
||||
);
|
||||
res.status(200).json(dbResponse);
|
||||
} catch (error) {
|
||||
@@ -226,7 +226,7 @@ router.post('/update', validateConvoAccess, async (req, res) => {
|
||||
const dbResponse = await saveConvo(
|
||||
req,
|
||||
{ conversationId, title: sanitizedTitle },
|
||||
{ context: `POST /api/convos/update ${conversationId}` },
|
||||
{ context: `POST /v1/chat/convos/update ${conversationId}` },
|
||||
);
|
||||
res.status(201).json(dbResponse);
|
||||
} catch (error) {
|
||||
|
||||
@@ -106,7 +106,7 @@ describe('file upload routes restore strict isolation context after multer', ()
|
||||
beforeAll(async () => {
|
||||
const { initialize } = require('./index');
|
||||
app = express();
|
||||
app.use('/api/files', await initialize());
|
||||
app.use('/v1/chat/files', await initialize());
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -123,12 +123,12 @@ describe('file upload routes restore strict isolation context after multer', ()
|
||||
});
|
||||
|
||||
it.each([
|
||||
['files', '/api/files'],
|
||||
['images', '/api/files/images'],
|
||||
['avatar', '/api/files/images/avatar'],
|
||||
['agent-avatar', '/api/files/images/agents/agent-1/avatar'],
|
||||
['assistant-avatar', '/api/files/images/assistants/asst-1/avatar'],
|
||||
['speech-stt', '/api/files/speech/stt'],
|
||||
['files', '/v1/chat/files'],
|
||||
['images', '/v1/chat/files/images'],
|
||||
['avatar', '/v1/chat/files/images/avatar'],
|
||||
['agent-avatar', '/v1/chat/files/images/agents/agent-1/avatar'],
|
||||
['assistant-avatar', '/v1/chat/files/images/assistants/asst-1/avatar'],
|
||||
['speech-stt', '/v1/chat/files/speech/stt'],
|
||||
])('restores context for %s upload', async (route, url) => {
|
||||
const res = await request(app).post(url);
|
||||
|
||||
@@ -142,7 +142,7 @@ describe('file upload routes restore strict isolation context after multer', ()
|
||||
role: 'USER',
|
||||
};
|
||||
|
||||
const res = await request(app).post('/api/files');
|
||||
const res = await request(app).post('/v1/chat/files');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toMatch(/Tenant context required/);
|
||||
|
||||
@@ -23,7 +23,7 @@ describe('Multer Configuration', () => {
|
||||
mockReq = {
|
||||
user: { id: 'test-user-123' },
|
||||
body: {},
|
||||
originalUrl: '/api/files/upload',
|
||||
originalUrl: '/v1/chat/files/upload',
|
||||
config: {
|
||||
paths: {
|
||||
uploads: tempDir,
|
||||
@@ -256,7 +256,7 @@ describe('Multer Configuration', () => {
|
||||
});
|
||||
|
||||
it('should handle audio files for speech-to-text endpoint with real config', async () => {
|
||||
mockReq.originalUrl = '/api/speech/stt';
|
||||
mockReq.originalUrl = '/v1/chat/speech/stt';
|
||||
|
||||
const multerInstance = await createMulterInstance();
|
||||
expect(multerInstance).toBeDefined();
|
||||
|
||||
@@ -47,7 +47,7 @@ const { getLogStores } = require('~/cache');
|
||||
|
||||
const router = Router();
|
||||
|
||||
const OAUTH_CSRF_COOKIE_PATH = '/api/mcp';
|
||||
const OAUTH_CSRF_COOKIE_PATH = '/v1/chat/mcp';
|
||||
|
||||
/**
|
||||
* Get all MCP tools available to the user
|
||||
@@ -677,7 +677,7 @@ const checkMCPCreate = generateCheckAccess({
|
||||
|
||||
/**
|
||||
* Get list of accessible MCP servers
|
||||
* @route GET /api/mcp/servers
|
||||
* @route GET /v1/chat/mcp/servers
|
||||
* @param {Object} req.query - Query parameters for pagination and search
|
||||
* @param {number} [req.query.limit] - Number of results per page
|
||||
* @param {string} [req.query.after] - Pagination cursor
|
||||
@@ -688,7 +688,7 @@ router.get('/servers', requireJwtAuth, checkMCPUsePermissions, getMCPServersList
|
||||
|
||||
/**
|
||||
* Create a new MCP server
|
||||
* @route POST /api/mcp/servers
|
||||
* @route POST /v1/chat/mcp/servers
|
||||
* @param {MCPServerCreateParams} req.body - The MCP server creation parameters.
|
||||
* @returns {MCPServer} 201 - Success response - application/json
|
||||
*/
|
||||
@@ -696,7 +696,7 @@ router.post('/servers', requireJwtAuth, checkMCPCreate, createMCPServerControlle
|
||||
|
||||
/**
|
||||
* Get single MCP server by ID
|
||||
* @route GET /api/mcp/servers/:serverName
|
||||
* @route GET /v1/chat/mcp/servers/:serverName
|
||||
* @param {string} req.params.serverName - MCP server identifier.
|
||||
* @returns {MCPServer} 200 - Success response - application/json
|
||||
*/
|
||||
@@ -713,7 +713,7 @@ router.get(
|
||||
|
||||
/**
|
||||
* Update MCP server
|
||||
* @route PATCH /api/mcp/servers/:serverName
|
||||
* @route PATCH /v1/chat/mcp/servers/:serverName
|
||||
* @param {string} req.params.serverName - MCP server identifier.
|
||||
* @param {MCPServerUpdateParams} req.body - The MCP server update parameters.
|
||||
* @returns {MCPServer} 200 - Success response - application/json
|
||||
@@ -731,7 +731,7 @@ router.patch(
|
||||
|
||||
/**
|
||||
* Delete MCP server
|
||||
* @route DELETE /api/mcp/servers/:serverName
|
||||
* @route DELETE /v1/chat/mcp/servers/:serverName
|
||||
* @param {string} req.params.serverName - MCP server identifier.
|
||||
* @returns {Object} 200 - Success response - application/json
|
||||
*/
|
||||
|
||||
@@ -188,7 +188,7 @@ router.post('/branch', async (req, res) => {
|
||||
};
|
||||
|
||||
const savedMessage = await saveMessage(req, newMessage, {
|
||||
context: 'POST /api/messages/branch',
|
||||
context: 'POST /v1/chat/messages/branch',
|
||||
});
|
||||
|
||||
if (!savedMessage) {
|
||||
@@ -265,7 +265,7 @@ router.post('/artifact/:messageId', async (req, res) => {
|
||||
content: message.content,
|
||||
user: req.user.id,
|
||||
},
|
||||
{ context: 'POST /api/messages/artifact/:messageId' },
|
||||
{ context: 'POST /v1/chat/messages/artifact/:messageId' },
|
||||
);
|
||||
|
||||
res.status(200).json({
|
||||
@@ -297,12 +297,12 @@ router.post('/:conversationId', validateMessageReq, async (req, res) => {
|
||||
const savedMessage = await saveMessage(
|
||||
req,
|
||||
{ ...message, user: req.user.id },
|
||||
{ context: 'POST /api/messages/:conversationId' },
|
||||
{ context: 'POST /v1/chat/messages/:conversationId' },
|
||||
);
|
||||
if (!savedMessage) {
|
||||
return res.status(400).json({ error: 'Message not saved' });
|
||||
}
|
||||
await saveConvo(req, savedMessage, { context: 'POST /api/messages/:conversationId' });
|
||||
await saveConvo(req, savedMessage, { context: 'POST /v1/chat/messages/:conversationId' });
|
||||
res.status(201).json(savedMessage);
|
||||
} catch (error) {
|
||||
logger.error('Error saving message:', error);
|
||||
|
||||
@@ -83,7 +83,7 @@ beforeAll(async () => {
|
||||
|
||||
// Import routes after middleware is set up
|
||||
promptRoutes = require('./prompts');
|
||||
app.use('/api/prompts', promptRoutes);
|
||||
app.use('/v1/chat/prompts', promptRoutes);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -180,13 +180,13 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
// Simple test to verify route is loaded
|
||||
it('should have routes loaded', async () => {
|
||||
// This should at least not crash
|
||||
const response = await request(app).get('/api/prompts/test-404');
|
||||
const response = await request(app).get('/v1/chat/prompts/test-404');
|
||||
|
||||
// We expect a 401 or 404, not 500
|
||||
expect(response.status).not.toBe(500);
|
||||
});
|
||||
|
||||
describe('POST /api/prompts - Create Prompt', () => {
|
||||
describe('POST /v1/chat/prompts - Create Prompt', () => {
|
||||
afterEach(async () => {
|
||||
await Prompt.deleteMany({});
|
||||
await PromptGroup.deleteMany({});
|
||||
@@ -204,7 +204,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app).post('/api/prompts').send(promptData);
|
||||
const response = await request(app).post('/v1/chat/prompts').send(promptData);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.prompt).toBeDefined();
|
||||
@@ -234,7 +234,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app).post('/api/prompts').send(promptData).expect(200);
|
||||
const response = await request(app).post('/v1/chat/prompts').send(promptData).expect(200);
|
||||
|
||||
expect(response.body.prompt).toBeDefined();
|
||||
expect(response.body.group).toBeDefined();
|
||||
@@ -252,7 +252,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/prompts/:promptId - Get Prompt', () => {
|
||||
describe('GET /v1/chat/prompts/:promptId - Get Prompt', () => {
|
||||
let testPrompt;
|
||||
let testGroup;
|
||||
|
||||
@@ -293,7 +293,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
grantedBy: testUsers.owner._id,
|
||||
});
|
||||
|
||||
const response = await request(app).get(`/api/prompts/${testPrompt._id}`);
|
||||
const response = await request(app).get(`/v1/chat/prompts/${testPrompt._id}`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body._id).toBe(testPrompt._id.toString());
|
||||
expect(response.body.prompt).toBe(testPrompt.prompt);
|
||||
@@ -303,7 +303,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
// Change the user to one without access
|
||||
setTestUser(app, testUsers.noAccess);
|
||||
|
||||
const response = await request(app).get(`/api/prompts/${testPrompt._id}`).expect(403);
|
||||
const response = await request(app).get(`/v1/chat/prompts/${testPrompt._id}`).expect(403);
|
||||
|
||||
// Verify error response
|
||||
expect(response.body.error).toBe('Forbidden');
|
||||
@@ -314,13 +314,13 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
// Set admin user
|
||||
setTestUser(app, testUsers.admin);
|
||||
|
||||
const response = await request(app).get(`/api/prompts/${testPrompt._id}`).expect(200);
|
||||
const response = await request(app).get(`/v1/chat/prompts/${testPrompt._id}`).expect(200);
|
||||
|
||||
expect(response.body._id).toBe(testPrompt._id.toString());
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/prompts/:promptId - Delete Prompt', () => {
|
||||
describe('DELETE /v1/chat/prompts/:promptId - Delete Prompt', () => {
|
||||
let testPrompt;
|
||||
let testGroup;
|
||||
|
||||
@@ -366,7 +366,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
it('should delete prompt when user has delete permissions', async () => {
|
||||
const response = await request(app)
|
||||
.delete(`/api/prompts/${testPrompt._id}`)
|
||||
.delete(`/v1/chat/prompts/${testPrompt._id}`)
|
||||
.query({ groupId: testGroup._id.toString() })
|
||||
.expect(200);
|
||||
|
||||
@@ -408,7 +408,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
setTestUser(app, testUsers.viewer);
|
||||
|
||||
await request(app)
|
||||
.delete(`/api/prompts/${authorPrompt._id}`)
|
||||
.delete(`/v1/chat/prompts/${authorPrompt._id}`)
|
||||
.query({ groupId: testGroup._id.toString() })
|
||||
.expect(403);
|
||||
|
||||
@@ -418,7 +418,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/prompts/:promptId/tags/production - Make Production', () => {
|
||||
describe('PATCH /v1/chat/prompts/:promptId/tags/production - Make Production', () => {
|
||||
let testPrompt;
|
||||
let testGroup;
|
||||
|
||||
@@ -462,7 +462,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
setTestUser(app, testUsers.owner);
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/${testPrompt._id}/tags/production`)
|
||||
.patch(`/v1/chat/prompts/${testPrompt._id}/tags/production`)
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.message).toBe('Prompt production made successfully');
|
||||
@@ -486,7 +486,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
// Set viewer user
|
||||
setTestUser(app, testUsers.viewer);
|
||||
|
||||
await request(app).patch(`/api/prompts/${testPrompt._id}/tags/production`).expect(403);
|
||||
await request(app).patch(`/v1/chat/prompts/${testPrompt._id}/tags/production`).expect(403);
|
||||
|
||||
// Verify prompt hasn't changed
|
||||
const unchangedGroup = await PromptGroup.findById(testGroup._id);
|
||||
@@ -538,13 +538,13 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
// Change user to someone without explicit permissions
|
||||
setTestUser(app, testUsers.noAccess);
|
||||
|
||||
const response = await request(app).get(`/api/prompts/${publicPrompt._id}`).expect(200);
|
||||
const response = await request(app).get(`/v1/chat/prompts/${publicPrompt._id}`).expect(200);
|
||||
|
||||
expect(response.body._id).toBe(publicPrompt._id.toString());
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/prompts/groups/:groupId - Update Prompt Group Security', () => {
|
||||
describe('PATCH /v1/chat/prompts/groups/:groupId - Update Prompt Group Security', () => {
|
||||
let testGroup;
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -581,7 +581,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(updateData)
|
||||
.expect(200);
|
||||
|
||||
@@ -597,7 +597,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -613,7 +613,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -629,7 +629,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -645,7 +645,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -661,7 +661,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -676,7 +676,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -696,7 +696,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${testGroup._id}`)
|
||||
.patch(`/v1/chat/prompts/groups/${testGroup._id}`)
|
||||
.send(maliciousUpdate)
|
||||
.expect(400);
|
||||
|
||||
@@ -741,7 +741,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
it('should correctly indicate hasMore when there are more pages', async () => {
|
||||
const response = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '10' })
|
||||
.expect(200);
|
||||
|
||||
@@ -755,7 +755,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
it('should correctly indicate no more pages on the last page', async () => {
|
||||
// First get the cursor for page 2
|
||||
const firstPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '10' })
|
||||
.expect(200);
|
||||
|
||||
@@ -764,7 +764,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Now fetch the second page using the cursor
|
||||
const response = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '10', cursor: firstPage.body.after })
|
||||
.expect(200);
|
||||
|
||||
@@ -775,7 +775,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
it('should support cursor-based pagination', async () => {
|
||||
// First page
|
||||
const firstPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5' })
|
||||
.expect(200);
|
||||
|
||||
@@ -785,7 +785,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Second page using cursor
|
||||
const secondPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5', cursor: firstPage.body.after })
|
||||
.expect(200);
|
||||
|
||||
@@ -848,7 +848,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Test pagination with category filter
|
||||
const firstPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5', category: 'test-cat-1' })
|
||||
.expect(200);
|
||||
|
||||
@@ -858,7 +858,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
expect(firstPage.body.after).toBeTruthy();
|
||||
|
||||
const secondPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5', cursor: firstPage.body.after, category: 'test-cat-1' })
|
||||
.expect(200);
|
||||
|
||||
@@ -916,7 +916,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Test pagination with name filter
|
||||
const firstPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '10', name: 'Search' })
|
||||
.expect(200);
|
||||
|
||||
@@ -926,7 +926,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
expect(firstPage.body.after).toBeTruthy();
|
||||
|
||||
const secondPage = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '10', cursor: firstPage.body.after, name: 'Search' })
|
||||
.expect(200);
|
||||
|
||||
@@ -984,7 +984,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Test pagination with both filters
|
||||
const response = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5', name: 'API', category: 'api-category' })
|
||||
.expect(200);
|
||||
|
||||
@@ -999,7 +999,7 @@ describe('Prompt Routes - ACL Permissions', () => {
|
||||
|
||||
// Page 2
|
||||
const page2 = await request(app)
|
||||
.get('/api/prompts/groups')
|
||||
.get('/v1/chat/prompts/groups')
|
||||
.query({ limit: '5', cursor: response.body.after, name: 'API', category: 'api-category' })
|
||||
.expect(200);
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ const createPermissionUpdateHandler = (permissionKey) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* GET /api/roles/:roleName
|
||||
* GET /v1/chat/roles/:roleName
|
||||
* Get a specific role by name
|
||||
*/
|
||||
router.get('/:roleName', async (req, res) => {
|
||||
@@ -131,43 +131,43 @@ router.get('/:roleName', async (req, res) => {
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/prompts
|
||||
* PUT /v1/chat/roles/:roleName/prompts
|
||||
* Update prompt permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/prompts', checkAdmin, createPermissionUpdateHandler('prompts'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/agents
|
||||
* PUT /v1/chat/roles/:roleName/agents
|
||||
* Update agent permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/agents', checkAdmin, createPermissionUpdateHandler('agents'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/memories
|
||||
* PUT /v1/chat/roles/:roleName/memories
|
||||
* Update memory permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/memories', checkAdmin, createPermissionUpdateHandler('memories'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/people-picker
|
||||
* PUT /v1/chat/roles/:roleName/people-picker
|
||||
* Update people picker permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/people-picker', checkAdmin, createPermissionUpdateHandler('people-picker'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/mcp-servers
|
||||
* PUT /v1/chat/roles/:roleName/mcp-servers
|
||||
* Update MCP servers permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/mcp-servers', checkAdmin, createPermissionUpdateHandler('mcp-servers'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/marketplace
|
||||
* PUT /v1/chat/roles/:roleName/marketplace
|
||||
* Update marketplace permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/marketplace', checkAdmin, createPermissionUpdateHandler('marketplace'));
|
||||
|
||||
/**
|
||||
* PUT /api/roles/:roleName/remote-agents
|
||||
* PUT /v1/chat/roles/:roleName/remote-agents
|
||||
* Update remote agents (API) permissions for a specific role
|
||||
*/
|
||||
router.put('/:roleName/remote-agents', checkAdmin, createPermissionUpdateHandler('remote-agents'));
|
||||
|
||||
@@ -141,7 +141,7 @@ beforeAll(async () => {
|
||||
});
|
||||
|
||||
currentTestUser = testUsers.owner;
|
||||
app.use('/api/skills', require('./skills'));
|
||||
app.use('/v1/chat/skills', require('./skills'));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -202,7 +202,7 @@ async function setupTestData() {
|
||||
|
||||
async function createSkillAsOwner(overrides = {}) {
|
||||
return request(app)
|
||||
.post('/api/skills')
|
||||
.post('/v1/chat/skills')
|
||||
.send({
|
||||
name: 'strict-file-skill',
|
||||
description: 'A strict tenant skill used in multipart route tests.',
|
||||
@@ -227,7 +227,7 @@ describe('Skill multipart routes under strict tenant isolation', () => {
|
||||
zip.file('scripts/run.sh', 'echo strict');
|
||||
const buffer = await zip.generateAsync({ type: 'nodebuffer' });
|
||||
|
||||
const res = await request(app).post('/api/skills/import').attach('file', buffer, {
|
||||
const res = await request(app).post('/v1/chat/skills/import').attach('file', buffer, {
|
||||
filename: 'strict-import.skill',
|
||||
contentType: 'application/zip',
|
||||
});
|
||||
@@ -274,7 +274,7 @@ describe('Skill multipart routes under strict tenant isolation', () => {
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/skills/import')
|
||||
.post('/v1/chat/skills/import')
|
||||
.attach('file', Buffer.from('# Request Tenant Markdown'), {
|
||||
filename: 'request-tenant.md',
|
||||
contentType: 'text/markdown',
|
||||
@@ -301,7 +301,7 @@ describe('Skill multipart routes under strict tenant isolation', () => {
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/skills/import')
|
||||
.post('/v1/chat/skills/import')
|
||||
.attach('file', Buffer.from('# No Tenant'), {
|
||||
filename: 'no-tenant.md',
|
||||
contentType: 'text/markdown',
|
||||
@@ -316,7 +316,7 @@ describe('Skill multipart routes under strict tenant isolation', () => {
|
||||
expect(created.status).toBe(201);
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/skills/${created.body._id}/files`)
|
||||
.post(`/v1/chat/skills/${created.body._id}/files`)
|
||||
.field('relativePath', 'scripts/manual.sh')
|
||||
.attach('file', Buffer.from('echo manual'), {
|
||||
filename: 'manual.sh',
|
||||
@@ -351,7 +351,7 @@ describe('Skill multipart routes under strict tenant isolation', () => {
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/skills/${created.body._id}/files`)
|
||||
.post(`/v1/chat/skills/${created.body._id}/files`)
|
||||
.field('relativePath', 'scripts/request-tenant.sh')
|
||||
.attach('file', Buffer.from('echo request tenant'), {
|
||||
filename: 'request-tenant.sh',
|
||||
|
||||
@@ -143,7 +143,7 @@ beforeAll(async () => {
|
||||
|
||||
currentTestUser = testUsers.owner;
|
||||
skillRoutes = require('./skills');
|
||||
app.use('/api/skills', skillRoutes);
|
||||
app.use('/v1/chat/skills', skillRoutes);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -223,7 +223,7 @@ async function createSkillAsOwner(overrides = {}) {
|
||||
// Description is deliberately kept above the 20-char short-description
|
||||
// warning threshold so existing tests don't trip the coaching warning.
|
||||
const res = await request(app)
|
||||
.post('/api/skills')
|
||||
.post('/v1/chat/skills')
|
||||
.send({
|
||||
name: 'demo-skill',
|
||||
description: 'A small demo skill used in routing integration tests.',
|
||||
@@ -240,7 +240,7 @@ describe('Skill routes', () => {
|
||||
});
|
||||
afterEach(() => errSpy.mockRestore());
|
||||
|
||||
describe('POST /api/skills', () => {
|
||||
describe('POST /v1/chat/skills', () => {
|
||||
it('creates a skill and grants SKILL_OWNER ACL', async () => {
|
||||
const res = await createSkillAsOwner();
|
||||
expect(res.status).toBe(201);
|
||||
@@ -306,7 +306,7 @@ describe('Skill routes', () => {
|
||||
});
|
||||
|
||||
it('rejects missing description with 400', async () => {
|
||||
const res = await request(app).post('/api/skills').send({ name: 'x-skill', body: '' });
|
||||
const res = await request(app).post('/v1/chat/skills').send({ name: 'x-skill', body: '' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
@@ -324,7 +324,7 @@ describe('Skill routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/skills/import', () => {
|
||||
describe('POST /v1/chat/skills/import', () => {
|
||||
it('enforces fileConfig.skills.fileSizeLimit before import handling', async () => {
|
||||
mockFileConfig = {
|
||||
skills: {
|
||||
@@ -333,7 +333,7 @@ describe('Skill routes', () => {
|
||||
};
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/skills/import')
|
||||
.post('/v1/chat/skills/import')
|
||||
.attach('file', Buffer.alloc(2 * 1024 * 1024), {
|
||||
filename: 'too-large.skill',
|
||||
contentType: 'application/zip',
|
||||
@@ -368,7 +368,7 @@ describe('Skill routes', () => {
|
||||
zip.file('scripts/imported-script.sh', 'echo imported');
|
||||
const buffer = await zip.generateAsync({ type: 'nodebuffer' });
|
||||
|
||||
const res = await request(app).post('/api/skills/import').attach('file', buffer, {
|
||||
const res = await request(app).post('/v1/chat/skills/import').attach('file', buffer, {
|
||||
filename: 'imported-skill.skill',
|
||||
contentType: 'application/zip',
|
||||
});
|
||||
@@ -395,7 +395,7 @@ describe('Skill routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/skills', () => {
|
||||
describe('GET /v1/chat/skills', () => {
|
||||
it('returns only skills the caller can access', async () => {
|
||||
const mine = await createSkillAsOwner({ name: 'mine-skill' });
|
||||
expect(mine.status).toBe(201);
|
||||
@@ -407,36 +407,36 @@ describe('Skill routes', () => {
|
||||
// users see their own skill only.
|
||||
|
||||
setTestUser(testUsers.owner);
|
||||
const res = await request(app).get('/api/skills');
|
||||
const res = await request(app).get('/v1/chat/skills');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.skills.length).toBe(1);
|
||||
expect(res.body.skills[0].name).toBe('mine-skill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/skills/:id', () => {
|
||||
describe('GET /v1/chat/skills/:id', () => {
|
||||
it('returns 403 when the user has no access', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
expect(created.status).toBe(201);
|
||||
setTestUser(testUsers.noAccess);
|
||||
const res = await request(app).get(`/api/skills/${created.body._id}`);
|
||||
const res = await request(app).get(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it('returns the skill to the owner with isPublic flag', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).get(`/api/skills/${created.body._id}`);
|
||||
const res = await request(app).get(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.name).toBe('demo-skill');
|
||||
expect(res.body.isPublic).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/skills/:id (optimistic concurrency)', () => {
|
||||
describe('PATCH /v1/chat/skills/:id (optimistic concurrency)', () => {
|
||||
it('updates with correct expectedVersion and bumps version', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ expectedVersion: 1, description: 'Updated description' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.version).toBe(2);
|
||||
@@ -446,12 +446,12 @@ describe('Skill routes', () => {
|
||||
it('returns 409 on stale expectedVersion', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const first = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ expectedVersion: 1, description: 'First' });
|
||||
expect(first.status).toBe(200);
|
||||
|
||||
const stale = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ expectedVersion: 1, description: 'Stale' });
|
||||
expect(stale.status).toBe(409);
|
||||
expect(stale.body.error).toBe('skill_version_conflict');
|
||||
@@ -461,7 +461,7 @@ describe('Skill routes', () => {
|
||||
it('rejects updates without expectedVersion', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ description: 'no version' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
@@ -470,16 +470,16 @@ describe('Skill routes', () => {
|
||||
const created = await createSkillAsOwner();
|
||||
setTestUser(testUsers.noAccess);
|
||||
const res = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ expectedVersion: 1, description: 'nope' });
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/skills/:id', () => {
|
||||
describe('DELETE /v1/chat/skills/:id', () => {
|
||||
it('deletes and cascades ACL entries', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).delete(`/api/skills/${created.body._id}`);
|
||||
const res = await request(app).delete(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.deleted).toBe(true);
|
||||
|
||||
@@ -493,33 +493,33 @@ describe('Skill routes', () => {
|
||||
it('returns 403 for a non-owner', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
setTestUser(testUsers.noAccess);
|
||||
const res = await request(app).delete(`/api/skills/${created.body._id}`);
|
||||
const res = await request(app).delete(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/skills/:id/files', () => {
|
||||
describe('GET /v1/chat/skills/:id/files', () => {
|
||||
it('returns an empty list for a skill with no files', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).get(`/api/skills/${created.body._id}/files`);
|
||||
const res = await request(app).get(`/v1/chat/skills/${created.body._id}/files`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.files).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/skills/:id/files (live)', () => {
|
||||
describe('POST /v1/chat/skills/:id/files (live)', () => {
|
||||
it('returns 400 when no file is provided', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).post(`/api/skills/${created.body._id}/files`);
|
||||
const res = await request(app).post(`/v1/chat/skills/${created.body._id}/files`);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/no file/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/skills/:id/files/:relativePath', () => {
|
||||
describe('GET /v1/chat/skills/:id/files/:relativePath', () => {
|
||||
it('returns SKILL.md content from skill body', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).get(`/api/skills/${created.body._id}/files/SKILL.md`);
|
||||
const res = await request(app).get(`/v1/chat/skills/${created.body._id}/files/SKILL.md`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.mimeType).toBe('text/markdown');
|
||||
expect(res.body.isBinary).toBe(false);
|
||||
@@ -530,13 +530,13 @@ describe('Skill routes', () => {
|
||||
it('returns 404 for a nonexistent file', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).get(
|
||||
`/api/skills/${created.body._id}/files/scripts%2Fmissing.sh`,
|
||||
`/v1/chat/skills/${created.body._id}/files/scripts%2Fmissing.sh`,
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/skills/:id/files/:relativePath', () => {
|
||||
describe('DELETE /v1/chat/skills/:id/files/:relativePath', () => {
|
||||
const { upsertSkillFile } = require('~/models');
|
||||
|
||||
it('deletes an existing skill file, bumps skill version, and returns 200', async () => {
|
||||
@@ -553,12 +553,12 @@ describe('Skill routes', () => {
|
||||
author: testUsers.owner._id,
|
||||
});
|
||||
|
||||
const beforeSkill = await request(app).get(`/api/skills/${created.body._id}`);
|
||||
const beforeSkill = await request(app).get(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(beforeSkill.body.fileCount).toBe(1);
|
||||
expect(beforeSkill.body.version).toBe(2);
|
||||
|
||||
const res = await request(app).delete(
|
||||
`/api/skills/${created.body._id}/files/scripts%2Fparse.sh`,
|
||||
`/v1/chat/skills/${created.body._id}/files/scripts%2Fparse.sh`,
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
@@ -567,7 +567,7 @@ describe('Skill routes', () => {
|
||||
deleted: true,
|
||||
});
|
||||
|
||||
const afterSkill = await request(app).get(`/api/skills/${created.body._id}`);
|
||||
const afterSkill = await request(app).get(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(afterSkill.body.fileCount).toBe(0);
|
||||
expect(afterSkill.body.version).toBe(3);
|
||||
});
|
||||
@@ -575,7 +575,7 @@ describe('Skill routes', () => {
|
||||
it('returns 404 when the file does not exist', async () => {
|
||||
const created = await createSkillAsOwner();
|
||||
const res = await request(app).delete(
|
||||
`/api/skills/${created.body._id}/files/scripts%2Fmissing.sh`,
|
||||
`/v1/chat/skills/${created.body._id}/files/scripts%2Fmissing.sh`,
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
@@ -584,7 +584,7 @@ describe('Skill routes', () => {
|
||||
const created = await createSkillAsOwner();
|
||||
setTestUser(testUsers.noAccess);
|
||||
const res = await request(app).delete(
|
||||
`/api/skills/${created.body._id}/files/scripts%2Fparse.sh`,
|
||||
`/v1/chat/skills/${created.body._id}/files/scripts%2Fparse.sh`,
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
@@ -604,12 +604,12 @@ describe('Skill routes', () => {
|
||||
|
||||
setTestUser(testUsers.editor);
|
||||
const res = await request(app)
|
||||
.patch(`/api/skills/${created.body._id}`)
|
||||
.patch(`/v1/chat/skills/${created.body._id}`)
|
||||
.send({ expectedVersion: 1, description: 'Edited by editor' });
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Editor should NOT be able to delete
|
||||
const del = await request(app).delete(`/api/skills/${created.body._id}`);
|
||||
const del = await request(app).delete(`/v1/chat/skills/${created.body._id}`);
|
||||
expect(del.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -176,7 +176,7 @@ async function createActionTool({
|
||||
|
||||
const stateToken = jwt.sign(statePayload, JWT_SECRET, { expiresIn: '10m' });
|
||||
try {
|
||||
const redirectUri = `${process.env.DOMAIN_CLIENT}/api/actions/${action_id}/oauth/callback`;
|
||||
const redirectUri = `${process.env.DOMAIN_CLIENT}/v1/chat/actions/${action_id}/oauth/callback`;
|
||||
const params = new URLSearchParams({
|
||||
client_id: metadata.oauth_client_id,
|
||||
scope: metadata.auth.scope,
|
||||
@@ -222,7 +222,7 @@ async function createActionTool({
|
||||
state: stateToken,
|
||||
userId: userId,
|
||||
client_url: metadata.auth.client_url,
|
||||
redirect_uri: `${process.env.DOMAIN_SERVER}/api/actions/${action_id}/oauth/callback`,
|
||||
redirect_uri: `${process.env.DOMAIN_SERVER}/v1/chat/actions/${action_id}/oauth/callback`,
|
||||
token_exchange_method: metadata.auth.token_exchange_method,
|
||||
/** Encrypted values */
|
||||
encrypted_oauth_client_id: encrypted.oauth_client_id,
|
||||
|
||||
@@ -214,7 +214,9 @@ const registerUser = async (user, additionalData = {}) => {
|
||||
//determine if this is the first registered user (not counting anonymous_user)
|
||||
const isFirstRegisteredUser = (await countUsers()) === 0;
|
||||
|
||||
const salt = bcrypt.genSaltSync(10);
|
||||
// No local password credential is stored — identity is owned by Hanzo IAM.
|
||||
// (This local path is gated off in prod via ALLOW_REGISTRATION=false; the
|
||||
// full local-strategy teardown lands with the identity cutover.)
|
||||
const newUserData = {
|
||||
provider: provider ?? 'local',
|
||||
email,
|
||||
@@ -222,7 +224,6 @@ const registerUser = async (user, additionalData = {}) => {
|
||||
name,
|
||||
avatar: null,
|
||||
role: isFirstRegisteredUser ? SystemRoles.ADMIN : SystemRoles.USER,
|
||||
password: bcrypt.hashSync(password, salt),
|
||||
...additionalData,
|
||||
};
|
||||
|
||||
@@ -327,43 +328,11 @@ const requestPasswordReset = async (req) => {
|
||||
* @param {String} password
|
||||
* @returns
|
||||
*/
|
||||
const resetPassword = async (userId, token, password) => {
|
||||
let passwordResetToken = await findToken(
|
||||
{
|
||||
userId,
|
||||
},
|
||||
{ sort: { createdAt: -1 } },
|
||||
);
|
||||
|
||||
if (!passwordResetToken) {
|
||||
return new Error('Invalid or expired password reset token');
|
||||
}
|
||||
|
||||
const isValid = bcrypt.compareSync(token, passwordResetToken.token);
|
||||
|
||||
if (!isValid) {
|
||||
return new Error('Invalid or expired password reset token');
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
const user = await updateUser(userId, { password: hash });
|
||||
|
||||
if (checkEmailConfig()) {
|
||||
await sendEmail({
|
||||
email: user.email,
|
||||
subject: 'Password Reset Successfully',
|
||||
payload: {
|
||||
appName: process.env.APP_TITLE || 'Hanzo Chat',
|
||||
name: user.name || user.username || user.email,
|
||||
year: new Date().getFullYear(),
|
||||
},
|
||||
template: 'passwordReset.handlebars',
|
||||
});
|
||||
}
|
||||
|
||||
await deleteTokens({ token: passwordResetToken.token });
|
||||
logger.info(`[resetPassword] Password reset successful. [Email: ${user.email}]`);
|
||||
return { message: 'Password reset was successful' };
|
||||
const resetPassword = async () => {
|
||||
// Chat stores no local password credential. Password reset is owned by Hanzo
|
||||
// IAM (hanzo.id); there is nothing to reset here. Prod already disables this
|
||||
// route (ALLOW_EMAIL_LOGIN=false) — this is the service-level guarantee.
|
||||
return new Error('Password reset is managed by Hanzo IAM (hanzo.id).');
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -413,6 +382,53 @@ const setAuthTokens = async (userId, res, _session = null) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @function persistOpenIDTokensToSession
|
||||
* Persist the OpenID tokenset material an on-behalf-of downstream call needs
|
||||
* (e.g. running the caller's canonical Hanzo Cloud `/v1/agents`) into the
|
||||
* server-side express-session — and ONLY there, never a browser cookie.
|
||||
*
|
||||
* This is DELIBERATELY decoupled from the token-refresh strategy. It runs on
|
||||
* EVERY OpenID login regardless of `OPENID_REUSE_TOKENS`; that flag alone still
|
||||
* governs whether `/v1/chat/auth/refresh` performs an OIDC refresh-grant. It writes
|
||||
* only server-side session state (no `token_provider`, `refreshToken`, or other
|
||||
* auth cookie), so it cannot alter the browser-facing login/refresh cookies — a
|
||||
* REUSE-disabled login stays byte-identical.
|
||||
*
|
||||
* The OIDC `refresh` credential is a SEPARATE concern from the on-behalf-of
|
||||
* BEARER: it is persisted only when passed EXPLICITLY as `refreshToken`, which
|
||||
* the REUSE path does (its session refreshes via OIDC and `refreshController` /
|
||||
* `logoutController` read `session.openidTokens.refreshToken`). The decoupled
|
||||
* default passes NO refresh credential — its session refreshes via the local
|
||||
* JWT cookie — so no OIDC refresh token is written here. That keeps the decoupled
|
||||
* session carrying only bearer material and leaves refresh/logout identical to a
|
||||
* non-OpenID login (they read the local cookie, never this session field).
|
||||
*
|
||||
* @param {Object} req - request carrying the express-session
|
||||
* @param {import('openid-client').TokenEndpointResponse & Partial<import('openid-client').TokenEndpointResponseHelpers>} tokenset
|
||||
* @param {string} [refreshToken] - OIDC refresh credential to bind to this session (REUSE mode only); omitted in the decoupled path
|
||||
* @returns {boolean} true if persisted; false when no session (or tokenset) was available
|
||||
*/
|
||||
const persistOpenIDTokensToSession = (req, tokenset, refreshToken) => {
|
||||
if (!req?.session) {
|
||||
logger.warn(
|
||||
'[persistOpenIDTokensToSession] No session available; on-behalf-of tokens not stored',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (!tokenset) {
|
||||
return false;
|
||||
}
|
||||
const expiryInMilliseconds = math(process.env.REFRESH_TOKEN_EXPIRY, DEFAULT_REFRESH_TOKEN_EXPIRY);
|
||||
req.session.openidTokens = {
|
||||
accessToken: tokenset.access_token,
|
||||
idToken: tokenset.id_token,
|
||||
refreshToken,
|
||||
expiresAt: Date.now() + expiryInMilliseconds,
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* @function setOpenIDAuthTokens
|
||||
* Set OpenID Authentication Tokens
|
||||
@@ -478,15 +494,8 @@ const setOpenIDAuthTokens = (tokenset, req, res, userId, existingRefreshToken) =
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
/** Store tokens server-side in session to avoid large cookies */
|
||||
if (req.session) {
|
||||
req.session.openidTokens = {
|
||||
accessToken: tokenset.access_token,
|
||||
idToken: tokenset.id_token,
|
||||
refreshToken: refreshToken,
|
||||
expiresAt: expirationDate.getTime(),
|
||||
};
|
||||
} else {
|
||||
/** Store tokens server-side in session to avoid large cookies (one writer). */
|
||||
if (!persistOpenIDTokensToSession(req, tokenset, refreshToken)) {
|
||||
logger.warn('[setOpenIDAuthTokens] No session available, falling back to cookies');
|
||||
res.cookie('openid_access_token', tokenset.access_token, {
|
||||
expires: expirationDate,
|
||||
@@ -596,6 +605,7 @@ module.exports = {
|
||||
setAuthTokens,
|
||||
resetPassword,
|
||||
setOpenIDAuthTokens,
|
||||
persistOpenIDTokensToSession,
|
||||
requestPasswordReset,
|
||||
resendVerificationEmail,
|
||||
};
|
||||
|
||||
@@ -36,7 +36,8 @@ jest.mock('~/server/services/Config', () => ({ getAppConfig: jest.fn() }));
|
||||
jest.mock('~/server/utils', () => ({ sendEmail: jest.fn() }));
|
||||
|
||||
const { shouldUseSecureCookie } = require('@hanzochat/api');
|
||||
const { setOpenIDAuthTokens } = require('./AuthService');
|
||||
const { setOpenIDAuthTokens, persistOpenIDTokensToSession } = require('./AuthService');
|
||||
const { logger } = require('@librechat/data-schemas');
|
||||
|
||||
/** Helper to build a mock Express response */
|
||||
function mockResponse() {
|
||||
@@ -267,3 +268,76 @@ describe('setOpenIDAuthTokens', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The on-behalf-of session writer, decoupled from the refresh strategy. Called on
|
||||
* every OpenID login (regardless of OPENID_REUSE_TOKENS) so downstream cloud
|
||||
* calls can run as the hanzo.id principal — and ONLY ever touches server-side
|
||||
* session state, never a browser cookie.
|
||||
*/
|
||||
describe('persistOpenIDTokensToSession', () => {
|
||||
const env = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
process.env = { ...env };
|
||||
delete process.env.REFRESH_TOKEN_EXPIRY; // fall back to DEFAULT_REFRESH_TOKEN_EXPIRY
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
process.env = env;
|
||||
});
|
||||
|
||||
it('stores ONLY the bearer material (no OIDC refresh credential) in the decoupled path', () => {
|
||||
// Decoupled call (no explicit refreshToken arg): the on-behalf-of bearer is
|
||||
// persisted, but the tokenset's refresh_token is NOT — the decoupled session
|
||||
// refreshes via the local JWT cookie, and leaking the OIDC refresh token into
|
||||
// the session would hijack logout's session lookup (findSession by the wrong
|
||||
// token) and leave the local session un-invalidated.
|
||||
const tokenset = {
|
||||
id_token: 'the-id-token',
|
||||
access_token: 'the-access-token',
|
||||
refresh_token: 'the-refresh-token',
|
||||
};
|
||||
const req = { session: {} };
|
||||
|
||||
const before = Date.now();
|
||||
const result = persistOpenIDTokensToSession(req, tokenset);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(req.session.openidTokens).toEqual({
|
||||
accessToken: 'the-access-token',
|
||||
idToken: 'the-id-token',
|
||||
refreshToken: undefined,
|
||||
expiresAt: expect.any(Number),
|
||||
});
|
||||
// Expiry is anchored ~REFRESH_TOKEN_EXPIRY (default 7d) ahead of now.
|
||||
expect(req.session.openidTokens.expiresAt).toBeGreaterThanOrEqual(before + 604800000);
|
||||
});
|
||||
|
||||
it('persists the OIDC refresh credential only when passed EXPLICITLY (REUSE path)', () => {
|
||||
const tokenset = { id_token: 'id', access_token: 'acc', refresh_token: 'tokenset-refresh' };
|
||||
const req = { session: {} };
|
||||
|
||||
// The REUSE caller (setOpenIDAuthTokens) resolves and passes the credential.
|
||||
persistOpenIDTokensToSession(req, tokenset, 'explicit-refresh');
|
||||
|
||||
expect(req.session.openidTokens.refreshToken).toBe('explicit-refresh');
|
||||
});
|
||||
|
||||
it('returns false and warns when no session is available (never a cookie)', () => {
|
||||
const req = { session: null };
|
||||
const result = persistOpenIDTokensToSession(req, { access_token: 'acc' });
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns false when no tokenset is provided', () => {
|
||||
const req = { session: {} };
|
||||
const result = persistOpenIDTokensToSession(req, undefined);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(req.session.openidTokens).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
const { logger } = require('@librechat/data-schemas');
|
||||
|
||||
/**
|
||||
* The canonical cloud agent registry is Hanzo Cloud `/v1/agents`
|
||||
* (github.com/hanzoai/cloud, clients/agents). This client lets chat's backend
|
||||
* RUN a caller's own cloud agents from the chat thread, without ever exposing
|
||||
* the user's IAM token to the browser.
|
||||
*
|
||||
* Tenant isolation is NOT enforced here — it is enforced BY cloud. This client
|
||||
* forwards the caller's own hanzo.id bearer (the OpenID id_token) as
|
||||
* `Authorization: Bearer <token>`; cloud's SanitizeIdentity middleware
|
||||
* (HIP-0026) validates it and pins `X-Org-Id` from the verified `owner` claim,
|
||||
* stripping any client-supplied copy. So a chat user can only ever reach their
|
||||
* OWN org's agents — chat is not trusted to assert the org, and this client
|
||||
* deliberately never sends an org header for cloud to trust.
|
||||
*
|
||||
* This is NOT an open proxy: the base host is fixed from env, the only paths are
|
||||
* the three hardcoded templates below, and the agent name is validated against
|
||||
* cloud's own handle grammar before it is ever placed in a URL (no traversal,
|
||||
* no SSRF).
|
||||
*
|
||||
* @example
|
||||
* const client = getCloudAgentsClient();
|
||||
* const { agents } = await client.list(userBearer);
|
||||
* const run = await client.run(userBearer, 'researcher', 'summarize Q3');
|
||||
*/
|
||||
|
||||
/**
|
||||
* Cloud's org-unique agent handle AND URL path segment. Mirrors nameRE in
|
||||
* cloud/clients/agents/agents.go exactly — the traversal/SSRF guard at chat's
|
||||
* boundary, so a malformed name is rejected before it reaches the network.
|
||||
*/
|
||||
const AGENT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
|
||||
/** Matches cloud's maxInput (128 KiB) so oversized input fails fast, locally. */
|
||||
const MAX_INPUT = 128 * 1024;
|
||||
|
||||
/**
|
||||
* Cap the upstream body we buffer. A run's output is bounded; refusing a runaway
|
||||
* or malformed response keeps one request from pinning the shared backend's
|
||||
* memory. Availability defense — the proxy is otherwise unbounded by size.
|
||||
*/
|
||||
const MAX_RESPONSE = 4 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Process-wide ceiling on concurrent in-flight calls to cloud. Each call holds a
|
||||
* socket + timer for up to `timeout` ms; without a cap, a burst (many users, or
|
||||
* one user within the per-user rate window) could saturate the shared backend.
|
||||
* Fail fast (503) past the ceiling rather than queue and hold resources.
|
||||
*/
|
||||
const MAX_CONCURRENT = Number(process.env.CLOUD_AGENT_MAX_CONCURRENT) || 50;
|
||||
|
||||
/**
|
||||
* HTTP timeout (ms) for a cloud call. A run is a real chat completion — a
|
||||
* zen5-mini answer routinely takes ~25-30s and larger models/prompts longer — so
|
||||
* the old 30s default aborted mid-run, surfacing as an in-UI 502 even though the
|
||||
* cloud run finished and recorded. 180s gives real runs headroom; override with
|
||||
* CLOUD_AGENT_TIMEOUT. (List/get are fast; the ceiling only matters for /run.)
|
||||
*/
|
||||
const DEFAULT_TIMEOUT = Number(process.env.CLOUD_AGENT_TIMEOUT) || 180000;
|
||||
|
||||
class CloudAgentsClient {
|
||||
/**
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.endpoint - Cloud base URL (e.g. https://api.hanzo.ai)
|
||||
* @param {number} [opts.timeout] - HTTP timeout in ms (default DEFAULT_TIMEOUT,
|
||||
* 180s; a run is a real chat completion so it needs far more headroom than a
|
||||
* metadata read — 30s aborted long runs mid-flight)
|
||||
* @param {number} [opts.maxConcurrent] - process-wide in-flight ceiling
|
||||
*/
|
||||
constructor({ endpoint, timeout = DEFAULT_TIMEOUT, maxConcurrent = MAX_CONCURRENT }) {
|
||||
this.endpoint = endpoint.replace(/\/+$/, '');
|
||||
this.timeout = timeout;
|
||||
this.maxConcurrent = maxConcurrent;
|
||||
this._inFlight = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an agent name against cloud's handle grammar. Throws a tagged error
|
||||
* (status 400) on failure so the route surfaces an honest client error.
|
||||
* @param {string} name
|
||||
* @returns {string} the trimmed, validated name
|
||||
*/
|
||||
static requireValidName(name) {
|
||||
const n = (name ?? '').toString().trim();
|
||||
if (!AGENT_NAME_RE.test(n)) {
|
||||
const err = new Error('invalid agent name');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* List the caller's cloud agents.
|
||||
* @param {string} bearer - the caller's hanzo.id id_token
|
||||
* @returns {Promise<{agents: Array}>}
|
||||
*/
|
||||
async list(bearer) {
|
||||
return this._request('GET', '/v1/agents', bearer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get one cloud agent (detail + recent runs).
|
||||
* @param {string} bearer
|
||||
* @param {string} name
|
||||
* @returns {Promise<Object>} cloud's AgentDetail
|
||||
*/
|
||||
async get(bearer, name) {
|
||||
const n = CloudAgentsClient.requireValidName(name);
|
||||
return this._request('GET', `/v1/agents/${encodeURIComponent(n)}`, bearer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one cloud agent with a caller-supplied input. Records a real run in
|
||||
* cloud and returns the RunResult (status "ok" with output, or an upstream
|
||||
* failure surfaced honestly).
|
||||
* @param {string} bearer
|
||||
* @param {string} name
|
||||
* @param {string} input
|
||||
* @returns {Promise<Object>} cloud's RunResult
|
||||
*/
|
||||
async run(bearer, name, input) {
|
||||
const n = CloudAgentsClient.requireValidName(name);
|
||||
const body = (input ?? '').toString();
|
||||
// Byte length, not UTF-16 units — matches cloud's byte-based maxInput exactly
|
||||
// (a multibyte string can be ~3x its .length in UTF-8).
|
||||
if (Buffer.byteLength(body, 'utf8') > MAX_INPUT) {
|
||||
const err = new Error('input too large');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
return this._request('POST', `/v1/agents/${encodeURIComponent(n)}/run`, bearer, {
|
||||
input: body,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} method
|
||||
* @param {string} path - one of the fixed templates above
|
||||
* @param {string} bearer - the caller's hanzo.id bearer (required)
|
||||
* @param {Object} [body]
|
||||
* @returns {Promise<Object>}
|
||||
*/
|
||||
async _request(method, path, bearer, body) {
|
||||
if (!bearer) {
|
||||
// Fail secure: never fall back to an ambient/service credential — that
|
||||
// would run as the wrong principal. Absent a user bearer, deny.
|
||||
const err = new Error('missing user credential');
|
||||
err.status = 401;
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (this._inFlight >= this.maxConcurrent) {
|
||||
// Shed load: the shared backend is saturated with upstream calls. Refusing
|
||||
// here protects every other tenant — availability over this one request.
|
||||
const err = new Error('cloud agents temporarily saturated');
|
||||
err.status = 503;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const url = `${this.endpoint}${path}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${bearer}`,
|
||||
};
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
||||
this._inFlight += 1;
|
||||
|
||||
try {
|
||||
const opts = { method, headers, signal: controller.signal };
|
||||
if (body && method !== 'GET') {
|
||||
opts.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const resp = await fetch(url, opts);
|
||||
const text = await this._readCapped(resp, controller);
|
||||
let json;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
json = { error: text };
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
// A run that executed but failed upstream comes back as 502 with a run
|
||||
// body (status/error) — preserve that so the caller can surface it.
|
||||
const err = new Error(`cloud ${method} ${path} returned ${resp.status}`);
|
||||
err.status = resp.status;
|
||||
err.body = json;
|
||||
throw err;
|
||||
}
|
||||
return json;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
this._inFlight -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the response body but never buffer more than MAX_RESPONSE bytes. Rejects
|
||||
* a declared-oversize body up front (Content-Length) and aborts a chunked
|
||||
* stream the instant it exceeds the cap, so a runaway upstream cannot exhaust
|
||||
* memory. Falls back to `.text()` when the runtime/mocks expose no stream body.
|
||||
* @param {Response} resp
|
||||
* @param {AbortController} controller
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async _readCapped(resp, controller) {
|
||||
const declared = Number(resp.headers?.get?.('content-length'));
|
||||
if (Number.isFinite(declared) && declared > MAX_RESPONSE) {
|
||||
controller.abort();
|
||||
const err = new Error('cloud response too large');
|
||||
err.status = 502;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const reader = resp.body?.getReader?.();
|
||||
if (!reader) {
|
||||
return resp.text().catch(() => '');
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let out = '';
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
total += value.byteLength;
|
||||
if (total > MAX_RESPONSE) {
|
||||
await reader.cancel();
|
||||
controller.abort();
|
||||
const err = new Error('cloud response too large');
|
||||
err.status = 502;
|
||||
throw err;
|
||||
}
|
||||
out += decoder.decode(value, { stream: true });
|
||||
}
|
||||
out += decoder.decode();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton, initialized lazily from env. Returns null when cloud agents are not
|
||||
* configured for this deployment (the route then answers with a disabled state).
|
||||
*/
|
||||
let _instance;
|
||||
|
||||
function getCloudAgentsClient() {
|
||||
if (_instance !== undefined) {
|
||||
return _instance;
|
||||
}
|
||||
|
||||
// Dedicated var first; fall back to the same host the rest of chat already
|
||||
// talks to (api.hanzo.ai), derived from OPENAI_BASE_URL by stripping the /v1.
|
||||
let endpoint = (process.env.HANZO_CLOUD_URL || '').trim();
|
||||
if (!endpoint) {
|
||||
const base = (process.env.OPENAI_BASE_URL || '').trim();
|
||||
if (base) {
|
||||
endpoint = base.replace(/\/v1\/?$/, '');
|
||||
}
|
||||
}
|
||||
|
||||
if (!endpoint) {
|
||||
_instance = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
_instance = new CloudAgentsClient({ endpoint });
|
||||
logger.info('[CloudAgentsClient] Initialized', { endpoint });
|
||||
return _instance;
|
||||
}
|
||||
|
||||
/** Reset the memoized singleton (tests only). */
|
||||
function _resetCloudAgentsClient() {
|
||||
_instance = undefined;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CloudAgentsClient,
|
||||
getCloudAgentsClient,
|
||||
_resetCloudAgentsClient,
|
||||
AGENT_NAME_RE,
|
||||
MAX_INPUT,
|
||||
MAX_RESPONSE,
|
||||
MAX_CONCURRENT,
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
jest.mock('@librechat/data-schemas', () => ({
|
||||
logger: {
|
||||
debug: jest.fn(),
|
||||
error: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const {
|
||||
CloudAgentsClient,
|
||||
getCloudAgentsClient,
|
||||
_resetCloudAgentsClient,
|
||||
AGENT_NAME_RE,
|
||||
MAX_INPUT,
|
||||
MAX_RESPONSE,
|
||||
} = require('./CloudAgentsClient');
|
||||
|
||||
/**
|
||||
* Build a fetch mock that captures the last request and returns a canned response.
|
||||
*/
|
||||
function mockFetch({ ok = true, status = 200, body = {} } = {}) {
|
||||
const calls = [];
|
||||
const fn = jest.fn(async (url, opts) => {
|
||||
calls.push({ url, opts });
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),
|
||||
};
|
||||
});
|
||||
fn.calls = calls;
|
||||
return fn;
|
||||
}
|
||||
|
||||
describe('CloudAgentsClient', () => {
|
||||
const BEARER = 'header.payload.sig';
|
||||
|
||||
afterEach(() => {
|
||||
_resetCloudAgentsClient();
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
describe('name validation (traversal / SSRF guard)', () => {
|
||||
const bad = ['', '.', '..', '../etc', 'a/b', 'name with space', 'a'.repeat(65), '-lead'];
|
||||
const good = ['researcher', 'a', 'A.b_c-1', '0abc'];
|
||||
|
||||
it('rejects malformed names before any network call', async () => {
|
||||
const fetch = mockFetch();
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
for (const name of bad) {
|
||||
await expect(client.get(BEARER, name)).rejects.toMatchObject({ status: 400 });
|
||||
}
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('accepts valid handles matching cloud grammar', () => {
|
||||
for (const name of good) {
|
||||
expect(AGENT_NAME_RE.test(name)).toBe(true);
|
||||
expect(CloudAgentsClient.requireValidName(name)).toBe(name);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('bearer forwarding + tenant model', () => {
|
||||
it('forwards the user bearer and NEVER sends an org header', async () => {
|
||||
const fetch = mockFetch({ body: { agents: [] } });
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await client.list(BEARER);
|
||||
|
||||
const { url, opts } = fetch.calls[0];
|
||||
expect(url).toBe('https://api.hanzo.ai/v1/agents');
|
||||
expect(opts.headers.Authorization).toBe(`Bearer ${BEARER}`);
|
||||
// Tenant isolation is cloud's job; chat must not assert an org.
|
||||
expect(opts.headers['X-Org-Id']).toBeUndefined();
|
||||
expect(opts.headers['X-Hanzo-Org']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails secure (401) with no fallback credential when bearer is missing', async () => {
|
||||
const fetch = mockFetch();
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await expect(client.list('')).rejects.toMatchObject({ status: 401 });
|
||||
await expect(client.run('', 'researcher', 'x')).rejects.toMatchObject({ status: 401 });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('run', () => {
|
||||
it('posts {input} to the run endpoint and returns the RunResult', async () => {
|
||||
const fetch = mockFetch({ body: { id: 'run_1', status: 'ok', output: 'hi' } });
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai/' });
|
||||
const run = await client.run(BEARER, 'researcher', 'summarize');
|
||||
|
||||
const { url, opts } = fetch.calls[0];
|
||||
expect(url).toBe('https://api.hanzo.ai/v1/agents/researcher/run');
|
||||
expect(opts.method).toBe('POST');
|
||||
expect(JSON.parse(opts.body)).toEqual({ input: 'summarize' });
|
||||
expect(run).toEqual({ id: 'run_1', status: 'ok', output: 'hi' });
|
||||
});
|
||||
|
||||
it('rejects oversized input locally (before the network)', async () => {
|
||||
const fetch = mockFetch();
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
const big = 'x'.repeat(128 * 1024 + 1);
|
||||
await expect(client.run(BEARER, 'researcher', big)).rejects.toMatchObject({ status: 400 });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces an upstream failure body (cloud 502 error run) with its status', async () => {
|
||||
const fetch = mockFetch({
|
||||
ok: false,
|
||||
status: 502,
|
||||
body: { id: 'run_2', status: 'error', error: 'model down' },
|
||||
});
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await expect(client.run(BEARER, 'researcher', 'x')).rejects.toMatchObject({
|
||||
status: 502,
|
||||
body: { status: 'error', error: 'model down' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('input byte cap', () => {
|
||||
it('rejects on UTF-8 BYTE length, not UTF-16 units (multibyte bypass)', async () => {
|
||||
const fetch = mockFetch();
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
// Half MAX_INPUT in .length, but 3 bytes/char in UTF-8 => 1.5x MAX_INPUT bytes.
|
||||
const multibyte = '你'.repeat(MAX_INPUT / 2);
|
||||
expect(multibyte.length).toBeLessThan(MAX_INPUT); // would pass a naive .length check
|
||||
expect(Buffer.byteLength(multibyte, 'utf8')).toBeGreaterThan(MAX_INPUT);
|
||||
await expect(client.run(BEARER, 'researcher', multibyte)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('response size cap (availability)', () => {
|
||||
it('rejects a declared-oversize body up front via Content-Length (502)', async () => {
|
||||
global.fetch = jest.fn(
|
||||
async () =>
|
||||
new Response('ok', {
|
||||
status: 200,
|
||||
headers: { 'content-length': String(MAX_RESPONSE + 1) },
|
||||
}),
|
||||
);
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await expect(client.list(BEARER)).rejects.toMatchObject({ status: 502 });
|
||||
});
|
||||
|
||||
it('aborts a chunked stream once it exceeds the cap (502)', async () => {
|
||||
const oversize = new Uint8Array(MAX_RESPONSE + 16);
|
||||
global.fetch = jest.fn(async () => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(oversize);
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
return new Response(stream, { status: 200 }); // chunked: no content-length
|
||||
});
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await expect(client.list(BEARER)).rejects.toMatchObject({ status: 502 });
|
||||
});
|
||||
|
||||
it('reads a normal small streamed body', async () => {
|
||||
global.fetch = jest.fn(
|
||||
async () => new Response(JSON.stringify({ agents: [] }), { status: 200 }),
|
||||
);
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
await expect(client.list(BEARER)).resolves.toEqual({ agents: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('concurrency cap (load shedding)', () => {
|
||||
it('sheds load with 503 once the in-flight ceiling is reached, before any fetch', async () => {
|
||||
const fetch = mockFetch({ body: { agents: [] } });
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai', maxConcurrent: 2 });
|
||||
client._inFlight = 2; // simulate the ceiling being saturated
|
||||
await expect(client.list(BEARER)).rejects.toMatchObject({ status: 503 });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('decrements in-flight after a call completes (no leak)', async () => {
|
||||
const fetch = mockFetch({ body: { agents: [] } });
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai', maxConcurrent: 1 });
|
||||
await client.list(BEARER);
|
||||
expect(client._inFlight).toBe(0);
|
||||
await client.list(BEARER); // ceiling of 1 is reusable across sequential calls
|
||||
expect(client._inFlight).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('endpoint normalization', () => {
|
||||
it('strips trailing slashes from the base URL', async () => {
|
||||
const fetch = mockFetch({ body: {} });
|
||||
global.fetch = fetch;
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai///' });
|
||||
await client.list(BEARER);
|
||||
expect(fetch.calls[0].url).toBe('https://api.hanzo.ai/v1/agents');
|
||||
});
|
||||
});
|
||||
|
||||
describe('run timeout (headroom for long completions)', () => {
|
||||
it('defaults to 180s so a long run is not aborted mid-flight (the 30s -> 502 bug)', () => {
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai' });
|
||||
expect(client.timeout).toBe(180000);
|
||||
});
|
||||
|
||||
it('honors an explicit constructor timeout', () => {
|
||||
const client = new CloudAgentsClient({ endpoint: 'https://api.hanzo.ai', timeout: 5000 });
|
||||
expect(client.timeout).toBe(5000);
|
||||
});
|
||||
|
||||
it('is overridable via CLOUD_AGENT_TIMEOUT (mirrors CLOUD_AGENT_MAX_CONCURRENT)', () => {
|
||||
const saved = process.env.CLOUD_AGENT_TIMEOUT;
|
||||
process.env.CLOUD_AGENT_TIMEOUT = '90000';
|
||||
// DEFAULT_TIMEOUT is read at module load, so re-require in isolation.
|
||||
jest.resetModules();
|
||||
const { CloudAgentsClient: Fresh } = require('./CloudAgentsClient');
|
||||
try {
|
||||
expect(new Fresh({ endpoint: 'https://api.hanzo.ai' }).timeout).toBe(90000);
|
||||
} finally {
|
||||
if (saved === undefined) {
|
||||
delete process.env.CLOUD_AGENT_TIMEOUT;
|
||||
} else {
|
||||
process.env.CLOUD_AGENT_TIMEOUT = saved;
|
||||
}
|
||||
jest.resetModules();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCloudAgentsClient (env wiring)', () => {
|
||||
const saved = {};
|
||||
beforeEach(() => {
|
||||
saved.HANZO_CLOUD_URL = process.env.HANZO_CLOUD_URL;
|
||||
saved.OPENAI_BASE_URL = process.env.OPENAI_BASE_URL;
|
||||
delete process.env.HANZO_CLOUD_URL;
|
||||
delete process.env.OPENAI_BASE_URL;
|
||||
_resetCloudAgentsClient();
|
||||
});
|
||||
afterEach(() => {
|
||||
process.env.HANZO_CLOUD_URL = saved.HANZO_CLOUD_URL;
|
||||
process.env.OPENAI_BASE_URL = saved.OPENAI_BASE_URL;
|
||||
if (saved.HANZO_CLOUD_URL === undefined) {
|
||||
delete process.env.HANZO_CLOUD_URL;
|
||||
}
|
||||
if (saved.OPENAI_BASE_URL === undefined) {
|
||||
delete process.env.OPENAI_BASE_URL;
|
||||
}
|
||||
_resetCloudAgentsClient();
|
||||
});
|
||||
|
||||
it('returns null when unconfigured', () => {
|
||||
expect(getCloudAgentsClient()).toBeNull();
|
||||
});
|
||||
|
||||
it('prefers HANZO_CLOUD_URL', () => {
|
||||
process.env.HANZO_CLOUD_URL = 'https://cloud.example';
|
||||
expect(getCloudAgentsClient().endpoint).toBe('https://cloud.example');
|
||||
});
|
||||
|
||||
it('derives the host from OPENAI_BASE_URL by stripping /v1', () => {
|
||||
process.env.OPENAI_BASE_URL = 'https://api.hanzo.ai/v1';
|
||||
expect(getCloudAgentsClient().endpoint).toBe('https://api.hanzo.ai');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,15 @@
|
||||
const { logger } = require('@librechat/data-schemas');
|
||||
|
||||
/**
|
||||
* CommerceClient provides a cached, fail-open interface to Hanzo Commerce
|
||||
* billing APIs. Pattern follows cloud-api's filter_balance.go:
|
||||
* CommerceClient is chat's READ-ONLY window into Hanzo Commerce (balance, tier,
|
||||
* credit breakdown). It NEVER writes: the single debit for an AI spend is the
|
||||
* cloud gateway's (api.hanzo.ai debits the forwarded per-user hk- key), and the
|
||||
* only credit (the first-chat starter grant) is issued by resolveHanzoCloudKey
|
||||
* (packages/api) at the request boundary. Two writers to one ledger is the
|
||||
* double-debit anti-pattern — so chat stays a reader. Pattern follows cloud-api's
|
||||
* filter_balance.go:
|
||||
* - 30s TTL balance/tier cache with async refresh
|
||||
* - Fire-and-forget usage recording queue
|
||||
* - All errors fail-open (local MongoDB is authoritative fallback)
|
||||
* - Reads fail CLOSED (the money gate); tier/breakdown fail open
|
||||
*
|
||||
* @example
|
||||
* const client = new CommerceClient({
|
||||
@@ -33,11 +37,6 @@ class CommerceClient {
|
||||
// Tier cache: userId -> { data, fetchedAt, refreshing }
|
||||
this._tierCache = new Map();
|
||||
|
||||
// Usage recording queue
|
||||
this._usageQueue = [];
|
||||
this._usageFlushing = false;
|
||||
this._usageFlushInterval = setInterval(() => this._flushUsageQueue(), 5000);
|
||||
|
||||
// Cache cleanup every 5 minutes
|
||||
this._cleanupInterval = setInterval(() => this._cleanupCaches(), 300000);
|
||||
}
|
||||
@@ -134,64 +133,6 @@ class CommerceClient {
|
||||
return { allowed, tier: tier.name, allowedModels: tier.allowedModels };
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue usage recording (fire-and-forget). Commerce calls BurnCredits
|
||||
* internally to burn trial grants first, then paid.
|
||||
*
|
||||
* @param {Object} usage
|
||||
* @param {string} usage.userId
|
||||
* @param {string} usage.model
|
||||
* @param {number} usage.promptTokens
|
||||
* @param {number} usage.completionTokens
|
||||
* @param {number} usage.amountCents - Cost in cents
|
||||
*/
|
||||
recordUsage({ userId, model, promptTokens, completionTokens, amountCents }) {
|
||||
this._usageQueue.push({
|
||||
user: userId,
|
||||
model,
|
||||
promptTokens: promptTokens || 0,
|
||||
completionTokens: completionTokens || 0,
|
||||
amount: amountCents || 0,
|
||||
currency: 'usd',
|
||||
status: 'completed',
|
||||
});
|
||||
|
||||
// Flush immediately if queue is large
|
||||
if (this._usageQueue.length >= 50) {
|
||||
this._flushUsageQueue().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a subject has the one-time $5 starter credit, idempotently.
|
||||
*
|
||||
* This posts to /v1/billing/grant-starter, which creates a real Deposit
|
||||
* transaction (tag "starter-credit", $5, 30-day expiry) — so it nets into
|
||||
* GET /v1/billing/balance, the account the gateway gate reads and debits.
|
||||
* (NOT a credit-grant record: those live in a separate ledger the balance
|
||||
* endpoint does not read, so they would never unblock the gate.)
|
||||
*
|
||||
* Idempotent + race-safe in Commerce (tag-deduped inside a transaction): safe
|
||||
* to call on every first chat; duplicate/concurrent calls never double-grant.
|
||||
*
|
||||
* @param {string} subject - Commerce billing subject (e.g. "hanzo/alice@gmail.com")
|
||||
* @returns {Promise<{granted: boolean}|null>} or null on failure
|
||||
*/
|
||||
async grantStarter(subject) {
|
||||
try {
|
||||
const resp = await this._request(
|
||||
'POST',
|
||||
'/v1/billing/grant-starter',
|
||||
{ user: subject, trigger: 'chat_first_use' },
|
||||
this._namespaceOf(subject),
|
||||
);
|
||||
return resp;
|
||||
} catch (err) {
|
||||
logger.error('[CommerceClient] Failed to ensure starter credit', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get credit balance breakdown by tag (trial vs purchased).
|
||||
*
|
||||
@@ -268,30 +209,6 @@ class CommerceClient {
|
||||
}
|
||||
}
|
||||
|
||||
async _flushUsageQueue() {
|
||||
if (this._usageFlushing || this._usageQueue.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._usageFlushing = true;
|
||||
const batch = this._usageQueue.splice(0, 100);
|
||||
|
||||
for (const usage of batch) {
|
||||
try {
|
||||
await this._request('POST', '/v1/billing/usage', usage);
|
||||
} catch (err) {
|
||||
logger.warn('[CommerceClient] Usage recording failed', {
|
||||
user: usage.user,
|
||||
model: usage.model,
|
||||
error: err.message,
|
||||
});
|
||||
// Don't retry — usage is also tracked locally in MongoDB
|
||||
}
|
||||
}
|
||||
|
||||
this._usageFlushing = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} method
|
||||
* @param {string} path
|
||||
@@ -351,10 +268,7 @@ class CommerceClient {
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearInterval(this._usageFlushInterval);
|
||||
clearInterval(this._cleanupInterval);
|
||||
// Flush remaining usage
|
||||
this._flushUsageQueue().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,10 @@ const buildOptions = (req, endpoint, parsedBody, endpointType) => {
|
||||
const agentPromise = loadAgent({
|
||||
req,
|
||||
spec,
|
||||
agent_id: isAgentsEndpoint(endpoint) ? agent_id : Constants.EPHEMERAL_AGENT_ID,
|
||||
// No agent selected on the agents endpoint → ad-hoc (ephemeral) chat, so the
|
||||
// user gets a reply without first creating/selecting an agent. Mirrors the
|
||||
// access middleware, which treats a missing id as ephemeral.
|
||||
agent_id: isAgentsEndpoint(endpoint) && agent_id ? agent_id : Constants.EPHEMERAL_AGENT_ID,
|
||||
endpoint,
|
||||
model_parameters,
|
||||
}).catch((error) => {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Regression: when no agent is created/selected, the agents endpoint must resolve
|
||||
* to an ephemeral (ad-hoc, plain-model) agent so the user gets a reply — instead
|
||||
* of loadAgent returning null because agent_id was missing.
|
||||
*
|
||||
* Hermetic: mocks data-schemas (no winston) and ~/models/Agent (no MongoDB).
|
||||
*/
|
||||
|
||||
jest.mock('@librechat/data-schemas', () => ({ logger: { error: jest.fn() } }));
|
||||
|
||||
jest.mock('librechat-data-provider', () => ({
|
||||
Constants: { EPHEMERAL_AGENT_ID: 'ephemeral' },
|
||||
isAgentsEndpoint: (endpoint) => endpoint === 'agents',
|
||||
removeNullishValues: (obj) =>
|
||||
Object.fromEntries(Object.entries(obj).filter(([, v]) => v != null)),
|
||||
}));
|
||||
|
||||
const mockLoadAgent = jest.fn(() => Promise.resolve({ id: 'ephemeral', model: 'zen3-nano' }));
|
||||
jest.mock('~/models/Agent', () => ({ loadAgent: mockLoadAgent }));
|
||||
|
||||
const { buildOptions } = require('./build');
|
||||
|
||||
const EPHEMERAL = 'ephemeral';
|
||||
|
||||
describe('agents buildOptions — missing agent_id resolves to ephemeral', () => {
|
||||
beforeEach(() => mockLoadAgent.mockClear());
|
||||
|
||||
test('no agent_id on agents endpoint → loadAgent called with EPHEMERAL_AGENT_ID', async () => {
|
||||
const req = { body: {}, user: { id: 'u1' } };
|
||||
// parsedBody as built from "My Agents" with no agent selected (no agent_id).
|
||||
const options = buildOptions(req, 'agents', { model: 'zen3-nano' });
|
||||
await options.agent;
|
||||
|
||||
expect(mockLoadAgent).toHaveBeenCalledTimes(1);
|
||||
expect(mockLoadAgent.mock.calls[0][0].agent_id).toBe(EPHEMERAL);
|
||||
});
|
||||
|
||||
test('real agent_id on agents endpoint is passed through unchanged', async () => {
|
||||
const req = { body: {}, user: { id: 'u1' } };
|
||||
const options = buildOptions(req, 'agents', { model: 'zen3-nano', agent_id: 'agent_real_42' });
|
||||
await options.agent;
|
||||
|
||||
expect(mockLoadAgent.mock.calls[0][0].agent_id).toBe('agent_real_42');
|
||||
});
|
||||
|
||||
test('non-agents endpoint always resolves to ephemeral', async () => {
|
||||
const req = { body: {}, user: { id: 'u1' } };
|
||||
const options = buildOptions(req, 'openAI', { model: 'zen3-nano', agent_id: 'agent_real_42' });
|
||||
await options.agent;
|
||||
|
||||
expect(mockLoadAgent.mock.calls[0][0].agent_id).toBe(EPHEMERAL);
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,7 @@ const createDownloadFallback = ({
|
||||
const basePath = getBasePath();
|
||||
return {
|
||||
filename: name,
|
||||
filepath: `${basePath}/api/files/code/download/${session_id}/${id}`,
|
||||
filepath: `${basePath}/v1/chat/files/code/download/${session_id}/${id}`,
|
||||
expiresAt,
|
||||
conversationId,
|
||||
toolCallId,
|
||||
|
||||
@@ -286,7 +286,7 @@ describe('Code Process', () => {
|
||||
const result = await processCodeOutput(baseParams);
|
||||
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('exceeds size limit'));
|
||||
expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');
|
||||
expect(result.filepath).toContain('/v1/chat/files/code/download/session-123/file-id-123');
|
||||
expect(result.expiresAt).toBeDefined();
|
||||
// Should not call createFile for oversized files (fallback path)
|
||||
expect(createFile).not.toHaveBeenCalled();
|
||||
@@ -307,7 +307,7 @@ describe('Code Process', () => {
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('saveBuffer not available'),
|
||||
);
|
||||
expect(result.filepath).toContain('/api/files/code/download/');
|
||||
expect(result.filepath).toContain('/v1/chat/files/code/download/');
|
||||
expect(result.filename).toBe('test-file.txt');
|
||||
});
|
||||
|
||||
@@ -316,7 +316,7 @@ describe('Code Process', () => {
|
||||
|
||||
const result = await processCodeOutput(baseParams);
|
||||
|
||||
expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');
|
||||
expect(result.filepath).toContain('/v1/chat/files/code/download/session-123/file-id-123');
|
||||
expect(result.conversationId).toBe('conv-123');
|
||||
expect(result.messageId).toBe('msg-123');
|
||||
expect(result.toolCallId).toBe('tool-call-123');
|
||||
|
||||
@@ -55,7 +55,7 @@ const buildGuestPrincipal = (id) => ({
|
||||
});
|
||||
|
||||
/**
|
||||
* Builds the guest-scoped `/api/user` response: the ephemeral principal only.
|
||||
* Builds the guest-scoped `/v1/chat/user` response: the ephemeral principal only.
|
||||
* Mirrors the safe-field shape the client expects (no password/totp/email/db id).
|
||||
*
|
||||
* @param {{ id: string }} principal
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
const removePorts = require('./removePorts');
|
||||
|
||||
/**
|
||||
* Resolves the real client IP for per-IP guest rate limiting.
|
||||
*
|
||||
* hanzo.chat is served behind Cloudflare → the DO LB → the ingress. With that
|
||||
* many hops, Express `req.ip` (via `trust proxy`) is not reliably the visitor's
|
||||
* address, which would let anonymous users share/reset their free-message bucket
|
||||
* (or collapse everyone into one bucket). Cloudflare always sets
|
||||
* `CF-Connecting-IP` to the true originating client and — unlike a
|
||||
* client-supplied `X-Forwarded-For` entry — a browser cannot forge it through
|
||||
* the CF edge. Prefer it; fall back to the trust-proxy-resolved `req.ip` when the
|
||||
* request did not transit Cloudflare (e.g. in-cluster/local).
|
||||
*
|
||||
* The returned string is the SOLE identity the guest quota keys on, so it must be
|
||||
* stable across guest tokens, cookie clears, and incognito sessions from the same
|
||||
* network origin.
|
||||
*
|
||||
* @param {import('express').Request} req
|
||||
* @returns {string}
|
||||
*/
|
||||
const guestClientIp = (req) => {
|
||||
const cf = req.headers?.['cf-connecting-ip'];
|
||||
if (typeof cf === 'string' && cf.trim()) {
|
||||
return cf.trim();
|
||||
}
|
||||
return removePorts(req);
|
||||
};
|
||||
|
||||
module.exports = guestClientIp;
|
||||
@@ -1,4 +1,5 @@
|
||||
const removePorts = require('./removePorts');
|
||||
const guestClientIp = require('./guestClientIp');
|
||||
const handleText = require('./handleText');
|
||||
const sendEmail = require('./sendEmail');
|
||||
const queue = require('./queue');
|
||||
@@ -7,6 +8,7 @@ const files = require('./files');
|
||||
module.exports = {
|
||||
...handleText,
|
||||
removePorts,
|
||||
guestClientIp,
|
||||
sendEmail,
|
||||
...files,
|
||||
...queue,
|
||||
|
||||
@@ -674,7 +674,7 @@ const setupOpenIdAdmin = (openidConfig) => {
|
||||
scope: process.env.OPENID_SCOPE,
|
||||
usePKCE: isEnabled(process.env.OPENID_USE_PKCE),
|
||||
clockTolerance: process.env.OPENID_CLOCK_TOLERANCE || 300,
|
||||
callbackURL: process.env.DOMAIN_SERVER + '/api/admin/oauth/openid/callback',
|
||||
callbackURL: process.env.DOMAIN_SERVER + '/v1/chat/admin/oauth/openid/callback',
|
||||
},
|
||||
createOpenIDCallback(true),
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user