Compare commits

...

7 Commits

9 changed files with 441 additions and 329 deletions

231
Cargo.lock generated
View File

@ -18,7 +18,7 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"cipher 0.4.4",
"cpufeatures",
]
@ -195,7 +195,7 @@ dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if 1.0.0",
"cfg-if",
"constant_time_eq",
"digest 0.10.6",
]
@ -260,12 +260,6 @@ version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "cfg-if"
version = "1.0.0"
@ -278,7 +272,7 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c80e5460aa66fe3b91d40bcbdab953a597b60053e34d684ac6903f863b680a6"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"cipher 0.3.0",
"cpufeatures",
"zeroize",
@ -368,7 +362,7 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
]
[[package]]
@ -378,7 +372,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695"
dependencies = [
"autocfg 1.1.0",
"cfg-if 1.0.0",
"cfg-if",
"crossbeam-utils",
"memoffset",
"scopeguard",
@ -390,32 +384,7 @@ version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b"
dependencies = [
"cfg-if 1.0.0",
]
[[package]]
name = "crossterm"
version = "0.17.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f4919d60f26ae233e14233cc39746c8c8bb8cd7b05840ace83604917b51b6c7"
dependencies = [
"bitflags",
"crossterm_winapi",
"lazy_static",
"libc",
"mio 0.7.14",
"parking_lot 0.10.2",
"signal-hook",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2265c3f8e080075d9b6417aa72293fc71662f34b4af2612d8d1b074d29510db"
dependencies = [
"winapi",
"cfg-if",
]
[[package]]
@ -492,9 +461,9 @@ version = "5.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"hashbrown",
"lock_api 0.4.9",
"lock_api",
"once_cell",
"parking_lot_core 0.9.7",
]
@ -633,7 +602,7 @@ version = "0.8.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
]
[[package]]
@ -864,7 +833,7 @@ version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"js-sys",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
@ -877,7 +846,7 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"js-sys",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
@ -1038,7 +1007,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26ac735f676c52305becf53264b91cea9866a8de61ccbf464405b377b9cbca9"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"js-sys",
"uuid 0.8.2",
"wasm-bindgen",
@ -1073,7 +1042,7 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
@ -1156,15 +1125,6 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f"
[[package]]
name = "lock_api"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75"
dependencies = [
"scopeguard",
]
[[package]]
name = "lock_api"
version = "0.4.9"
@ -1181,7 +1141,7 @@ version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
]
[[package]]
@ -1399,19 +1359,6 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mio"
version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc"
dependencies = [
"libc",
"log",
"miow",
"ntapi",
"winapi",
]
[[package]]
name = "mio"
version = "0.8.6"
@ -1424,15 +1371,6 @@ dependencies = [
"windows-sys 0.45.0",
]
[[package]]
name = "miow"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21"
dependencies = [
"winapi",
]
[[package]]
name = "native-tls"
version = "0.2.11"
@ -1451,28 +1389,6 @@ dependencies = [
"tempfile",
]
[[package]]
name = "nix"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50e4785f2c3b7589a0d0c1dd60285e1188adac4006e8abd6dd578e1567027363"
dependencies = [
"bitflags",
"cc",
"cfg-if 0.1.10",
"libc",
"void",
]
[[package]]
name = "ntapi"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f"
dependencies = [
"winapi",
]
[[package]]
name = "num_cpus"
version = "1.15.0"
@ -1502,7 +1418,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e30d8bc91859781f0a943411186324d580f2bbeb71b452fe91ae344806af3f1"
dependencies = [
"bitflags",
"cfg-if 1.0.0",
"cfg-if",
"foreign-types",
"libc",
"once_cell",
@ -1539,16 +1455,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "parking_lot"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3a704eb390aafdc107b0e392f56a82b668e3a71366993b5340f5833fd62505e"
dependencies = [
"lock_api 0.3.4",
"parking_lot_core 0.7.3",
]
[[package]]
name = "parking_lot"
version = "0.11.2"
@ -1556,31 +1462,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api 0.4.9",
"lock_api",
"parking_lot_core 0.8.6",
]
[[package]]
name = "parking_lot_core"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b93f386bb233083c799e6e642a9d73db98c24a5deeb95ffc85bf281255dffc98"
dependencies = [
"cfg-if 0.1.10",
"cloudabi",
"libc",
"redox_syscall 0.1.57",
"smallvec",
"winapi",
]
[[package]]
name = "parking_lot_core"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"instant",
"libc",
"redox_syscall 0.2.16",
@ -1594,7 +1486,7 @@ version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"libc",
"redox_syscall 0.2.16",
"smallvec",
@ -1950,12 +1842,6 @@ dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "redox_syscall"
version = "0.1.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce"
[[package]]
name = "redox_syscall"
version = "0.2.16"
@ -2039,6 +1925,27 @@ dependencies = [
"winreg",
]
[[package]]
name = "rpassword"
version = "7.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6678cf63ab3491898c0d021b493c94c9b221d91295294a2a5746eacbe5928322"
dependencies = [
"libc",
"rtoolbox",
"winapi",
]
[[package]]
name = "rtoolbox"
version = "0.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "034e22c514f5c0cb8a10ff341b9b048b5ceb21591f31c8f44c43b960f9b3524a"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "ruma"
version = "0.7.4"
@ -2160,7 +2067,7 @@ checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"
[[package]]
name = "scam-police"
version = "0.3.0"
version = "0.5.0"
dependencies = [
"anyhow",
"dirs",
@ -2168,25 +2075,13 @@ dependencies = [
"once_cell",
"rand 0.8.5",
"reqwest",
"scanpw",
"rpassword",
"serde",
"serde_json",
"tokio",
"url",
]
[[package]]
name = "scanpw"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80f65c5c067e5eb335001a5f5f659fa3c0f75f3b90e1ccdd697570d9027242c5"
dependencies = [
"cfg-if 0.1.10",
"crossterm",
"nix",
"winapi",
]
[[package]]
name = "schannel"
version = "0.1.21"
@ -2284,7 +2179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800"
dependencies = [
"block-buffer 0.9.0",
"cfg-if 1.0.0",
"cfg-if",
"cpufeatures",
"digest 0.9.0",
"opaque-debug",
@ -2296,31 +2191,11 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"cpufeatures",
"digest 0.10.6",
]
[[package]]
name = "signal-hook"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e31d442c16f047a671b5a71e2161d6e68814012b7f5379d269ebd915fac2729"
dependencies = [
"libc",
"mio 0.7.14",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
dependencies = [
"libc",
]
[[package]]
name = "signature"
version = "1.6.4"
@ -2349,7 +2224,7 @@ dependencies = [
"fxhash",
"libc",
"log",
"parking_lot 0.11.2",
"parking_lot",
]
[[package]]
@ -2428,7 +2303,7 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"fastrand",
"redox_syscall 0.3.5",
"rustix",
@ -2479,7 +2354,7 @@ dependencies = [
"autocfg 1.1.0",
"bytes",
"libc",
"mio 0.8.6",
"mio",
"num_cpus",
"pin-project-lite",
"socket2",
@ -2560,7 +2435,7 @@ version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
@ -2711,12 +2586,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]]
name = "want"
version = "0.3.0"
@ -2745,7 +2614,7 @@ version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"serde",
"serde_json",
"wasm-bindgen-macro",
@ -2772,7 +2641,7 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454"
dependencies = [
"cfg-if 1.0.0",
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
@ -2815,7 +2684,7 @@ checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f"
dependencies = [
"futures",
"js-sys",
"parking_lot 0.11.2",
"parking_lot",
"pin-utils",
"wasm-bindgen",
"wasm-bindgen-futures",

View File

@ -1,6 +1,6 @@
[package]
name = "scam-police"
version = "0.3.0"
version = "0.5.0"
edition = "2021"
authors = [ "@0xf8:projectsegfau.lt", "@jjj333:pain.agency" ]
@ -13,7 +13,7 @@ matrix-sdk = "0.6.2"
once_cell = "1.17.1"
rand = "0.8.5"
reqwest = "0.11.16"
scanpw = "0.1.0"
rpassword = "7.2.0"
serde = "1.0.160"
serde_json = "1.0.95"
tokio = { version = "1.27.0", features = ["macros", "rt-multi-thread"] }

View File

@ -1,5 +1,5 @@
{
"scams":{
"keywords":{
"verbs":[
"earn",
"make", "making", "made",
@ -9,11 +9,13 @@
"cashout",
"sell",
"get",
"pay",
"sex",
"meet",
"upload",
"login",
"send",
"join",
"buy",
"check",
"private"
@ -27,13 +29,15 @@
"paypal",
"bitcoin", "btc",
"etherium", " eth",
"usd",
"nft",
"token",
"free",
"meet",
"upload",
"gift",
"card",
"nude",
"18+"
"18+",
"pay"
],
"socials":[
"l.wl.co/",
@ -43,6 +47,9 @@
"matrix.to/",
"wa.me/",
"t.me/",
"cash.app",
"cash app",
"cashapp",
"discord.gg/",
"discord",
"is.gd/",
@ -51,10 +58,9 @@
"wickr",
"kik",
"instagram",
"dm me",
"👇", "👆️",
"+1", "+2"
],
"response":"Warning! This message is likely to be a scam, hoping to lure you in and steal your money. Please visit [ https://www.sec.gov/oiea/investor-alerts-and-bulletins/digital-asset-and-crypto-investment-scams-investor-alert ] for more information. [!mods !modhelp]",
"response_md":"Warning! This message is likely to be a <b>scam</b>, hoping to lure you in and steal your money! Please visit <a href=\"https://www.sec.gov/oiea/investor-alerts-and-bulletins/digital-asset-and-crypto-investment-scams-investor-alert\">here</a> for more information. [!mods !modhelp]"
]
}
}

18
config/responses.json Normal file
View File

@ -0,0 +1,18 @@
{
"reply": {
"Ok": null,
"MaybeScam": null,
"LikelyScam": {
"plain": "Watch out, the message you replied to has been detected as a scam! Please don't do anything they ask you to do! Stay safe",
"html": "Watch out, the message you replied to has been detected as a <b>scam</b>! <u>Please don't do anything they ask you to do</u>! Stay safe"
}
},
"message": {
"Ok": null,
"MaybeScam": null,
"LikelyScam": {
"plain": "Warning! This message is likely to be a scam, seeking to lure you in and steal your money! Please visit these resources for more information:\n- https://www.sec.gov/oiea/investor-alerts-and-bulletins/digital-asset-and-crypto-investment-scams-investor-alert \n [!mods !modhelp]",
"html": "Warning! This message is likely to be a <b>scam</b>, seeking to lure you in and steal your money! Please visit these resources for more information: <ul><li><a href=\"https://www.sec.gov/oiea/investor-alerts-and-bulletins/digital-asset-and-crypto-investment-scams-investor-alert\">https://www.sec.gov/oiea/investor-alerts-and-bulletins/digital-asset-and-crypto-investment-scams-investor-alert</a></li></ul> [!mods !modhelp]"
}
}
}

View File

@ -2,15 +2,24 @@ use serde_json::Value;
pub struct Config {
pub keywords: Value,
pub responses: Value,
}
impl Config {
pub fn load() -> Config {
let keywords_reader = std::fs::File::open("config/keywords.json").expect("Couldn't find keywords.json");
let keywords: Value = serde_json::from_reader(keywords_reader).expect("Couldn't read keywords.json");
let keywords_reader =
std::fs::File::open("config/keywords.json").expect("Couldn't find keywords.json");
let keywords: Value =
serde_json::from_reader(keywords_reader).expect("Couldn't read keywords");
let responses_reader =
std::fs::File::open("config/responses.json").expect("Couldn't find responses.json");
let responses: Value =
serde_json::from_reader(responses_reader).expect("Couldn't read responses");
Self {
keywords
keywords,
responses,
}
}
}
}

165
src/judge.rs Normal file
View File

@ -0,0 +1,165 @@
use crate::{
keywords::{KeywordCategory, Keywords},
CONFIG,
};
use matrix_sdk::{
room::Joined,
ruma::events::room::message::{OriginalRoomMessageEvent, RoomMessageEventContent},
};
use serde_json::json;
#[derive(Debug)]
pub enum JudgementResult {
Ok,
MaybeScam, // hit atleast one category
LikelyScam, // hit all categories
}
impl JudgementResult {
pub fn to_json_var(&self) -> &str {
match self {
Self::Ok => "Ok",
Self::MaybeScam => "MaybeScam",
Self::LikelyScam => "LikelyScam",
}
}
}
pub struct Judgement {
pub text: String,
}
impl Judgement {
pub fn judge(&self) -> anyhow::Result<JudgementResult> {
// Load keywords
let mut keywords = CONFIG.keywords.clone();
let keywords = keywords
.as_object_mut()
.unwrap()
.get_mut("keywords")
.unwrap();
// Turn json into Keywords
let verbs = Keywords::create("verbs", &keywords["verbs"]);
let currencies = Keywords::create("currencies", &keywords["currencies"]);
let socials = Keywords::create("socials", &keywords["socials"]);
// Count occurences
let mut counter = KeywordCategory::create_counter_map();
counter.insert(KeywordCategory::Verb, verbs.find(&self.text));
counter.insert(KeywordCategory::Currency, currencies.find(&self.text));
counter.insert(KeywordCategory::Social, socials.find(&self.text));
let mut count_all = 0;
let total = counter.len();
for (_category, count) in counter.to_owned() {
if count > 0 {
count_all = count_all + 1;
}
}
if count_all == 0 {
return Ok(JudgementResult::Ok);
};
if count_all < total {
return Ok(JudgementResult::MaybeScam);
};
Ok(JudgementResult::LikelyScam)
}
pub async fn send_debug(&self, room: &Joined) -> anyhow::Result<()> {
// Load keywords
let mut keywords = CONFIG.keywords.clone();
let keywords = keywords
.as_object_mut()
.unwrap()
.get_mut("keywords")
.unwrap();
// Turn json into Keywords
let verbs = Keywords::create("verbs", &keywords["verbs"]);
let currencies = Keywords::create("currencies", &keywords["currencies"]);
let socials = Keywords::create("socials", &keywords["socials"]);
// Count occurences
let mut counter = KeywordCategory::create_counter_map();
counter.insert(KeywordCategory::Verb, verbs.find(&self.text));
counter.insert(KeywordCategory::Currency, currencies.find(&self.text));
counter.insert(KeywordCategory::Social, socials.find(&self.text));
let mut count_all = 0;
let total = counter.len();
for (_category, count) in counter.to_owned() {
if count > 0 {
count_all = count_all + 1;
}
}
let mut result = JudgementResult::LikelyScam;
if count_all == 0 {
result = JudgementResult::Ok
}
if count_all < total {
result = JudgementResult::MaybeScam
}
// Send message
let msg = RoomMessageEventContent::text_html(
format!("{counter:?}, {count_all}/{total}, {result:?}"),
format!("<code>{counter:?}</code><br>Categories covered: <code>{count_all}/{total}</code><br>Verdict: <code>{result:?}</code>"));
room.send(msg, None).await.expect("Couldn't send message");
Ok(())
}
pub async fn alert(
room: &Joined,
event: &OriginalRoomMessageEvent,
result: JudgementResult,
is_reply: bool,
) -> anyhow::Result<()> {
let mut responses = CONFIG.responses.clone();
let responses = responses.as_object_mut().unwrap();
// Determine which message to send
let section = if is_reply {
responses["reply"].as_object().unwrap()
} else {
responses["message"].as_object().unwrap()
};
let response_type = section.get(result.to_json_var()).unwrap();
if response_type.is_null() {
anyhow::bail!("Called alert with result that has no detection message");
}
let response_type = response_type.as_object().unwrap();
let plain = response_type["plain"].as_str().unwrap();
let html = response_type["html"].as_str().unwrap();
// Send message
let msg = RoomMessageEventContent::text_html(plain, html);
room.send(msg, None).await.expect("Couldn't send message");
// Todo: Add room config?
// let reply = msg.make_reply_to(event);
// room.send(reply, None).await.expect("Couldn't send message");
// Send reaction
if !is_reply {
room.send_raw(
json!({
"m.relates_to": {
"rel_type": "m.annotation",
"event_id": event.event_id.to_string(),
"key": "🚨🚨 SCAM 🚨🚨"
}}),
"m.reaction",
None,
)
.await
.expect("Couldn't send reaction");
}
Ok(())
}
}

View File

@ -10,54 +10,52 @@ pub enum KeywordCategory {
impl std::fmt::Display for KeywordCategory {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use KeywordCategory::*;
match self {
Verb => write!(f, "Verb"),
Verb => write!(f, "Verb"),
Currency => write!(f, "Currency"),
Social => write!(f, "Social"),
Social => write!(f, "Social"),
}
}
}
impl KeywordCategory {
pub fn to_json_var(&self) -> &str {
use KeywordCategory::*;
match self {
Verb => "verbs",
Verb => "verbs",
Currency => "currencies",
Social => "socials",
Social => "socials",
}
}
pub fn from_json_var(var: &str) -> Result<Self,()> {
pub fn from_json_var(var: &str) -> Result<Self, ()> {
use KeywordCategory::*;
match var {
"verbs" => Ok(Verb),
"verbs" => Ok(Verb),
"currencies" => Ok(Currency),
"socials" => Ok(Social),
_ => Err(())
"socials" => Ok(Social),
_ => Err(()),
}
}
pub fn create_counter_map() -> HashMap<KeywordCategory,u64> {
pub fn create_counter_map() -> HashMap<KeywordCategory, u64> {
use KeywordCategory::*;
let mut map: HashMap<KeywordCategory,u64> = HashMap::new();
let mut map: HashMap<KeywordCategory, u64> = HashMap::new();
map.insert(Verb, 0);
map.insert(Currency, 0);
map.insert(Social, 0);
map
}
}
pub struct Keywords {
pub category: KeywordCategory,
pub words: Vec<Value>
pub words: Vec<Value>,
}
impl Keywords {
@ -66,24 +64,24 @@ impl Keywords {
let Ok(category) = KeywordCategory::from_json_var(name) else {
panic!("Couldn't translate \"{name}\" to KeywordCategory");
};
Self {
category,
words: v.to_vec()
words: v.to_vec(),
}
}
pub fn find(&self, hay: &str) -> u64 {
let mut hits: u64 = 0;
for kw in self.words.to_owned().into_iter() {
let kw = kw.as_str().unwrap();
if hay.contains(kw) {
hits += 1
}
}
hits
}
}
}

View File

@ -1,86 +1,126 @@
use matrix_sdk::{
room::Room,
ruma::{events::room::message::{
MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent, Relation
}, OwnedRoomId},
ruma::{
events::room::message::{
MessageType, OriginalSyncRoomMessageEvent, Relation, RoomMessageEvent,
},
OwnedRoomId,
},
Error, LoopCtrl,
};
use once_cell::sync::Lazy;
use serde_json::json;
pub mod matrix;
pub mod config;
pub mod judge;
pub mod keywords;
pub mod matrix;
static CONFIG: Lazy<config::Config> = Lazy::new(|| config::Config::load());
async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) -> anyhow::Result<()> {
if let Room::Joined(room) = room {
let orig_event = event.to_owned().into_full_event(OwnedRoomId::from(room.room_id()));
let orig_event = event
.to_owned()
.into_full_event(OwnedRoomId::from(room.room_id()));
// Ignore non-text
let MessageType::Text(text_content) = event.to_owned().content.msgtype else {
return;
return Ok(());
};
// Too short to be a scam lol
if text_content.body.chars().count() < 12 {
return Ok(());
}
let text_content = text_content.body.to_lowercase();
let debug = text_content.contains(";spdebug");
// Ignore own messages
if event.sender == room.client().user_id().expect("Couldn't get user_id").to_string() { return }
// Ignore replies
if !debug
&& event.sender
== room
.client()
.user_id()
.expect("Couldn't get user_id")
.to_string()
{
return Ok(());
}
let judgement = judge::Judgement { text: text_content };
// Handle replies
if let Some(relation) = orig_event.to_owned().content.relates_to {
if match relation {
Relation::Reply { in_reply_to: _ } => true,
_ => false
if let Some(event) = match relation {
Relation::Reply { in_reply_to } => {
let replied_event = room.event(&in_reply_to.event_id).await?;
let t = replied_event.event.get_field::<&str>("type")?;
if t.as_deref() == Some("m.room.message") {
let event = replied_event.event.deserialize_as::<RoomMessageEvent>()?;
Some(event.to_owned())
} else {
None
}
}
_ => None,
} {
return
let event = event.as_original().unwrap();
let content = event.content.to_owned().body().to_lowercase();
if !debug
&& event.sender
== room
.client()
.user_id()
.expect("Couldn't get user_id")
.to_string()
{
return Ok(());
}
let reply_judgement = judge::Judgement { text: content };
if debug {
reply_judgement.send_debug(&room).await?;
return Ok(());
}
match reply_judgement.judge()? {
judge::JudgementResult::Ok => (),
judge::JudgementResult::MaybeScam => (),
judge::JudgementResult::LikelyScam => {
judge::Judgement::alert(
&room,
&orig_event,
judge::JudgementResult::LikelyScam,
true,
)
.await?;
return Ok(());
}
}
}
}
// Too short to be a scam lol
if text_content.body.chars().count() < 12 { return }
let text_content = text_content.body.to_lowercase();
// Load keywords
let mut keywords = CONFIG.keywords.clone();
let scams = keywords.as_object_mut().unwrap().get_mut("scams").unwrap();
// Turn json into Keywords
let verbs = keywords::Keywords::create("verbs", &scams["verbs"]);
let currencies = keywords::Keywords::create("currencies", &scams["currencies"]);
let socials = keywords::Keywords::create("socials", &scams["socials"]);
// Count occurences
let mut counter = keywords::KeywordCategory::create_counter_map();
counter.insert(keywords::KeywordCategory::Verb, verbs.find(&text_content));
counter.insert(keywords::KeywordCategory::Currency, currencies.find(&text_content));
counter.insert(keywords::KeywordCategory::Social, socials.find(&text_content));
// Test if every category has atleast one hit
let mut hit_all = true;
for (_category, count) in counter.to_owned() {
hit_all = hit_all && count != 0;
}
if hit_all {
// Add stats to end of response
let response = format!("{}\nDetection stats: {:?}", scams["response"].as_str().unwrap(), counter.to_owned());
let response_html = format!("{}<br>Detection stats: <code>{:?}</code>", scams["response_md"].as_str().unwrap(), counter.to_owned());
// Send message
let msg = RoomMessageEventContent::text_html(response, response_html);
let reply = msg.make_reply_to(&orig_event);
room.send(reply, None).await.expect("Couldn't send message");
// Send reaction
room.send_raw(json!({
"m.relates_to": {
"rel_type": "m.annotation",
"event_id": orig_event.event_id.to_string(),
"key": "🚨🚨 SCAM 🚨🚨"
}}), "m.reaction", None).await.expect("Couldn't send reaction");
match judgement.judge()? {
judge::JudgementResult::Ok => return Ok(()),
judge::JudgementResult::MaybeScam => return Ok(()),
judge::JudgementResult::LikelyScam => {
judge::Judgement::alert(
&room,
&orig_event,
judge::JudgementResult::LikelyScam,
false,
)
.await?;
return Ok(());
}
}
}
Ok(())
}
#[tokio::main]
@ -95,9 +135,15 @@ async fn main() -> anyhow::Result<()> {
let (client, sync_token) = if session_file.exists() {
matrix::restore_session(&session_file).await?
} else if args.len() > 1 {
(matrix::login(&data_dir, &session_file, args.get(1).unwrap().to_owned()).await?, None)
(
matrix::login(&data_dir, &session_file, args.get(1).unwrap().to_owned()).await?,
None,
)
} else {
anyhow::bail!("No previous session found, please run \"{} <MXID>\"", args.get(0).unwrap());
anyhow::bail!(
"No previous session found, please run \"{} <MXID>\"",
args.get(0).unwrap()
);
};
let (client, sync_settings) = match matrix::sync(client, sync_token).await {
@ -110,15 +156,17 @@ async fn main() -> anyhow::Result<()> {
client.add_event_handler(on_room_message);
client.sync_with_result_callback(sync_settings, |sync_result| async move {
let response = sync_result?;
client
.sync_with_result_callback(sync_settings, |sync_result| async move {
let response = sync_result?;
matrix::persist_sync_token(response.next_batch)
matrix::persist_sync_token(response.next_batch)
.await
.map_err(|err| Error::UnknownError(err.into()))?;
Ok(LoopCtrl::Continue)
}).await?;
Ok(LoopCtrl::Continue)
})
.await?;
Ok(())
}

View File

@ -1,12 +1,12 @@
use matrix_sdk::{
config::SyncSettings, ruma::api::client::filter::FilterDefinition, Client, Session
config::SyncSettings, ruma::api::client::filter::FilterDefinition, Client, Session,
};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use serde::{Deserialize, Serialize};
use serde_json::{Value, from_str};
use std::path::{Path, PathBuf};
use reqwest::Client as http;
use scanpw::scanpw;
use rpassword::prompt_password;
use serde::{Deserialize, Serialize};
use serde_json::{from_str, Value};
use std::path::{Path, PathBuf};
use tokio::fs;
#[derive(Debug, Serialize, Deserialize)]
@ -24,7 +24,6 @@ pub struct FullSession {
sync_token: Option<String>,
}
//
// Matrix Login & Init
//
@ -36,7 +35,7 @@ pub async fn login(data_dir: &Path, session_file: &Path, mxid: String) -> anyhow
let (client, client_session) = build_client(data_dir, hs).await?;
loop {
let password = scanpw!("Password\n> ");
let password = prompt_password("Password\n> ")?;
match client
.login_username(&user, &password)
@ -84,33 +83,33 @@ pub async fn build_client(data_dir: &Path, hs: String) -> anyhow::Result<(Client
.collect();
match Client::builder()
.homeserver_url(&hs)
.sled_store(&db_path, Some(&passphrase))?
.build()
.await
{
Ok(client) => {
println!("[*] Homeserver OK");
return Ok((
client,
ClientSession {
homeserver: hs,
db_path,
passphrase,
},
))
}
Err(error) => match &error {
matrix_sdk::ClientBuildError::AutoDiscovery(_)
| matrix_sdk::ClientBuildError::Url(_)
| matrix_sdk::ClientBuildError::Http(_) => {
anyhow::bail!("[!] {error:?}");
}
_ => {
return Err(error.into());
}
},
.homeserver_url(&hs)
.sled_store(&db_path, Some(&passphrase))?
.build()
.await
{
Ok(client) => {
println!("[*] Homeserver OK");
return Ok((
client,
ClientSession {
homeserver: hs,
db_path,
passphrase,
},
));
}
Err(error) => match &error {
matrix_sdk::ClientBuildError::AutoDiscovery(_)
| matrix_sdk::ClientBuildError::Url(_)
| matrix_sdk::ClientBuildError::Http(_) => {
anyhow::bail!("[!] {error:?}");
}
_ => {
return Err(error.into());
}
},
}
}
//
@ -141,7 +140,10 @@ pub async fn resolve_homeserver(homeserver: String) -> anyhow::Result<String> {
hs.pop();
}
let ident = http::new().get(format!("{hs}/.well-known/matrix/client")).send().await;
let ident = http::new()
.get(format!("{hs}/.well-known/matrix/client"))
.send()
.await;
match ident {
Ok(r) => {
let body = r.text().await?;
@ -150,14 +152,11 @@ pub async fn resolve_homeserver(homeserver: String) -> anyhow::Result<String> {
let discovered = json["m.homeserver"]["base_url"].as_str().unwrap();
Ok(discovered.to_string())
},
Err(e) => {
Err(e.into())
}
Err(e) => Err(e.into()),
}
}
//
// Persistence
//
@ -233,4 +232,4 @@ pub async fn restore_session(session_file: &Path) -> anyhow::Result<(Client, Opt
client.restore_login(user_session).await?;
Ok((client, sync_token))
}
}