api_ianmenethil_comreqInputFilter.ts8 matches
16* console.log(clean); // <script>alert("xss")</script>
17*/
18export function sanitizeInput(input: any): any {
19if (typeof input === "string") {
20// Check for blocked patterns
60* }
61*/
62export function validateRequestSize(request: Request): boolean {
63const contentLength = request.headers.get("content-length");
64if (contentLength) {
92* }
93*/
94export function validateJsonPayloadSize(jsonString: string): boolean {
95const size = new TextEncoder().encode(jsonString).length;
96const isValid = size <= InputValidationConfig.maxJsonPayload;
120* }
121*/
122export function validateUrlLength(url: string): boolean {
123const isValid = url.length <= InputValidationConfig.maxUrlLength;
124147* }
148*/
149export function validateFileType(mimeType: string): boolean {
150const isValid = InputValidationConfig.allowedFileTypes.includes(mimeType);
151169* @returns True if input contains blocked patterns
170*/
171export function containsBlockedPatterns(input: string): boolean {
172for (const pattern of InputValidationConfig.blockedPatterns) {
173if (pattern.test(input)) {
190*
191* @param c - Hono context object containing request and response data
192* @param next - Next middleware function in the Hono processing chain
193* @returns Promise<void> - Continues to next middleware or throws HTTPException on security violation
194* @throws HTTPException - 413 Request Entity Too Large, 414 URI Too Long, 400 Bad Request
255*
256* @param c - Hono context object
257* @param next - Next middleware function
258*/
259export const sanitizeBodyMiddleware = async (
84}
8586/* Header validation (original functionality) ---------------------- */
87if (!cfg.enabled) {
88await next();
api_ianmenethil_comreqBody.ts3 matches
5455/**
56* Validation utility functions for common input patterns.
57* Provides reusable validators for UUID, alphanumeric, length, and enum validation.
58*/
393*
394* @param c - Hono context object containing request and response data
395* @param next - Next middleware function in the Hono processing chain
396* @returns Promise<void> - Completes after validation check and next() execution
397*/
425/**
426* @param schemaName - Name of the validation schema to retrieve from available schemas
427* @returns Corresponding validator function for the specified schema type
428*/
429export const getBodyValidator = (schemaName: keyof typeof bodyValidationSchemas) => {
api_ianmenethil_comrateLimiter.ts12 matches
28};
2930async function initTables() {
31await sqlService.createTable("rate_limit_violations", {
32id: { type: "INTEGER", primaryKey: true, autoIncrement: true },
58}
5960async function persistViolation(v: RateLimitViolation) {
61await sqlService.insert("rate_limit_violations", {
62ip: v.ip,
68}
6970async function persistBlockStatus(b: IPBlockStatus) {
71await sqlService.execute({
72sql: `INSERT OR REPLACE INTO ip_block_status
86}
8788async function persistBlacklist(ip: string, reason: string) {
89const key = "rate-limiter/blacklist.json";
90const json = (await blobService.getJSON<Record<string, unknown>>(key)) ?? {};
93}
9495async function loadBlacklist() {
96const key = "rate-limiter/blacklist.json";
97const json = await blobService.getJSON<Record<string, unknown>>(key);
114];
115116function getClientIP(c: Context): string {
117for (const h of HEADER_CANDIDATES) {
118const v = c.req.header(h);
122}
123124async function currentViolationCount(ip: string): Promise<number> {
125if (!AUTO_BLOCK_CONFIG.persistToStorage) {
126return memoryCache.violationCounts.get(ip) ?? 0;
137}
138139async function addViolation(ip: string, ep: string, ua?: string) {
140const v: RateLimitViolation = {
141ip,
153154/* Threat detection & auto-blocking */
155async function inspectThreat(ip: string): Promise<ThreatDetectionResult> {
156if (memoryCache.blacklistedIPs.has(ip)) {
157return { action: "blacklist", reason: "already blacklisted", violationCount: 0 };
183}
184185async function temporaryBlock(ip: string, reason: string, vCount: number) {
186const until = new Date(getSydneyTimestamp() + AUTO_BLOCK_CONFIG.blockDuration * 60 * 1000);
187const st: IPBlockStatus = {
201/* Middleware */
202/* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
203export async function enhancedRateLimitMiddleware(c: Context, next: Next) {
204if (!AUTO_BLOCK_CONFIG.enabled) return await next();
205250251/* Back-compat wrapper (same signature as old middleware) */
252export default function createBackendRateLimitMiddleware(): MiddlewareHandler<
253{ Variables: HonoVariables }
254> {
api_ianmenethil_comnetworkFilter.ts3 matches
110c.set("securityContext", newSecurityContextUpdate);
111await next();
112function safeMatch(ipToMatch: string, range: string, errTpl: string): boolean {
113try {
114return checkIpRange(ipToMatch, range);
118}
119}
120function logIfBlocked(msg: string) {
121if (cfg.logBlocked) console.warn(msg);
122}
123function throwForbidden(
124config: NetworkFilterConfig,
125codeKey: keyof NetworkFilterConfig["errorCodes"],
api_ianmenethil_comlogging.ts2 matches
182* Centralised security-event logger (โ ๏ธ do not remove).
183*/
184export function logSecurityEvent(
185type: string,
186details: unknown,
287288/* --- alert stub ---------------------------------------------------- */
289function triggerSecurityAlert(event: SecurityEvent): void {
290// TODO: integrate pager-duty / email / webhook
291console.error(
api_ianmenethil_comgeoFilter.ts4 matches
16}>("middleware.geofence").geofencing;
1718function logGeoEvent(type: string, details: GeoEventDetails): void {
19const logData = {
20type,
29}
3031export function checkGeoRestriction(request: Request): GeoFilterResult {
32if (!GEO.enabled) {
33return { allowed: true, country: "XX", reason: "Geofencing disabled" };
124/* Middleware */
125/* ------------------------------------------------------------------ */
126export function createGeoFilterMiddleware() {
127return async (c: Context, next: Next) => {
128if (!GEO.enabled) return await next();
152}
153154export async function geoDataExtractionMiddleware(
155c: Context,
156next: Next,
61* @returns HTTPException with formatted JSON response
62*/
63export function buildError(
64cfg: HeaderInspectionConfig,
65msg: string,
167168/**
169* Helper function to throw HTTP errors with consistent formatting and error codes.
170*
171* Creates HTTPException instances with standardized status codes and optional
176* @param message - Error message to include in the HTTP response body
177* @param code - Optional error code for categorization and debugging purposes
178* @returns void - Function throws HTTPException instead of returning
179* @throws HTTPException - Always throws with provided status and formatted message
180*
192193/**
194* Configuration management functions for error handler settings.
195*/
196219*
220* @param _c - Hono context object (unused but required by middleware signature)
221* @param next - Next middleware function in the processing chain
222* @returns Promise<void> - Completes after error handling or next() execution
223* @throws HTTPException - Converts all errors to HTTPException format for global handler
api_ianmenethil_comcsrf.ts1 match
110111/* helper to throw HTTPException with consistent body */
112function throwCsrfError(message: string, code: string): never {
113const payload = {
114error: message,
api_ianmenethil_comcloudflareHelpers.ts10 matches
9* Extracts and parses CF-Visitor header which contains JSON data
10*/
11function parseVisitorHeader(visitorHeader: string | undefined): Record<string, unknown> | null {
12if (!visitorHeader) return null;
1323* Validates and sanitizes coordinate values
24*/
25function parseCoordinate(coord: string | undefined): number | null {
26if (!coord) return null;
2733* Extracts all Cloudflare headers from the request and structures them for use
34*/
35export function extractCloudflareHeaders(c: Context): CloudflareHeaderData {
36const headers = c.req.raw.headers;
37104* Logs CF header data
105*/
106export function logCFData(cfData: CloudflareHeaderData, zid?: string): void {
107console.log(
108`[CF-Headers] ${zid ? `[${zid}] ` : ""}Headers processed: ${
113114/**
115* Helper function to get Cloudflare data from context
116*/
117export function getCFData(c: Context): CloudflareHeaderData | null {
118return c.get("cfData") || null;
119}
120121/**
122* Helper function to check if request came through Cloudflare
123*/
124export function isCloudflareRequest(c: Context): boolean {
125const cfData = getCFData(c);
126return cfData?.hasCloudflareHeaders || false;
128129/**
130* Helper function to get geographic summary string
131*/
132export function getGeographicSummary(c: Context): string {
133const cfData = getCFData(c);
134if (!cfData) return "Unknown location";