Compare commits

...
Author SHA1 Message Date
hanzo-dev c9fd1cfc07 ci(data-schemas): isolate native-sqlite specs one-file-per-process; v0.9.16
The 15 specs that instantiate the native better-sqlite3 driver corrupt each
other under a shared jest worker: jest gives each spec file its own JS module
realm while the native addon is process-cached per worker, so cross-file state
breaks sibling in-memory databases (driver-agnostic — reproduces with mainstream
better-sqlite3; a compound json_extract UNIQUE stops firing). Prod is unaffected
(one realm, one shared handle for the process lifetime).

test:ci now runs test/ci.mjs: the normal coverage pass for everything except the
native-driver set (via testPathIgnorePatterns), then each of those 15 specs in
its own jest process, exiting non-zero on any failure. NOT --runInBand /
maxWorkers=1 (a single shared worker still corrupts). No test weakening, no skips.

Bump chat 0.9.15 -> 0.9.16 (patch).
2026-07-04 15:51:44 -07:00
hanzo-dev 5feca644e2 fix(store/sqlite): close shared handle on rekey + test teardown (real leak)
sharedSqliteHandle() reassigned sharedHandle on a collection-key change without
closing the prior connection — a latent native-handle leak on any rekey. Close
it before replacing, and export closeSharedSqliteHandle() so storeRegistry.spec
(rekeys twice) and tenantIsolation.coverage.spec tear the handle down instead of
leaking it past the file.

NOTE: this fixes the real leak the review identified, but does NOT resolve the
cross-file store-spec flake. That flake is a separate, deeper issue (see report):
driver-agnostic (reproduces with mainstream better-sqlite3 too), isolated to the
store's create path, timing/heap-sensitive (any probe masks it), and NOT fixed by
closing handles/GC/statement-cache/wrapper-pinning. Every store suite passes in
its own process; production (single long-lived handle, one module realm) is
unaffected.
2026-07-04 15:35:37 -07:00
hanzo-dev 72a5c71fe3 fix(store/sqlite): swap node:sqlite→better-sqlite3-multiple-ciphers (Node 20) + honor tenant sentinel in debug log
node:sqlite (DatabaseSync) is a Node 22+ builtin; prod runs Node 20 (Alpine),
so require('node:sqlite') threw ERR_UNKNOWN_BUILTIN_MODULE, cascading through
createModels → applySqliteOverrides → openDatabase and breaking the built dist
("createModels is not a function"). Swap to better-sqlite3-multiple-ciphers
12.11.1 (engines include 20.x, synchronous drop-in, SQLCipher AES-256 at rest —
the Node embodiment of the hanzoai/sqlite contract).

- data-schemas dep + root pnpm.onlyBuiltDependencies allowlist (native addon);
  rollup externalizes the driver.
- openDatabase(): lazy require of the driver, identical WAL/synchronous/
  busy_timeout/foreign_keys pragmas. Wire the CHAT_SQLITE_KEY encryption seam
  (SQLCipher cipher/legacy/key pragmas applied before any page-touching
  statement; 64-hex validated, fail-closed; key/path never logged). KMS/CEK
  derivation is Milestone 2.
- DocModel: retype db to the driver's Database instance; binding/return parity
  already correct (booleans→1/0, dates→ISO, TEXT reads only). engine untouched
  (27/27 held).
- parsers: restore the structured-logging-context impl dropped in an upstream
  merge (spec #13110 landed without its parsers.ts) — appendRequestContext for
  non-debug lines and drop the __SYSTEM__ tenant sentinel from debug traversal.
- models: register the SystemGrant model in createModels (schema/model/methods/
  SQLite-spec + coverage guard all existed; only the registration was dangling).

Scrub all node:sqlite/DatabaseSync references from src (comments + spec names).
2026-07-04 14:40:03 -07:00
hanzo-devandz 31bd2144cf fix(store/sqlite): guard engine setPath/deletePath against prototype pollution
The SQLite store's update path feeds attacker-influenced keys ($set/$unset/
$inc/$push/$addToSet — conversation import, saveConvo, agent metadata) straight
into setPath, which walked cur['__proto__'] / cur['constructor'] and could mutate
a shared prototype (global prototype pollution). Reject any dotted path whose
segments include __proto__/prototype/constructor (and the single-segment own-key
case a JSON.parse'd body produces). Legitimate nested writes are unaffected.

engine.spec: +5 guard cases (dotted $set, constructor.prototype, JSON-sourced
own __proto__, $setOnInsert/$inc, legit nested still writes). 27/27 green on
Node 20 (pure-JS engine, no node:sqlite dependency).
2026-07-04 14:14:56 -07:00
zeekayandClaude Fable 5 8360c518b6 fix(backfill): resolve @librechat/data-schemas via workspace path fallback
The pnpm workspace does not hoist a bare @librechat/data-schemas symlink to
the app root where the backfill runs (node config/backfill-sqlite.js), so a
bare require throws MODULE_NOT_FOUND in the pod. Fall back to the workspace
path (packages/data-schemas). Verified: require('/app/packages/data-schemas')
resolves in the chat pod.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 13:15:39 -07:00
zeekayandClaude Fable 5 bd938fc6c6 feat(store): dual-write mirror + auth/billing specs to drop chat-docdb (0.9.15)
The Mongo→SQLite cutover, completed so chat-docdb can be DELETED with zero
data loss and an instant revert at every step.

- DualWriteModel: wraps a primary (served) + mirror model; reads/props fall
  through to primary, the 10 write methods run on primary then replicate the
  affected docs to the mirror KEYED BY THE PRIMARY'S _id (upsert if present,
  delete if gone). Symmetric — same code mirrors mongoose->sqlite (pre-flip)
  and sqlite->mongoose (post-flip escape hatch). Mirror failures are logged,
  never thrown, so the served path can't break; gaps are caught by the
  pre-flip count reconcile + the idempotent backfill.
- DocModel.upsertRaw: exact by-_id upsert (verbatim, no timestamp stamping) —
  the shared primitive for the mirror AND the backfill, so live mirroring and
  the one-shot copy converge on one keyspace without duplicating.
- Seam: applySqliteOverrides now honors TWO flags — CHAT_STORE_SQLITE (served)
  + CHAT_STORE_DUALWRITE (mirrored) — yielding the four cutover states. One
  shared node:sqlite connection per process (was per-createModels-call).
- Route User/Session/Token through the handle (methods/index.ts) and add the
  auth+billing CollectionSpecs (User/Session/Token/Balance/Transaction). These
  are the collections actually populated in chat-docdb outside the 24 already
  wired; User is the hot-path record every request loads and every conversation
  references by _id, so it MUST move for a lossless Mongo delete.
- connectDb() is now Mongo-optional: unset MONGO_URI => SQLite-only mode, skip
  the connection (final state, chat-docdb gone) with bufferCommands off so a
  stray mongoose query fails fast instead of hanging.
- Dockerfile{,.multi,.static}: node:20/22-alpine -> ghcr.io/hanzoai/nodejs
  :v24.18.0 (Node 24; node:sqlite built in, better-sqlite3 compiles).
- config/backfill-sqlite.js: one-shot Mongo->SQLite copy + count reconcile.

Tests: DualWriteModel.spec (10) green — mirror-by-primary-_id both directions,
read passthrough, bulkWrite, idempotent backfill, all 29 specs build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 13:04:11 -07:00
b6a82bcf8f fix(agents): raise cloud-agent run timeout 30s→180s (long-run 502) (#58)
* fix(agents): raise cloud-agent run timeout 30s→180s (env CLOUD_AGENT_TIMEOUT)

A cloud agent run is a real chat completion — a zen5-mini answer routinely
takes ~25-30s (measured 28s), larger models/prompts longer. The hardcoded 30s
client timeout aborted long runs mid-flight, surfacing in the UI as a 502 even
though the cloud run finished and was recorded. Bump the default to 180s and
make it env-configurable (CLOUD_AGENT_TIMEOUT), matching the existing
CLOUD_AGENT_MAX_CONCURRENT knob. List/get are fast; this headroom only affects
/run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(agents): lock cloud-agent run timeout contract (180s default + env override)

Adds coverage the timeout bump lacked: asserts the 180s default (the fix for
the 30s -> in-UI 502), that an explicit constructor timeout wins, and that
CLOUD_AGENT_TIMEOUT overrides the module-load default (isolated re-require).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 05:14:04 -07:00
zeekayandClaude Opus 4.8 650ad06b15 ci: ignore all three transitive-pinned otel packages in depcheck
The unpinned depcheck (workflow installs latest each run) shifts which
@opentelemetry/* packages it reports: it flagged only @opentelemetry/core
before, now also exporter-trace-otlp-http and sdk-trace-base. All three are
transitive deps of @opentelemetry/sdk-node (imported/driven via NodeSDK in
packages/api/src/telemetry/sdk.ts), pinned top-level for otel version
alignment, none imported by name. Ignore the complete set so ROOT_UNUSED is
empty regardless of depcheck's version-dependent otel detection. Only
@opentelemetry/api is imported directly and stays checked.

Verified locally: with the three ignored, depcheck's root output contains only
@opentelemetry/api, which the workflow's used-in-code list subtracts -> empty.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 04:47:57 -07:00
zeekayandClaude Opus 4.8 52bcd7de06 ci: silence otel-core depcheck false-positive + post PR comments via github-script
detect-unused-packages and detect-unused-i18next-strings each hard-fail on the
comment step because the ARC runners have no `gh` CLI (`gh api` -> exit 127), and
detect-unused-packages additionally flags @opentelemetry/core.

- Add .depcheckrc.yml ignoring @opentelemetry/core: it is a transitive
  requirement of the otel stack in use (sdk-node / sdk-trace-base /
  exporter-trace-otlp-http), intentionally version-pinned at the top level and
  never imported by name, so depcheck reports a false positive. Verified locally:
  with the ignore, depcheck no longer lists it (it was the sole ROOT_UNUSED item).
- Move both workflows' "post comment" step from `gh api` to
  actions/github-script@v7 (Octokit + built-in token; jobs already grant
  pull-requests: write). No dependency on a gh binary that isn't on the runner.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 04:33:19 -07:00
zeekayandClaude Opus 4.8 495340a3b7 i18n: remove orphaned en key com_agents_cloud_section
Genuinely unused: defined only in en/translation.json, referenced nowhere in
code (the sibling com_agents_cloud_* keys are all used; this section-header
string never shipped a consumer). Its presence was the sole finding of the
detect-unused-i18next-strings workflow, which hard-fails on any unused key.
Removing it makes that check pass without weakening it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 04:26:23 -07:00
zeekayandClaude Opus 4.8 864c8a7bc7 ci: fix workspace-build OOM heap + drop dead LiteLLM lint workflow
Two pre-existing, repo-wide CI failures that reddened main and every PR:

1. test.yml / e2e.yml OOM'd building packages/api (rollup peaks ~5 GiB RSS;
   Node's default ~2 GiB old-space heap => "heap out of memory", exit 134).
   Add the same NODE_OPTIONS heap knob backend-review.yml/frontend-review.yml
   already use (6144, well under the 8 GiB runner limit). Verified: build:api
   completes in ~54s at 6144 (peak RSS 4.98 GiB); it OOMs at 3072.

2. test-linting.yml ("LiteLLM Linting") lints a litellm/ Python dir that does
   not exist in this repo and runs `poetry install` with no pyproject.toml, so
   it always failed at "Install dependencies". Pure upstream LibreChat/LiteLLM
   residue — the real JS lint is eslint-ci.yml ("Run ESLint Linting"), which
   passes. Remove the dead workflow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 04:18:13 -07:00
zeekayandClaude Fable 5 1bcdcfc1e1 chore(chat): runtime image node:20 -> node:22-alpine (0.9.13)
Node >= 22.5 ships `node:sqlite` (DatabaseSync), which the SQLite document
store requires once CHAT_STORE_SQLITE / CHAT_STORE_DUALWRITE is enabled.
Dockerfile.static was already node:22-alpine; this brings the runtime image
to parity. The store lazy-requires node:sqlite (stores/sqlite/index.ts), so
with the flag unset the runtime boots unchanged — this is a pure Node bump,
no SQLite enabled.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 01:10:29 -07:00
72700de2f0 fix(mcp): full connection/transport port (proxy + response-size caps + WS SSRF) + wire suite into CI (#61)
* fix(mcp): restore drifted ~/auth SSRF/allowedAddresses helpers

The tests + callers (hardenedFetch, MCPOAuthHandler, MCP connection) already
expected the port-scoped allowedAddresses SSRF surface (LibreChat #12933/#13022),
but domain.ts/agent.ts had been reduced to the pre-#12933 versions while their
specs were trimmed to match — a tests-without-impl drift babel hid at test time.

Restore the upstream pair (matched impl + spec):
- domain.ts: isAddressAllowed; 3-arg resolveHostnameSSRF/isSSRFTarget (allowed
  host:port exemption); isOAuthUrlAllowed; validateEndpointURL; port-scoped
  isMCPDomainAllowed fail-closed on unparseable allowlisted URLs.
- agent.ts: createSSRFSafeUndiciConnect(allowedAddresses, port) + allowedAddresses
  connect-time exemption (fixes the dead 2-arg call in hardenedFetch.ts).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): restore circuit-breaker config + OAuth reconnection cooldown

mcpConfig gains the CB_* connect/disconnect circuit-breaker knobs and
OAuthReconnectionTracker regains its progressive cooldown (5m/10m/20m/30m capped)
that reconnection-storm.test.ts asserts. Both were trimmed while their tests
stayed at the upstream version.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): finish connection.ts transport port — proxy, response caps, WS SSRF

Completes the half-ported MCP connection/transport layer (LibreChat
#13076/#13219/#13224/#13274). The test suite (MCPConnectionSSRF,
MCPConnectionAgentLifecycle, reconnection-storm) was byte-identical to upstream
but the implementation stopped at the redirect-SSRF guard, leaving 22
tests-without-impl in MCPConnectionSSRF alone.

- Proxy support: serverConfig.proxy + PROXY/HTTP(S)_PROXY env with full NO_PROXY
  semantics (wildcard, CIDR, IP-range, IPv6, host-suffix, port scoping); per-URL
  ProxyAgent/Agent dispatcher selection tracked in this.agents; recomputed across
  redirects; proxied-target SSRF preflight (IP literal -> resolveHostnameSSRF,
  hostname -> allowedAddresses exemption or reject).
- Response-size caps: guardStreamableHTTPResponses opt-in wraps the body stream
  with MCP_STREAMABLE_HTTP_MAX_RESPONSE_BYTES + MCP_STREAMABLE_HTTP_MAX_LINE_BYTES,
  emitting a JSON-RPC error SSE frame instead of unbounded buffering.
- WS SSRF: resolveHostnameSSRF(host, allowedAddresses, port) now runs regardless
  of useSSRFProtection (allowlist deployments), closing DNS-rebind to private IPs.
- Connect-lifecycle circuit breaker + agent cleanup (closeAgents) on disconnect.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(mcp): accept proxy + sseReadTimeout in MCP server config schema

Adds ProxyUrlSchema (http/https/socks, env-var resolved) to SSE/streamable-http
options and sseReadTimeout to the base schema so connection.ts's proxy/idle-read
support is reachable from real config. proxy is admin-only: z.never() in the
UI/API user-input schema.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci(chat): gate MCP connection/transport suite in the primary test workflow

Root cause of the drift: test.yml (the Hanzo-active CI) only ran 'test:api'
(the api/ Express dir) and 'test:client' — packages/api tests never ran here, so
the connection.ts port could drift from its byte-identical tests unnoticed.

Add packages/api 'test:transport' (MCPConnection*, MCPRedirectSSRFGuard,
reconnection-storm, MCPManager, auth domain/agent SSRF specs, hardenedFetch,
OAuthReconnection*) and run it in test.yml. A future half-port of the transport
layer now fails CI loudly. No .skip's exist in these suites; nothing un-skipped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 00:44:05 -07:00
zeekayandClaude Opus 4.8 32acfb52e3 fix(chat): stream #titleConvo so the Hanzo gateway response parses (real auto-title fix)
Root cause of new chats never titling: the title path invokes the model
NON-streaming (stream:false). The Hanzo Cloud gateway returns a valid
{choices:[{message}]} body, but the pinned langchain ChatOpenAI parses that
non-streaming body to ZERO generations, so invoke() throws
'Cannot read properties of undefined (reading \'message\')' and no title is
saved. Every agent RUN already streams (SSE), which parses the same gateway
correctly — that is why generation works but titles did not.

Force clientOptions.streaming = true in #titleConvo (after the omitTitleOptions
filter, which strips 'streaming'). Verified against the live gateway with Dave's
per-user key: streaming=true -> clean title; streaming=false -> the crash.

Pairs with the zen5-flash repoint (fast, non-reasoning): streaming fixes the
parse for all models; zen5-flash keeps the call under the 45s title timeout
(zen3-nano/qwen3-8b took ~60s).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 22:38:02 -07:00
zeekayandClaude Opus 4.8 3cb0488797 fix(chat): title/summary model zen3-nano -> zen5-flash (fast, non-reasoning)
New chats didn't reliably auto-title: zen3-nano maps to the reasoning model
qwen3-8b (live upstream), which took 16-31s per title — routinely near the
45s #titleConvo timeout. The other 6 families pointed titleModel at
third-party names (llama-3.1-8b, qwen3-coder-flash, ...) that are NOT in the
live gateway catalog, so they returned a 200 error-envelope.

Repoint every family's titleModel (and the Hanzo summaryModel) to zen5-flash:
a fast, NON-reasoning, in-catalog model (live upstream deepseek-4-flash) that
returns a clean single-line title in ~1-2s. Picked by direct api.hanzo.ai/v1
probes: zen5-flash ~1.5s clean; zen3-nano 16-31s; zen5-mini 10-20s; zen5 /
zen3-vl >40s; zen5-nano not servable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 21:43:57 -07:00
zeekayandClaude Opus 4.8 43cc8a73bb fix(chat): make #titleConvo envelope-safe (parity with agent runs)
The Hanzo Cloud gateway answers some failures with HTTP 200 + a JSON
error-envelope ({status:"error", msg}) that has no `choices`. On the
title path the OpenAI client parsed that 200 to `undefined` and
#titleConvo threw `Cannot read properties of undefined (reading 'message')`,
so new conversations never got a title.

Apply the same wrapHanzoGatewayFetch rewrite agent runs use, now explicitly
on the title client's fetch, so the envelope becomes a clean 402 the outer
try/catch skips gracefully. Export the wrapper from @hanzochat/api; the
re-wrap is idempotent (a second pass sees a 402, not a 200 envelope) and
response-only, so per-user hk- billing and normal completions are untouched.

Adds an idempotency unit test (7/7 pass).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 21:43:49 -07:00
zeekayandClaude Opus 4.8 e4c75ffdd1 docs(chat): title-route limitation note (zen3-nano) — config source of truth
The #titleConvo path no longer 404s (zen5-nano was off-catalog), but full
auto-title still needs a follow-up: zen3-nano reasons past the 45s title timeout,
and off-title-path models (e.g. llama-3.1-8b) return a 200 error-envelope the
title client mis-parses. Needs the gateway-envelope rewrite on #titleConvo + a
fast non-reasoning title model. librechat.yaml is the source the chat-config
ConfigMap is generated from (not used at runtime; CONFIG_PATH=/app/chat.yaml).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 21:12:29 -07:00
zeekayandClaude Opus 4.8 8486223c89 chore(chat): 0.9.10 — ensō icon fix folded into the design-maven pass
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:25:02 -07:00
zeekayandClaude Opus 4.8 fa01f11732 fix(chat): ensō for the Zen family in UnknownIcon (the real icon path)
Custom endpoints resolve their icon via getIconKey -> 'unknown' -> UnknownIcon
(by endpoint NAME), not icons[custom] — so the earlier icons[custom] remap was
inert (reverted). The Hanzo house endpoint had no asset/iconURL match and fell
through to the generic lucide "bot". Now:
- 'hanzo'/'zen' -> ZenLogoIcon (ensō), matching the assistant message avatar,
  on the welcome screen + model pill + picker menu.
- qwen/google-gemma/openai-gpt-oss -> real provider marks by name (the
  KnownEndpoints enum lacks those keys). DeepSeek/Mistral logos unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:24:54 -07:00
zeekayandClaude Opus 4.8 6e56f51429 chore(chat): 0.9.9 — design-maven polish pass (true-black, ensō, monochrome)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:10:46 -07:00
zeekayandClaude Opus 4.8 e27fb77e5b feat(chat): polish welcome heading + code blocks
- Welcome heading: tracking-tight for crisp large-display type (Linear/Vercel).
- Code blocks: hairline-bordered true-black surface (rounded-lg, border-medium,
  #0a0a0a) with a subtle bottom-bordered header instead of the heavier grey bar;
  reads calm + monochrome now that code renders in Geist Mono.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:10:00 -07:00
zeekayandClaude Opus 4.8 d2ded972bc feat(chat): monochrome brand — ensō everywhere, neutral avatars, kill leaks
- Zen ensō (円相) replaces the generic lucide "bot" for the custom Zen endpoint:
  welcome screen, model pill and menu icon now match the assistant avatar.
- Monochrome avatars: collapse the colorful DiceBear palette to a neutral grey
  ramp (the green "GU" guest chip is gone), and neutralize the periwinkle
  no-seed fallback in Icon/Avatar.
- Kill the stray "(" glyph: the right control-panel NavToggle handle was floating
  mid-edge at 0.25 opacity; now invisible until hover (header controls remain).
- Model-picker menu separator used cool border-slate-*; now neutral border-light.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:03:20 -07:00
zeekayandClaude Opus 4.8 5e9a043837 feat(chat): true-black hard-default theme + crisp type + auto-title fix
- Hard-default to dark (true-black) unless the user explicitly picks light:
  ThemeProvider getInitialTheme + index.html no-flash script now default dark,
  and the loading canvas is true #000 (was blue-tinted #070b13). theme-color #000.
- Crisp type: font-synthesis:none + antialiased. Basel ships 400/500 only, so
  faux-bold was blurring headings; hierarchy now comes from size + the real
  Medium face. Code now renders Geist Mono (was forced to Consolas via !important).
- Auto-title: repoint titleModel/summaryModel zen5-nano -> zen3-nano (zen5-nano
  isn't in the live /v1/models catalog, so #titleConvo 404'd and new chats never
  auto-titled). zen3-nano is the known-good guest/test model.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 19:03:10 -07:00
zeekayandClaude Opus 4.8 d31f7546bd fix(chat): seed GUEST role default so guest generation stops crashing (0.9.8)
Root cause: commit 46b636c8c0 (server-side anonymous guest chat) added
GUEST to the SystemRoles enum and stamped guest JWTs with role=GUEST, but
never added a roleDefaults[GUEST] entry nor seeded the role. Every guest
generation ran checkAccess -> getRoleByName('GUEST'), which missed the DB,
fell into the self-heal branch `if (!role && SystemRoles['GUEST'])`
(truthy) and called `new Role(roleDefaults['GUEST']).save()` ===
`new Role(undefined)` -> "Role validation failed: name: Path `name` is
required" -> the whole generation threw. Since the logged-out landing IS
the guest composer (0.9.3), nearly every visitor hit this.

Fix (three orthogonal parts):
- data-provider/roles.ts: add the missing roleDefaults[GUEST] (named,
  mirrors USER's minimal grant; guest scope is enforced by
  enforceGuestScope middleware, not by these permissions).
- data-schemas initializeRoles: seed GUEST at boot alongside ADMIN/USER so
  it is deterministic, not lazily created.
- models/Role.js: gate the self-heal create on roleDefaults[roleName]
  (possessing the canonical defaults) instead of SystemRoles[roleName]
  (mere enum membership). roleDefaults entries always carry a name, so a
  nameless create is now structurally impossible.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:59:51 -07:00
zeekayandClaude Opus 4.8 7f0bdb3145 feat(build): "Build an app" affordance — hanzo.app handoff + inline build shell (0.9.7)
Uniform "build an app" entry across chat -> app -> console. One pure module
(utils/buildApp.ts) is the single source of the hanzo.app builder wire
(hanzo.app/dev?prompt=) and the `/build [prompt]` command grammar; every
surface funnels through it (DRY).

Phase 1 (ships): the hanzo.app handoff, reachable three ways —
- `/build [prompt]` slash command, intercepted in ChatForm.onSubmit
- "Build this as an app" action on assistant messages (HoverButtons)
- the inline preview pane's "Open in App" CTA
All open https://hanzo.app/dev?prompt=<encoded> in a new tab (noopener).

Phase 2 (scaffold): inline build mode. A `buildMode` recoil flag toggled by the
composer "Build an app" button (BuildAppButton) makes ChatView render a
stripped-down split — chat thread on the left + a side preview pane
(BuildApp/BuildPreviewPane) on the right. The pane is a placeholder whose CTA is
the Phase 1 handoff, seeded live from the composer text. A `/build` route
deep-links into build mode (seeds the composer from ?prompt=/?q=). When buildMode
is off, ChatView renders byte-identical to before (zero regression to normal chat
or the guest landing). Phase 3 (real inline codegen/preview) is documented inline.

9 unit tests for buildApp (url + command grammar). Guest flow untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:18:15 -07:00
zeekayandClaude Opus 4.8 523c38b371 fix(store): lazy-require node:sqlite so the server boots on Node 20 (0.9.6)
The SQLite DocModel store statically `import`s `DatabaseSync` from
`node:sqlite` at the top of `stores/sqlite/{index,DocModel}.ts`. That module
is re-exported by the data-schemas package index, which the API server loads
at boot — so the eager `require('node:sqlite')` in the bundled dist runs
unconditionally. `node:sqlite` only exists on Node >= 22.5; the runtime image
is node:20-alpine, so boot dies with
`ERR_UNKNOWN_BUILTIN_MODULE: No such built-in module: node:sqlite`
(crashloop) — independent of the store's inert-by-default flag.

The store is only ever exercised when `CHAT_STORE_SQLITE` is set (a CSV of
collections), via `createSqliteHandle` -> `openDatabase`. Make the import
lazy: `import type` for the erased type references, and a single
function-scoped `require('node:sqlite')` inside `openDatabase`. Module load
no longer touches the builtin, so the server boots on Node 20 with the store
inert; when the flag is set (on a Node >= 22.5 runtime) it works verbatim.

Proven: rebuilt dist has no module-scope require; loading dist/index.cjs with
`node:sqlite` blocked (simulated Node 20) succeeds, and openDatabase() still
defers to the builtin only when actually opening a database.

Unblocks deploying any main-based image (incl. the 0.9.5 guest-chat fix).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:13:28 -07:00
zeekayandClaude Opus 4.8 de8a33d8a3 fix(chat): guest can send + never bounce to /login (0.9.5)
Two anonymous-guest client bugs, both proven with live Playwright.

BUG A — guest can't SEND ("Unknown endpoint: Hanzo"):
`new QueryClient()` was built in App's render body, so every re-render
minted a fresh EMPTY client. A guest's expected 401s (mcp/servers,
files/config, keys?name=Hanzo, …) fire the queryCache `onError` →
`setError` → App re-render → the provider swaps in an empty client. The
lazy chat-form's `useChatFunctions` then reads `getQueryData([endpoints])`
off an endpoints-less client, so the custom `Hanzo` endpoint resolves with
`endpointType === undefined` and `parseCompactConvo` throws
"Unknown endpoint: Hanzo" — the completion POST never happens. Backend is
correct: guest token → /v1/chat/endpoints={Hanzo:{type:custom}},
/v1/chat/models={Hanzo:[zen3-nano]}. Fix: stabilize the client with
`useState(() => new QueryClient(...))` — one client, one cache, every
consumer (incl. the lazy chunk) shares the populated store.

BUG B — intermittent first-load /login redirect:
The axios 401 interceptor hard-`window.location.href`'d to /login whenever
a one-shot refresh yielded no token. On a cold visit the guest bearer is
still in flight (`isGuestSession()` false because there's no bearer yet),
so an early expected 401 bounced the visitor to /login, racing the
guest-acquire. Fix: only hard-redirect when a real *session* bearer is
actually present (`currentBearer() != null && !isGuestSession()`); an
anonymous cold-start with no bearer is left to routing/the login gate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:47:29 -07:00
zeekayandClaude Opus 4.8 2f2378ab21 fix(chat): keep guests on chat surface — don't hard-redirect 401s to /login
The axios 401 interceptor hard-redirected to /login whenever a one-shot
refresh yielded no token. A guest (anonymous preview) session carries a
{guest:true} JWT that is valid ONLY on the chat-completion route; every
other endpoint (/api/mcp/servers, /api/files/config, ...) answers 401 by
design. Those expected 401s bounced the guest to /login, wiping the guest
session in an infinite loop, so the landing never rendered the composer.

Derive guest-ness from the active bearer (isGuestSession) and skip the
hard redirect for guests — real users with a truly-expired session still
redirect. Fixes anonymous-guest landing on hanzo.chat.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:33:31 -07:00
120c39a197 feat(image): text-to-image via the Hanzo gateway, metered per-user
Enables 'generate an image of X' to render a real image inline through the
DALLE3 agent tool pointed at the Hanzo gateway (/v1/images/generations):
- DALLE3.js: model is configurable (DALLE3_MODEL, e.g. zen3-image); DALL-E-3-only
  knobs (quality/style) are sent ONLY for a dall-e model so the Hanzo image
  backend never sees a param it would reject. Agent path already fetches the
  result server-side and returns it inline (upstream host never reaches client).
- handleTools.js: dalle is now a custom constructor that injects the signed-in
  user's PER-USER hk- key (resolveHanzoCloudKey) so image generation is metered
  to them — mirroring the chat per-user key path. Guests keep the shared key;
  an authed user whose key can't be resolved FAILS CLOSED (no shared-org spend).

Deploy also sets env DALLE_REVERSE_PROXY=https://api.hanzo.ai/v1/images/generations
and DALLE3_MODEL=zen3-image. Zen-brand model id only; upstream never surfaced.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:51:13 -07:00
8d2549322a feat(store): SQLite DocModel migration (29 domains) + read-only commerce + identity-a — inert by default (CHAT_STORE_SQLITE unset = pure mongoose) (#60)
* feat(data-schemas): pure Mongo-shaped query/update engine for SQLite store

Correctness core of the mongoose->SQLite migration seam: pure, I/O-free
matchesFilter / applyUpdate / projectDoc / sortDocs implementing the exact
Mongo operator subset the chat data methods use ($eq $ne $in $nin $gt/$gte
$lt/$lte $exists $regex $not $and $or $nor; $set $unset $setOnInsert $inc
$push $pull $addToSet). Date-aware comparison, mongo null/absent semantics.
21 unit tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): SQLite DocModel + handle backing the Model API on node:sqlite

DocModel presents the Mongoose Model-API subset the chat data methods use
(findOne/find/findOneAndUpdate/updateOne/updateMany/deleteMany/deleteOne/
countDocuments/distinct/create/insertMany/bulkWrite + chainable QueryBuilder
with select/sort/limit/skip/lean/deleteMany). Docs stored as JSON via node:sqlite
(stdlib, zero new dep); JSON1 expression indexes on unique/anchor fields; exact
mongo semantics delegated to the pure engine; date rehydration on read; no
mongoose, no tenant middleware (Conversation/Message are not tenant-plugged
upstream). createSqliteHandle() returns a mongoose-shaped handle the unchanged
method factories run against. 7 adapter tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): prove conversations+messages fully off mongoose on SQLite

- Decouple message.ts + conversation.ts from the mongoose package: factories now
  take a structural DataHandle ({models}) satisfied by BOTH mongoose and the
  SQLite handle. Only type-only imports from 'mongoose' remain; zero runtime
  mongoose in the data path for this domain.
- engine: type-aware operand coercion so cursor pagination (String(Date) operand
  vs Date field) compares chronologically, mirroring mongoose schema casting.
- convoMessage.sqlite.spec: 14 tests running the REAL createMessageMethods /
  createConversationMethods against createSqliteHandle — save/upsert, get,
  update, delete, deleteMessagesSince, cursor pagination, bulk, archived +
  retention-visibility filtering, getConvosQueried, cross-collection deleteConvos,
  deleteNullOrEmptyConversations, searchConversation. All green.

Isolates one unrelated pre-existing fork gap via jest mock: this tree's
librechat-data-provider never synced the RetentionMode enum (upstream #13049),
so message.ts/conversation.ts reference an undefined export on the mongoose path
too. Documented for separate fix.

42/42 store tests green (engine 21 + DocModel 7 + contract 14).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): registry-aware createModels + store exports (the seam)

createModels now applies per-domain backend selection via CHAT_STORE_SQLITE
(CSV of collection names -> SQLite DocModel). Unset default = pure mongoose,
live path unchanged; only collections with a CollectionSpec are overridable
(fails closed otherwise). Exports createSqliteHandle/DocModel/CollectionSpec/
DataHandle from the package index. node:sqlite + node:crypto added to rollup
externals. Package builds clean (rollup, EXIT=0); 45/45 store+registry tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(data-schemas): drop local build artifacts + shared-deps symlink from branch

Revert dist/* to base (CI rebuilds bundles deterministically — no local builds)
and untrack the packages/data-schemas/node_modules dev symlink. Source-only branch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 2 — Preset, ConversationTag, SharedLink on SQLite

Migrate three self-contained, non-tenant-plugged chat-document domains onto the
DocModel store behind the same seam. Decouple their factories to DataHandle;
createMethods now passes a registry-aware handle to createShareMethods so the
CHAT_STORE_SQLITE flag flips Share (pattern-2) in the live path too.

DocModel extensions (all reusable for later batches):
- compound unique indexes (ConversationTag {tag,user})
- ObjectId-ref casting on write + cross-collection .populate() (SharedLink.messages -> Message)
- findByIdAndUpdate / findOneAndDelete; findOneAndUpdate is now a chainable
  QueryBuilder (mutate mode) so .lean()/.select()/.populate() chain after a write
- schema defaults on insert (SharedLink.isPublic:true)
engine: mixed-update semantics (top-level fields fold into $set) + $pullAll.

Contract specs run the REAL createPreset/ConversationTag/Share methods against
createSqliteHandle. 60/60 store+contract+registry tests green; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 3 — Project on SQLite + realtime-vs-storage finding

Project migrated (pattern-1, registry-aware): add DocModel.findById; CollectionSpec
with array defaults; contract spec mirrors api/models/Project.js exact ops
(getProjectByName upsert, $addToSet $each, $pull $in, updateMany $pull).

Prompt/PromptGroup deferred with rationale: they construct mongoose.Types.ObjectId,
use an aggregate $lookup/$unwind pipeline + populate + manual tenant/ACL
(accessibleIds: ObjectId[]) — need an aggregate primitive, not the mechanical
recipe. Categories read-path is already mongoose-free (getCategories is static).

REALTIME finding (verified codebase-wide): chat has ZERO Mongo change-streams /
tailable cursors / .watch(). Its realtime is SSE token streaming (sendEvent /
agent GenerationJobManager) tied to the generation request — application layer,
DB-independent. So NO migrated domain needs a DB-subscription replacement; plain
node:sqlite is correct for all. Hanzo Base realtime is reserved for future
DB-driven push (multi-device live sync, presence, collab sessions) — none today.
Documented at the storage-decision source (collections.ts).

63/63 store+contract+registry green; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 4 — File, Key, PluginAuth, Banner on SQLite

Migrate four non-tenant storage domains onto the DocModel store. Decouple their
factories to DataHandle; createMethods passes the registry-aware handle to
File/Key/PluginAuth (pattern-2); Banner is pattern-1 (~/db/models).

- Key: encrypted roundtrip proven (updateUserKey encrypt -> getUserKey decrypt)
  against SQLite; CREDS_KEY/IV set via jest setupFiles (runs before module load).
- PluginAuth: replaced a redundant `new Model().save()` else-branch with
  Model.create (equivalent on mongoose, part of the shared Model API — DocModel
  supports it). No behavior change.
- Realtime directive recorded: Conversation+Message are the Base-realtime cutover
  targets ("Base for realtime, SQLite for storage"); all other migrated domains
  are pure storage. Empirically chat has zero Mongo change-streams (realtime=SSE),
  so the SQLite store is correct in the interim; Base swap is backend-only.

MCPServer deferred (constructs mongoose.Types.ObjectId + _id ObjectId cursor).
70/70 store+contract+registry tests green; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 5 — tenant-aware DocModel variant + Config on SQLite

Add tenant isolation to the store, mirroring the mongoose applyTenantIsolation
plugin, gated by CollectionSpec.tenantIsolated (unlocks Config/Skill/SkillFile/
SystemGrant):
- scopeFilter: every read/write filter scoped to getTenantId() (SYSTEM bypasses;
  no-tenant + TENANT_ISOLATION_STRICT=true fails closed) — wired at the single
  candidates() chokepoint.
- stampTenant: inserts stamped with tenantId (create/insertMany/upsert).
- sanitizeTenantUpdate: update payloads cannot mutate tenantId (throws cross-tenant;
  strips from $set/$setOnInsert/$unset/top-level) — wired into
  mutateOne/updateOne/updateMany/bulkWrite.

Config migrated (compound unique {principalType,principalId,tenantId}); decouple
createConfigMethods to DataHandle; QueryBuilder.session() no-op (single connection).
Fix: anchorWhere binds booleans as 1/0 (node:sqlite rejects JS booleans; json_extract
returns 1/0) — hardens every boolean-filtered collection.

batch5 contract spec proves cross-tenant isolation with REAL createConfigMethods:
per-tenant stamping, identical principals isolated across tenants, tenant-scoped
list/find, no cross-tenant delete. 74/74 green; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 6 — SystemGrant on SQLite + ObjectId read-coercion

SystemGrant migrated (tenant-plugged, same recipe as Config): CollectionSpec with
compound unique {principalType,principalId,capability,tenantId} + tenantIsolated;
add DocModel.exists(); decouple createSystemGrantMethods to DataHandle.

Add ObjectId read-coercion to the engine (coerceId): filters carrying real
mongoose ObjectId operands (SystemGrant.normalizePrincipalId casts USER ids to
Types.ObjectId) now compare against the hex strings the store persists (docs
stringify ObjectIds to hex; _ids are ObjectId-hex). Applied in comparable /
valueEquals / anchorWhere. This is the shared primitive that unblocks the
ObjectId-coupled domains (Skill/SkillFile, MCPServer, Prompt/PromptGroup).

Contract spec runs REAL createSystemGrantMethods with USER principals
(ObjectId path exercised end-to-end): grant/has(exists)/revoke, idempotent upsert,
platform-vs-tenant isolation. 77/77 green; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 7a — ObjectId shim + MCPServer, Skill, SkillFile

Add handle.Types.ObjectId shim (thin: store _ids are already ObjectId-hex,
coerceId resolves comparison/storage): a 24-hex ObjectId class with toHexString/
toString/toJSON/equals/isValid, exposed as SqliteHandle.Types and typed on
DataHandle.Types. createMethods' dbHandle now carries mongoose.Types (real
ObjectIds coerce too).

- MCPServer (pattern-2): full real-method spec — create / findByServerName /
  findByObjectId (findById + ObjectId operand) / byAuthor / update / delete +
  unique serverName. Decouple models + Types to handle; wired via dbHandle.
- Skill/SkillFile (tenant-plugged): decouple models + Types to handle; storage
  contract proven — compound unique, ACL _id-in-accessibleIds ObjectId filtering
  via coercion, SkillFile upsert. Their 800-line ACL/validation method layer
  rides on these ops (full harness = follow-up).

81/81 green across 10 suites; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 7b — aggregate primitive + Prompt, PromptGroup

Add DocModel.aggregate supporting the bounded stage set the chat methods use
($match / $lookup / $unwind / $sort / $limit / $project), run in JS over
candidate docs; $lookup resolves the mongo collection name to a sibling model
(prompts -> Prompt) and joins via the shared engine. Fix deepCoerceIds: coerce
ObjectId-like values to hex BEFORE structuredClone in create/insertOne (clone
was stripping the shim's methods, serializing productionId as an object husk).

Prompt / PromptGroup migrated (pattern-1): decouple models + Types to handle;
CollectionSpecs with productionId/prompts refs. Contract spec proves the
aggregate primitive directly AND the REAL getPromptGroup end-to-end (casts _id
-> ObjectId, $lookup productionId -> Prompt, $unwind preserveNullAndEmptyArrays).

All storage-tier domains are now on the DocModel. 85/85 green across 11 suites;
rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Skill/SkillFile full-method harness + findOneAndUpdate(new:false) fix

Close the Skill/SkillFile proof gap: real createSkillMethods with stub ACL deps
(PermissionService injected) — createSkill (validation + uniqueness), getSkillById,
getSkillByName(accessibleIds ObjectId ACL), updateSkill optimistic version bump,
deleteSkill (+ removeAllPermissions), and SkillFile upsert (new-vs-replace) /
getByPath / list. Skill + SkillFile now fully proven, not just storage-proven.

Fix mutateOne: findOneAndUpdate(new:false, upsert:true) now returns null on an
insert (no pre-image) and the old doc on update — mongoose semantics that
upsertSkillFile's atomic new-vs-replace fileCount detection depends on. Locked
with a direct DocModel.spec test. All prior findOneAndUpdate upserts use new:true
(unaffected).

89/89 green across 12 suites; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 8a — 7 chat-native domains on SQLite

Migrate MemoryEntry, ToolCall, Assistant, Action, AccessRole, Role, AgentApiKey
onto the DocModel store (mechanical: no external subsystem owns them — cloud
/v1/agents is additive, there is no /v1/memory, and app-domain authz has no IAM
equivalent). Decouple all 7 factories to DataHandle; createMethods passes the
registry-aware handle to Role/Memory/AgentApiKey/AccessRole (pattern-2).

Adapt role.initializeRoles off the `new Role().save()` mongoose-document pattern
to the shared Model API (findOne/create/updateOne) — equivalent on both backends.

Contract spec runs the REAL methods: memory set/create(dup-throws)/list/delete,
toolcall create/get/byConvo/delete, assistant/action upsert+get+delete, accessRole
create/find/list/delete, role initializeRoles seeds + listRoles, agentApiKey
create/validate(hash)/list. 96/96 SQLite-spec tests green; rollup build EXIT=0.
(Pre-existing mongoose specs fail identically on base — fork gaps, out of scope.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(data-schemas): Batch 8b — Agent, AgentCategory, AclEntry, Group on SQLite

Migrate the ObjectId/aggregate/ACL chat-native domains. Decouple factories to
DataHandle (models + Types); wire AgentCategory/AclEntry/UserGroup through the
registry handle. Agent uses the ObjectId shim (version tracking, _id cursor);
AgentCategory uses the aggregate primitive; AclEntry uses bitwise permission
queries; Group links members by id.

Store primitives added/fixed (all reusable):
- aggregate $group (with $sum/$first/$last/$max/$min/$push/$addToSet) — powers
  AgentCategory.getCategoriesWithCounts.
- bitwise operators $bitsAllSet/$bitsAnySet/$bitsAllClear/$bitsAnyClear — powers
  AclEntry.hasPermission.
- applyUpdate deepCoerceIds the upsert seed (ObjectId shims survived to storage
  as hex, fixing findOneAndUpdate-upsert with ObjectId filter fields).
- array-safe index anchor: json_each(...) EXISTS replaces json_extract= so
  {field: value} over an ARRAY field (Mongo array-contains, e.g. Group.memberIds,
  tags, projectIds) hits the index instead of being excluded by the prefilter.

Contract spec runs REAL methods: agent create/get/update/delete, category $group
counts, acl grant/has(bitwise)/revoke, group create/find/addMember/getUserGroups.
100/100 SQLite-spec tests green across 14 suites; rollup build EXIT=0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(billing): chat→commerce debit wiring behind COMMERCE_WRITES (default OFF)

Step 2 of the money migration. Default OFF = current local-Mongo billing path
runs byte-for-byte; the Commerce-first fail-closed READ gate is unchanged.

CommerceClient (the previously-dead write methods, now correct):
- recordUsage now debits the billing SUBJECT (billingSubject(owner,email)) — not
  the Mongo user id — with amountMicros (lossless micro-USD; commerce rounds to
  nearest cent + records exact micros) + requestId (stable per-spend idempotency
  key → no double-debit) + totalTokens/provider.
- _flushUsageQueue now passes X-Hanzo-Org per entry (was omitted → debits hit the
  wrong tenant and never netted the balance the gate reads). Fixed.
- add deposit() for credits (POST /v1/billing/deposit).

Wiring (flag-gated, additive, fail-open):
- commerceWrites.js: COMMERCE_WRITES gate + recordCommerceDebit (never throws
  into the spend path; local Mongo authoritative until cutover).
- createTransaction: after the local debit, ALSO record to commerce when the
  flag is ON and the request threaded `subject` (tokenValue is micro-USD;
  transaction _id is the idempotency key). Inert until subject is threaded + the
  flag flipped.

Tests (executed, PASS): CommerceClient.spec — recordUsage builds the right body
(subject/amountMicros/requestId/totalTokens) + X-Hanzo-Org header, no _namespace
leak; the flag gate is OFF by default.

REMAINING (gated): thread `subject` into txMetadata at the spendTokens call
sites; wire credits (deposit/grantStarter); Step-3 live-verify; then retire local
writes behind the flag. Local Balance/Transaction writes are NOT retired.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(billing): revert chat→commerce debit — the gateway is the single debit authority

The COMMERCE_WRITES chat-debit hook (bf6302a72c, today) is a double-debit
footgun and is reverted. It contradicts the established, LIVE architecture:

  - hanzoCloudKey.ts (module doc): every IAM user has one hk- Cloud key; "the
    cloud gateway (api.hanzo.ai) debits that key's org commerce balance and
    returns 402 when the org runs out. Forwarding the right per-user key ===
    correct per-user billing automatically." initialize.ts forwards that key on
    every authed request (baseURL api.hanzo.ai/v1).
  - packages/api usage.ts (NOTE, 2026-06-27): a prior chat→commerce write in
    recordCollectedUsage was a SECOND debit to a mis-keyed account; it was
    REMOVED. "Chat must NOT also record usage to Commerce."
  - prod CR universe/.../crs/chat.yaml: HANZO_PER_USER_KEY=true, balance gate
    off, and in its own words "chat records NO usage to commerce (that write was
    removed); the single debit is still cloud's, per the user's hk- key."

Two writers to one ledger for one spend = double charge. The gateway is the ONE
debit authority for AI spend across every product (chat/code/agents/API); a
per-client debit path is the wrong DRY seam. So chat stays a READER of Commerce.

Removed (the whole unused chat→commerce WRITE surface):
  - api/models/commerceWrites.js (the COMMERCE_WRITES gate + recordCommerceDebit)
  - the recordCommerceDebit call + import in Transaction.js (now a comment
    stating the single-debit invariant)
  - CommerceClient.recordUsage (the debit) + its now-dead _usageQueue /
    _flushUsageQueue machinery + interval; deposit/grantStarter (unused credit
    helpers — the real first-chat grant is resolveHanzoCloudKey's direct POST
    /v1/billing/grant-starter in packages/api, the correct layer)
  - CommerceClient.spec.js (only tested the removed surface)

Kept (CommerceClient is now purely read-only, one responsibility):
  checkBalance (fail-closed money gate), getTierConfig, isModelAllowed,
  getCreditBreakdown — all live (balanceMethods.js, Balance.js).

Verify: node --check clean on both edited files; zero dangling references to the
removed symbols repo-wide; balanceMethods.spec mocks only the kept READ surface.

Money domain off-Mongo status after this: Commerce (via the gateway) is the
balance/debit authority — no Mongo Balance/Transaction WRITE is authoritative in
prod (gate off). The local Transaction doc remains an in-app usage log only;
retiring/relocating it to the SQLite store is tracked with the cutover.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(identity): User is a thin IAM projection — drop the local password credential (step a)

Identity migration step (a): IAM (hanzo.id) owns identity; chat's User doc is a
thin OIDC-keyed projection (provider='openid', openidId=userinfo.sub, org from
userinfo), never a second credential store.

Confirmed no OIDC path writes a password: openidStrategy.js (508-523) and
process.js createSocialUser build the User with NO password; createUser
(packages/data-schemas) writes no default; the schema field was select:false.
The ONLY writers were two local-email flows, both gated OFF in prod
(ALLOW_REGISTRATION=false, ALLOW_EMAIL_LOGIN=false).

Changes (source only — Docker rebuilds packages/data-schemas dist via
`pnpm run frontend`):
  - schema/user.ts: remove the `password` field. The User projection carries no
    local secret. (IUser keeps `password?: string` — always undefined — so the
    disabled local strategy / comparePassword still compile; the full
    local-strategy teardown lands with the cutover.)
  - AuthService.registerUser: stop writing password (local signup stores no
    credential).
  - AuthService.resetPassword: reject — "Password reset is managed by Hanzo IAM
    (hanzo.id)." Nothing to reset locally.

Login-safety: the authed OIDC flow (openidStrategy) references `password` ZERO
times — provably untouched by this change. comparePassword/localStrategy run
only when local login is enabled (off in prod), so removing the field is inert
for the live path.

Verify: data-schemas builds clean; store-registry + convo/message + user-schema
specs green (17/17 targeted); full suite identical to clean tree
(1210 pass / 250 pre-existing mongo-env fails / 100 skip — my change adds zero
failures). LIVE Dave-login verification is the deploy-time gate in the cutover
runbook — this branch is not deployed, so prod is untouched (default path stays
pure-mongoose + password field until the cutover deploy).

STOP before step (b): OPENID_REUSE_TOKENS is the documented login-breaker
(chat.yaml: =true → /api/auth/refresh 403 at hanzo.id → login dead). Do NOT flip
until the IAM refresh-token fix lands and is live-verified.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:33:53 -07:00
zandGitHub c3257d2238 Merge pull request #59 from hanzoai/feat/kill-api-prefix
refactor(chat): kill /api/ prefix → /v1/chat/* (#42 flagship)
2026-07-03 13:58:15 -07:00
hanzo-dev 87b581388d fix(chat): migrate regex-form /api survivors (telemetry matchers + OAuth actionId parse)
Two regex-form OUR-route references the string-based sweep couldn't reach:

- api metrics.ts PATH_NORMALIZATIONS: matcher regexes still /^\\/api\\/...
  while replacements were /v1/chat/... — a half-migration. Real request
  paths (/v1/chat/*) never matched -> high-cardinality routes (stream/status/
  files/messages/convos/agents/tags/tools/sessions with IDs) unnormalized ->
  Prometheus label cardinality blowup. Matchers -> /^\\/v1\\/chat\\/.
  (Aligns with metrics.spec's already-migrated /v1/chat/X/#id expectations.)
- client ToolCall.tsx: regex extracting actionId from the Action OAuth
  redirect_uri matched /api/actions/:id/oauth/callback; callback is now
  /v1/chat/actions/... -> actionId parse failed -> Action OAuth UI broken.

OUR-route /api now ZERO in all forms (string, template, regex, cookie-path).
2026-07-03 13:55:43 -07:00
hanzo-dev 2abc855b9c fix(chat): migrate no-trailing-slash /api survivors the sweep missed
Blue's transform anchored on '/api/' (trailing slash) and missed 4 places
where the path ends exactly at '/api':

- client MarkdownComponents.tsx: chat-message file links built as
  ${origin}/api/files/... -> BROKEN (files now at /v1/chat/files).
  Fixed base -> /v1/chat. [user-facing regression: file downloads]
- data-provider getDomainServerBaseUrl(): same ${origin}/api -> /v1/chat.
- api oauth/csrf.ts OAUTH_SESSION_COOKIE_PATH '/api' -> '/v1/chat': the
  OAuth session cookie (24h CSRF fallback) was never sent to the relocated
  /v1/chat/{actions,mcp} callbacks. [vector-6 miss]
- api metrics.ts path normalization '=== /api' -> '=== /v1/chat' (matches
  sibling /images,/avatars pattern).

OUR-route /api/ now ZERO across mounts, fetches, base-URLs, cookie paths,
redirect_uris.
2026-07-03 13:55:43 -07:00
hanzo-dev fdbb17da6c fix(chat): revert over-swept third-party paths + fix resources API URL
Red-team review of the /api/ -> /v1/chat/* migration found the sweep
over-reached into paths that are NOT the chat mount prefix:

- client/src/utils/resources.ts: REMOTE_AGENT 'copy API endpoint' URL was
  mangled /api/v1/responses -> /v1/chat/v1/responses (double-prefix, no
  route serves it). Canonicalize to /v1/responses (OpenAI-compat Responses
  API). User-facing.
- data-provider actions.spec + openapiSpecs (scholar-ai.net, swapi.dev) +
  api mcp.spec wss template: third-party API path fixtures wrongly swept to
  /v1/chat/*. Reverted to /api/* (they represent EXTERNAL APIs, not chat
  routes). Fixes 5 failing createURL/executor tests.
- Stale doc comments: useFavorites (/v1/user -> /v1/chat/user), tokens.ts
  typedef ref.

OUR-route /api/ remains ZERO. Login/OAuth/SSE/CSRF paths unaffected.
2026-07-03 13:55:43 -07:00
hanzo-dev ec32864a00 refactor(chat): eliminate /api/ prefix -> /v1/chat/* (namespaced, no-collision)
App REST surface moves from /api/* to /v1/chat/* in lockstep across server
mounts, client URL builders, SSE stream paths, OAuth redirect_uris, telemetry
route-grouping, RUM proxy, and the nginx bridge.

Namespace /v1/chat/* (not flat /v1/) to avoid colliding with the OpenAI-compat
inference surface (/v1/chat/completions, /v1/models -> router_backend) and to
match the canonical chat/openapi.yaml. Social OIDC login (/oauth/*) and /health
are unchanged (login-safe).

Levers:
- server: api/server/index.js 26 app.use('/v1/chat/*') mounts (+ experimental.js)
- client: packages/data-provider/src/api-endpoints.ts (75 builders) + config.ts
Lockstep: checkBan matcher, Files/Code download path, actions/mcp CSRF cookie
paths, ActionService + mcp/oauth handler redirect_uris, admin OpenID callback,
telemetry middleware/sdk/stream, rum proxy path, vite dev proxy + PWA denylist,
robots.txt, .env.example, pr-preview health-path (/api/health -> /health).

Third-party APIs chat CALLS are untouched (Ollama, Wolfram, Discord, GitHub
Enterprise, Mistral, OpenRouter, DataDog). Live-surface /api/: 683 -> 0.
Also untracks runtime log artifacts (api/logs, client/junit.xml; already gitignored).
2026-07-03 13:55:43 -07:00
zeekayandClaude Opus 4.8 3e83bc6779 feat(guest): logged-out landing IS the chat composer + airtight per-IP quota (0.9.3)
ChatGPT-style anonymous preview: when ALLOW_GUEST_CHAT is on, a logged-out
visitor renders the real chat view (composer + starter cards + model picker)
and can send a message as a guest on the free Zen model, WITHOUT logging in.
Sign-in is only prompted after the free per-IP quota (402 GUEST_LIMIT).

Client (the missing wiring — server guest path was already complete):
- ChatRoute now renders ChatView for canChat = isAuthenticated || isGuest;
  /api/models + /api/endpoints queries run for guests (guest-scoped config),
  and the roles gate treats a guest as loaded (no agent access). Previously
  ChatRoute hard-returned null for !isAuthenticated, so a guest got the shell
  but no composer.
- useAuthRedirect now surfaces isGuest.

Abuse control (airtight, server-enforced):
- guestMessageLimiter + guestTokenLimiter now key on the REAL client IP via
  utils/guestClientIp (Cloudflare CF-Connecting-IP, falls back to req.ip), NOT
  the guest token — clearing cookies / incognito / minting a fresh token can't
  reset the count. Shared Redis limiterCache holds it across replicas.
- guestLimiters env parsed as positive ints.

Prod runs GUEST_MESSAGE_MAX=2. Guests always use the shared capped HANZO_API_KEY
(per-user hk- billing is skipped for guest principals).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 12:59:48 -07:00
zeekayandClaude Opus 4.8 39e5a71c7e chore(chat): release 0.9.2 — design unification (Basel Grotesk + Geist Mono, PanelLeft sidebar, dark tokens)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 08:55:06 -07:00
1eb2caecec fix(mcp): close redirect-based SSRF on MCP request path (backport LibreChat #12931) (#57)
* fix(mcp): block private IPs when the connector resolves all addresses

undici's connect-time DNS lookup calls the SSRF-safe wrapper with
{ all: true }, so dns.lookup returns a LookupAddress[] rather than a
single string. The previous guard only inspected `typeof address ===
'string'`, silently failing open on the array shape — a hostname
resolving to a private/reserved IP would pass unchecked.

Normalize both shapes to a flat address list and reject if ANY resolved
address is private, mirroring upstream LibreChat's getBlockedLookupAddress.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(mcp): re-check SSRF on every redirect hop, strip cross-origin creds

An MCP server URL is server-controlled. Our customFetch issued the
request with undici's default redirect:'follow', so a public MCP server
(which passes the add-time isMCPDomainAllowed check) could 301/302/307/
308-redirect the connection to an internal IP literal (169.254.169.254
cloud metadata, 127.0.0.1, in-cluster 10.x/172.16-31/192.168 services).
undici skips its connect-time DNS lookup for IP literals, so the
redirect hop reached the internal target unguarded — a live SSRF on the
multi-tenant chat surface (proven: a 301 to 127.0.0.1/latest/meta-data/
was followed).

Harden createFetchFunction to follow redirects manually (redirect:
'manual'):
- Only 307/308 are followed, up to MAX_REDIRECTS=5; 301/302/303 are
  returned unfollowed (the MCP SDK rejects a bare 3xx).
- Every hop's target is re-validated with isSSRFTarget (catches IP
  literals the connect lookup skips) + resolveHostnameSSRF (catches
  hostnames resolving to private IPs); a blocked hop is not followed.
- Cross-origin hops strip credential headers (Authorization, cookie,
  mcp-session-id, plus runtime/config secret header keys) so a bearer
  token / session id never leaks to a redirect target's origin.
- Cross-origin hops pin an SSRF-safe connect dispatcher for the rest of
  the chain, closing the allowlist-mode DNS-rebinding gap.

Mirrors upstream LibreChat MCP redirect SSRF hardening (PR #12931).
Redirect targets get no allowlist exemption by design.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(mcp): prove redirect SSRF guard rejects internal-IP targets

End-to-end test using the REAL isSSRFTarget/resolveHostnameSSRF
classifiers (the sibling MCPConnectionSSRF suite mocks ~/auth). Stands
up loopback HTTP servers and asserts a 302/307/308 redirect to an
internal IP literal is never followed — the redirect is issued
(entryHit) but the internal metadata endpoint is never reached
(internalHit stays false). Also pins the classifier: 169.254.169.254,
127.0.0.1, RFC1918, localhost, ::1 are SSRF targets; a public hostname
is not.

Reverting the connection.ts guard makes all three redirect cases fail
(internal endpoint reached), confirming the test exercises the fix.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 08:54:19 -07:00
zandGitHub d44146f1fc Merge pull request #56 from hanzoai/design/unify-basel-geist-mono
design: unify Basel Grotesk + Geist Mono, sidebar icon, panels, dark tokens
2026-07-03 08:46:21 -07:00
zeekayandClaude Opus 4.8 dca8e39e69 design: unify sidebar toggle to lucide PanelLeft + Basel/Geist Mono type
Converge hanzo.chat onto the shared @hanzo/ui design language:
- Sidebar toggle glyph: replace the custom filled panel SVG with the
  canonical lucide PanelLeft geometry (stroke-2, 24x24). Kept as the shared
  `Sidebar` export so OpenSidebar/NewChat/ExpandedPanel all get the one
  canonical icon with zero call-site churn.
- Typography: Basel Grotesk (UI/body/display/heading, self-hosted woff2/woff,
  Book 400 + Medium 500) as tailwind `sans`; Geist Mono (code/data) as
  tailwind `mono` via CDN. Replaces Inter / Roboto Mono.

Dark aesthetic already matches the target (true-black OLED #000 / #0a0a0a).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:44:36 -07:00
zeekayandClaude Opus 4.8 72b061877a config(chat): full multi-provider picker — Zen default + Qwen/Llama/DeepSeek/Mistral/Gemma/GPT-OSS
Mirror the live chat-config CM: house-brand Zen (default zen5-mini) plus the
independent third-party families the gateway serves, current-gen models only
(no sunset zen4). Same api.hanzo.ai/v1 gateway + per-user key → identical
Commerce metering across all families.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:12:32 -07:00
zandGitHub 5a3aede148 Merge pull request #55 from hanzoai/polish/chat-empty-state
polish(chat): premium starter cards — Railway × OpenAI (0.9.1)
2026-07-03 01:08:18 -07:00
zandClaude Opus 4.8 4f25c3131a polish(chat): premium starter cards (Railway x OpenAI); 0.9.1
Elevate the empty-state starters from flat chips to a refined 2-col card grid:
lucide icon in a rounded well, hover lift (-translate-y) + soft shadow + border
lightening, smooth 200ms ease-out, focus-visible ring, reduced-motion safe.
Uses existing theme tokens (surface-primary-alt / border-light / text-secondary)
so it tracks light+dark + the monochrome brand. Agent starters render in the
same grid (default icon).

Proper semver: 0.9.0 -> 0.9.1 (patch, visual refinement of the 0.9.0 feature).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:07:58 -07:00
zeekayandClaude Opus 4.8 512289012c merge(chat): unify → main — true-black theme, Zen ensō logo, /v1 unify, provider families
Brings the true-black OLED dark theme (style.css), the Zen ensō avatar
(ZenLogoIcon replacing the generic robot on the Zen/custom endpoint), the
chat→api.hanzo.ai/v1 unification, and the multi-provider picker (Zen house
brand + open families) onto main for a published build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:06:05 -07:00
zandGitHub 3af4415366 Merge pull request #54 from hanzoai/feat/chat-default-starters
feat(chat): default starter prompts on empty state (0.9.0)
2026-07-03 01:01:07 -07:00
zandClaude Opus 4.8 749784a50c feat(chat): default starter prompts on empty state; release 0.9.0
Plain-model chats (e.g. zen5-mini) showed a bare empty state — LibreChat only
rendered conversation starters for agents/assistants. Add 4 curated default
starters as the fallback so every empty chat gets ChatGPT/Claude-style
suggestion chips, wired through the existing useSubmitMessage path (landing-only;
agents that intentionally omit starters are untouched).

Proper semver: v0.8.3-rc1 (rc, non-standard v-prefix) -> 0.9.0 (minor, feature).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:00:44 -07:00
zeekayandClaude Opus 4.8 26e83d7645 fix(chat): drop Qwen + DeepSeek families (brand policy — Zen upstreams)
Qwen3 and DeepSeek are the upstreams behind Zen's flagship tiers
(zen5-max→qwen3.5-397b, zen5-pro/flash→deepseek-v4-pro/deepseek-4-flash).
Listing a Qwen or DeepSeek family next to Hanzo/Zen reveals the Zen mapping —
the single most forbidden thing in the brand policy. Keep only genuinely
independent open-weight families Zen's flagships don't build on: Meta Llama
and Mistral. Final picker: Hanzo (Zen, default zen5-mini) + Meta Llama +
Mistral. Every model is served by api.hanzo.ai/v1/models and its DO upstream
is verified invocable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 00:41:53 -07:00
zeekayandClaude Opus 4.8 662f054658 feat(chat): unified model picker — Zen + open families (Meta/Mistral/DeepSeek/Qwen)
Mirror librechat.yaml to the LIVE chat-config CM (v1.3.4) and add per-family
custom endpoints alongside Hanzo/Zen. Every endpoint is the same
api.hanzo.ai/v1 gateway carrying the per-user HANZO_API_KEY, so metering is
identical across families (the cloud billing gate). Hanzo stays customOrder:0
with the zen5-mini default.

Families listed are the ones the gateway can genuinely invoke today via
DigitalOcean GenAI (funded): Meta Llama, Mistral, DeepSeek, Qwen. OpenAI and
Anthropic branded resale is intentionally omitted — no funded key path exists
yet (direct OPENAI/ANTHROPIC keys unfunded; DO account lacks proprietary
access), so listing them would surface non-invocable models. Documented inline
for a one-block-each add once a funded key/enablement lands.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 00:27:53 -07:00
zeekayandClaude Opus 4.8 150c5fff4d fix(chat): live zen5+zen3 catalog in librechat.yaml mirror (drop sunset zen4)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:47:32 -07:00
zeekayandClaude Opus 4.8 abe59a625c feat(theme): true-black OLED dark theme + Zen ensō avatar
Dark theme pushed toward black per brand: main canvas #000, panels/sidebar
#050505/#0a0a0a, elevated controls (input, cards) #171717 — remapped the `.dark`
--surface-* + shadcn HSL block onto new near-black gray steps (--gray-925/950/975)
in one place (DRY; the scale, not per-component overrides).

Zen avatar: the custom endpoint (hanzo.chat is Zen-only — Hanzo AI zen* models)
rendered the generic LibreChat "custom" robot glyph because the custom branch
hardcodes CustomMinimalIcon and ignores the endpoint iconURL. Replaced with a
proper ZenLogoIcon (ensō — the single-brushstroke Zen circle, monochrome
currentColor so it reads on true-black), named 'Zen'.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:36:18 -07:00
zeekayandClaude Opus 4.8 14bb1bf35a fix(landing): drop raw upstream base-model names (brand policy)
The logged-out landing page listed Zen's upstream families (DeepSeek R1,
Qwen3, Llama 4, Phi-4) in the "third-party models" grid and named DeepSeek/
Qwen in the 100+ Models blurb — a brand-policy leak (Zen must present as our
own family; no raw Qwen/DeepSeek/Kimi/Llama/HuggingFace names). Keep only the
genuine independent providers offered via the gateway (GPT-5, Claude Opus 4,
Gemini 2.5, Grok, Mistral Large, Command R+) and lead the blurb with the Zen
family. Ships on next chat image build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:28:32 -07:00
zeekayandClaude Opus 4.8 9f6c243327 docs(unify): map chat→api.hanzo.ai/v1 architecture + enforce zen-only picker
Investigate-before-ripping map of hanzo.chat as the cloud "chat view":
- Documents the ONE inference path (POST /api/agents/chat/Hanzo →
  api.hanzo.ai/v1/chat/completions, per-user hk- key, SSE) plus code-exec →
  /v1/exec, websearch → /v1/websearch, cloud agents → /v1/agents. No shadow
  LLM backend; config.yaml/litellm is dead upstream residue.
- Flags the ONE real parallel store: LibreChat Mongo (convos/messages/presets/
  prompts/users/balances/files/sessions). Go backend has casibase-named
  persistence (/v1/get-chats,/v1/add-message) + a speced-but-unimplemented
  chat/openapi.yaml (/v1/chat/convos|messages|presets). Kill path documented;
  do NOT rip Mongo (data loss + dead chat) — coordinate with openapi.
- IAM-native status: prod passport OIDC → hanzo.id (client hanzo-chat), LIVE;
  static SPA mode uses client app-chat (align) on dormant @hanzo/iam ^0.4.0.
- @hanzo/ui (Tailwind/shadcn, chat's stack) vs @hanzo/gui (Tamagui/Next15,
  console's stack): unify via @hanzo/ui, not a framework-swap rewrite.

librechat.yaml: drop gpt-4o/claude from the Hanzo endpoint default so the repo
reference mirrors the authoritative prod ConfigMap — zen-only picker, no raw
upstream names (brand policy). One way.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:18:09 -07:00
hanzo-dev 34096ffe12 fix(agents): mandatory principal-binding + no OIDC refresh in decoupled session
Red-team hardening of the on-behalf-of decouple:

- cloud.js getUserCloudBearer: bind EVERY forwarded token (id_token AND the
  access_token fallback, session or cookie) via isForwardableToken. Principal
  binding is now MANDATORY (sub === req.user.openidId) with no fail-open when
  openidId/sub is absent, and the access_token fallback is bound too — closes
  the unbound-access_token and null-binding confused-deputy paths.
- AuthService.persistOpenIDTokensToSession: take the OIDC refresh credential
  EXPLICITLY (not from the tokenset). The decoupled default persists only the
  on-behalf-of bearer (id_token/access_token), NOT the OIDC refresh_token, so
  logout keeps using the local cookie -> findSession matches -> the server-side
  session is invalidated (was silently skipped once openidTokens landed in the
  decoupled session). REUSE path unchanged (passes the resolved credential).

Tests: cloud.spec + AuthService.spec green (bound-access, opaque-401,
foreign-401, null-openidId-401, cookie-injection-401, decoupled-omits-refresh).
Pre-existing oauth admin-exchange arity failures untouched (out of scope).
2026-07-02 18:12:25 -07:00
hanzo-dev a12198a01f fix(agents): decouple hanzo.id id_token persistence from the OIDC refresh gate
/api/agents/cloud returned 401 "cloud agents require hanzo.id sign-in" for
EVERY signed-in user: getUserCloudBearer forwarded the id_token read from
req.session.openidTokens, which is only populated by setOpenIDAuthTokens —
called at login solely when OPENID_REUSE_TOKENS=true. The live deploy runs
OPENID_REUSE_TOKENS=false on purpose (true makes /api/auth/refresh use the OIDC
refresh-grant, which 403s against hanzo.id and breaks login), so the id_token
was never persisted and the cloud-agent run was dead on arrival. One flag
braided two orthogonal concerns: (a) persist the id_token for downstream
on-behalf-of calls, (b) use the OIDC refresh-grant on token refresh.

Decouple:
- AuthService: new persistOpenIDTokensToSession(req, tokenset) — the one writer
  of req.session.openidTokens (server-side only, never a cookie). setOpenIDAuth-
  Tokens now delegates its session write to it (DRY, behavior-preserving).
- oauth login: an OpenID login ALWAYS persists the id_token to the session,
  regardless of OPENID_REUSE_TOKENS. With REUSE disabled the login still runs
  setAuthTokens (local-JWT refresh) so login/refresh cookies are byte-identical;
  only server-side session state is added. Persist is wrapped so it can never
  break the login redirect. OPENID_REUSE_TOKENS now SOLELY gates the refresh-grant.
- cloud proxy: getUserCloudBearer keys off the VALIDATED principal
  (req.user.provider === 'openid'), not the mutable token_provider cookie, so the
  on-behalf-of decision is tied to identity. The forwarded id_token must also name
  req.user (sub === openidId) and be unexpired — expired/absent yields an honest
  401, never a fabricated run. Confused deputy denied at the identity layer.

Durable refresh of the ~1h id_token (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.

Tests (jest): cloud proxy re-keyed to the principal + honest expiry/binding/
confused-deputy (20); oauth persists id_token when REUSE=false, uses the OIDC
writer when true, local user never persists, login survives a persist failure
(4); persistOpenIDTokensToSession session/expiry/no-session/no-tokenset (4).
Refresh path unchanged.

Note: oauth.spec's 2 admin-exchange tests are pre-existing red on origin/main
(spec expects a 7-arg generateAdminExchangeCode; source passes 4) — orthogonal
to this change, proven by a stashed baseline.
2026-07-02 17:43:58 -07:00
hanzo-dev 4abec9f46a harden(agents): rate-limit + load-shed + principal-guard the cloud-agent run proxy
Red review of the cloud /v1/agents run proxy: core security (SSRF, CSRF,
token-exfil, wrong-principal, mount-order, injection) confirmed closed; three
gaps fixed:

- MEDIUM: the run proxy (a real billable cloud completion) escaped the throttle
  guarding the sibling chat-completion path. Add per-user cloudAgentLimiter on
  the whole /cloud router (CLOUD_AGENT_USER_MAX/_WINDOW), a process-wide in-flight
  ceiling with fail-fast 503 (CLOUD_AGENT_MAX_CONCURRENT), and a 4 MiB buffered-
  response cap (Content-Length fast path + streamed abort) so no single call can
  pin the shared backend's memory.
- LOW: only forward OpenID tokens when the request itself is an OpenID login
  (token_provider==='openid'); a local-JWT user with a stale OpenID session can
  no longer run as that prior identity (confused deputy).
- LOW: cap input by UTF-8 BYTE length, not UTF-16 units, matching cloud's maxInput.

Tests: api 34 passed (was 25; +9: principal-guard, cookie-read, byte-cap,
response-cap x3, concurrency-cap x2). eslint clean.
2026-07-02 13:56:56 -07:00
hanzo-dev 7c4c1b676c harden(agents): validate cloud agent :name at the HTTP boundary
Move the cloud handle-grammar guard to the route boundary via router.param,
not only inside CloudAgentsClient. A malformed/decoded :name (traversal,
null byte, CRLF, backslash, space) is now rejected with 400 before any client
call is constructed — defense at the boundary. Production was already safe
(the client rejects the same names), but the guard belongs at the entry point.

Adds boundary-validation tests proving decoded smuggles (../etc, ../admin,
..\evil, %00, %0d, %20) 400 without reaching the client. cloud route 14/14,
CloudAgentsClient 11/11 green.
2026-07-02 00:22:19 -07:00
hanzo-dev 0138889e81 feat(agents): run canonical cloud /v1/agents from chat + mobile builder fixes
Add cloud-agent RUN alongside the existing LibreChat-legacy agent builder
(which is untouched). The canonical registry is cloud /v1/agents; chat now
lets a signed-in user run their OWN cloud agents from the thread via a
/agent <name> [prompt] slash command and via the @mention picker.

Backend (server-side proxy, token never reaches the browser):
- CloudAgentsClient forwards the user's hanzo.id id_token as a Bearer to
  cloud; cloud's SanitizeIdentity (HIP-0026) validates it and pins X-Org-Id
  from the owner claim, so a user only reaches their own org. Not an open
  proxy: fixed host from HANZO_CLOUD_URL (falls back to OPENAI_BASE_URL host),
  three fixed endpoints, agent name validated against cloud's handle grammar
  (traversal/SSRF guard), 128KB input cap, 30s timeout, fail-secure 401 on
  missing token (no service-token fallback).
- /api/agents/cloud/{,:name,:name/run} router, requireJwtAuth (guests rejected),
  honest error passthrough. Mounted before the legacy /:id route.

Frontend (DRY, one run path, reuses Mention/MentionItem):
- useRunCloudAgent renders the run in-thread; parseAgentCommand is the single
  command grammar; /agent and @mention both funnel through it.
- Cloud agents surface in @mention (cloudAgent type) and a /agent popover.

Mobile: AgentConfig responsive padding + full-width wrapping error text +
stacked tool/action buttons; AgentPanel form min-w-0 to stop overflow <768px.

Convergence of chat's /api/agents CRUD onto /v1/agents is a later step.

Tests: CloudAgentsClient (11) + cloud route (7) + parseAgentCommand (8) green.
2026-07-02 00:18:02 -07:00
devandDarkhorse7stars 9ef8cf46a9 fix(analytics): bake VITE_ANALYTICS_SITE_ID into the Vite build
The index.html tracker tag uses %VITE_ANALYTICS_SITE_ID%, substituted by
Vite at build time. The var was never set at build, so the placeholder
shipped literally and the browser POSTed website id '%VITE_ANALYTICS_SITE_ID%'
to analytics.hanzo.ai/api/send -> 400. The CR only set NEXT_PUBLIC_ANALYTICS_SITE_ID
(runtime, wrong prefix + phase for a Vite build). Default the real registered
Hanzo Chat site id as a Docker ARG/ENV so the frontend build bakes it in.
2026-07-01 10:30:00 -05:00
dev 4d96ee9e4d fix(pwa): precache index.html so the SW nav fallback resolves
vite-plugin-pwa's default navigateFallback is 'index.html', so the SW
binds createHandlerBoundToURL('index.html'). index.html was in globIgnores
(not precached) -> 'non-precached-url: index.html' -> the service worker
breaks and strands users on a stale shell after each deploy (they see
/api/* 401s until a manual SW clear). Precache it; registerType:autoUpdate
keeps it fresh on release.
2026-07-01 08:53:07 -05:00
c4f48f6af5 feat(chat): wire Run Code + Web Search to Hanzo unified backend (no external SaaS) (#52)
Both Agent Builder capabilities were 🔑-gated because nothing was wired.

- librechat.yaml: add webSearch{} pinned to Hanzo's own /v1/websearch surface
  — searchProvider=searxng (Hanzo metasearch), scraperProvider=firecrawl
  (Hanzo Crawl), no reranker. NO external Serper/Tavily/Jina/Cohere. Add
  endpoints.agents.capabilities so execute_code + web_search show active.
- .env.hanzo-cloud: the old CODE_EXECUTION_ENDPOINT/RUNTIME_API_KEY were DEAD
  (LibreChat never reads them, and the path was /execute not /exec). Replace
  with the real vars: LIBRECHAT_CODE_BASEURL=https://api.hanzo.ai/v1 +
  LIBRECHAT_CODE_API_KEY (KMS). Add SEARXNG_INSTANCE_URL / FIRECRAWL_API_URL /
  WEBSEARCH_API_KEY -> api.hanzo.ai/v1/websearch.
- .env.example: document the Hanzo-backend vars as the one way; note external
  providers are intentionally disabled.

Validated against the LibreChat Zod configSchema: CONFIG VALID (searxng +
firecrawl + execute_code/web_search capabilities).

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-30 18:39:33 -07:00
f466b6c2ca fix(chat): treat missing agent_id as ephemeral so 'hi' just replies (#51)
In the agents-centric chat UI ('My Agents'), sending a message with no agent
created/selected POSTed to the agents completion endpoint without an agent_id,
which canAccessAgentFromBody rejected with 400 'agent_id is required in request
body'. A missing agent_id on the agents endpoint is an ad-hoc (ephemeral) chat,
not an error — isEphemeralAgentId(undefined) is already true.

- canAccessAgentFromBody: drop the 400 branch; a missing id falls through the
  existing ephemeral path (no per-agent ACL) to plain chat.
- agents/build.buildOptions: resolve a missing agent_id to EPHEMERAL_AGENT_ID so
  loadAgent builds an ephemeral plain-model agent instead of returning null.
- Hermetic regression specs for both fix points (no Mongo/winston); update the
  stale middleware test that codified the 400.

Logged-in user types 'hi' -> ephemeral agent on the configured default model ->
reply, with no agent build required first.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-29 22:07:27 -07:00
z 26591fb2ba docs(brand): add hero banner 2026-06-28 20:06:46 -07:00
z f54d01289b chore(brand): dynamic hero banner 2026-06-28 20:06:45 -07:00
Hanzo AI 1a8456bbb9 fix(chat): surface Hanzo gateway 200 error-envelope instead of crashing the agent run
The Hanzo Cloud gateway (api.hanzo.ai) answers some failures -- most importantly a request for a premium model (e.g. zen5-mini) when the caller's balance is only the $5 starter credit -- with HTTP 200 and a JSON error envelope ({status:"error", msg}) that carries no `choices`. The OpenAI client treated the 200 as success and parsed the choices-less body to `undefined`, so the agent run threw the opaque "Cannot read properties of undefined (reading 'role')" (and the title call died on reading 'message') -- no AI reply rendered, the generation job expired, and the resume stream 404'd.

Wrap the custom-endpoint OpenAI client fetch (scoped to the Hanzo gateway) so that envelope is rewritten into a clean 402 carrying the gateway's actionable message. Successful SSE streams and normal completions pass through untouched; the request is never inspected, so per-user hk- billing is unaffected.

- packages/api: hanzoGatewayFetch response-only wrapper + wire into initializeCustom + unit tests
2026-06-27 23:48:12 -07:00
Hanzo AI 0dfa7df1da fix(chat): default new conversations to the Hanzo endpoint, not bare agents
A fresh /c/new defaulted to the built-in `agents` endpoint with no agent
selected. All chat routes through POST /api/agents/chat/:endpoint; with
endpoint=agents and no agent_id the access middleware (canAccessAgentFromBody)
returns 400 "agent_id is required in request body" and the SSE stream never
starts — every first message failed with no AI response.

Root cause: orderEndpointsConfig gives built-in `agents` order 1 but defaults
every custom endpoint to order 9999, so the client's getDefaultEndpoint picked
`agents` first. The intended override — a custom endpoint's `customOrder` — was
silently dropped by loadCustomEndpointsConfig (it never emitted `order`), even
though orderEndpointsConfig already types the custom spread as `& { order?: number }`.

Fix: loadCustomEndpointsConfig now honors `customOrder` -> `order`, and the Hanzo
endpoint sets `customOrder: 0` so it outranks `agents`. A new conversation now
defaults to Hanzo, which routes as an ephemeral agent (provider=Hanzo) through
the proven per-user hk- key path (resolveHanzoCloudKey) — real AI response,
metered, no agent_id 400. Agents endpoint stays available for explicit selection.

- packages/api: honor customOrder, widen TCustomEndpointsConfig, + unit test
- librechat.yaml: customOrder: 0 on Hanzo (mirrored in universe chat-config)
2026-06-27 22:22:06 -07:00
Hanzo AI 44d41f6235 fix(billing): auto-$5 starter credit on first chat + per-user billing subject
New-account chat now works end to end, fail-closed, no shared-org bleed:

- resolveHanzoCloudKey computes the canonical per-user billing subject
  (object.BillingSubject parity: 'owner/name' for the shared hanzo catch-all),
  stamps it on req.user, and ensures the one-time $5 Commerce starter credit on
  THAT subject (POST /v1/billing/grant-starter) BEFORE forwarding the user's
  hk- key — so the gateway's first balance check sees $5 instead of 402-ing.
  Idempotent (in-process + commerce tag-dedupe), best-effort (gateway enforces).
- CommerceClient: checkBalance/tier/breakdown key on the subject and derive the
  X-Hanzo-Org namespace from it; replace the wrong-ledger createTrialGrant
  (credit-grants, invisible to /billing/balance) with grantStarter (Deposit).
- balanceMethods gate keys on the per-user subject (req.user.billingSubject).
- Drop chat-side Commerce usage write (single debit = the gateway).
- Remove the dead createTrialGrant call in user.ts (never fired for SSO users,
  wrong ledger).
2026-06-27 17:57:43 -07:00
Hanzo AI 0becb68c80 fix(billing): converge money path on per-user hk- (single debit) + exempt guests
The prior HEAD (4233c8760) was reverted in the preceding commit: it rewrote the
gate to forward the user's IAM JWT to commerce AND added a chat-side
spendTokens -> /v1/billing/usage decrement. With per-user hk- forwarding ON,
that double-debits (cloud gateway debits the org via the user's hk- key, AND
chat debits the same org via spendTokens). One money authority only: the cloud
gateway debits via the per-user hk- key; chat's balanceMethods is a READ-ONLY,
fail-closed pre-flight gate (service token + X-Hanzo-Org, the proven pattern).

This commit adds the one missing piece for the anon free tier: guests are
exempt from the balance gate. Guests hit checkBalance via BaseClient
(supportsBalanceCheck[custom]=true) with no billing org; under startBalance:0
the legacy local gate would block the free tier entirely. Their spend is
bounded instead by (1) the per-IP guest message limiter and (2) the separate,
small-capped, NON-exempt guest key (HANZO_API_KEY) the gateway 402s when empty.

Tests: fail-closed decision matrix (funded/insufficient/unavailable/
model_not_allowed/no-org) + guest exemption. 8/8 green.
2026-06-27 12:26:37 -07:00
Hanzo AI 04210dea16 Revert "fix(billing): IAM-native, fail-closed AI metering (stop unmetered leak)"
This reverts commit 4233c8760f.
2026-06-27 12:21:31 -07:00
Hanzo AI 4233c8760f fix(billing): IAM-native, fail-closed AI metering (stop unmetered leak)
Commerce is already IAM-native + multi-tenant; chat was sending a static
service token (not a JWT) so commerce 401'd and the balance check fell open =
unmetered AI. Rewire to forward the logged-in user's hanzo.id IAM JWT per
request and fail CLOSED.

- CommerceClient: drop the static COMMERCE_TOKEN singleton; every call carries
  the user's IAM JWT (Authorization: Bearer). getMyBalance (fail-closed read),
  grantWelcome ($5 idempotent), recordUsage (decrement). getIamToken/
  getBillingOrg/computeUsageCents/recordCommerceSpend helpers.
- balanceMethods.checkBalance: IAM-native money gate, FAIL CLOSED — no token /
  commerce-unreachable / below-min => refuse. Funded user passes. Self-heals a
  new account by granting the idempotent $5 once and re-reading (a spent wallet
  stays blocked — grant is tag-deduped).
- spendTokens / spendStructuredTokens: decrement the user's per-org commerce
  balance, mirroring the local ledger cost; threaded from the agent spend sites.
- openidStrategy: grant the $5 welcome credit on new-account signup under the
  user's IAM identity (synchronous, best-effort).
- Balance controller: surface the authoritative commerce balance (display).
- Tests: fail-closed/fail-open decision matrix + cost mirror (12 cases).

Requires OPENID_REUSE_TOKENS=true (chat CR) so the IAM JWT is on the request,
and COMMERCE_EDGE_AUTH=true + hanzo-chat audience (commerce CR).
2026-06-27 11:21:52 -07:00
Hanzo AI d20ba76651 fix(billing): per-user hk- key forwarding + commerce-first fail-closed balance gate (stop the bleed)
hanzo.chat money path. Previously every authenticated chat ran on z's shared
hk- key (hanzo/z) against the shared 'hanzo' commerce org, plus a $5 local
startBalance per user and a fail-OPEN balance gate -> unbounded free spend.

- Per-user billing: resolve (mint on first chat) each authenticated user's OWN
  hk- key from IAM by org+email and forward it to the gateway, which debits
  THEIR org. New packages/api/src/endpoints/custom/hanzoCloudKey.ts; injected at
  the single apiKey chokepoint in custom/initialize.ts. FAIL CLOSED: an authed
  user whose key cannot be resolved is blocked, never falls back to the shared
  key. The resolver also stamps the authoritative billing org back onto req.user
  (OIDC 'owner' can be the Casdoor super-org 'admin', not the real billing org).
- Balance gate commerce-first + FAIL CLOSED + decisive (balanceMethods.js):
  when commerce is configured and the user's org is known, the org's commerce
  balance is authoritative (>= HANZO_MIN_BALANCE); insufficient/unreachable ->
  block. No fall-through to local tokenCredits, so startBalance:0 cannot
  false-block a funded user. CommerceClient balance read is now fail-closed
  (throws on cold error) and per-org scoped (X-Hanzo-Org).
- startBalance: 0 (librechat.yaml): no free local credits; new users claim $5
  at billing.hanzo.ai. Client shows a claim-credit link on empty balance.

Gated by HANZO_PER_USER_KEY=true (reuses OPENID_* client creds for IAM).
2026-06-27 10:59:29 -07:00
Hanzo AI 3e36ede65d fix(theme): monochrome UI — neutralize blue-hued tokens (222/215/220 → 0 0%) + #2563eb ring/border → gray
The dark theme tinted all panels/sidebar blue via --background/--card/--border/
--input/--muted/--accent at hue 222 (and ring #2563eb). Neutralized to 0%
saturation (grayscale) to match the Hanzo monochrome brand.
2026-06-26 23:42:25 -07:00
Hanzo AI 18f3d9ce80 fix(brand): convert residual landing-page red accents to monochrome white
The monochrome rebrand changed the LandingPage `colors` object + login CTAs
but left 8 inline rgba(253,68,68,…) (#fd4444) accents — hero gradient,
"AI Chat Platform" badge border, Zen-models card border/bg + hover, and the
"Free credit" pricing tier border/bg/label. Convert all to rgba(255,255,255,…)
(preserving alpha), matching the existing white monochrome accents. The
terminal traffic-light dots (bg-red/yellow/green-500) already render grey via
the tailwind color-scale remap. Landing is now fully black/white/grey.
2026-06-26 19:45:46 -07:00
Hanzo AI 5578ef924d feat(brand): monochrome Hanzo rebrand — feather→H-mark, white CTAs, canonical favicon
Replace the upstream LibreChat feather/quill brand fallback with the
official Hanzo ▼/H mark (currentColor, monochrome) across every agent and
endpoint icon path (Landing welcome via ConvoIcon→AgentAvatar, agent
avatars, message + minimal icons).

Collapse all Tailwind color scales (green/red/blue/sky/…/rose) to a single
neutral grey ramp so UI chrome is black/white/grey only; destructive
semantics keep one muted red via --text-destructive. Convert the green
Create/Save CTAs (Add-MCP-Server dialog, Agent + Assistant builders,
preset and API-key dialogs) and .btn-primary to the adaptive
white-on-dark primary button.

Set favicon/PWA assets to the canonical hanzo.app ▼/H set (favicon.ico
byte-identical to hanzo.app) and the manifest theme_color to monochrome.

Tests: 34 passed — Hanzo-mark fallback assertions updated.
2026-06-26 19:19:23 -07:00
Hanzo AI 5e0b6038af chore(iam): unify @hanzo/iam to ^0.13.1; BrowserIamSdk->IAM (localStorage PKCE login fix)
client/package.json: ^0.4.0 -> ^0.13.1 (npm latest). 0.13.x moves the PKCE tx (state+verifier) from sessionStorage to localStorage so it survives the OAuth redirect, fixing login.

iam.ts: BrowserIamSdk class renamed to IAM. Import bare '@hanzo/iam' (not the '/browser' subpath): the client tsconfig uses moduleResolution=node, which cannot resolve the exports subpath for types; the bare entry (dist/index.d.ts) re-exports IAM and Vite still bundles dist/browser.js via the browser export condition. Constructor config (IAMConfig) is unchanged.

OAuthCallback.tsx: IAMToken fields camelCased in 0.13 (access_token -> accessToken); without this the callback never set the auth header.

Lockfile: pnpm-lock.yaml regenerated (authoritative per packageManager=pnpm@10.27.0 + Dockerfile 'pnpm install --frozen-lockfile'). package-lock.json/bun.lock left untouched (not consumed by any build or CI).
2026-06-26 13:11:15 -07:00
a5a2498997 fix(oauth): scope loginLimiter to initiation routes, not OIDC callbacks (fixes 429 on code exchange) (#42)
Co-authored-by: Antje Worring <worringantje@gmail.com>
2026-06-25 15:22:56 -07:00
Antje Worring dbed3bf2fb fix(csp): allow analytics + Cloudflare beacon scripts, fonts, media
The CSP script-src was 'self' only, blocking the app's own
analytics.hanzo.ai/script.js and static.cloudflareinsights.com beacon, plus a
data: font and assets/silence.mp3 (console errors + broken assets on every
page load). Allow-list the two external script hosts in script-src/connect-src
and add font-src/media-src for data:/blob:.
2026-06-23 18:05:34 -07:00
Antje Worring 462dbfdc84 fix(branding): canonical @hanzo blocky-H assets/logo.svg (replace placeholder 24x24 H)
The OIDC/model iconURL and OPENID_IMAGE_URL point at hanzo.chat/assets/logo.svg;
that asset was still a made-up 24x24 single-path H. Replace with the canonical
64x64 blocky-H (5 paths) byte-matching @hanzo/brand — matches what the live
0.7.12 image serves.
2026-06-23 14:29:53 -07:00
hanzoandAntje Worring c2aff88ca6 fix(branding): real @hanzo blocky-H logo+favicon, dev-only devtools, working OIDC button icon
- App.jsx: gate ReactQueryDevtools behind import.meta.env.DEV via lazy dynamic
  import so the devtools floating button (red flower) never ships in prod.
- librechat.yaml + compose.prod.yml: OIDC/model iconURL & OPENID_IMAGE_URL
  hanzo.ai/logo/icon.svg (404) -> hanzo.chat/assets/logo.svg (served, canonical).
- index.html: add scalable SVG favicon (canonical blocky-H) as primary icon.
- post-build.cjs: copy favicon.ico into dist root so /favicon.ico serves.
- add real multi-size favicon.ico generated from @hanzo/brand favicon (blocky-H).

logo.svg/favicons already match @hanzo/brand canonical blocky-H byte-for-byte;
prod was serving a stale dist (title 'Chat', no assets) -> fresh build fixes.
2026-06-23 14:29:53 -07:00
Hanzo DevandGitHub 05396959ae Merge pull request #50 from hanzoai/fix/guest-bootstrap-endpoints
fix(guest): UI-bootstrap endpoints serve guest-scoped data (fix HTTP 500 → working composer)
2026-06-21 14:12:49 -07:00
zeekay da475d299b feat(guest): serve guest-scoped data on UI-bootstrap endpoints
The composer hard-requires a handful of read-only bootstrap calls. Switch
exactly those to requireGuestOrJwtAuth and add a guest branch that returns
safe, scoped data — never a DB lookup, never another user's data:

- GET /api/endpoints  → ONLY the guest endpoint (Hanzo)
- GET /api/models     → ONLY the single guest model
- GET /api/user       → ephemeral guest principal (no email)
- GET /api/convos     → empty conversation page
- GET /api/user/settings/favorites → []
- GET /api/agents/chat/active      → { activeJobIds: [] }

Every mutation and read-by-id route stays JWT-only and rejects guests with
a clean 401 (post jwt-strategy fix). Banner (optionalJwtAuth) now resolves
with no user for guests. Adds controller + full-chain integration tests.
2026-06-21 14:10:21 -07:00
zeekay 2e794d3228 feat(guest): central guest principal + scoped-config builders
Single source of truth in guestConfig.js for the ephemeral guest shape:
- buildGuestPrincipal(id): plain GUEST req.user (no DB id/email)
- buildGuestUser: safe /api/user payload (name 'Guest', no email)
- buildGuestEndpointsConfig: ONLY the configured guest endpoint
- buildGuestModelsConfig: ONLY the single configured guest model

requireGuestOrJwtAuth now builds its principal from buildGuestPrincipal
(adds name 'Guest'), keeping the guest shape DRY across auth and bootstrap.
2026-06-21 14:10:12 -07:00
zeekay 9cd97355fe fix(guest): jwt strategy rejects guest tokens cleanly (no CastError → 500)
The guest JWT carries a synthetic `guest_<uuid>` id that is not a Mongo
ObjectId. On any requireJwtAuth route the 'jwt' passport strategy called
getUserById(guest_id) → Mongoose CastError → done(err) → HTTP 500.

Detect the `guest: true` claim at the top of the verify callback and
return done(null, false) before any DB lookup. Guest tokens now fail the
strict strategy with a clean 401, and reach their scoped routes only via
requireGuestOrJwtAuth. Fail closed by construction.
2026-06-21 14:10:05 -07:00
Hanzo DevandGitHub b70c5400a2 Merge pull request #49 from hanzoai/fix/guest-route-guard
fix(guest): route guard honors guest mode (composer for logged-out)
2026-06-21 13:45:38 -07:00
zeekay 8a89cfed07 fix(guest): useAuthRedirect must honor guest mode (stop bouncing guests to /login)
The chat route guard redirected any !isAuthenticated user to /login on a
300ms timer, ignoring isGuest/allowGuestChat and beating startup-config
load — so logged-out guests never reached the composer. Wait for config,
and skip the redirect when guest chat is enabled or the user is a guest.
2026-06-21 13:45:32 -07:00
Hanzo DevandGitHub c3114a1258 Merge pull request #48 from hanzoai/fix/guest-acquire-race
fix(guest): acquire guest session when allowGuestChat resolves (fixes landing-page race)
2026-06-21 13:26:05 -07:00
zeekay 821b3b59a2 fix(guest): acquire guest session when allowGuestChat config resolves
silentRefresh's guest fallback could run before startupConfig loaded
(allowGuestChat undefined) and was never retried, leaving logged-out
visitors on the landing page instead of the guest composer. Add a
dedicated effect that acquires the guest token once the flag is true.
2026-06-21 13:25:59 -07:00
Hanzo DevandGitHub 8a6c63a869 Merge pull request #47 from hanzoai/feat/guest-chat
feat(guest): anonymous guest preview chat (opt-in, fail-closed)
2026-06-21 12:52:28 -07:00
zeekay 86ecab135e docs(guest): document guest-chat env vars and security model 2026-06-21 12:46:56 -07:00
zeekay 196e3c3d61 feat(guest): client guest-chat mode + login gate
When unauthenticated and startupConfig.allowGuestChat is set, acquire a
guest token on load and render the chat composer instead of the landing
gate. On a 402 GUEST_LIMIT response, surface GuestLimitDialog which
triggers the existing OpenID/hanzo.id login flow.

- useGuestAuth: acquires an ephemeral guest session via dataService.
- AuthContext: isGuest state; guest fallback in silentRefresh; userQuery
  and silentRefresh disabled for guests (capability-scoped).
- Root: render chat for guests (auth-gated hooks stay disabled); mount
  GuestLimitDialog.
- useResumableSSE: dispatch guestLimitReached on 402 GUEST_LIMIT.
2026-06-21 12:46:56 -07:00
zeekay 46b636c8c0 feat(guest): server-side anonymous guest chat (fail-closed, scoped)
Add an opt-in anonymous preview mode gated behind ALLOW_GUEST_CHAT
(default off). Guests get a per-IP free quota (GUEST_MESSAGE_MAX,
default 3) on the free Zen model via the Hanzo gateway endpoint.

- POST /api/auth/guest issues a short-lived guest JWT ({guest:true},
  per-token random id) signed with JWT_SECRET; rate-limited per IP.
- requireGuestOrJwtAuth accepts guest tokens ONLY on the chat-completion
  router; the standard jwt strategy rejects them everywhere else.
- enforceGuestScope pins endpoint+model to the free Zen endpoint and
  strips agents/tools/files/spec/preset server-side.
- guestMessageLimiter enforces the per-IP quota via the shared Redis
  limiterCache; returns 402 {type:'GUEST_LIMIT'} on exhaustion.
- Reserved chat subpaths (stream/active/status/abort) stay JWT-only.
- Expose allowGuestChat/guestMessageMax in /api/config; add GUEST role.

Tests: 27 unit/integration tests covering config, guest auth wrapper,
scope enforcement, quota, and the router chain.
2026-06-21 12:46:27 -07:00
0cc792d02d fix(agents): stop post-reply error banner from nulled config.configurable (#46)
run.processStream (@librechat/agents >= 3.1.52) treats the passed config as
owned and, in its post-stream cleanup, sets config.configurable = undefined to
break the AsyncLocalStorage -> LangGraph reference chain that keeps heavy graph
state (base64 images/PDFs) alive (agents dist/esm/run.mjs:239). Reading
config.configurable.hide_sequential_outputs AFTER runAgents() therefore threw
"Cannot read properties of undefined (reading 'hide_sequential_outputs')",
caught by chatCompletion and pushed as an ERROR content part -- the red
post-reply banner. The same throw aborted the post-stream finalize, which is
why auto-titling also stopped.

Hoist the read to before runAgents() (the value is a static agent property only
needed afterward by the deprecated Agent Chain output filter), so it no longer
depends on post-run config state. Matches upstream LibreChat's fix
(PR #11942, a0f9782e6).

Adds a regression test that reproduces the mutation (processStream nulls
config.configurable) and asserts no ERROR content part is produced, plus
coverage for the hide_sequential_outputs true/false filter behavior.

Co-authored-by: Antje Worring <worringantje@gmail.com>
2026-06-21 10:28:01 -07:00
zeekay ca632b467f chore: restore upstream attribution + NOTICE (OSS compliance) 2026-06-21 02:10:07 -07:00
9df97c7393 fix(deps): dedupe @ariakit/react to a single instance (fixes chat Nav crash) (#44)
After the session-handoff fix let authenticated users reach /c/new, the
chat Nav crashed the whole route with react-router-looking 'Invariant
failed' — actually an Ariakit invariant: useMenuButton(store||context,
false). Root cause: two @ariakit/react copies in the bundle — the app
(client, ^0.4.15 -> 0.4.23) and @librechat/client (packages/client,
^0.4.16 -> nested 0.4.21). DropdownPopup (from @librechat/client) creates
<MenuProvider> in one Ariakit instance; BookmarkNav's <MenuButton> reads
the MenuProvider context of the *other* instance -> empty -> invariant ->
ErrorBoundary 'Oops! Something Unexpected Occurred'.

Pin @ariakit/react to a single 0.4.29 (latest 0.4.x; satisfies both
^0.4.15 and ^0.4.16) via overrides + pnpm.overrides so app and
@librechat/client share one Ariakit module/context. Verified:
@librechat/client + client (Vite) rebuild green; lockfile now resolves a
single @ariakit/react@0.4.29 with no nested copy.

Co-authored-by: Antje Worring <worringantje@gmail.com>
2026-06-21 00:42:56 -07:00
394 changed files with 21204 additions and 4695 deletions
+16
View File
@@ -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"
+40 -19
View File
@@ -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 #
#===================================#
@@ -463,6 +474,21 @@ ALLOW_REGISTRATION=true
ALLOW_SOCIAL_LOGIN=false
ALLOW_SOCIAL_REGISTRATION=false
ALLOW_PASSWORD_RESET=false
#=====================================================#
# Guest Chat (anonymous preview) #
#=====================================================#
# Off by default. When enabled, unauthenticated visitors get a small free
# quota on the free Zen model routed through api.hanzo.ai. After the quota is
# spent the UI surfaces the existing OpenID/hanzo.id login. Guests are scoped
# server-side to the free model only and rejected from every other route.
ALLOW_GUEST_CHAT=false
# GUEST_MESSAGE_MAX=3 # free messages per IP before login is required
# GUEST_ENDPOINT=Hanzo # custom endpoint name from librechat.yaml (api.hanzo.ai)
# GUEST_MODEL=zen3-nano # free Zen model id guests are pinned to
# GUEST_TOKEN_EXPIRY=3600000 # guest JWT lifetime in ms (default 1h)
# GUEST_TOKEN_MAX=20 # max guest sessions issued per IP per window
# GUEST_TOKEN_WINDOW=60 # guest-session issuance window in minutes
# ALLOW_ACCOUNT_DELETION=true # note: enabled by default if omitted/commented out
ALLOW_UNVERIFIED_EMAIL_LOGIN=true
@@ -810,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
View File
@@ -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
+9
View File
@@ -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

+3
View File
@@ -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
+23 -22
View File
@@ -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 != '[]'
+1 -1
View File
@@ -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
-57
View File
@@ -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)
+16
View File
@@ -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
+27 -27
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
+1
View File
@@ -5,6 +5,7 @@ Portions of this software are licensed as follows:
---
MIT License
Copyright (c) 2023 LibreChat (Danny Avila)
Copyright (c) 2023 Hanzo AI Inc
Originally based on LibreChat by Berri AI.
+206
View File
@@ -90,6 +90,212 @@ CREDS_KEY= CREDS_IV= # Credential encryption
- `uv` bundled for MCP server support
- `dompurify` must be in `client/package.json` (externalized by bundler)
## Guest Chat (anonymous preview)
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`). 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 /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. 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`,
`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):
+6
View File
@@ -0,0 +1,6 @@
chat
Copyright (c) 2023 Hanzo AI Inc.
This product includes software from LibreChat (https://github.com/danny-avila/LibreChat), licensed under MIT:
Copyright (c) 2023 LibreChat (Danny Avila)
+2
View File
@@ -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.
+6 -6
View File
@@ -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...".
+18 -8
View File
@@ -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
+26 -1
View File
@@ -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
View File
@@ -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"
}
-8
View File
@@ -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.
-115
View File
@@ -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...
-3
View File
@@ -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...
-3
View File
@@ -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
-3
View File
@@ -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...
-4
View File
@@ -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)"}
-4
View File
@@ -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"}
-4
View File
@@ -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"}
+6 -6
View File
@@ -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
View File
@@ -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();
+8
View File
@@ -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(),
+106 -44
View File
@@ -1,5 +1,6 @@
const { logger } = require('@librechat/data-schemas');
const { ViolationTypes } = require('librechat-data-provider');
const { billingSubject } = require('@hanzochat/api');
const { createAutoRefillTransaction } = require('./Transaction');
const { logViolation } = require('~/cache');
const { getMultiplier } = require('./tx');
@@ -22,6 +23,21 @@ function getMinBalance() {
return 0;
}
/**
* Minimum balance in COMMERCE cents (commerce balances are in cents).
* Derived from HANZO_MIN_BALANCE (USD). Used by the commerce-first money gate.
*/
function getMinBalanceCents() {
const envVal = process.env.HANZO_MIN_BALANCE;
if (envVal != null && envVal !== '') {
const usd = parseFloat(envVal);
if (!isNaN(usd) && usd > 0) {
return Math.round(usd * 100);
}
}
return 0;
}
function isInvalidDate(date) {
return isNaN(date);
}
@@ -50,10 +66,24 @@ const checkModelAccess = async function (userId, model) {
};
/**
* Simple check method that calculates token cost and returns balance info.
* Integrates with Commerce balance gate when configured (fail-open).
* Calculates token cost and decides whether the request may proceed.
*
* MONEY GATE — Commerce-first and FAIL CLOSED (this is the money path; better to
* block a user than bleed). When Commerce is configured and we can identify the
* user's billing org (their IAM `organization`), Commerce is AUTHORITATIVE:
* - sufficient org balance (>= HANZO_MIN_BALANCE) → allowed (decisive; we do
* NOT fall through to the local tokenCredits gate, so startBalance:0 never
* false-blocks a Commerce-funded user);
* - insufficient / unreachable / no billing identity → BLOCKED.
* The cloud gateway separately debits the user's own hk- key against this same
* org, so this check is the pre-flight that yields a clean "claim credit" UX
* instead of a raw gateway 402.
*
* When Commerce is not configured (or no billing identity), falls back to the
* legacy local tokenCredits gate.
*/
const checkBalanceRecord = async function ({
req,
user,
model,
endpoint,
@@ -65,7 +95,79 @@ const checkBalanceRecord = async function ({
const multiplier = getMultiplier({ valueKey, tokenType, model, endpoint, endpointTokenConfig });
const tokenCost = amount * multiplier;
// Retrieve the balance record
// Guests (anonymous preview) are NOT balance-gated here. Their spend is bounded
// two ways, neither of which is an authed user's org balance: (1) the per-IP
// guest message limiter (GUEST_MESSAGE_MAX, default 3) and (2) the separate,
// small-capped, NON-exempt guest key (HANZO_API_KEY) whose own org's Commerce
// balance the cloud gateway debits and 402s when empty. Running them through the
// Commerce/local gate (startBalance:0) would block the free tier entirely.
if (req?.user?.guest === true) {
return { canSpend: true, balance: 0, tokenCost };
}
const commerceClient = getCommerceClient();
const billingOrg = (req?.user?.organization ?? '').toString().trim();
// Per-user billing subject — prefer the one resolveHanzoCloudKey stamped from
// the authoritative IAM identity; otherwise derive it from organization + email
// (name == email for individual signups). This keys the gate on the SAME
// account the gateway debits (per-user for the shared "hanzo" catch-all), not
// the shared org balance.
const subject =
(req?.user?.billingSubject ?? '').toString().trim() ||
billingSubject(billingOrg, req?.user?.email);
// Commerce-first authoritative gate (per-subject, fail closed).
if (commerceClient && subject) {
let commerceBalance;
try {
commerceBalance = await commerceClient.checkBalance(subject);
} catch (err) {
logger.error('[Balance.check] Commerce unreachable — blocking (fail-closed)', {
user,
subject,
error: err.message,
});
return { canSpend: false, balance: 0, tokenCost, reason: 'commerce_unavailable' };
}
const available = commerceBalance.available || 0;
const minCents = Math.max(getMinBalanceCents(), 1);
if (available < minCents) {
logger.debug('[Balance.check] Commerce balance insufficient', {
user,
subject,
available,
minCents,
});
return { canSpend: false, balance: available, tokenCost, reason: 'commerce_insufficient' };
}
// Tier/model access (fail-open: a tier hiccup must not block a funded user).
if (model) {
try {
const modelAccess = await commerceClient.isModelAllowed(subject, model);
if (!modelAccess.allowed) {
return {
canSpend: false,
balance: available,
tokenCost,
reason: 'model_not_allowed',
tier: modelAccess.tier,
allowedModels: modelAccess.allowedModels,
};
}
} catch (err) {
logger.warn('[Balance.check] Tier check failed, allowing (balance ok)', {
error: err.message,
});
}
}
// Decisive: Commerce says funded → allow. Do not consult local credits.
return { canSpend: true, balance: available, tokenCost };
}
// ── Legacy local-credit gate (Commerce not configured / no billing identity) ──
let record = await Balance.findOne({ user }).lean();
if (!record) {
logger.debug('[Balance.check] No balance record found for user', { user });
@@ -76,46 +178,6 @@ const checkBalanceRecord = async function ({
};
}
// Commerce balance gate: if configured, check Commerce first (fail-open)
const commerceClient = getCommerceClient();
if (commerceClient && record.commerceUserId) {
try {
const commerceBalance = await commerceClient.checkBalance(record.commerceUserId);
if (!commerceBalance.sufficient) {
logger.debug('[Balance.check] Commerce balance insufficient', {
user,
commerceUserId: record.commerceUserId,
available: commerceBalance.available,
});
return { canSpend: false, balance: 0, tokenCost, reason: 'commerce_insufficient' };
}
// Check model access via Commerce tier
if (model) {
const modelAccess = await commerceClient.isModelAllowed(record.commerceUserId, model);
if (!modelAccess.allowed) {
logger.debug('[Balance.check] Model not allowed for tier', {
user,
model,
tier: modelAccess.tier,
allowedModels: modelAccess.allowedModels,
});
return {
canSpend: false,
balance: record.tokenCredits,
tokenCost,
reason: 'model_not_allowed',
tier: modelAccess.tier,
allowedModels: modelAccess.allowedModels,
};
}
}
} catch (err) {
// Fail-open: Commerce error → fall through to local check
logger.warn('[Balance.check] Commerce check failed, falling back to local', { error: err.message });
}
}
let balance = record.tokenCredits;
// Check if credits have expired
@@ -224,7 +286,7 @@ const addIntervalToDate = (date, value, unit) => {
* @throws {Error} Throws an error if there's an issue with the balance check.
*/
const checkBalance = async ({ req, res, txData }) => {
const result = await checkBalanceRecord(txData);
const result = await checkBalanceRecord({ ...txData, req });
if (result.canSpend) {
return true;
}
+122
View File
@@ -0,0 +1,122 @@
// Money-gate decision matrix for the Commerce-first, FAIL-CLOSED balance gate
// (per-org via service token + X-Hanzo-Org; the cloud gateway debits the user's
// own hk- key against the SAME org). Proves both directions: unmetered AI never
// leaks (block on any ambiguity), and funded users + capped guests are never
// wrongly blocked.
const mockClient = {
checkBalance: jest.fn(),
isModelAllowed: jest.fn(),
};
jest.mock('@librechat/data-schemas', () => ({
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
}));
jest.mock('~/server/services/CommerceClient', () => ({
getCommerceClient: jest.fn(() => mockClient),
}));
jest.mock('~/cache', () => ({ logViolation: jest.fn().mockResolvedValue(undefined) }));
jest.mock('./tx', () => ({ getMultiplier: () => 1 }));
jest.mock('./Transaction', () => ({ createAutoRefillTransaction: jest.fn() }));
jest.mock('~/db/models', () => ({ Balance: { findOne: jest.fn() } }));
jest.mock('librechat-data-provider', () => ({
ViolationTypes: { TOKEN_BALANCE: 'token_balance' },
}));
const { checkBalance } = require('./balanceMethods');
const { getCommerceClient } = require('~/server/services/CommerceClient');
const { Balance } = require('~/db/models');
const argsFor = (user) => ({
req: { user },
res: {},
txData: { user: user?.id ?? 'u1', tokenType: 'prompt', amount: 100, model: 'zen4-mini' },
});
// checkBalance resolves `true` when allowed, throws a JSON error (carrying
// `reason`) when blocked.
const decide = async (user = { id: 'u1', organization: 'acme' }) => {
try {
const ok = await checkBalance(argsFor(user));
return { allowed: ok, reason: null };
} catch (err) {
let reason = null;
try {
reason = JSON.parse(err.message).reason;
} catch (_) {
reason = err.message;
}
return { allowed: false, reason };
}
};
describe('checkBalance — Commerce-first money gate (fail closed)', () => {
beforeEach(() => {
jest.clearAllMocks();
getCommerceClient.mockReturnValue(mockClient);
mockClient.isModelAllowed.mockResolvedValue({ allowed: true, tier: 't', allowedModels: ['*'] });
process.env.HANZO_MIN_BALANCE = '1.00'; // 100 cents minimum
});
it('ALLOWS a guest WITHOUT consulting Commerce (capped by IP limiter + guest key)', async () => {
const { allowed } = await decide({ id: 'g1', guest: true });
expect(allowed).toBe(true);
expect(mockClient.checkBalance).not.toHaveBeenCalled();
expect(Balance.findOne).not.toHaveBeenCalled();
});
it('ALLOWS a funded org (available >= min)', async () => {
mockClient.checkBalance.mockResolvedValue({ sufficient: true, available: 500 });
const { allowed, reason } = await decide();
expect(allowed).toBe(true);
expect(reason).toBeNull();
expect(mockClient.checkBalance).toHaveBeenCalledWith('acme');
});
it('BLOCKS commerce_insufficient when balance below minimum ($0 → claim $5)', async () => {
mockClient.checkBalance.mockResolvedValue({ sufficient: false, available: 0 });
const { allowed, reason } = await decide();
expect(allowed).toBe(false);
expect(reason).toBe('commerce_insufficient');
});
it('BLOCKS commerce_insufficient when balance is a tiny non-zero below min', async () => {
mockClient.checkBalance.mockResolvedValue({ sufficient: true, available: 50 }); // $0.50 < $1
const { allowed, reason } = await decide();
expect(allowed).toBe(false);
expect(reason).toBe('commerce_insufficient');
});
it('FAILS CLOSED (commerce_unavailable) when Commerce throws — never bleeds', async () => {
mockClient.checkBalance.mockRejectedValue(new Error('ECONNREFUSED'));
const { allowed, reason } = await decide();
expect(allowed).toBe(false);
expect(reason).toBe('commerce_unavailable');
});
it('BLOCKS model_not_allowed for a funded org whose tier forbids the model', async () => {
mockClient.checkBalance.mockResolvedValue({ sufficient: true, available: 500 });
mockClient.isModelAllowed.mockResolvedValue({
allowed: false,
tier: 'free',
allowedModels: ['zen3-nano'],
});
const { allowed, reason } = await decide();
expect(allowed).toBe(false);
expect(reason).toBe('model_not_allowed');
});
it('ALLOWS a funded org even if the tier check itself errors (fail-open tier, balance ok)', async () => {
mockClient.checkBalance.mockResolvedValue({ sufficient: true, available: 500 });
mockClient.isModelAllowed.mockRejectedValue(new Error('tier-check 500'));
const { allowed } = await decide();
expect(allowed).toBe(true);
});
it('FAILS CLOSED for an authed user with NO billing org (no commerce branch, no local credits)', async () => {
Balance.findOne.mockReturnValue({ lean: () => Promise.resolve(null) });
const { allowed } = await decide({ id: 'u2', organization: '' });
expect(allowed).toBe(false);
expect(mockClient.checkBalance).not.toHaveBeenCalled();
});
});
@@ -1,6 +1,10 @@
const { getEndpointsConfig } = require('~/server/services/Config');
const { buildGuestEndpointsConfig } = require('~/server/services/guestConfig');
async function endpointController(req, res) {
if (req.user?.guest === true) {
return res.send(JSON.stringify(buildGuestEndpointsConfig()));
}
const endpointsConfig = await getEndpointsConfig(req);
res.send(JSON.stringify(endpointsConfig));
}
@@ -72,6 +72,9 @@ const updateFavoritesController = async (req, res) => {
const getFavoritesController = async (req, res) => {
try {
if (req.user?.guest === true) {
return res.status(200).json([]);
}
const userId = req.user.id;
const user = await getUserById(userId, 'favorites');
@@ -1,6 +1,7 @@
const { logger } = require('@librechat/data-schemas');
const { CacheKeys } = require('librechat-data-provider');
const { loadDefaultModels, loadConfigModels } = require('~/server/services/Config');
const { buildGuestModelsConfig } = require('~/server/services/guestConfig');
const { getLogStores } = require('~/cache');
/**
@@ -39,6 +40,9 @@ async function loadModels(req) {
async function modelController(req, res) {
try {
if (req.user?.guest === true) {
return res.send(buildGuestModelsConfig());
}
const modelConfig = await loadModels(req);
res.send(modelConfig);
} catch (error) {
@@ -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 {
+4
View File
@@ -40,12 +40,16 @@ const { invalidateCachedTools } = require('~/server/services/Config/getCachedToo
const { needsRefresh, getNewS3URL } = require('~/server/services/Files/S3/crud');
const { processDeleteRequest } = require('~/server/services/Files/process');
const { getAppConfig } = require('~/server/services/Config');
const { buildGuestUser } = require('~/server/services/guestConfig');
const { deleteToolCalls } = require('~/models/ToolCall');
const { deleteUserPrompts } = require('~/models/Prompt');
const { deleteUserAgents } = require('~/models/Agent');
const { getLogStores } = require('~/cache');
const getUserController = async (req, res) => {
if (req.user?.guest === true) {
return res.status(200).send(buildGuestUser(req.user));
}
const appConfig = await getAppConfig({ role: req.user?.role });
/** @type {IUser} */
const userData = req.user.toObject != null ? req.user.toObject() : { ...req.user };
@@ -0,0 +1,91 @@
/**
* Guest-scoped bootstrap controllers: verify that a guest principal receives
* safe, scoped data (and never triggers a DB lookup) on the read-only endpoints
* the chat composer hard-requires.
*/
jest.mock('@hanzochat/api', () => ({
isEnabled: (value) => value === 'true' || value === true,
}));
jest.mock('librechat-data-provider', () => ({
EModelEndpoint: { custom: 'custom' },
CacheKeys: { CONFIG_STORE: 'CONFIG_STORE', MODELS_CONFIG: 'MODELS_CONFIG' },
Tools: {},
Constants: {},
FileSources: { local: 'local', s3: 's3' },
}));
jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },
webSearchKeys: [],
}));
// --- EndpointController deps ---
jest.mock('~/server/services/Config', () => ({
getEndpointsConfig: jest.fn(),
loadDefaultModels: jest.fn(),
loadConfigModels: jest.fn(),
getAppConfig: jest.fn(),
}));
jest.mock('~/cache', () => ({ getLogStores: jest.fn(() => ({ get: jest.fn(), set: jest.fn() })) }));
const { getEndpointsConfig } = require('~/server/services/Config');
const endpointController = require('~/server/controllers/EndpointController');
const { modelController } = require('~/server/controllers/ModelController');
const guestReq = (overrides = {}) => ({
user: { id: 'guest_abc', role: 'GUEST', name: 'Guest', guest: true },
...overrides,
});
const mockRes = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.send = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
describe('guest bootstrap controllers', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
jest.clearAllMocks();
process.env.ALLOW_GUEST_CHAT = 'true';
process.env.GUEST_ENDPOINT = 'Hanzo';
process.env.GUEST_MODEL = 'zen5-mini';
});
afterAll(() => {
process.env = originalEnv;
});
describe('GET /v1/chat/endpoints', () => {
it('returns ONLY the guest endpoint, no DB/config read', async () => {
const req = guestReq();
const res = mockRes();
await endpointController(req, res);
expect(getEndpointsConfig).not.toHaveBeenCalled();
const payload = JSON.parse(res.send.mock.calls[0][0]);
expect(Object.keys(payload)).toEqual(['Hanzo']);
expect(payload.Hanzo).toMatchObject({ type: 'custom', userProvide: false });
});
it('falls through to the real config for non-guest users', async () => {
getEndpointsConfig.mockResolvedValue({ Hanzo: {}, openAI: {} });
const req = { user: { id: 'real', role: 'USER' } };
const res = mockRes();
await endpointController(req, res);
expect(getEndpointsConfig).toHaveBeenCalledTimes(1);
});
});
describe('GET /v1/chat/models', () => {
it('returns ONLY the single guest model under the guest endpoint', async () => {
const req = guestReq();
const res = mockRes();
await modelController(req, res);
expect(res.send).toHaveBeenCalledWith({ Hanzo: ['zen5-mini'] });
});
});
});
+40 -2
View File
@@ -15,6 +15,7 @@ const {
getBalanceConfig,
getProviderConfig,
omitTitleOptions,
wrapHanzoGatewayFetch,
memoryInstructions,
applyContextToAgent,
createTokenCounter,
@@ -891,9 +892,20 @@ class AgentClient extends BaseClient {
config.signal = null;
};
/**
* Capture before running the graph. `run.processStream` (via
* `@librechat/agents`) treats the passed `config` as owned and, during its
* post-stream cleanup, sets `config.configurable = undefined` to break the
* reference chain that keeps heavy graph state (base64 images/PDFs) alive.
* Reading `config.configurable.hide_sequential_outputs` AFTER `runAgents`
* therefore throws `Cannot read properties of undefined`, which surfaces as
* the post-reply error banner. Hoisting the read keeps the deprecated Agent
* Chain filter working without depending on post-run config state.
*/
const hideSequentialOutputs = config.configurable.hide_sequential_outputs;
await runAgents(initialMessages);
/** @deprecated Agent Chain */
if (config.configurable.hide_sequential_outputs) {
if (hideSequentialOutputs) {
this.contentParts = this.contentParts.filter((part, index) => {
// Include parts that are either:
// 1. At or after the finalContentStart index
@@ -929,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({
@@ -1058,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;
}
@@ -1074,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 ||
@@ -15,6 +15,7 @@ jest.mock('@hanzochat/api', () => ({
checkAccess: jest.fn(),
initializeAgent: jest.fn(),
createMemoryProcessor: jest.fn(),
createRun: jest.fn(),
}));
jest.mock('~/models/Agent', () => ({
@@ -2257,3 +2258,122 @@ describe('AgentClient - titleConvo', () => {
});
});
});
describe('AgentClient - chatCompletion post-reply banner regression', () => {
/**
* Regression for the post-reply error banner:
* "Cannot read properties of undefined (reading 'hide_sequential_outputs')".
*
* `run.processStream` (from `@librechat/agents` >= 3.1.52) treats the passed
* `config` as owned and, in its post-stream cleanup, sets
* `config.configurable = undefined` to break the AsyncLocalStorage reference
* chain that keeps heavy graph state (base64 images/PDFs) alive. The
* controller must therefore NOT read `config.configurable.hide_sequential_outputs`
* AFTER the stream completes, or it throws and pushes an ERROR content part
* (the red banner) which also aborts the post-stream finalize (auto-titling).
* This test reproduces that mutation and asserts no ERROR part is produced.
*/
const { createRun } = require('@hanzochat/api');
const { ContentTypes } = require('librechat-data-provider');
let processStreamMock;
const makeClient = (agentOverrides = {}) => {
const agent = {
id: 'agent-123',
endpoint: EModelEndpoint.openAI,
provider: EModelEndpoint.openAI,
model_parameters: { model: 'gpt-4' },
...agentOverrides,
};
const req = {
user: { id: 'user-123' },
body: {},
config: { endpoints: {} },
};
const client = new AgentClient({
req,
res: {},
agent,
endpoint: EModelEndpoint.openAI,
contentParts: [],
collectedUsage: [],
artifactPromises: [],
endpointTokenConfig: {},
});
client.conversationId = 'convo-123';
client.responseMessageId = 'response-123';
client.parentMessageId = '00000000-0000-0000-0000-000000000000';
client.user = 'user-123';
// Avoid DB / memory side effects unrelated to this regression.
client.recordCollectedUsage = jest.fn().mockResolvedValue();
client.runMemory = jest.fn().mockResolvedValue(undefined);
client.awaitMemoryWithTimeout = jest.fn().mockResolvedValue(undefined);
return client;
};
beforeEach(() => {
jest.clearAllMocks();
// Faithfully mimic `@librechat/agents` Run.processStream cleanup: it nulls
// the caller's `config.configurable` after the stream finishes.
processStreamMock = jest.fn(async (_inputs, config) => {
config.configurable = undefined;
return [];
});
createRun.mockResolvedValue({
Graph: {},
processStream: processStreamMock,
});
});
const errorParts = (client) =>
(client.getContentParts() || []).filter((p) => p && p.type === ContentTypes.ERROR);
it('does not push an error content part when processStream nulls config.configurable', async () => {
const client = makeClient();
await expect(
client.sendCompletion('hello', { abortController: new AbortController() }),
).resolves.toBeDefined();
expect(processStreamMock).toHaveBeenCalledTimes(1);
// The config passed to processStream had configurable nulled (reproduction sanity check).
const passedConfig = processStreamMock.mock.calls[0][1];
expect(passedConfig.configurable).toBeUndefined();
// The fix: no banner-producing ERROR part despite the nulled configurable.
expect(errorParts(client)).toHaveLength(0);
});
it('still applies the deprecated hide_sequential_outputs filter using the pre-stream value', async () => {
const client = makeClient({ hide_sequential_outputs: true });
// Seed multiple content parts; the filter keeps only the last part plus
// tool_call parts. With the value captured before the stream, the filter
// must run even though config.configurable is undefined afterwards.
client.contentParts = [
{ type: 'text', text: 'intermediate-1' },
{ type: 'text', text: 'intermediate-2' },
{ type: 'text', text: 'final' },
];
await client.sendCompletion('hello', { abortController: new AbortController() });
expect(errorParts(client)).toHaveLength(0);
// hide_sequential_outputs collapses to the final part only (no tool calls present).
expect(client.contentParts).toEqual([{ type: 'text', text: 'final' }]);
});
it('leaves content parts intact when hide_sequential_outputs is falsy', async () => {
const client = makeClient({ hide_sequential_outputs: false });
client.contentParts = [
{ type: 'text', text: 'a' },
{ type: 'text', text: 'b' },
];
await client.sendCompletion('hello', { abortController: new AbortController() });
expect(errorParts(client)).toHaveLength(0);
expect(client.contentParts).toEqual([
{ type: 'text', text: 'a' },
{ type: 'text', text: 'b' },
]);
});
});
@@ -0,0 +1,45 @@
const { randomUUID } = require('node:crypto');
const jwt = require('jsonwebtoken');
const { logger } = require('@librechat/data-schemas');
const { getGuestConfig, GUEST_ROLE } = require('~/server/services/guestConfig');
/**
* Issues a short-lived guest token for anonymous preview chat.
*
* The token is signed with `JWT_SECRET` and carries a `guest: true` claim plus a
* per-token random id, so guest principals are ephemeral and isolated from each
* other. It is rejected by the standard `jwt` strategy (no matching DB user),
* which keeps every non-chat route closed to guests.
*
* @param {ServerRequest} req
* @param {ServerResponse} res
*/
const guestTokenController = async (req, res) => {
const config = getGuestConfig();
if (!config.enabled) {
return res.status(404).json({ message: 'Guest chat is not enabled' });
}
if (!process.env.JWT_SECRET) {
logger.error('[guestTokenController] JWT_SECRET is not configured');
return res.status(500).json({ message: 'Server misconfiguration' });
}
const id = `guest_${randomUUID()}`;
const expiresInSeconds = Math.floor(config.tokenExpiryMs / 1000);
const token = jwt.sign({ id, guest: true, role: GUEST_ROLE }, process.env.JWT_SECRET, {
expiresIn: expiresInSeconds,
});
return res.status(200).json({
token,
expiresIn: expiresInSeconds,
endpoint: config.endpoint,
model: config.model,
messageMax: config.messageMax,
});
};
module.exports = { guestTokenController };
+31 -8
View File
@@ -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);
}
+86 -1
View File
@@ -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();
});
});
});
+4 -4
View File
@@ -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
View File
@@ -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);
+27 -27
View File
@@ -136,7 +136,7 @@ const startServer = async () => {
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; connect-src 'self' https://*.hanzo.ai https://*.hanzo.chat wss://*.hanzo.chat; frame-ancestors 'none';",
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://analytics.hanzo.ai https://static.cloudflareinsights.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; media-src 'self' data: blob:; connect-src 'self' https://*.hanzo.ai https://*.hanzo.chat wss://*.hanzo.chat https://static.cloudflareinsights.com https://cloudflareinsights.com; frame-ancestors 'none';",
);
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
next();
@@ -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);
+1 -1
View File
@@ -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',
});
@@ -0,0 +1,118 @@
jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },
}));
jest.mock('librechat-data-provider', () => ({
EModelEndpoint: { custom: 'custom', agents: 'agents' },
}));
jest.mock('~/server/services/guestConfig', () => ({
getGuestConfig: jest.fn(),
}));
const { getGuestConfig } = require('~/server/services/guestConfig');
const enforceGuestScope = require('../enforceGuestScope');
const mockRes = () => ({ status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() });
describe('enforceGuestScope', () => {
beforeEach(() => {
jest.clearAllMocks();
getGuestConfig.mockReturnValue({
enabled: true,
endpoint: 'Hanzo',
model: 'zen3-nano',
messageMax: 3,
});
});
it('passes non-guest requests through untouched', () => {
const req = { user: { id: 'u1', role: 'USER' }, body: { endpoint: 'OpenAI', model: 'gpt-4o' } };
const next = jest.fn();
enforceGuestScope(req, mockRes(), next);
expect(next).toHaveBeenCalledWith();
expect(req.body.endpoint).toBe('OpenAI');
expect(req.body.model).toBe('gpt-4o');
});
it('rejects a guest naming a different endpoint (403)', () => {
const req = { user: { id: 'g1', guest: true }, body: { endpoint: 'OpenAI' } };
const res = mockRes();
const next = jest.fn();
enforceGuestScope(req, res, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(next).not.toHaveBeenCalled();
});
it('rejects a guest naming a different (paid) model (403)', () => {
const req = { user: { id: 'g1', guest: true }, body: { endpoint: 'Hanzo', model: 'zen4-max' } };
const res = mockRes();
const next = jest.fn();
enforceGuestScope(req, res, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(next).not.toHaveBeenCalled();
});
it('pins endpoint, type, and model for a compliant guest request', () => {
const req = {
user: { id: 'g1', guest: true },
body: { endpoint: 'Hanzo', model: 'zen3-nano', text: 'hi' },
};
const next = jest.fn();
enforceGuestScope(req, mockRes(), next);
expect(next).toHaveBeenCalledWith();
expect(req.body.endpoint).toBe('Hanzo');
expect(req.body.endpointType).toBe('custom');
expect(req.body.model).toBe('zen3-nano');
});
it('pins endpoint/model even when the guest omits them', () => {
const req = { user: { id: 'g1', guest: true }, body: { text: 'hi' } };
const next = jest.fn();
enforceGuestScope(req, mockRes(), next);
expect(next).toHaveBeenCalledWith();
expect(req.body.endpoint).toBe('Hanzo');
expect(req.body.model).toBe('zen3-nano');
});
it('strips every privileged capability from a guest request', () => {
const req = {
user: { id: 'g1', guest: true },
body: {
endpoint: 'Hanzo',
model: 'zen3-nano',
agent_id: 'agent_evil',
spec: 'paid-spec',
preset: { foo: 'bar' },
files: [{ file_id: 'f1' }],
tools: ['execute_code'],
tool_resources: { x: 1 },
resendFiles: true,
promptPrefix: 'jailbreak',
web_search: true,
},
};
const next = jest.fn();
enforceGuestScope(req, mockRes(), next);
expect(next).toHaveBeenCalledWith();
expect(req.body.agent_id).toBeUndefined();
expect(req.body.spec).toBeUndefined();
expect(req.body.preset).toBeUndefined();
expect(req.body.files).toBeUndefined();
expect(req.body.tools).toBeUndefined();
expect(req.body.tool_resources).toBeUndefined();
expect(req.body.resendFiles).toBeUndefined();
expect(req.body.promptPrefix).toBeUndefined();
expect(req.body.web_search).toBeUndefined();
});
it('returns 404 for a guest when guest chat is disabled mid-flight', () => {
getGuestConfig.mockReturnValue({ enabled: false, endpoint: 'Hanzo', model: 'zen3-nano' });
const req = { user: { id: 'g1', guest: true }, body: {} };
const res = mockRes();
const next = jest.fn();
enforceGuestScope(req, res, next);
expect(res.status).toHaveBeenCalledWith(404);
expect(next).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,134 @@
/**
* Integration test for the guest chat middleware chain composition:
* guest auth -> scope enforcement -> quota, plus the reserved-subpath guard
* that keeps management routes (abort/active/...) on the JWT-only parent router.
*/
const express = require('express');
const jwt = require('jsonwebtoken');
const request = require('supertest');
jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },
}));
jest.mock('@hanzochat/api', () => ({
isEnabled: (value) => value === 'true' || value === true,
limiterCache: () => undefined,
}));
jest.mock('librechat-data-provider', () => ({
EModelEndpoint: { custom: 'custom', agents: 'agents' },
}));
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', () =>
jest.fn((req, res, next) => {
req.user = { id: 'real-user', role: 'USER' };
next();
}),
);
const requireGuestOrJwtAuth = require('../requireGuestOrJwtAuth');
const enforceGuestScope = require('../enforceGuestScope');
const { guestMessageLimiter } = require('../limiters/guestMessageLimiter');
const JWT_SECRET = 'test-guest-secret';
const buildRouter = () => {
const router = express.Router();
const RESERVED = new Set(['abort', 'active']);
const chatRouter = express.Router();
chatRouter.use((req, res, next) => {
const subpath = req.path.split('/').filter(Boolean)[0];
if (RESERVED.has(subpath)) {
return next('router');
}
return next();
});
chatRouter.use(requireGuestOrJwtAuth);
chatRouter.use(enforceGuestScope);
chatRouter.use(guestMessageLimiter);
chatRouter.post('/', (req, res) =>
res
.status(200)
.json({ endpoint: req.body.endpoint, model: req.body.model, role: req.user.role }),
);
router.use('/chat', chatRouter);
// JWT-only management route on the parent (after the guest router)
router.post('/chat/abort', require('../requireJwtAuth'), (req, res) =>
res.status(200).json({ aborted: true, role: req.user.role }),
);
return router;
};
const buildApp = () => {
const app = express();
app.use(express.json());
app.use('/v1/chat/agents', buildRouter());
return app;
};
const guestToken = () => jwt.sign({ id: 'guest_1', guest: true, role: 'GUEST' }, JWT_SECRET);
describe('guest chat middleware chain', () => {
beforeEach(() => {
process.env.JWT_SECRET = JWT_SECRET;
process.env.ALLOW_GUEST_CHAT = 'true';
process.env.GUEST_MESSAGE_MAX = '2';
process.env.GUEST_ENDPOINT = 'Hanzo';
process.env.GUEST_MODEL = 'zen3-nano';
});
afterEach(() => {
delete process.env.ALLOW_GUEST_CHAT;
delete process.env.GUEST_MESSAGE_MAX;
delete process.env.GUEST_ENDPOINT;
delete process.env.GUEST_MODEL;
});
it('lets a guest reach the completion route, pinned to the free endpoint/model', async () => {
const res = await request(buildApp())
.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' });
expect(res.status).toBe(200);
expect(res.body).toEqual({ endpoint: 'Hanzo', model: 'zen3-nano', role: 'GUEST' });
});
it('returns 402 GUEST_LIMIT after the quota is exhausted', async () => {
const app = buildApp();
const ip = '10.1.0.2';
const send = () =>
request(app)
.post('/v1/chat/agents/chat')
.set('Authorization', `Bearer ${guestToken()}`)
.set('x-test-ip', ip)
.send({ endpoint: 'Hanzo', model: 'zen3-nano', text: 'hi' });
expect((await send()).status).toBe(200);
expect((await send()).status).toBe(200);
const blocked = await send();
expect(blocked.status).toBe(402);
expect(blocked.body.type).toBe('GUEST_LIMIT');
});
it('routes reserved /chat/abort to the JWT-only handler, not the guest router', async () => {
const res = await request(buildApp())
.post('/v1/chat/agents/chat/abort')
.set('Authorization', `Bearer ${guestToken()}`)
.set('x-test-ip', '10.1.0.3')
.send({ streamId: 'x' });
// requireJwtAuth mock forces a real USER; guest never reaches abort.
expect(res.status).toBe(200);
expect(res.body).toEqual({ aborted: true, role: 'USER' });
});
});
@@ -0,0 +1,86 @@
const jwt = require('jsonwebtoken');
jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },
}));
jest.mock('../requireJwtAuth', () => jest.fn((req, res, next) => next('jwt-fallback')));
const requireJwtAuth = require('../requireJwtAuth');
const requireGuestOrJwtAuth = require('../requireGuestOrJwtAuth');
const JWT_SECRET = 'test-guest-secret';
const mockRes = () => ({ status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() });
const guestToken = (claims = {}) =>
jwt.sign({ id: 'guest_abc', guest: true, role: 'GUEST', ...claims }, JWT_SECRET);
describe('requireGuestOrJwtAuth', () => {
beforeEach(() => {
jest.clearAllMocks();
process.env.JWT_SECRET = JWT_SECRET;
process.env.ALLOW_GUEST_CHAT = 'true';
});
afterEach(() => {
delete process.env.ALLOW_GUEST_CHAT;
});
it('delegates to requireJwtAuth when guest chat is disabled', () => {
process.env.ALLOW_GUEST_CHAT = 'false';
const req = { headers: { authorization: `Bearer ${guestToken()}` } };
const next = jest.fn();
requireGuestOrJwtAuth(req, mockRes(), next);
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
it('authenticates a valid guest token as an ephemeral GUEST principal', () => {
const req = { headers: { authorization: `Bearer ${guestToken()}` } };
const next = jest.fn();
requireGuestOrJwtAuth(req, mockRes(), next);
expect(requireJwtAuth).not.toHaveBeenCalled();
expect(next).toHaveBeenCalledWith();
expect(req.user).toEqual({ id: 'guest_abc', role: 'GUEST', name: 'Guest', guest: true });
});
it('delegates to requireJwtAuth when no bearer token is present', () => {
const req = { headers: {} };
requireGuestOrJwtAuth(req, mockRes(), jest.fn());
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
it('delegates to requireJwtAuth for a non-guest (regular) JWT', () => {
const userToken = jwt.sign({ id: 'real-user' }, JWT_SECRET);
const req = { headers: { authorization: `Bearer ${userToken}` } };
requireGuestOrJwtAuth(req, mockRes(), jest.fn());
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
it('delegates to requireJwtAuth for a token signed with the wrong secret (fail closed)', () => {
const forged = jwt.sign({ id: 'guest_x', guest: true }, 'wrong-secret');
const req = { headers: { authorization: `Bearer ${forged}` } };
requireGuestOrJwtAuth(req, mockRes(), jest.fn());
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
it('delegates to requireJwtAuth when guest claim is missing', () => {
const token = jwt.sign({ id: 'guest_x' }, JWT_SECRET);
const req = { headers: { authorization: `Bearer ${token}` } };
requireGuestOrJwtAuth(req, mockRes(), jest.fn());
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
it('delegates to requireJwtAuth when guest token lacks an id', () => {
const token = jwt.sign({ guest: true }, JWT_SECRET);
const req = { headers: { authorization: `Bearer ${token}` } };
requireGuestOrJwtAuth(req, mockRes(), jest.fn());
expect(requireJwtAuth).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
});
});
@@ -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 = () => ({
+1 -1
View File
@@ -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,61 @@
const { logger } = require('@librechat/data-schemas');
const { EModelEndpoint } = require('librechat-data-provider');
const { getGuestConfig } = require('~/server/services/guestConfig');
/**
* Server-side capability scope for guest principals.
*
* Runs after guest authentication and before `buildEndpointOption`. For guest
* requests it pins the endpoint and model to the configured free Zen endpoint and
* strips every capability a guest must not reach (paid models, agents, tools,
* files, model specs, presets). The client is never trusted: any guest request
* that names a different endpoint/model is rejected rather than silently rewritten.
*
* Non-guest requests pass through untouched.
*
* @param {ServerRequest} req
* @param {ServerResponse} res
* @param {import('express').NextFunction} next
*/
const enforceGuestScope = (req, res, next) => {
if (req.user?.guest !== true) {
return next();
}
const config = getGuestConfig();
if (!config.enabled) {
return res.status(404).json({ message: 'Guest chat is not enabled' });
}
const body = req.body || {};
const { endpoint, model } = body;
if (endpoint != null && endpoint !== config.endpoint) {
logger.warn(`[enforceGuestScope] Guest ${req.user.id} rejected endpoint: ${endpoint}`);
return res.status(403).json({ message: 'Guests may only use the free preview model' });
}
if (model != null && model !== config.model) {
logger.warn(`[enforceGuestScope] Guest ${req.user.id} rejected model: ${model}`);
return res.status(403).json({ message: 'Guests may only use the free preview model' });
}
body.endpoint = config.endpoint;
body.endpointType = EModelEndpoint.custom;
body.model = config.model;
delete body.agent_id;
delete body.spec;
delete body.preset;
delete body.files;
delete body.tools;
delete body.tool_resources;
delete body.resendFiles;
delete body.promptPrefix;
delete body.web_search;
req.body = body;
return next();
};
module.exports = enforceGuestScope;
+4
View File
@@ -10,6 +10,8 @@ const requireLdapAuth = require('./requireLdapAuth');
const abortMiddleware = require('./abortMiddleware');
const checkInviteUser = require('./checkInviteUser');
const requireJwtAuth = require('./requireJwtAuth');
const requireGuestOrJwtAuth = require('./requireGuestOrJwtAuth');
const enforceGuestScope = require('./enforceGuestScope');
const configMiddleware = require('./config/app');
const validateModel = require('./validateModel');
const moderateText = require('./moderateText');
@@ -36,6 +38,8 @@ module.exports = {
moderateText,
validateModel,
requireJwtAuth,
requireGuestOrJwtAuth,
enforceGuestScope,
checkInviteUser,
requireLdapAuth,
requireLocalAuth,
@@ -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;
@@ -0,0 +1,41 @@
const rateLimit = require('express-rate-limit');
const { limiterCache } = require('@hanzochat/api');
const { guestClientIp } = require('~/server/utils');
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;
const windowInMinutes = windowMs / 60000;
const handler = (req, res) => {
return res.status(429).json({
message: `Too many guest sessions, please try again after ${windowInMinutes} minutes.`,
});
};
/**
* 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: guestClientIp,
store: limiterCache('guest_token_limiter'),
});
module.exports = { guestTokenLimiter };
@@ -0,0 +1,36 @@
const rateLimit = require('express-rate-limit');
const { limiterCache } = require('@hanzochat/api');
const { guestClientIp } = require('~/server/utils');
const { getGuestConfig } = require('~/server/services/guestConfig');
const GUEST_LIMIT_WINDOW_MS = 24 * 60 * 60 * 1000;
const handler = (req, res) => {
return res.status(402).json({
type: 'GUEST_LIMIT',
message: 'Guest message limit reached. Log in to continue.',
});
};
/**
* Per-IP quota limiter for anonymous guest chat completions.
*
* Reuses the shared Redis-backed `limiterCache` infrastructure (same store as the
* 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.
*/
const guestMessageLimiter = rateLimit({
windowMs: GUEST_LIMIT_WINDOW_MS,
max: () => getGuestConfig().messageMax,
handler,
keyGenerator: guestClientIp,
skip: (req) => req.user?.guest !== true,
store: limiterCache('guest_message_limiter'),
});
module.exports = { guestMessageLimiter };
@@ -0,0 +1,78 @@
const express = require('express');
const request = require('supertest');
jest.mock('@hanzochat/api', () => ({
limiterCache: () => undefined,
}));
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', () => ({
getGuestConfig: jest.fn(),
}));
const { getGuestConfig } = require('~/server/services/guestConfig');
const { guestMessageLimiter } = require('./guestMessageLimiter');
const buildApp = (user) => {
const app = express();
app.use((req, _res, next) => {
req.user = user;
next();
});
app.use(guestMessageLimiter);
app.post('/chat', (_req, res) => res.status(200).json({ ok: true }));
return app;
};
describe('guestMessageLimiter', () => {
beforeEach(() => {
jest.clearAllMocks();
getGuestConfig.mockReturnValue({
enabled: true,
messageMax: 3,
endpoint: 'Hanzo',
model: 'zen3-nano',
});
});
it('allows up to GUEST_MESSAGE_MAX guest messages then returns 402 GUEST_LIMIT', async () => {
const app = buildApp({ id: 'g1', guest: true });
const ip = '10.0.0.1';
for (let i = 0; i < 3; i++) {
const res = await request(app).post('/chat').set('x-test-ip', ip);
expect(res.status).toBe(200);
}
const blocked = await request(app).post('/chat').set('x-test-ip', ip);
expect(blocked.status).toBe(402);
expect(blocked.body.type).toBe('GUEST_LIMIT');
});
it('counts quota per IP independently', async () => {
const app = buildApp({ id: 'g1', guest: true });
for (let i = 0; i < 3; i++) {
await request(app).post('/chat').set('x-test-ip', '10.0.0.2');
}
const blocked = await request(app).post('/chat').set('x-test-ip', '10.0.0.2');
expect(blocked.status).toBe(402);
const fresh = await request(app).post('/chat').set('x-test-ip', '10.0.0.3');
expect(fresh.status).toBe(200);
});
it('never counts or blocks authenticated (non-guest) users', async () => {
const app = buildApp({ id: 'real-user', role: 'USER' });
for (let i = 0; i < 10; i++) {
const res = await request(app).post('/chat').set('x-test-ip', '10.0.0.4');
expect(res.status).toBe(200);
}
});
});
+6
View File
@@ -2,11 +2,14 @@ const createTTSLimiters = require('./ttsLimiters');
const createSTTLimiters = require('./sttLimiters');
const loginLimiter = require('./loginLimiter');
const { guestTokenLimiter } = require('./guestLimiters');
const { guestMessageLimiter } = require('./guestMessageLimiter');
const importLimiters = require('./importLimiters');
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');
@@ -17,8 +20,11 @@ module.exports = {
...messageLimiters,
...forkLimiters,
loginLimiter,
guestTokenLimiter,
guestMessageLimiter,
registerLimiter,
toolCallLimiter,
cloudAgentLimiter,
createTTSLimiters,
createSTTLimiters,
verifyEmailLimiter,
@@ -0,0 +1,59 @@
const jwt = require('jsonwebtoken');
const { logger } = require('@librechat/data-schemas');
const requireJwtAuth = require('./requireJwtAuth');
const { getGuestConfig, buildGuestPrincipal } = require('~/server/services/guestConfig');
/**
* Extracts a bearer token from the Authorization header.
* @param {ServerRequest} req
* @returns {string|null}
*/
const getBearerToken = (req) => {
const header = req.headers?.authorization;
if (!header || !header.startsWith('Bearer ')) {
return null;
}
return header.slice('Bearer '.length).trim();
};
/**
* Guest-aware authentication, applied ONLY to chat-completion routes.
*
* When `ALLOW_GUEST_CHAT` is enabled and the bearer token is a valid guest token
* (`guest: true`, signed with `JWT_SECRET`), an ephemeral guest principal is set
* on `req.user` and the request proceeds. Otherwise the request falls through to
* the standard `requireJwtAuth`, which rejects guest tokens everywhere else
* (the `jwt` strategy requires a matching DB user). Fail closed by construction.
*
* @param {ServerRequest} req
* @param {ServerResponse} res
* @param {import('express').NextFunction} next
*/
const requireGuestOrJwtAuth = (req, res, next) => {
const config = getGuestConfig();
if (!config.enabled) {
return requireJwtAuth(req, res, next);
}
const token = getBearerToken(req);
if (!token) {
return requireJwtAuth(req, res, next);
}
let payload;
try {
payload = jwt.verify(token, process.env.JWT_SECRET);
} catch (_err) {
return requireJwtAuth(req, res, next);
}
if (payload?.guest !== true || !payload.id) {
return requireJwtAuth(req, res, next);
}
req.user = buildGuestPrincipal(payload.id);
logger.debug(`[requireGuestOrJwtAuth] Guest principal authenticated: ${payload.id}`);
return next();
};
module.exports = requireGuestOrJwtAuth;
+11 -11
View File
@@ -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');
});
+1 -1
View File
@@ -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);
+31 -31
View File
@@ -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: {},
});
+9 -9
View File
@@ -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,
@@ -0,0 +1,136 @@
/**
* End-to-end auth chain for guest bootstrap: real passport `jwt` strategy +
* real `requireGuestOrJwtAuth` / `requireJwtAuth` + real controllers, driven by
* a real signed guest JWT.
*
* Proves:
* - a guest token on a JWT-only route returns a clean 401 (NOT 500/CastError),
* - /v1/chat/endpoints, /v1/chat/user, /v1/chat/convos return guest-scoped data,
* - a non-bootstrap protected route still 401s for a guest.
*/
const jwt = require('jsonwebtoken');
const express = require('express');
const passport = require('passport');
const request = require('supertest');
jest.mock('@hanzochat/api', () => ({
isEnabled: (value) => value === 'true' || value === true,
}));
jest.mock('librechat-data-provider', () => ({
EModelEndpoint: { custom: 'custom' },
SystemRoles: { USER: 'USER' },
}));
jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },
}));
// getUserById would throw a Mongoose CastError on a guest id; assert it is never
// reached for a guest, and returns null (→ clean 401) for a real-but-missing id.
jest.mock('~/models', () => ({
getUserById: jest.fn(async (id) => {
if (String(id).startsWith('guest_')) {
throw new Error('CastError: Cast to ObjectId failed for value "' + id + '"');
}
return null;
}),
updateUser: jest.fn(),
}));
const { getUserById } = require('~/models');
const jwtLogin = require('~/strategies/jwtStrategy');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
const requireGuestOrJwtAuth = require('~/server/middleware/requireGuestOrJwtAuth');
const { buildGuestEndpointsConfig, buildGuestUser } = require('~/server/services/guestConfig');
const JWT_SECRET = 'integration-guest-secret';
const buildApp = () => {
const app = express();
app.use(express.json());
app.use(passport.initialize());
passport.use(jwtLogin());
// Bootstrap (guest-aware) routes.
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('/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('/v1/chat/convos', requireGuestOrJwtAuth, (req, res) => {
if (req.user?.guest === true) {
return res.status(200).json({ conversations: [], nextCursor: null });
}
return res.status(200).json({ conversations: ['real'] });
});
// Non-bootstrap protected route (JWT-only): must reject guests.
app.get('/v1/chat/prompts', requireJwtAuth, (req, res) => res.status(200).json({ ok: true }));
return app;
};
describe('guest bootstrap auth chain (integration)', () => {
let app;
const guestToken = jwt.sign({ id: 'guest_abc-123', guest: true, role: 'GUEST' }, JWT_SECRET);
beforeAll(() => {
process.env.JWT_SECRET = JWT_SECRET;
process.env.ALLOW_GUEST_CHAT = 'true';
process.env.GUEST_ENDPOINT = 'Hanzo';
process.env.GUEST_MODEL = 'zen5-mini';
app = buildApp();
});
afterEach(() => jest.clearAllMocks());
it('GET /v1/chat/endpoints → 200 with ONLY the guest endpoint', async () => {
const res = await request(app)
.get('/v1/chat/endpoints')
.set('Authorization', `Bearer ${guestToken}`);
expect(res.status).toBe(200);
const body = JSON.parse(res.text);
expect(Object.keys(body)).toEqual(['Hanzo']);
expect(getUserById).not.toHaveBeenCalled();
});
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 /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 /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 /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('/v1/chat/prompts').set('Authorization', `Bearer ${realToken}`);
expect(res.status).toBe(401);
expect(getUserById).toHaveBeenCalledTimes(1);
});
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);
});
});
+10 -10
View File
@@ -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);
+4 -4
View File
@@ -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();
+82 -82
View File
@@ -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(
+230
View File
@@ -0,0 +1,230 @@
/**
* Regression test for the OAuth login rate-limiter scoping fix.
*
* Background: `loginLimiter` (LOGIN_MAX per 5 min, keyed by IP) used to be
* applied as blanket router middleware (`router.use(loginLimiter)`), which also
* covered the OIDC/social callback routes. Behind a shared LB/CDN IP, with
* OPENID_AUTO_REDIRECT firing `/oauth/openid` on every page load, the per-IP
* budget was exhausted instantly and the IdP code-exchange callback got 429 -
* aborting the token exchange and breaking login.
*
* The fix scopes `loginLimiter` to the human-initiated entry points (the GETs
* that REDIRECT to the IdP) and leaves the machine-driven callback routes
* (the IdP returning a one-time code) un-limited.
*
* This test mounts the REAL oauth router with the REAL `loginLimiter` and only
* stubs the heavy leaf deps (passport, openid-client, controllers, config, db),
* mirroring server/routes/__tests__/convos-duplicate-ratelimit.spec.js.
*/
const express = require('express');
const request = require('supertest');
// passport.authenticate(...) -> a middleware that signals "reached the handler"
// (in prod this would redirect to the IdP for initiation, or exchange the code
// for callbacks). Returning 200 lets us detect whether the limiter intercepted
// the request with 429 BEFORE control reached the auth handler.
jest.mock('passport', () => ({
authenticate: jest.fn(() => (req, res) => res.status(200).json({ reached: true })),
}));
jest.mock('openid-client', () => ({
randomState: jest.fn(() => 'test-state'),
}));
jest.mock('@librechat/data-schemas', () => ({
logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
}));
jest.mock('librechat-data-provider', () => ({
ErrorTypes: { AUTH_FAILED: 'AUTH_FAILED' },
ViolationTypes: { LOGINS: 'logins' },
}));
// `limiterCache: () => undefined` makes express-rate-limit fall back to its
// built-in in-process MemoryStore (no Redis), same as the convos limiter test.
jest.mock('@hanzochat/api', () => ({
createSetBalanceConfig: jest.fn(() => (req, res, next) => next()),
limiterCache: jest.fn(() => undefined),
}));
// loginLimiter.js does `require('~/cache')` (the index, which also pulls
// getLogStores) and `require('~/server/utils')` (index, which pulls
// sendEmail/files/queue). Mock both indexes to the minimal real/inert surface
// the limiter actually uses: a no-op violation logger and the dependency-free
// `removePorts` IP key generator.
jest.mock('~/cache', () => ({
logViolation: jest.fn().mockResolvedValue(undefined),
}));
jest.mock('~/server/utils', () => ({
removePorts: jest.requireActual('~/server/utils/removePorts'),
}));
// oauth.js imports { checkDomainAllowed, loginLimiter, logHeaders } from the
// middleware index, whose full require graph is too heavy for a hermetic unit
// test. Mock the index but expose the REAL `loginLimiter` (the unit under test)
// via requireActual of the leaf file — mirroring how
// convos-duplicate-ratelimit.spec.js pulls the real forkLimiters. The other two
// are inert passthroughs (not under test here).
jest.mock('~/server/middleware', () => {
const loginLimiter = jest.requireActual('~/server/middleware/limiters/loginLimiter');
return {
loginLimiter,
logHeaders: (req, res, next) => next(),
checkDomainAllowed: (req, res, next) => next(),
};
});
jest.mock('~/server/controllers/auth/oauth', () => ({
createOAuthHandler: jest.fn(() => (req, res) => res.status(200).json({ handler: true })),
}));
jest.mock('~/server/services/Config', () => ({
getAppConfig: jest.fn(),
}));
jest.mock('~/db/models', () => ({
Balance: {},
}));
const LOGIN_INITIATION = '/oauth/openid';
const LOGIN_CALLBACK = '/oauth/openid/callback';
describe('OAuth router — loginLimiter scoping', () => {
const savedEnv = {};
beforeAll(() => {
savedEnv.LOGIN_MAX = process.env.LOGIN_MAX;
savedEnv.LOGIN_WINDOW = process.env.LOGIN_WINDOW;
savedEnv.DOMAIN_CLIENT = process.env.DOMAIN_CLIENT;
savedEnv.DOMAIN_SERVER = process.env.DOMAIN_SERVER;
});
afterAll(() => {
for (const key of Object.keys(savedEnv)) {
if (savedEnv[key] === undefined) {
delete process.env[key];
} else {
process.env[key] = savedEnv[key];
}
}
});
// The limiter reads LOGIN_MAX/LOGIN_WINDOW at module-load time, so build the
// app inside isolateModules AFTER setting env to get a fresh limiter+store.
const buildApp = () => {
let oauthRouter;
jest.isolateModules(() => {
oauthRouter = require('../oauth');
});
const app = express();
app.use(express.json());
app.use('/oauth', oauthRouter);
return app;
};
beforeEach(() => {
jest.clearAllMocks();
process.env.LOGIN_MAX = '1';
process.env.LOGIN_WINDOW = '5';
process.env.DOMAIN_CLIENT = 'http://localhost:3080';
process.env.DOMAIN_SERVER = 'http://localhost:3080';
});
describe('initiation route (redirect-to-IdP) IS rate-limited', () => {
it('returns 429 once an initiation route exceeds LOGIN_MAX', async () => {
const app = buildApp();
const max = parseInt(process.env.LOGIN_MAX, 10);
for (let i = 0; i < max; i++) {
const ok = await request(app).get(LOGIN_INITIATION);
expect(ok.status).toBe(200);
expect(ok.body.reached).toBe(true);
}
const limited = await request(app).get(LOGIN_INITIATION);
expect(limited.status).toBe(429);
expect(limited.body.message).toMatch(/too many/i);
});
});
describe('callback route (IdP-returns-code) is NOT rate-limited', () => {
it('never returns 429 even when hammered well past LOGIN_MAX', async () => {
const app = buildApp();
const hits = parseInt(process.env.LOGIN_MAX, 10) + 5;
for (let i = 0; i < hits; i++) {
const res = await request(app).get(LOGIN_CALLBACK);
// The callback may legitimately 200/redirect/fail auth — it must just
// never be throttled with 429.
expect(res.status).not.toBe(429);
}
});
it('does not consume the initiation budget (callback hits never trip the limiter)', async () => {
const app = buildApp();
// Hammer the callback far past the limit first.
for (let i = 0; i < 10; i++) {
const res = await request(app).get(LOGIN_CALLBACK);
expect(res.status).not.toBe(429);
}
// The single allowed initiation request must still succeed: callbacks and
// initiations do not share a (broken) blanket budget.
const ok = await request(app).get(LOGIN_INITIATION);
expect(ok.status).toBe(200);
});
});
describe('router wiring (defense-in-depth structural assertion)', () => {
// Even independent of runtime behavior, assert the limiter is present in the
// initiation route's middleware stack and absent from every callback stack.
const limiterStackByPath = () => {
let oauthRouter;
let loginLimiter;
jest.isolateModules(() => {
oauthRouter = require('../oauth');
// Same instance the router received (the mocked index re-exports the
// real leaf limiter), so reference-equality in the stack is meaningful.
({ loginLimiter } = require('~/server/middleware'));
});
const byPath = {};
for (const layer of oauthRouter.stack) {
if (!layer.route) continue; // skip router.use(logHeaders) etc.
const handles = layer.route.stack.map((s) => s.handle);
byPath[layer.route.path] = handles.includes(loginLimiter);
}
return byPath;
};
it('applies loginLimiter to every initiation route and to NO callback route', () => {
const limited = limiterStackByPath();
const initiationRoutes = [
'/google',
'/facebook',
'/openid',
'/github',
'/discord',
'/apple',
'/saml',
];
const callbackRoutes = [
'/google/callback',
'/facebook/callback',
'/openid/callback',
'/github/callback',
'/discord/callback',
'/apple/callback',
'/saml/callback',
];
for (const path of initiationRoutes) {
expect(limited[path]).toBe(true);
}
for (const path of callbackRoutes) {
expect(limited[path]).toBe(false);
}
});
});
});
+13 -13
View File
@@ -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);
});
+12 -12
View File
@@ -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);
+7 -7
View File
@@ -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);
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 }
*/
+4 -4
View File
@@ -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');
+201
View File
@@ -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;
+72 -16
View File
@@ -8,11 +8,15 @@ const {
messageIpLimiter,
configMiddleware,
messageUserLimiter,
enforceGuestScope,
guestMessageLimiter,
requireGuestOrJwtAuth,
} = require('~/server/middleware');
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 ?? {};
@@ -21,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
*/
@@ -29,14 +33,80 @@ 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);
/**
* Guest-capable chat completion router.
*
* Mounted before the JWT-only routes below so anonymous guests (when
* `ALLOW_GUEST_CHAT` is enabled) can reach ONLY the completion endpoints. Auth
* here accepts either a guest token or a real JWT; `enforceGuestScope` then pins
* guests to the free Zen endpoint/model and strips every other capability, and
* `guestMessageLimiter` enforces the per-IP guest quota. Every other agents route
* (management, CRUD, files) remains gated by the strict `requireJwtAuth` below,
* which rejects guest tokens.
*/
const RESERVED_CHAT_SUBPATHS = new Set(['stream', 'active', 'status', 'abort']);
const chatRouter = express.Router();
/**
* Defer reserved management subpaths (stream/active/status/abort) to the
* JWT-only handlers defined on the parent router. Without this guard the
* completion route's `POST /:endpoint` would shadow `POST /chat/abort`.
*/
chatRouter.use((req, res, next) => {
const subpath = req.path.split('/').filter(Boolean)[0];
if (RESERVED_CHAT_SUBPATHS.has(subpath)) {
return next('router');
}
return next();
});
chatRouter.use(requireGuestOrJwtAuth);
chatRouter.use(checkBan);
chatRouter.use(uaParser);
chatRouter.use(configMiddleware);
chatRouter.use(enforceGuestScope);
chatRouter.use(guestMessageLimiter);
if (isEnabled(LIMIT_MESSAGE_IP)) {
chatRouter.use(messageIpLimiter);
}
if (isEnabled(LIMIT_MESSAGE_USER)) {
chatRouter.use(messageUserLimiter);
}
chatRouter.use('/', chat);
router.use('/chat', chatRouter);
/**
* Guest-safe active-jobs poll. Guests never own a generation job, so this
* returns an empty set without a DB/user lookup. Registered BEFORE the strict
* JWT guard below so the composer's bootstrap poll doesn't 401-loop for guests;
* every other agents route stays JWT-only and rejects guest tokens.
*/
router.get('/chat/active', requireGuestOrJwtAuth, async (req, res, next) => {
if (req.user?.guest === true) {
return res.json({ activeJobIds: [] });
}
return next();
});
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);
/**
@@ -269,18 +339,4 @@ router.post('/chat/abort', async (req, res) => {
return res.status(404).json({ error: 'Job not found', streamId: jobStreamId });
});
const chatRouter = express.Router();
chatRouter.use(configMiddleware);
if (isEnabled(LIMIT_MESSAGE_IP)) {
chatRouter.use(messageIpLimiter);
}
if (isEnabled(LIMIT_MESSAGE_USER)) {
chatRouter.use(messageUserLimiter);
}
chatRouter.use('/', chat);
router.use('/chat', chatRouter);
module.exports = router;
+6 -6
View File
@@ -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);
+2
View File
@@ -17,6 +17,7 @@ const {
const { verify2FAWithTempToken } = require('~/server/controllers/auth/TwoFactorAuthController');
const { logoutController } = require('~/server/controllers/auth/LogoutController');
const { loginController } = require('~/server/controllers/auth/LoginController');
const { guestTokenController } = require('~/server/controllers/auth/GuestController');
const { getAppConfig } = require('~/server/services/Config');
const middleware = require('~/server/middleware');
const { Balance } = require('~/db/models');
@@ -41,6 +42,7 @@ router.post(
loginController,
);
router.post('/refresh', refreshController);
router.post('/guest', middleware.guestTokenLimiter, middleware.checkBan, guestTokenController);
router.post(
'/register',
middleware.registerLimiter,
+5
View File
@@ -5,6 +5,7 @@ const { isEnabled, getBalanceConfig } = require('@hanzochat/api');
const { Constants, CacheKeys, defaultSocialLogins } = require('librechat-data-provider');
const { getLdapConfig } = require('~/server/services/Config/ldap');
const { getAppConfig } = require('~/server/services/Config/app');
const { getGuestConfig } = require('~/server/services/guestConfig');
const { getProjectByName } = require('~/models/Project');
const { getLogStores } = require('~/cache');
@@ -59,6 +60,8 @@ router.get('/', async function (req, res) {
const balanceConfig = getBalanceConfig(appConfig);
const guestConfig = getGuestConfig();
// Strip server-internal fields from balance config before sending to client.
// commerce.endpoint leaks K8s service URLs; commerce.token is a bearer secret.
const clientBalanceConfig = balanceConfig
@@ -121,6 +124,8 @@ router.get('/', async function (req, res) {
sharePointPickerGraphScope: process.env.SHAREPOINT_PICKER_GRAPH_SCOPE,
sharePointPickerSharePointScope: process.env.SHAREPOINT_PICKER_SHAREPOINT_SCOPE,
openidReuseTokens,
allowGuestChat: guestConfig.enabled,
guestMessageMax: guestConfig.enabled ? guestConfig.messageMax : undefined,
conversationImportMaxFileSize: process.env.CONVERSATION_IMPORT_MAX_FILE_SIZE_BYTES
? parseInt(process.env.CONVERSATION_IMPORT_MAX_FILE_SIZE_BYTES, 10)
: 0,
+16 -4
View File
@@ -15,6 +15,7 @@ const { forkConversation, duplicateConversation } = require('~/server/utils/impo
const { storage, importFileFilter } = require('~/server/routes/files/multer');
const { deleteAllSharedLinks, deleteConvoSharedLink } = require('~/models');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
const requireGuestOrJwtAuth = require('~/server/middleware/requireGuestOrJwtAuth');
const { importConversations } = require('~/server/utils/import');
const { deleteToolCalls } = require('~/models/ToolCall');
const getLogStores = require('~/cache/getLogStores');
@@ -25,9 +26,17 @@ const assistantClients = {
};
const router = express.Router();
router.use(requireJwtAuth);
router.get('/', async (req, res) => {
/**
* Guest-accessible conversation list. Guests have no persisted conversations, so
* this returns an empty, well-formed page enough for the UI to mount the chat
* history pane without a DB lookup. Registered with guest-aware auth BEFORE the
* strict JWT guard below; every mutation/read-by-id route stays JWT-only.
*/
router.get('/', requireGuestOrJwtAuth, async (req, res) => {
if (req.user?.guest === true) {
return res.status(200).json({ conversations: [], nextCursor: null });
}
const limit = parseInt(req.query.limit, 10) || 25;
const cursor = req.query.cursor;
const isArchived = isEnabled(req.query.isArchived);
@@ -57,6 +66,9 @@ router.get('/', async (req, res) => {
}
});
/** Every route below reads or writes persisted user data — JWT-only, no guests. */
router.use(requireJwtAuth);
router.get('/:conversationId', async (req, res) => {
const { conversationId } = req.params;
const convo = await getConvo(req.user.id, conversationId);
@@ -174,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) {
@@ -214,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) {
+2 -2
View File
@@ -1,8 +1,8 @@
const express = require('express');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
const requireGuestOrJwtAuth = require('~/server/middleware/requireGuestOrJwtAuth');
const endpointController = require('~/server/controllers/EndpointController');
const router = express.Router();
router.get('/', requireJwtAuth, endpointController);
router.get('/', requireGuestOrJwtAuth, endpointController);
module.exports = router;
+8 -8
View File
@@ -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/);
+2 -2
View File
@@ -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();
+6 -6
View File
@@ -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
*/

Some files were not shown because too many files have changed in this diff Show More