Skip to content

Commit

Permalink
Merge 4158d71 into 5cd76f5
Browse files Browse the repository at this point in the history
  • Loading branch information
ninoseki committed Mar 12, 2022
2 parents 5cd76f5 + 4158d71 commit b68d6b3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 28 deletions.
42 changes: 14 additions & 28 deletions src/index.ts
@@ -1,5 +1,5 @@
import escapeStringRegexp from "escape-string-regexp";
import { refang as _refang } from "ioc-extractor";
import { extractIPv4s, refang as _refang } from "ioc-extractor";
import { extractDomains } from "ioc-extractor";
import { dedup, sortByValue } from "ioc-extractor/dist/src/aux/auxiliary";

Expand Down Expand Up @@ -28,35 +28,20 @@ function replaceDotBeforeTLD(text: string): string {
return replaced.join("");
}

function matchesWithRegExp(s: string, regexp: RegExp): string[] {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const matched = s.match(regexp);
return matched === null ? [] : sortByValue(dedup(matched));
}

const getIPv4RegExpString = (): string => {
return "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\[?\\.]?){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
};

const getIPv4RegExp = (): RegExp => {
const ipv4 = getIPv4RegExpString();
return new RegExp(ipv4, "gi");
};
function defangIPs(text: string): string {
const chunks = text.split(" ");

function extractIPv4s(s: string): string[] {
const regexp = getIPv4RegExp();
return matchesWithRegExp(s, regexp);
}
const convertedChunks = chunks.map((chunk) => {
const refanged = refang(chunk);
const ipv4s = extractIPv4s(refanged);
if (ipv4s.length === 1) {
return replaceDot(refanged);
}

function defangIPs(text: string): string {
const ipv4s = extractIPv4s(text);
return chunk;
});

for (const ipv4 of ipv4s) {
const escaped = escapeStringRegexp(ipv4);
const regexp = new RegExp(escaped, "g");
text = text.replace(regexp, replaceDot(ipv4));
}
return text;
return convertedChunks.join(" ");
}

function defangDomains(text: string): string {
Expand All @@ -76,8 +61,9 @@ function defangHTTPSchemes(text: string): string {
}

export function defang(text: string): string {
text = defangHTTPSchemes(text);
text = defangIPs(text);
text = defangDomains(text);
text = defangHTTPSchemes(text);

return text;
}
1 change: 1 addition & 0 deletions src/spec/defang.spec.ts
Expand Up @@ -41,6 +41,7 @@ describe("defang", () => {
["1[.]1[.]1.1", "1[.]1.1.1"],
["test[] 1[.]1[.]1.1", "test[] 1[.]1.1.1"],
["test[.] 1[.]1[.]1.1", "test[.] 1[.]1.1.1"],
["test[.]com 1[.]1[.]1.1", "test[.]com 1[.]1.1.1"],
])(
"should adjust format even if it is already defanged",
(string, expected) => {
Expand Down

0 comments on commit b68d6b3

Please sign in to comment.