release(v2.7.3): tenant SQL scoping, spoof-proof rate limits, safe fraud demo, non-root Docker & full parity

This commit is contained in:
Amirul Islam Redwan71
2026-11-27 04:47:06 +06:00
parent c827fdfee6
commit a3392ae69f
65 changed files with 911 additions and 1228 deletions
+31 -6
View File
@@ -149,6 +149,10 @@ export function hasByokCredentials(req) {
return validateByokHeaders(req).isByok;
}
export function extractBearerToken(req) {
const cachedQueryTok = req._extractedQueryToken;
if (typeof cachedQueryTok === "string" && cachedQueryTok) {
return cachedQueryTok;
}
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
if (typeof authHeader === "string") {
const trimmed = authHeader.trim();
@@ -161,12 +165,33 @@ export function extractBearerToken(req) {
if (typeof customKey === "string" && customKey.trim()) {
return customKey.trim();
}
// Support query parameter tokens for remote AI agent connectors (Claude Desktop, Cursor, Glama, Zapier, Custom GPTs)
const q = req.query;
if (q) {
const candidate = q.token || q.key || q.apiKey || q.api_key;
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
// NEW-05 Fix: Restrict query-parameter tokens strictly to MCP/SSE connector endpoints (never /admin, /track, /webhooks, /oauth)
// and scrub secret query parameters from req.url / req.originalUrl immediately to prevent downstream log exposure.
if (process.env.ALLOW_QUERY_TOKEN !== "false") {
const reqPath = (req.path || (req.url ? req.url.split("?")[0] : "")).trim();
if (reqPath === "/mcp" || reqPath === "/sse" || reqPath === "/messages") {
const q = req.query;
if (q) {
const candidate = q.token || q.key || q.apiKey || q.api_key;
if (typeof candidate === "string" && candidate.trim()) {
const cleanTok = candidate.trim();
req._extractedQueryToken = cleanTok;
req._usedQueryToken = true;
delete q.token;
delete q.key;
delete q.apiKey;
delete q.api_key;
if (typeof req.url === "string" && req.url.includes("?")) {
req.url = req.url.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]").replace(/\?&/, "?");
}
if (typeof req.originalUrl === "string" && req.originalUrl.includes("?")) {
req.originalUrl = req.originalUrl
.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]")
.replace(/\?&/, "?");
}
return cleanTok;
}
}
}
}
return undefined;
+10 -3
View File
@@ -1,5 +1,12 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { resolveAuthContextAsync } from "./auth.js";
import { createRateLimiter } from "./rate_limit.js";
const oauthLimiter = createRateLimiter({
windowMs: 60 * 1000,
max: 20,
name: "OAuth 2.1 Security Gateway",
message: "Too many OAuth authentication or registration attempts. Please retry in a minute.",
});
const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour
const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability)
const AUTH_CODE_TTL_SEC = 300; // 5 minutes
@@ -978,7 +985,7 @@ export function registerOAuthRoutes(app) {
app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler);
app.get("/.well-known/openid-configuration", authServerMetadataHandler);
// 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof)
app.post("/oauth/register", (req, res) => {
app.post("/oauth/register", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store");
const body = (req.body || {});
const rawUris = body.redirect_uris;
@@ -1086,7 +1093,7 @@ export function registerOAuthRoutes(app) {
}));
});
// 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission)
app.post("/oauth/authorize", async (req, res) => {
app.post("/oauth/authorize", oauthLimiter, async (req, res) => {
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
@@ -1217,7 +1224,7 @@ export function registerOAuthRoutes(app) {
return res.redirect(302, callback.toString());
});
// 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token)
app.post("/oauth/token", (req, res) => {
app.post("/oauth/token", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache");
const b = (req.body || {});
+7
View File
@@ -5,5 +5,12 @@ interface RateLimiterOptions {
message?: string;
name?: string;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export declare function resolveRateLimitIp(req: Request): string;
export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void;
export {};
+48 -24
View File
@@ -1,3 +1,48 @@
import { isIP } from "node:net";
function normalizeIpLiteral(raw) {
const trimmed = raw.trim();
if (trimmed.startsWith("::ffff:")) {
return trimmed.slice(7);
}
return trimmed;
}
function isPrivateOrLoopbackIp(ip) {
const norm = normalizeIpLiteral(ip).toLowerCase();
if (!norm || norm === "127.0.0.1" || norm === "::1" || norm === "0.0.0.0")
return true;
if (norm.startsWith("127.") || norm.startsWith("10.") || norm.startsWith("192.168.") || norm.startsWith("169.254.")) {
return true;
}
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(norm)) {
return true;
}
if (norm.startsWith("fc") || norm.startsWith("fd") || norm.startsWith("fe80:")) {
return true;
}
return false;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export function resolveRateLimitIp(req) {
const cfIpRaw = req.headers["cf-connecting-ip"];
const cfRay = req.headers["cf-ray"];
if (typeof cfIpRaw === "string" && typeof cfRay === "string" && cfRay.trim().length > 0) {
const cfIp = normalizeIpLiteral(cfIpRaw);
if (isIP(cfIp) !== 0 && !isPrivateOrLoopbackIp(cfIp)) {
return cfIp;
}
}
const expressIp = typeof req.ip === "string" && req.ip.trim() ? normalizeIpLiteral(req.ip) : "";
if (expressIp && isIP(expressIp) !== 0) {
return expressIp;
}
const socketIp = req.socket?.remoteAddress ? normalizeIpLiteral(req.socket.remoteAddress) : "";
return socketIp || "unknown";
}
export function createRateLimiter(options) {
const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options;
const store = new Map();
@@ -11,32 +56,11 @@ export function createRateLimiter(options) {
}
}, 5 * 60 * 1000).unref();
return (req, res, next) => {
// Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx)
const cfIp = req.headers["cf-connecting-ip"];
const xForwardedFor = req.headers["x-forwarded-for"];
let clientIp = "";
if (typeof cfIp === "string") {
clientIp = cfIp.trim();
}
else if (typeof xForwardedFor === "string") {
clientIp = xForwardedFor.split(",")[0].trim();
}
else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
clientIp = xForwardedFor[0].trim();
}
else {
clientIp = req.socket?.remoteAddress || "unknown";
}
// Bypass loopback and internal orchestration networks
if (clientIp === "127.0.0.1" ||
clientIp === "::1" ||
clientIp === "::ffff:127.0.0.1" ||
clientIp.startsWith("10.") ||
clientIp.startsWith("172.16.") ||
clientIp.startsWith("172.17.") ||
clientIp.startsWith("172.18.")) {
// Allow high-speed local test execution unless test explicitly requests rate-limit enforcement
if (process.env.NODE_ENV === "test" && req.headers["x-test-enforce-ratelimit"] !== "1") {
return next();
}
const clientIp = resolveRateLimitIp(req);
const now = Date.now();
let record = store.get(clientIp);
if (!record || now > record.resetAt) {