api_ianmenethil_compathUtils.ts3 matches
10* {id} -> :id
11*/
12export function convertOpenApiPathToHono(openApiPath: string): string {
13return openApiPath.replace(/\{([^}]+)\}/g, ":$1");
14}
18* :id -> {id}
19*/
20export function convertHonoPathToOpenApi(honoPath: string): string {
21return honoPath.replace(/:([^/]+)/g, "{$1}");
22}
25* Extract parameters from OpenAPI path
26*/
27export function extractOpenApiParams(
28pathTemplate: string,
29actualPath: string,
api_ianmenethil_comzTracker.ts6 matches
11import { getCurrentDateInSydney, getSydneyTimestampMillis } from "@/utils/dateUtils.ts";
1213function generateZID(): string {
14// Generate two 4-character random parts from UUIDs
15const randomPart1 = crypto.randomUUID().slice(0, 4);
32* @returns Decoded ZID components or null if invalid
33*/
34export function decodeZID(encodedZid: string): {
35originalString: string;
36randomPart1: string;
72*
73* @param c - Hono context
74* @param next - Next middleware function
75*/
76export const zidTrackingMiddleware = async (
152* @returns Current ZID or null if not set
153*/
154export function getZID(c: Context<{ Variables: Variables }>): string | null {
155return c.get("zid") || null;
156}
161* @returns Request timing info or null if not available
162*/
163export function getRequestTiming(c: Context<{ Variables: Variables }>): {
164startTime: number;
165duration: number;
181* @param data - Additional log data
182*/
183export function logWithZID(
184{ c, level, message, data }: {
185c: Context<{ Variables: Variables }>;
api_ianmenethil_comsessionManager.ts3 matches
19*
20* @param c - Hono context with Variables type extension for session data
21* @param next - Next middleware function in the chain
22* @throws {Error} When session parsing fails or cookie operations encounter errors
23*/
148149/**
150* Configuration management functions for cookie session middleware
151*/
152162newConfig: Partial<CookieSessionConfig>,
163) => {
164// updateConfig functionality has been removed
165console.warn(
166"updateSessionConfig is called, but runtime config updates are currently disabled.",
api_ianmenethil_comreqQuery.ts2 matches
116*
117* @param c - Hono context object containing request and response data
118* @param next - Next middleware function in the Hono processing chain
119* @returns Promise<void> - Completes after validation check and next() execution
120*/
140/**
141* @param schemaName - Name of the validation schema to retrieve from available schemas
142* @returns Corresponding validator function for the specified schema type
143*/
144export const getQueryValidator = (schemaName: keyof typeof queryValidationSchemas) => {
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(