feat(enterprise): add Privacy Policy, Data Retention schedule, Sliding-Window Rate Limiting, Optional Auth Layer, Speeding A brand icon, and GitHub footer link

This commit is contained in:
root
2026-10-22 01:21:50 +00:00
parent 55795a3e02
commit be213678f4
16 changed files with 904 additions and 25 deletions
+34
View File
@@ -0,0 +1,34 @@
import { Request, Response, NextFunction } from "express";
export interface AuraAuthContext {
isByok: boolean;
isMasterAuthorized: boolean;
callerToken?: string;
}
declare global {
namespace Express {
interface Request {
auraAuth?: AuraAuthContext;
}
}
}
/**
* Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys)
*/
export declare function hasByokCredentials(req: Request): boolean;
/**
* Extract bearer token or API key from request
*/
export declare function extractAuthToken(req: Request): string | undefined;
/**
* Optional Auth Evaluator:
* Public endpoints, discovery, and BYOK requests are permitted.
* If server has AURA_API_KEY set, master-account mutating actions require authentication.
*/
export declare function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void;
/**
* Helper to verify whether an action requires master auth and whether it is granted
*/
export declare function isActionPermitted(req: Request, toolName: string): {
permitted: boolean;
reason?: string;
};
+72
View File
@@ -0,0 +1,72 @@
/**
* Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys)
*/
export function hasByokCredentials(req) {
const h = req.headers;
const q = req.query;
const hasKey = (header, query) => Boolean(h[header] || q[query]);
return Boolean(hasKey("x-steadfast-api-key", "steadfast_key") ||
hasKey("x-pathao-client-id", "pathao_client_id") ||
hasKey("x-redx-api-token", "redx_token") ||
hasKey("x-paperfly-api-key", "paperfly_key"));
}
/**
* Extract bearer token or API key from request
*/
export function extractAuthToken(req) {
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
if (typeof authHeader === "string") {
if (authHeader.startsWith("Bearer ") || authHeader.startsWith("bearer ")) {
return authHeader.slice(7).trim();
}
return authHeader.trim();
}
const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"];
if (typeof customKey === "string") {
return customKey.trim();
}
const qKey = req.query["aura_key"] || req.query["api_key"];
if (typeof qKey === "string") {
return qKey.trim();
}
return undefined;
}
/**
* Optional Auth Evaluator:
* Public endpoints, discovery, and BYOK requests are permitted.
* If server has AURA_API_KEY set, master-account mutating actions require authentication.
*/
export function optionalAuthMiddleware(req, res, next) {
const serverApiKey = process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN;
const isByok = hasByokCredentials(req);
const callerToken = extractAuthToken(req);
const isMasterAuthorized = Boolean(!serverApiKey || (callerToken && callerToken === serverApiKey));
req.auraAuth = {
isByok,
isMasterAuthorized,
callerToken,
};
next();
}
/**
* Helper to verify whether an action requires master auth and whether it is granted
*/
export function isActionPermitted(req, toolName) {
const isMutatingAction = ["create_parcel", "get_balance", "resolve_ndr_issue"].includes(toolName);
// Read-only tools (list_couriers, calculate_delivery_zone_and_fee, compare_courier_rates, etc.) are always permitted
if (!isMutatingAction) {
return { permitted: true };
}
// If caller brought their own courier credentials, they are modifying their own account — permitted!
if (req.auraAuth?.isByok) {
return { permitted: true };
}
// If using server default merchant credentials, verify master authorization
if (req.auraAuth?.isMasterAuthorized) {
return { permitted: true };
}
return {
permitted: false,
reason: `Unauthorized: Dispatching parcels or checking wallet balance using the master merchant account requires a valid Aura API key (pass 'Authorization: Bearer <token>' or 'x-aura-key') or Bring-Your-Own-Keys (BYOK) courier headers.`,
};
}
+9
View File
@@ -0,0 +1,9 @@
import { Request, Response, NextFunction } from "express";
interface RateLimiterOptions {
windowMs: number;
max: number;
message?: string;
name?: string;
}
export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void;
export {};
+71
View File
@@ -0,0 +1,71 @@
export function createRateLimiter(options) {
const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options;
const store = new Map();
// Prune expired rate limit entries every 5 minutes to avoid memory bloat
setInterval(() => {
const now = Date.now();
for (const [key, record] of store.entries()) {
if (now > record.resetAt) {
store.delete(key);
}
}
}, 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.")) {
return next();
}
const now = Date.now();
let record = store.get(clientIp);
if (!record || now > record.resetAt) {
record = {
count: 1,
resetAt: now + windowMs,
};
store.set(clientIp, record);
}
else {
record.count++;
}
const remaining = Math.max(0, max - record.count);
const resetTimeSec = Math.ceil(record.resetAt / 1000);
const retryAfterSec = Math.ceil((record.resetAt - now) / 1000);
res.setHeader("X-RateLimit-Limit", max);
res.setHeader("X-RateLimit-Remaining", remaining);
res.setHeader("X-RateLimit-Reset", resetTimeSec);
if (record.count > max) {
res.setHeader("Retry-After", retryAfterSec);
res.status(429).json({
error: "Too Many Requests",
limiter: name,
message,
retryAfterSeconds: retryAfterSec,
timestamp: new Date().toISOString(),
});
return;
}
next();
};
}