Files
chat/api/server/middleware/validateImageRequest.js
zeekay 551236b1a5 route: one namespace — everything chat serves lives under /v1/chat
Five things answered outside /v1/chat/. Four of them are chat's; they move.

  /health                -> /v1/chat/health
  POST /oauth/iam/session-> POST /v1/chat/auth/iam/session   (it is auth)
  GET  /oauth/openid[/callback], /oauth/error
                         -> /v1/chat/auth/openid[/callback], /v1/chat/auth/error
  /images/               -> /v1/chat/images/

The fifth — the built assets at / and the SPA catch-all — is the SPA's, and
stays. Every caller moved in the same commit: api-endpoints (health, iamSession),
the metrics + telemetry health filter, the helm probes, the PR-preview workflow,
the PWA nav-fallback denylist. `ErrorController` matched a failed OIDC callback
by the substring '/oauth/', which the move would have silently broken; it now
matches the route.

Images are the one persisted case: a conversation stores the served path, and
history is immutable. New writes emit /v1/chat/images/…; /images/* answers one
permanent redirect; `isServedImage` (data-provider, the one place that knows the
namespace) recognises both. Local deletion maps the served path back to disk.

Two routers were written, tested, advertised to the browser — and never mounted,
so both were a guaranteed 404: skills (types say /v1/chat/skills) and the RUM
OTLP proxy (`rum/proxy` advertises /v1/chat/rum). Mounted where they said.

Deleted, with zero callers: server/experimental.js — a drifted second copy of
the whole mount table, still referencing a router that no longer exists, that
would have silently absorbed this move and diverged again; and nginx.hanzo.conf,
referenced by no compose/Dockerfile/chart, whose own /health shadowed chat's.

Gates collapsed to their one behavior, and the env deleted:

  ALLOW_SOCIAL_LOGIN     IAM is the one identity provider; false produced a
                         server with no way to sign in. socialLogins.js is now
                         iamLogin.js — one name for one thing.
  CONTINUE_ON_UNCAUGHT_EXCEPTION  keeps a process alive in an unknown state
                         instead of letting the kubelet replace it.
  CONFIG_BYPASS_VALIDATION        boots on invalid config, on request.
  MCP_SKIP_CODE_CHALLENGE_CHECK   turns off PKCE verification.
  OPENID_JWKS_URL_CACHE_ENABLED   read as `isEnabled(x) || true` — never off.
                         A second, differently-defaulted read lived in
                         remoteAgentAuth; both are now just on.
  NO_INDEX               a third boolean idiom for a header we always want.
  DISABLE_COMPRESSION, ENABLE_IMAGE_OUTPUT_GZIP_SCAN — we write these images
                         ourselves, as PNG/GIF; none is gzipped on disk.

Tests fail without the change: the auth router spec (6 of 7) against the old
router, the static spec against the old env-gated one, the config spec now sets
CONFIG_BYPASS_VALIDATION=true and still expects the exit, the error spec against
the '/oauth/' matcher, and index.spec asserts the top level serves HTML — so a
probe or caller left behind fails loudly instead of looking green.
2026-07-26 17:04:33 -07:00

164 lines
5.5 KiB
JavaScript

const cookies = require('cookie');
const jwt = require('jsonwebtoken');
const { logger } = require('@hanzochat/data-schemas');
const { isEnabled, getBasePath } = require('@hanzochat/api');
const { imagesRoute } = require('@hanzochat/data-provider');
const OBJECT_ID_LENGTH = 24;
const OBJECT_ID_PATTERN = /^[0-9a-f]{24}$/i;
/**
* Validates if a string is a valid MongoDB ObjectId
* @param {string} id - String to validate
* @returns {boolean} - Whether string is a valid ObjectId format
*/
function isValidObjectId(id) {
if (typeof id !== 'string') {
return false;
}
if (id.length !== OBJECT_ID_LENGTH) {
return false;
}
return OBJECT_ID_PATTERN.test(id);
}
/**
* Validates a Chat refresh token
* @param {string} refreshToken - The refresh token to validate
* @returns {{valid: boolean, userId?: string, error?: string}} - Validation result
*/
function validateToken(refreshToken) {
try {
const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
if (!isValidObjectId(payload.id)) {
return { valid: false, error: 'Invalid User ID' };
}
const currentTimeInSeconds = Math.floor(Date.now() / 1000);
if (payload.exp < currentTimeInSeconds) {
return { valid: false, error: 'Refresh token expired' };
}
return { valid: true, userId: payload.id };
} catch (err) {
logger.warn('[validateToken]', err);
return { valid: false, error: 'Invalid token' };
}
}
/**
* Factory to create the `validateImageRequest` middleware with configured secureImageLinks
* @param {boolean} [secureImageLinks] - Whether secure image links are enabled
*/
function createValidateImageRequest(secureImageLinks) {
if (!secureImageLinks) {
return (_req, _res, next) => next();
}
/**
* Middleware to validate image request.
* Supports both Chat refresh tokens and OpenID JWT tokens.
* Must be set by `secureImageLinks` via custom config file.
*/
return async function validateImageRequest(req, res, next) {
try {
const cookieHeader = req.headers.cookie;
if (!cookieHeader) {
logger.warn('[validateImageRequest] No cookies provided');
return res.status(401).send('Unauthorized');
}
const parsedCookies = cookies.parse(cookieHeader);
const tokenProvider = parsedCookies.token_provider;
let userIdForPath;
if (tokenProvider === 'openid' && isEnabled(process.env.OPENID_REUSE_TOKENS)) {
/** For OpenID users with OPENID_REUSE_TOKENS, use openid_user_id cookie */
const openidUserId = parsedCookies.openid_user_id;
if (!openidUserId) {
logger.warn('[validateImageRequest] No OpenID user ID cookie found');
return res.status(403).send('Access Denied');
}
const validationResult = validateToken(openidUserId);
if (!validationResult.valid) {
logger.warn(`[validateImageRequest] ${validationResult.error}`);
return res.status(403).send('Access Denied');
}
userIdForPath = validationResult.userId;
} else {
/**
* For non-OpenID users (or OpenID without REUSE_TOKENS), use refreshToken from cookies.
* These users authenticate via setAuthTokens() which stores refreshToken in cookies.
*/
const refreshToken = parsedCookies.refreshToken;
if (!refreshToken) {
logger.warn('[validateImageRequest] Token not provided');
return res.status(401).send('Unauthorized');
}
const validationResult = validateToken(refreshToken);
if (!validationResult.valid) {
logger.warn(`[validateImageRequest] ${validationResult.error}`);
return res.status(403).send('Access Denied');
}
userIdForPath = validationResult.userId;
}
if (!userIdForPath) {
logger.warn('[validateImageRequest] No user ID available for path validation');
return res.status(403).send('Access Denied');
}
const MAX_URL_LENGTH = 2048;
if (req.originalUrl.length > MAX_URL_LENGTH) {
logger.warn('[validateImageRequest] URL too long');
return res.status(403).send('Access Denied');
}
if (req.originalUrl.includes('\x00')) {
logger.warn('[validateImageRequest] URL contains null byte');
return res.status(403).send('Access Denied');
}
let fullPath;
try {
fullPath = decodeURIComponent(req.originalUrl);
} catch {
logger.warn('[validateImageRequest] Invalid URL encoding');
return res.status(403).send('Access Denied');
}
const basePath = getBasePath();
const imagesPath = `${basePath}${imagesRoute}`;
const agentAvatarPattern = new RegExp(
`^${imagesPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/[a-f0-9]{24}/agent-[^/]*$`,
);
if (agentAvatarPattern.test(fullPath)) {
logger.debug('[validateImageRequest] Image request validated');
return next();
}
const escapedUserId = userIdForPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pathPattern = new RegExp(
`^${imagesPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/${escapedUserId}/[^/]+$`,
);
if (pathPattern.test(fullPath)) {
logger.debug('[validateImageRequest] Image request validated');
next();
} else {
logger.warn('[validateImageRequest] Invalid image path');
res.status(403).send('Access Denied');
}
} catch (error) {
logger.error('[validateImageRequest] Error:', error);
res.status(500).send('Internal Server Error');
}
};
}
module.exports = createValidateImageRequest;