LibreChat/api/server/routes/agents/chat.js
Danny Avila 67b7b441b2
🛂 feat: Filter Model-Bound Content by Source (#14425)
* feat: introduce optional content protection seam

* feat: enforce source-aware content filters

* feat: complete source-aware content enforcement

* test: activate skill file-text fail-close fixtures

* fix: harden source-aware content filters

* fix: harden model-bound content filtering

* fix: preserve legacy filters and generated files

* fix: inspect shared scalar metadata

* test: align mocks with current dev dependencies

* feat: add persisted content filter safeguards

* feat: complete source-aware content filter enforcement

* fix: move resume content preflight into TypeScript

* fix: close content inspection edge cases

* fix: harden content protection boundaries

* fix: complete content protection safeguards

* test: align persisted memory filter coverage

* fix: reconcile content protection with current dev

* fix: reconcile content protection with latest dev

* fix: close content protection review gaps

* fix: enforce source-aware provider boundaries

* fix: preserve legacy PII preflight semantics

* test: stabilize stored branch preflight fixture

* fix: defer agent writes until protected model admission

* perf: harden source-aware model-bound filtering

* fix: canonicalize provider lineage before validation

* fix: satisfy model-bound callback type checks

* perf: Bound content protection filtering work

* fix: Bound submission array traversal

* fix: Stabilize bounded content snapshots

* fix: Scope model-bound traversal overflows

* fix: Preserve scoped content inspection

* fix: Accumulate aggregate traversal scopes

* fix: centralize content policy boundaries

* test: align deferred tool policy context

* test: align controller policy mocks

* style: normalize content protection imports

* fix: close content policy review gaps

* fix: narrow active skill policy config

* fix: address content protection review boundaries

* fix: retain exact provenance overflow sentinel

* fix: preserve literal and scoped provenance updates

* fix: narrow persisted edit provenance

* fix: isolate exact overflow attribution

* fix: centralize stored prompt protection

* fix: fail closed on incomplete transcript evidence

* fix: align canonical transcript routing

* refactor: centralize content policy preflights

* fix: isolate upload policy error typing

* style: sort policy preflight imports

* refactor: centralize content policy boundaries
2026-08-21 22:43:32 -04:00

126 lines
4.6 KiB
JavaScript

const express = require('express');
const { logger } = require('@librechat/data-schemas');
const {
createMessageFilterPii,
generateCheckAccess,
skipAgentCheck,
applyResumeContext,
applyResumeModelParameters,
GenerationJobManager,
getSafeErrorMetadata,
} = require('@librechat/api');
const { PermissionTypes, Permissions, PermissionBits } = require('librechat-data-provider');
const {
moderateText,
// validateModel,
validateConvoAccess,
buildEndpointOption,
canAccessAgentFromBody,
} = require('~/server/middleware');
const { initializeClient } = require('~/server/services/Endpoints/agents');
const guardSubagentThreadTurn = require('~/server/middleware/validate/subagentThreadTurn');
const AgentController = require('~/server/controllers/agents/request');
const ResumeController = require('~/server/controllers/agents/resume');
const addTitle = require('~/server/services/Endpoints/agents/title');
const { getFiles, getRoleByName } = require('~/models');
const router = express.Router();
const checkAgentAccess = generateCheckAccess({
permissionType: PermissionTypes.AGENTS,
permissions: [Permissions.USE],
skipCheck: skipAgentCheck,
getRoleByName,
});
const checkAgentResourceAccess = canAccessAgentFromBody({
requiredPermission: PermissionBits.VIEW,
});
/**
* Replay the paused turn's graph-determining config onto a resume request BEFORE the
* rest of the chain (PII filter, agent-access, buildEndpointOption) reads it. The client
* can't reliably re-send the ephemeral-agent config after a reload/cross-session, so the
* server restores it from the pending action — the resume then rebuilds the SAME
* agent/graph the run paused on (and a crafted resume can't swap the tool set). No-op for
* every non-resume route.
*/
const restoreResumeContext = async (req, res, next) => {
if (req.path !== '/resume') {
return next();
}
try {
const streamId = req.body?.conversationId;
if (streamId) {
const job = await GenerationJobManager.getJob(streamId);
const resumeContext = job?.metadata?.pendingAction?.resumeContext;
applyResumeContext(req.body, resumeContext);
// Replay the paused turn's resolved model parameters. Ephemeral agents derive these
// (temperature, max tokens, custom endpoint params) from the request body, which the
// resume payload omits — without this the continuation runs with defaults. They're
// scattered top-level fields (folded into model_parameters by buildOptions' rest
// spread), not part of the RESUME_CONTEXT_KEYS allowlist, so merge them back here.
// Generation params are authoritative, but routing, graph identity, and resume-action
// fields remain owned by the restored context/request envelope.
applyResumeModelParameters(req.body, resumeContext?.model_parameters);
}
} catch (err) {
logger.warn('[agents/chat] Failed to restore resume context', getSafeErrorMetadata(err));
}
next();
};
router.use(restoreResumeContext);
router.use(
createMessageFilterPii({
getConfig: (req) => req.config?.messageFilter?.pii,
getFilters: (req) => req.config?.filters,
getFiles,
}),
);
router.use(moderateText);
router.use(checkAgentAccess);
router.use(checkAgentResourceAccess);
router.use(validateConvoAccess);
router.use(guardSubagentThreadTurn);
router.use(buildEndpointOption);
const controller = async (req, res, next) => {
await AgentController(req, res, next, initializeClient, addTitle);
};
const resumeController = async (req, res, next) => {
await ResumeController(req, res, next, initializeClient, addTitle);
};
/**
* @route POST /resume
* @desc Resume a generation paused for human-in-the-loop review (tool approval or
* ask-user answer). Shares this router's middleware so the agent/endpoint are
* reconstructed from the request exactly like a normal turn. Declared before
* `/:endpoint` so it is not captured as an ephemeral endpoint name.
* @access Private
* @returns {void}
*/
router.post('/resume', resumeController);
/**
* @route POST / (regular endpoint)
* @desc Chat with an assistant
* @access Public
* @param {express.Request} req - The request object, containing the request data.
* @param {express.Response} res - The response object, used to send back a response.
* @returns {void}
*/
router.post('/', controller);
/**
* @route POST /:endpoint (ephemeral agents)
* @desc Chat with an assistant
* @access Public
* @param {express.Request} req - The request object, containing the request data.
* @param {express.Response} res - The response object, used to send back a response.
* @returns {void}
*/
router.post('/:endpoint', controller);
module.exports = router;