Giter Site home page Giter Site logo

nostr-filter's Introduction

Introduction

Nostr-filter is a user-friendly filtering program designed to improve the management of your Nostr relay server. This program enables you to easily filter out undesired events, block specific users, and limit access from certain IP addresses or ranges. By employing regular expressions for content filtering, a list of public keys for user blocking, and a list of CIDR notations for IP address filtering, you can effortlessly tailor the settings to your preferences and ensure a smooth and optimized experience for your Nostr relay users.

Installation

To run nostr-filter, you need to have Docker and Docker Compose installed.

  1. Clone this repository.

Change directory to the cloned repository.

cd nostr-filter/
  1. Build the Docker image.
docker compose build
  1. Start the Docker container.
docker compose up -d

Configuration

In the .env file, you can configure the following options:

LISTEN_PORT=8081
UPSTREAM_HTTP_URL=http://192.168.1.1:8080
UPSTREAM_WS_URL=ws://192.168.1.1:8080

In the filter.ts file, you can configure the following options:

  1. Content Filters contentFilters is an array of regular expression patterns used to filter Nostr event contents. To add a new filtering pattern, simply add a new regular expression pattern to the array. For example:
const contentFilters: RegExp[] = [
  /avive/i,
  /web3/i,
  /lnbc/,
  // Add more patterns below
];
  1. Blocked Public Keys blockedPubkeys is an array of public keys that represent users you wish to block. To block a user, add their public key to the array. For example:
const blockedPubkeys: string[] = [
  "examplePublicKey1",
  "examplePublicKey2",
  // Add more public keys to block below
];
  1. Client IP Address CIDR Filters cidrRanges is an array of CIDR notations representing IP addresses or ranges that you want to filter. To add a new CIDR filter, simply add the IP address or range to the array. For example:
const cidrRanges: string[] = [
  "1.2.3.4/32",
  "5.67.89.101/32",
  // Add more IP addresses or ranges below
];

Once you have configured the settings according to your needs, the script will filter Nostr event contents, block users, and filter client IP addresses based on your defined patterns and lists.

Usage

To use nostr-filter, you need a Nostr client that sends messages to the WebSocket server. You can connect to the Nostr relay using the URL ws://<server_address>:<listen_port>.

Contributing

We welcome contributions from the community. If you would like to contribute to nostr-filter, please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your changes.
  3. Make your changes and commit them to your branch.
  4. Submit a pull request with a description of your changes.

Please make sure to follow the code style and conventions used in the project. If you have any questions or need help, feel free to open an issue.

License

nostr-filter is licensed under the MIT License.

nostr-filter's People

Contributors

atrifat avatar imksoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nostr-filter's Issues

Better error handling for invalid JSON request

There is an edge case whenever nostr-filter proxy relay accept invalid JSON request. It will crash the program immediately since there is no error handler in JSON.parse() statement.

Example:

echo '["REQ","subid",{"limit:1}]' | nostcat ws://localhost:8085

or any invalid json message

echo '["EVENT",{"id"::1}]' | nostcat ws://localhost:8085

This issue will become bigger issue whenever bad actor repeat this request and make nostr-filter relay always crash (Denial of Service).

I will send PR later for this issue imksoo-san. Please review it.

Clarification for IP code block position

imksoo-san, i want to ask and confirm about IP detection code block.

Currently, filter.ts has implementation like this:

let upstreamSocket = new WebSocket(upstreamWsUrl);
connectUpstream(upstreamSocket, downstreamSocket);

// クライアントとの接続が確立したら、アイドルタイムアウトを設定
setIdleTimeout(downstreamSocket);

// 接続が確立されるたびにカウントを増やす
connectionCount++;

const ip =
(typeof req.headers["cloudfront-viewer-address"] === "string"
  ? req.headers["cloudfront-viewer-address"]
    .split(":")
    .slice(0, -1)
    .join(":")
  : undefined) ||
(typeof req.headers["x-real-ip"] === "string"
  ? req.headers["x-real-ip"]
  : undefined) ||
(typeof req.headers["x-forwarded-for"] === "string"
  ? req.headers["x-forwarded-for"].split(",")[0].trim()
  : undefined) ||
(typeof req.socket.remoteAddress === "string"
  ? req.socket.remoteAddress
  : "unknown-ip-addr");

// 接続元のクライアントPortを取得
const port =
  (typeof req.headers["cloudfront-viewer-address"] === "string"
    ? parseInt(
      req.headers["cloudfront-viewer-address"].split(":").slice(-1)[0],
    )
    : undefined) ||
  (typeof req.headers["x-real-port"] === "string"
    ? parseInt(req.headers["x-real-port"])
    : 0);

Is it fine if those const ip, and const port are moved into upper position before let upstreamSocket declaration? Based on my observation, it should be fine if we move them into upper position than let upstreamSocket declaration? Right?

const ip =
(typeof req.headers["cloudfront-viewer-address"] === "string"
  ? req.headers["cloudfront-viewer-address"]
    .split(":")
    .slice(0, -1)
    .join(":")
  : undefined) ||
(typeof req.headers["x-real-ip"] === "string"
  ? req.headers["x-real-ip"]
  : undefined) ||
(typeof req.headers["x-forwarded-for"] === "string"
  ? req.headers["x-forwarded-for"].split(",")[0].trim()
  : undefined) ||
(typeof req.socket.remoteAddress === "string"
  ? req.socket.remoteAddress
  : "unknown-ip-addr");

// 接続元のクライアントPortを取得
const port =
  (typeof req.headers["cloudfront-viewer-address"] === "string"
    ? parseInt(
      req.headers["cloudfront-viewer-address"].split(":").slice(-1)[0],
    )
    : undefined) ||
  (typeof req.headers["x-real-port"] === "string"
    ? parseInt(req.headers["x-real-port"])
    : 0);
    
let upstreamSocket = new WebSocket(upstreamWsUrl);
connectUpstream(upstreamSocket, downstreamSocket);

// クライアントとの接続が確立したら、アイドルタイムアウトを設定
setIdleTimeout(downstreamSocket);

// 接続が確立されるたびにカウントを増やす
connectionCount++;

Currently, i need to make those ip and port position in upper position before upstreamSocket. I want to make sure if it is really ok to do that.

Thank you, imksoo-san.

Bug logic in whitelisted pubkey check

Kirino-san, there is bug logic in whitelisted pubkey check feature that i have proposed before in #2

The following test will show that despite the pubkey (pseudo pubkey) is true but the old implementation will give false result. It happens because the second and the third loop check change the shouldRelay=false

const event = ["", { pubkey: "alice" }];
const whitelistedPubkeys = ["alice", "bob", "charlie"];

let shouldRelay = true;
let because = "";

for (const allowed of whitelistedPubkeys) {
  if (event[1].pubkey !== allowed) {
    shouldRelay = false;
    because = "Only whitelisted pubkey can write events";
    // break;
  } else {
    shouldRelay = true;
    because = "";
  }
}

console.log("old implementation", "shouldRelay: ", shouldRelay);

I have fixed that in new implementation as follows

const event = ["", { pubkey: "alice" }];
const whitelistedPubkeys = ["alice", "bob", "charlie"];

let shouldRelay = true;
let because = "";
if (shouldRelay && whitelistedPubkeys.length > 0) {
  const isWhitelistPubkey = whitelistedPubkeys.includes(event[1].pubkey);

  if (!isWhitelistPubkey) {
    shouldRelay = false;
    because = "Only whitelisted pubkey can write events";
  }
}

console.log("new implementation", "shouldRelay: ", shouldRelay);

I will send the PR shortly.

Thank you.

Add production node env support

imksoo-san, i have seen some cases whenever nostr-filter log a lot messages (console.log) the performance of nostr-filter will be slower. In my case, i found that by limiting/suppressing in "production" environment can help solve this issue.

I will send the PR later. Thank you.

Add whitelisted pubkeys support to write events

Sometimes, relay operator want to limit their user only to selected whitelisted pubkey. Any other events outside of whitelisted pubkeys should be rejected. This will be helpful especially for relay implementation which doesn't have built-in whitelist features. nostr-filter can act as proxy in the front of those relay.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.