Skip to content

Commit

Permalink
Encoder/Decoder URL safety fix
Browse files Browse the repository at this point in the history
  • Loading branch information
ghluka committed Apr 27, 2024
1 parent b9b72a6 commit 89f29ef
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
12 changes: 10 additions & 2 deletions techdemos/encode/js/encoders/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,35 @@ function encodeURIAggressive(text) {
return encoded_text;
}

var safe_keys = {"!": "%21", "#": "%23", "$": "%24", "%": "%25", "&": "%26", "'": "%27", "(": "%28", ")": "%29", "*": "%2A", "+": "%2B", ",": "%2C", "-": "%2D", ".": "%2E", "/": "%2F", "=": "%3D", ":": "%3A", ";": "%3B", "=": "%3D", "?": "%3F", "@": "%40"};

function encodeURINonDestructive(text) {
var encoded_text = encodeURIAggressive(text);

// protocol
if (encoded_text.includes("%3A%2F%2F")) {
encoded_text = encoded_text.replace("%3A%2F%2F", "://");
const protocol = decodeURI(encoded_text.split("://")[0])
encoded_text = protocol + "://" + encoded_text.split("://")[1];
}

encoded_text = encoded_text.replaceAll("%2F", "/").replaceAll("%3F", "?").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%3D", "=");
for (const [key, value] of Object.entries(safe_keys)) {
encoded_text = encoded_text.replaceAll(value, key);
}

return encoded_text;
}

function decodeURINonDestructive(text) {
// protocol
if (text.includes("://")) {
const protocol = encodeURIAggressive(text.split("://")[0]);
text = protocol + "%3A%2F%2F" + text.split("://")[1];
}

text = text.replaceAll("/", "%2F").replaceAll("?", "%3F").replaceAll("&", "%26").replaceAll("+", "%2B").replaceAll("=", "%3D");
for (const [key, value] of Object.entries(safe_keys)) {
text = text.replaceAll(key, value);
}

return decodeURIComponent(decodeURI(text));
}
Expand Down
6 changes: 3 additions & 3 deletions techdemos/encode/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ const codes = {
encode: encodeURI,
decode: decodeURI
},
"URL (component)": {
"URL (Component)": {
encode: encodeURIComponent,
decode: decodeURIComponent
},
"URL (aggressive)": {
"URL (Aggressive)": {
encode: encodeURIAggressive,
decode: text => decodeURIComponent(decodeURI(text))
},
"URL (aggressive, non destructive)": {
"URL (Aggressive, non destructive)": {
encode: encodeURINonDestructive,
decode: decodeURINonDestructive
},
Expand Down

0 comments on commit 89f29ef

Please sign in to comment.