Saltearse al contenido

Spam Filter Tutorial

Esta página aún no está disponible en tu idioma.

Spam Filter is an exciting new feature of ALTCHA’s security stack that allows you to classify data, effectively eliminating spam from your forms.

To learn more about the Spam Filter, refer to the Spam Filter documentation.

In this tutorial, we’ll explore different methods of integrating the Spam Filter into your website.

We’ll use Astro as our framework of choice, assuming basic familiarity with the Astro tutorial.

How Does the Spam Filter Work?

The Spam Filter employs natural language processing and machine learning techniques to analyze data and determine whether it qualifies as spam or not. In addition to inspecting text content, the Spam Filter conducts assessments on provided email addresses and user IP addresses.

When activated within the widget, the Spam Filter processes data client-side through ALTCHA’s API before the form submission occurs. This proactive approach empowers users by providing insights into why their message might be classified as spam, enabling them to refine their message accordingly. Moreover, this methodology streamlines integration, mitigating the need for HTTP requests from your server. Consequently, it reduces network latency and minimizes potential issues stemming from network connectivity.

Create an API Key

To access the API, obtain a new API key, which you can create for free.

Enable the Spam Filter

To enable the Spam Filter with the widget, add the spamfilter attribute to the <altcha-widget> tag:

src/pages/index.astro
<altcha-widget
challengeurl={`https://eu.altcha.org/api/v1/challenge?apiKey=${ALTCHA_API_KEY}`}
spamfilter
></altcha-widget>

Field Auto-Detection

The widget automatically identifies the email field (input[type="email"]) and all textual fields (input[type="text"], textarea") and forwards their values for classification. You can opt to exclude specific fields from classification by appending the data-no-spamfilter attribute to those fields.

Alternatively, you can explicitly define which fields to submit for classification using the fields configuration property. Refer to the Spam Filter configuration for more details.

Update Server Verification

With spamfilter enabled, the widget sends a different payload format. The new payload contains additional information about the classification result.

To adjust the server verification, make the following changes in the file from the Astro tutorial:

src/pages/index.astro
---
import { verifySolution } from "altcha-lib";
import { verifyServerSignature } from "altcha-lib";
const ALTCHA_API_KEY = "ckey_...";
const ALTCHA_API_SECRET = "csec_...";
if (Astro.request.method === "POST") {
try {
const data = await Astro.request.formData();
const altchaPayload = data.get("altcha")?.toString();
if (!altchaPayload) {
throw new Error("Altcha payload missing.");
}
if (await verifySolution(altchaPayload, ALTCHA_API_SECRET)) {
const { verificationData, verified } = await verifyServerSignature(altchaPayload, ALTCHA_API_SECRET);
if (verified) {
console.log('Verification successful', Object.fromEntries(data))
// TODO: process data
} else {
console.log('Verification failed')
// TODO: report failure to user
}
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
}
---

The change consists of replacing the verifySolution function with the verifyServerSignature function, which returns an object containing:

  • verificationData - (object) The additional classification data
  • verified - (boolean) Whether the payload has been verified

For more information, refer to the server verification documentation.

This approach allows form submission even if the data is classified as spam. It is up to you and your server implementation to decide how to handle spam.

A recommended way to handle data classified as spam is to accept it and label it as “spam” for later review.

You also have the option to prevent form submission when spam is detected. See below.

Block Spam Submissions

To prevent spam submissions on the client, add the blockspam attribute to the widget.

src/pages/index.astro
<altcha-widget
challengeurl={`https://eu.altcha.org/api/v1/challenge?apiKey=${ALTCHA_API_KEY}`}
spamfilter
blockspam
></altcha-widget>

This will effectively prevent form submission when the classification detects spam. You should still check the payload and verify the signature on your server.

Improve the User Experience

When using the blockspam attribute, it may be a good idea to inform the user why their data was classified as spam. Reporting the reasons for the negative classification helps end-users correct their submission.

To capture the classification result, add an event listener to the widget to listen for the serververification event:

src/pages/index.astro
<script>
import("altcha").then(() => {
const el = document.querySelector("altcha-widget");
if (el) {
el.addEventListener("serververification", (event) => {
const result = (event as CustomEvent).detail;
console.log("Classification:", result.classification);
console.log("Reasons:", result.reasons);
if (result.classification === 'BAD') {
alert(
"Sorry! We cannot submit your message, because we think it is spam." +
"\n\nReasons:\n" +
result.reasons.map((reason: string) => "- " + reason).join("\n")
);
}
});
}
});
</script>

The example above shows a message listing reasons why the message was classified as spam. Your app should translate the reasons and provide guidance for fixing issues when possible.

The reasons will be in formats like: text.PROFANITY, email.MX, ipAddress.TOR, etc. See the complete list of scoring rules.

Configuring the Spam Filter

The Spam Filter allows you to customize various features, such as expected or blocked countries, preferred languages of the text, or disabled rules. To configure the spam filter, use the configure method:

src/pages/index.astro
<script>
import("altcha").then(() => {
const el = document.querySelector("altcha-widget");
if (el) {
el.configure({
spamfilter: {
blockedCountries: ["af", "kp"],
disableRules: ["text.PROFANITY"],
expectedCountries: ["gb", "de", "fr"],
expectedLanguages: ["en", "de", "fr"],
},
});
}
});
</script>

Utilizing the API

Another approach to working with the Spam Filter is by accessing the HTTP API directly from your server (POST /api/v1/classify endpoint). This method enables you to check for spam after the user submits the form and classify incoming data server-side.

For more details, consult the API Reference.

const resp = await fetch(`https://eu.altcha.org/api/v1/classify?apiKey=${ALTCHA_API_KEY}`, {
body: JSON.stringify({
text: 'Text to classify...',
}),
headers: {
'content-type': 'application/json',
},
method: 'POST',
});
const result = await resp.json();

That’s All!

Using the Spam Filter makes protecting against spam and unwanted content easy and effective. Learn more about all of the Spam Filter’s features.

For a complete working example, refer to the repository.