Skip to content

Commit

Permalink
Payload limits validation added
Browse files Browse the repository at this point in the history
  • Loading branch information
RNEvok committed Jan 23, 2024
1 parent f6d9f9e commit b8b9eb5
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ const CONFIG_INNER = {
"PRODUCTION": true,
"DEVELOPMENT": true
}
},
PAYLOAD_LIMITS: {
MAX_KB_SIZE: 512,
MAX_BYTE_SIZE: 524288, // 512 Kb * 1024 (byte / Kb)
MIN_STRING_LENGTH_POSSIBLE_OVERLOAD: 131072 // MAX_BYTE_SIZE / 4
}
};

Expand Down
11 changes: 10 additions & 1 deletion helpers/helperFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CONFIG } from "../config";
import { ObjectT } from "../types";
import { payloadSizeValidator } from "./payloadSizeValidator";

export function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
Expand Down Expand Up @@ -71,7 +72,7 @@ export const getFormDataMeta = (fData: FormData) => {

// Custom JSON.stringify wrapper that keeps as much metadata as possible
export const jsonStringifyKeepMeta = (data: ObjectT<any>) => {
return JSON.stringify(
const dataStringified = JSON.stringify(
data,
function(key, value) {
const type = typeof value;
Expand All @@ -86,4 +87,12 @@ export const jsonStringifyKeepMeta = (data: ObjectT<any>) => {
}
}
);

if (payloadSizeValidator(dataStringified))
return dataStringified;

const message = `Payload data was skipped (${CONFIG.PAYLOAD_LIMITS.MAX_KB_SIZE} Kb limit exceeded)`;
codebudConsoleWarn(message);

return JSON.stringify({message});
}
27 changes: 27 additions & 0 deletions helpers/payloadSizeValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CONFIG } from "../config";

// returns the byte length of an utf8 string
const byteLength = (str: string) => {
var s = str.length;

for (var i = str.length - 1; i >= 0; i--) {
var code = str.charCodeAt(i);

if (code > 0x7f && code <= 0x7ff)
s++;
else if (code > 0x7ff && code <= 0xffff)
s += 2;
if (code >= 0xDC00 && code <= 0xDFFF)
i--; //trail surrogate
}

return s;
}

// Returns true if str byte size is ok, and false otherwise
export const payloadSizeValidator = (str: string) => {
if (str.length < CONFIG.PAYLOAD_LIMITS.MIN_STRING_LENGTH_POSSIBLE_OVERLOAD)
return true;

return byteLength(str) <= CONFIG.PAYLOAD_LIMITS.MAX_BYTE_SIZE;
}

0 comments on commit b8b9eb5

Please sign in to comment.