diff --git a/.changeset/split-readme-into-guides.md b/.changeset/split-readme-into-guides.md new file mode 100644 index 000000000..e24f86ef4 --- /dev/null +++ b/.changeset/split-readme-into-guides.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +docs: split the README into a landing page and reference guides + +The README had grown to 731 lines and carried a full payments walkthrough, an operations manual and a duplicate of the standalone setup steps. It is now 264 lines: what the relay is, the supported NIPs, requirements, the Docker quick start, and a table pointing at the guide for each task. The payments and operations material moved to `docs/PAYMENTS.md` and `docs/OPERATIONS.md` verbatim, and the standalone setup points at the development quick start in `CONTRIBUTING.md` instead of repeating it. `docs/SETUP.md` now links its payments pointer at the new file. The moved instructions were then checked against the code: the importer write semantics, the admission-fee sum, the knex fallback database name, the LNURL `/callback` convention, and the standalone database and Redis steps. `docker-compose.yml` now forwards `NWC_URL`, and `.env.example` names it correctly. diff --git a/.env.example b/.env.example index 64191de5f..929f4ced7 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,10 @@ DB_USER=nostr_ts_relay DB_PASSWORD=nostr_ts_relay # Alternatively, use a URI: # DB_URI=postgresql://nostr_ts_relay:nostr_ts_relay@localhost:5432/nostr_ts_relay +# Migrations (knexfile.js) read DATABASE_URI from the environment; the relay reads DB_URI or DB_*. +# knex does not load this file, so export DATABASE_URI in the shell that runs `pnpm db:migrate`, +# pointing it at the same database, or the schema is created somewhere the relay never opens. +# DATABASE_URI=postgresql://nostr_ts_relay:nostr_ts_relay@localhost:5432/nostr_ts_relay # --- DB POOL TUNING (Optional) --- # DB_MIN_POOL_SIZE=0 @@ -64,7 +68,7 @@ WORKER_COUNT=2 # Defaults to CPU count. Use 1 or 2 for local testing. # NODELESS_WEBHOOK_SECRET= # OPENNODE_API_KEY= # LNBITS_API_KEY= -# ALBY_NWC_URL=nostr+walletconnect://?relay=&secret= +# NWC_URL=nostr+walletconnect://?relay=&secret= # --- READ REPLICAS (Optional) --- # READ_REPLICA_ENABLED=false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 44340e503..20214d2d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,39 +68,68 @@ pnpm run cli -- start ### Development Quick Start (Standalone) -Set the required environment variables (or copy `.env.example` to `.env` and edit it): +Set and export the required environment variables (or copy `.env.example` to `.env` and edit it): ``` -DB_URI="postgresql://postgres:postgres@localhost:5432/nostr_ts_relay_test" -DB_USER=postgres +export DB_URI="postgresql://postgres:postgres@localhost:5432/nostr_ts_relay" +export DATABASE_URI="$DB_URI" +export DB_USER=postgres ``` or: ``` -DB_HOST=localhost -DB_PORT=5432 -DB_NAME=nostr_ts_relay -DB_USER=postgres -DB_PASSWORD=postgres +export DB_HOST=localhost +export DB_PORT=5432 +export DB_NAME=nostr_ts_relay +export DB_USER=postgres +export DB_PASSWORD=postgres ``` +`DATABASE_URI` is not a duplicate of `DB_URI`: the relay reads `.env` and `DB_URI`, while `pnpm db:migrate` reads `DATABASE_URI` from the exported environment and otherwise falls back to the `DB_*` variables with `nostream` as the database name. Two traps follow: knex does not load `.env`, so a `DATABASE_URI` written there alone never reaches the migration; and migrating with only `DB_URI` set writes the schema into a database the relay never opens. Keep the two in step. The integration suite uses its own `nostr_ts_relay_test` database (see the tests section below). + ``` -REDIS_URI="redis://default:nostr_ts_relay@localhost:6379" +export REDIS_URI="redis://default:nostr_ts_relay@localhost:6379" -REDIS_HOST=localhost -REDIS_PORT=6379 -REDIS_USER=default -REDIS_PASSWORD=nostr_ts_relay +export REDIS_HOST=localhost +export REDIS_PORT=6379 +export REDIS_USER=default +export REDIS_PASSWORD=nostr_ts_relay ``` Generate a long random secret and set `SECRET`: ``` -SECRET=aaabbbccc...dddeeefff +export SECRET=aaabbbccc...dddeeefff # Secret shortened for brevity ``` +Create the database the relay will use, with the connection values you just set +(`localhost:5432`, user `postgres`, database `nostr_ts_relay`): + +``` +$ psql -h localhost -p 5432 -U postgres -W +postgres=# create database nostr_ts_relay; +postgres=# quit +``` + +`.env.example` ships `DB_NAME=nostr_ts_relay` and `DB_USER=nostr_ts_relay`. If you copy that file instead of the block above, the relay connects as the `nostr_ts_relay` role, which the commands here never create: either set `DB_USER=postgres` in `.env`, or create that role and make it the database owner. + +The next step sets a server-wide Redis password, so read this first: on a Redis instance another application also uses, either run a dedicated instance for the relay, or leave the password alone, drop the `REDIS_URI` line above and put the existing credentials in `REDIS_*`. `REDIS_URI` takes precedence over the `REDIS_*` variables, so leaving it in place would send the relay to a password that no longer exists. + +Set the Redis password the default configuration expects, and verify it: + +``` +$ redis-cli +127.0.0.1:6379> CONFIG SET requirepass "nostr_ts_relay" +OK +127.0.0.1:6379> AUTH nostr_ts_relay +Ok +127.0.0.1:6379> quit +``` + +`CONFIG SET` lasts only until Redis restarts. On a dedicated instance, put `requirepass nostr_ts_relay` in the server's configuration file as well, so the password survives a restart. + Run migrations (at least once and after pulling new changes): ``` @@ -211,22 +240,25 @@ Change to the project's directory: cd /path/to/nostream ``` -Set the following environment variables: +The relay prefers `DB_URI` over `DB_*`, and the CLI starts with `node --env-file-if-exists=.env`, which fills in a variable that is not already set. So a `DB_URI` left in `.env` by the quick start, or exported in this shell, silently points the tests at the development database: they write their fixtures there and delete them again, and the run proves nothing about a clean schema. Use whichever form matches how you configure the relay: ``` -DB_URI="postgresql://postgres:postgres@localhost:5432/nostr_ts_relay_test" +export DB_URI="postgresql://postgres:postgres@localhost:5432/nostr_ts_relay_test" or -DB_HOST=localhost -DB_PORT=5432 -DB_NAME=nostr_ts_relay_test -DB_USER=postgres -DB_PASSWORD=postgres -DB_MIN_POOL_SIZE=1 -DB_MAX_POOL_SIZE=2 +export DB_URI='' +export DB_HOST=localhost +export DB_PORT=5432 +export DB_NAME=nostr_ts_relay_test +export DB_USER=postgres +export DB_PASSWORD=postgres +export DB_MIN_POOL_SIZE=1 +export DB_MAX_POOL_SIZE=2 ``` +The empty `DB_URI` is deliberate: `--env-file-if-exists` does not overwrite a variable that already exists, so an empty value stops `.env` from supplying the development database, and the client treats it as unset. + Run the integration tests: ``` diff --git a/README.md b/README.md index 921c3d8c6..29257f5be 100644 --- a/README.md +++ b/README.md @@ -42,25 +42,23 @@ The project master repository is available on [GitHub](https://github.com/cameri [![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template/Xfk5F7?referralCode=Kfv2ly) -## Table of contents - -- [Features](#features) -- [Requirements](#requirements) -- [Quick start (Docker Compose)](#quick-start-docker-compose) - - [Importing events from JSON Lines or JSON Arrays](#importing-events-from-json-lines-or-json-arrays) - - [NIP-43 invite codes](#nip-43-invite-codes) -- [Quick start (Standalone)](#quick-start-standalone) -- [Production Setup Guide](#production-setup-guide) - - [Accepting payments](#accepting-payments) -- [Running as a Service](#running-as-a-service) -- [Troubleshooting](#troubleshooting) -- [Export Events](#export-events) -- [Benchmark Database Queries](#benchmark-database-queries) -- [Relay Maintenance](#relay-maintenance) -- [Configuration](#configuration) -- [Development & Contributing](#development--contributing) -- [Dev Channel](#dev-channel) -- [License](#license) +## Documentation + +Start with the guide for what you want to do; the README stays short on purpose. + +| Guide | Covers | +| --- | --- | +| [Production setup](docs/SETUP.md) | Host preparation, Docker Compose, TLS reverse proxy, verification | +| [Deployment runbook](docs/DEPLOY-RUNBOOK.md) | Releasing images, zero-downtime updates, health checks | +| [Configuration](CONFIGURATION.md) | Every environment variable and setting | +| [CLI](CLI.md) | `nostream` commands, exit codes, config commands, development helpers | +| [Payments](docs/PAYMENTS.md) | Charging an admission fee with ZEBEDEE, Nodeless, OpenNode, LNbits, LNURL or NWC | +| [Operations](docs/OPERATIONS.md) | Backups, maintenance, query benchmarking, systemd, troubleshooting | +| [Peering](docs/PEERING.md) | Configuring peers, authenticating, syncing their events | +| [Redis](docs/REDIS.md) | Why the relay needs Redis, and how to configure it | +| [Contributing](CONTRIBUTING.md) | Development setup, tests, load and performance testing | +| [Security policy](SECURITY.md) | Reporting a vulnerability | +| [Changelog](CHANGELOG.md) | Released changes | ## Features @@ -178,491 +176,26 @@ Print I2P hostname(s): nostream info --i2p-hostname ``` -The old shell wrapper scripts are no longer shipped in `scripts/`. -Use the unified `nostream` CLI directly instead: +The old shell wrapper scripts are no longer shipped in `scripts/`. [CLI.md](CLI.md) +lists the `nostream` command each one became. -``` -scripts/start -> nostream start -scripts/start_with_tor -> nostream start --tor -scripts/start_with_i2p -> nostream start --i2p -scripts/start_with_nginx -> nostream start --nginx -scripts/stop -> nostream stop -scripts/print_tor_hostname -> nostream info --tor-hostname -scripts/print_i2p_hostname -> nostream info --i2p-hostname -scripts/update -> nostream update -scripts/clean -> nostream clean -``` - -### Importing events from JSON Lines or JSON Arrays - -You can import NIP-01 events from `.jsonl` (JSON Lines) or `.json` (JSON array) files directly into the relay database. - -Compressed `.jsonl` files are also supported and decompressed on-the-fly: - -- `.jsonl.gz` (Gzip) -- `.jsonl.xz` (XZ) - -Basic import: -``` -nostream import ./events.jsonl -``` - -Equivalent alias form: -``` -nostream import --file ./events.jsonl -``` +### Importing events -Import from a JSON array file (compatible with `nostream export --format json`): -``` -nostream import --file ./events.json -``` - -Import a compressed backup: -``` -nostream import ./events.jsonl.gz -nostream import ./events.jsonl.xz -``` - -Set a custom batch size (default: `1000`): -``` -nostream import ./events.jsonl --batch-size 500 -``` - -The importer: - -- Processes the file line-by-line to keep memory usage bounded. -- Streams JSON array items one by one to keep memory usage bounded. -- Validates NIP-01 schema, event id hash, and Schnorr signature before insertion. -- Inserts in database transactions per batch. -- Skips duplicates without failing the whole import. -- Prints progress in the format: - `[Processed: 50,000 | Inserted: 45,000 | Skipped: 5,000 | Errors: 0]` +Import `.jsonl`, `.json` and compressed backups with `nostream import`. The +full reference, including batch sizes and progress output, is in +[Operations](docs/OPERATIONS.md#importing-events). ### NIP-43 invite codes -Kind 28934 join requests are implemented. Mint a code and share it out of band: - -``` -nostream invite create --json -docker compose exec nostream node src/cli/index.js invite create -``` - -Users can also request a code themselves: the relay answers a `REQ` for kind 28935 by -minting one on the fly. Off by default — set `nip43.allowInviteRequests` to enable it. - -See [CLI.md](CLI.md) for `--uses` / `--expires-in` and Docker vs local Postgres, and -[CONFIGURATION.md](CONFIGURATION.md) for the invite request settings. - -## Quick Start (Standalone) - -Set the following environment variables: - -``` -DB_URI="postgresql://postgres:postgres@localhost:5432/nostr_ts_relay_test" -DB_USER=postgres -``` - or -``` -DB_HOST=localhost -DB_PORT=5432 -DB_NAME=nostr_ts_relay -DB_USER=postgres -DB_PASSWORD=postgres -``` - -``` -REDIS_URI="redis://default:nostr_ts_relay@localhost:6379" - -REDIS_HOST=localhost -REDIS_PORT=6379 -REDIS_USER=default -REDIS_PASSWORD=nostr_ts_relay -``` - -Generate a long random secret and set SECRET: -You may want to use `openssl rand -hex 128` to generate a secret. - -``` -SECRET=aaabbbccc...dddeeefff -# Secret shortened for brevity -``` - -### Initializing the database - -Create `nostr_ts_relay` database: +Mint a code with `nostream invite create`, or let users request one by setting +`nip43.allowInviteRequests`. See [CLI.md](CLI.md#nip-43-invite-codes) and +[Configuration](CONFIGURATION.md). -``` -$ psql -h $DB_HOST -p $DB_PORT -U $DB_USER -W -postgres=# create database nostr_ts_relay; -postgres=# quit -``` - -Start Redis and use `redis-cli` to set the default password and verify: -``` -$ redis-cli -127.0.0.1:6379> CONFIG SET requirepass "nostr_ts_relay" -OK -127.0.0.1:6379> AUTH nostr_ts_relay -Ok -``` - -Clone repository and enter directory: -``` -git clone git@github.com:Cameri/nostream.git -cd nostream -``` - -Install dependencies: - -``` -corepack enable -pnpm install -``` - -Run migrations (at least once and after pulling new changes): - -``` -pnpm db:migrate -``` - -Create .nostr folder inside nostream project folder and copy over the settings file: - -``` -mkdir .nostr -cp resources/default-settings.yaml .nostr/settings.yaml -``` - -To start in development mode: +### Running from source instead -``` -pnpm dev -``` - -Or, start in production mode: - -``` -pnpm start -``` - -To clean up the build, coverage and test reports run: - -``` -pnpm clean -``` -## Production Setup Guide - -For a step-by-step walkthrough covering host preparation, Docker Compose deployment, reverse proxy configuration with TLS, and verification, see the official [Production Setup Guide](https://nostream.dev/docs/setup). - -Prefer to explore all reference guides? See the [documentation index](https://nostream.dev/docs). - -### Accepting Payments - -1. Before you begin - - Complete the [Production Setup Guide](https://nostream.dev/docs/setup) or one of the Quick Start guides in this document - - Create a `.env` file - - On `.nostr/settings.yaml` file make the following changes: - - Set `payments.enabled` to `true` - - Set `payments.feeSchedules.admission.enabled` to `true` - - Set `limits.event.pubkey.minBalance` to the minimum balance in msats required to accept events (i.e. `1000000` to require a balance of `1000` sats) - - Choose one of the following payment processors: `zebedee`, `nodeless`, `opennode`, `lnbits`, `lnurl`, `nwc` - -2. [ZEBEDEE](https://zebedee.io) - - Complete the step "Before you begin" - - [Sign up for a ZEBEDEE Developer Dashboard account](https://dashboard.zebedee.io/signup), create a new LIVE Project, and get that Project's API Key - - Set `ZEBEDEE_API_KEY` environment variable with the API Key above on your `.env` file - -``` - ZEBEDEE_API_KEY={YOUR_ZEBEDEE_API_KEY_HERE} -``` - - - Follow the required steps for all payments processors - - On `.nostr/settings.yaml` file make the following changes: - - `payments.processor` to `zebedee` - - `paymentsProcessors.zebedee.callbackBaseURL` to match your Nostream URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/zebedee`) - - Restart Nostream (`nostream stop` followed by `nostream start`) - - Read the in-depth guide for more information: [Set Up a Paid Nostr Relay with ZEBEDEE API](https://docs.zbdpay.com/payments/nostr/nostr-relay) - -3. [Nodeless](https://nodeless.io/?ref=587f477f-ba1c-4bd3-8986-8302c98f6731) - - Complete the step "Before you begin" - - [Sign up](https://nodeless.io/?ref=587f477f-ba1c-4bd3-8986-8302c98f6731) for a new account, create a new store and take note of the store ID - - Go to Profile > API Tokens and generate a new key and take note of it - - Create a store webhook with your Nodeless callback URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/nodeless`) and make sure to enable all of the events. Grab the generated store webhook secret - - Set `NODELESS_API_KEY` and `NODELESS_WEBHOOK_SECRET` environment variables with generated API key and webhook secret, respectively - -``` - NODELESS_API_KEY={YOUR_NODELESS_API_KEY} - NODELESS_WEBHOOK_SECRET={YOUR_NODELESS_WEBHOOK_SECRET} -``` - - - On your `.nostr/settings.yaml` file make the following changes: - - Set `payments.processor` to `nodeless` - - Set `paymentsProcessors.nodeless.storeId` to your store ID - - Restart Nostream (`nostream stop` followed by `nostream start`) - -4. [OpenNode](https://www.opennode.com/) - - Complete the step "Before you begin" - - Sign up for a new account and get verified - - Go to Developers > Integrations and setup two-factor authentication - - Create a new API Key with Invoices permission - - Set `OPENNODE_API_KEY` environment variable on your `.env` file - - ``` - OPENNODE_API_KEY={YOUR_OPENNODE_API_KEY} - ``` - - - On your `.nostr/settings.yaml` file make the following changes: - - Set `payments.processor` to `opennode` - - Restart Nostream (`nostream stop` followed by `nostream start`) - -5. [LNBITS](https://lnbits.com/) - - Complete the step "Before you begin" - - Create a new wallet on you public LNbits instance - - [Demo](https://legend.lnbits.com/) server must not be used for production - - Your instance must be accessible from the internet and have a valid SSL/TLS certificate - - Get wallet Invoice/read key (in Api docs section of your wallet) - - set `LNBITS_API_KEY` environment variable with the Invoice/read key Key above on your `.env` file - - ``` - LNBITS_API_KEY={YOUR_LNBITS_API_KEY_HERE} - ``` - - On your `.nostr/settings.yaml` file make the following changes: - - Set `payments.processor` to `lnbits` - - set `lnbits.baseURL` to your LNbits instance URL (e.g. `https://{YOUR_LNBITS_DOMAIN_HERE}/`) - - Set `paymentsProcessors.lnbits.callbackBaseURL` to match your Nostream URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/lnbits`) - - Restart Nostream (`nostream stop` followed by `nostream start`) - -6. [Alby](https://getalby.com/) or any LNURL Provider with [LNURL-verify](https://github.com/lnurl/luds/issues/182) support - - Complete the step "Before you begin" - - [Create a new account](https://getalby.com/user/new) if you don't have an LNURL - - On your `.nostr/settings.yaml` file make the following changes: - - Set `payments.processor` to `lnurl` - - Set `lnurl.invoiceURL` to your LNURL (e.g. `https://getalby.com/lnurlp/your-username`) - - Restart Nostream (`nostream stop` followed by `nostream start`) - -7. Nostr Wallet Connect (NIP-47 / NWC) - - Complete the step "Before you begin" - - Create an app connection in your NWC-compatible wallet and copy the generated NWC URL - - Set `NWC_URL` environment variable on your `.env` file - - ``` - NWC_URL={NOSTR_WALLET_CONNECT_URL} - ``` - - - On your `.nostr/settings.yaml` file make the following changes: - - Set `payments.processor` to `nwc` - - Restart Nostream (`nostream stop` followed by `nostream start`) - -8. Ensure payments are required for your public key - - Visit https://{YOUR-DOMAIN}/ - - You should be presented with a form requesting an admission fee to be paid - - Fill out the form and take the necessary steps to pay the invoice - - Wait until the screen indicates that payment was received - - Add your relay URL to your favorite Nostr client (wss://{YOUR-DOMAIN}) and wait for it to connect - - Send a couple notes to test - - Go to https://websocketking.com/ and connect to your relay (wss://{YOUR_DOMAIN}) - - Convert your npub to hexadecimal using a [Key Converter](https://damus.io/key/) - - Send the following JSON message: `["REQ", "payment-test", {"authors":["your-pubkey-in-hexadecimal"]}]` - - You should get back the few notes you sent earlier - -## Running as a Service - -By default this server will run continuously until you stop it with Ctrl+C or until the system restarts. - -You can [install as a systemd service](https://www.swissrouting.com/nostr.html#installing-as-a-service) if you want the server to run again automatically whenever the system is restarted. For example: - -``` -$ nano /etc/systemd/system/nostream.service - -# Note: replace "User=..." with your username, and -# "/home/nostr/nostream" with the directory where you cloned the repo. - -[Unit] -Description=Nostr TS Relay -After=network.target -StartLimitIntervalSec=0 - -[Service] -Type=simple -Restart=always -RestartSec=5 -User=nostr -WorkingDirectory=/home/nostr/nostream -ExecStart=/usr/bin/env bash -lc 'cd /home/nostr/nostream && nostream start' -ExecStop=/usr/bin/env bash -lc 'cd /home/nostr/nostream && nostream stop' - -[Install] -WantedBy=multi-user.target -``` - -And then: - -``` -systemctl enable nostream -systemctl start nostream -``` - -The logs can be viewed with: - -``` -journalctl -u nostream -``` - -## Development & Contributing - -For development environment setup, testing, linting, load testing, and contribution guidelines -(including the issue fairness policy, husky pre-commit hooks, and changeset workflow), see -[CONTRIBUTING.md](CONTRIBUTING.md). - -## Export Events - -Export all stored events to either [JSON Lines](https://jsonlines.org/) (`.jsonl`) or JSON array (`.json`) format. The export streams rows from the database using cursors, so it works safely on relays with millions of events without loading them into memory. - -Optional compression is supported for lower storage and transfer costs: - -- Gzip via Node's native `zlib` -- XZ via `lzma-native` - -``` -nostream export # writes to events.jsonl -nostream export --output backup-2024-01-01.jsonl # custom filename -nostream export --output backup.jsonl.gz --compress --format=gzip -nostream export --output backup.jsonl.xz --compress --format=xz -nostream export --output backup-2024-01-01.jsonl # alias form -nostream export --output backup-2024-01-01.json --format json # JSON array output -``` - -Flags: - -- `--compress` / `-z`: enable compression. -- `--format `: compression format. If omitted while compression is enabled, - format is inferred from file extension (`.gz` / `.xz`) and defaults to `gzip`. - -After completion, the exporter prints a summary with: - -- Raw bytes generated from JSONL lines -- Output bytes written to disk -- Compression delta (smaller/larger) -- Throughput in events/sec and bytes/sec - -Optional XZ tuning (environment variables): - -- `NOSTREAM_XZ_THREADS`: max worker threads for XZ compression. - Defaults to `4` and is automatically capped to available CPU cores minus one. -- `NOSTREAM_XZ_PRESET`: compression preset from `0` (fastest, larger output) - to `9` (slowest, smallest output). Default is `6`. - -The script reads the same `DB_*` environment variables used by the relay (see [CONFIGURATION.md](CONFIGURATION.md)). - -## Benchmark Database Queries - -Run the read-only query benchmark to record the planner's choices and timings for the relay's hot-path queries (REQ subscriptions, vanish checks, purge scans, pending-invoice polls): - -``` -pnpm db:benchmark -pnpm db:benchmark --runs 5 --kind 1 --limit 500 -``` - -The benchmark only issues `EXPLAIN (ANALYZE, BUFFERS)` and `SELECT` statements against your configured database — it never writes. It loads `DB_*` variables from `.env` automatically (via `node --env-file-if-exists=.env`), so no extra setup is required beyond the one you already need to run the relay. Use it to confirm the `events_active_pubkey_kind_created_at_idx`, `events_deleted_at_partial_idx`, and `invoices_pending_created_at_idx` indexes are being picked up. - -For a reproducible before/after proof on a throwaway dataset, run: - -``` -pnpm db:verify-index-impact -``` - -It seeds ~200k synthetic events, drops the hot-path indexes, runs EXPLAIN (ANALYZE, BUFFERS) for each hot query, recreates the indexes, and prints a BEFORE/AFTER table. See the *Database indexes and benchmarking* section of [CONFIGURATION.md](CONFIGURATION.md). -## Relay Maintenance - -Use `nostream dev db:clean` to wipe or prune `events` table data. This also removes -corresponding data from the derived `event_tags` table when present. - -Dry run (no deletion): - -``` -nostream dev db:clean --all --dry-run -``` - -Full wipe: - -``` -nostream dev db:clean --all --force -``` - -Delete events older than N days: - -``` -nostream dev db:clean --older-than=30 --force -``` - -Delete only selected kinds: - -``` -nostream dev db:clean --kinds=1,7,4 --force -``` - -Delete only selected kinds older than N days: - -``` -nostream dev db:clean --older-than=30 --kinds=1,7,4 --force -``` - -By default, the command asks for explicit confirmation (`Type 'DELETE' to confirm`). -Use `--force` to skip the prompt. - - -## Troubleshooting - -### Linux: Docker DNS resolution failures (`EAI_AGAIN`) - -On some Linux environments (especially rolling-release distros or setups using -`systemd-resolved`), `docker compose` builds can fail with DNS errors such as: - -- `getaddrinfo EAI_AGAIN registry.npmjs.org` -- `Temporary failure in name resolution` - -To fix this, configure Docker daemon DNS in `/etc/docker/daemon.json`. - -1. Create or update `/etc/docker/daemon.json`: - -``` -sudo mkdir -p /etc/docker -sudo nano /etc/docker/daemon.json -``` - - Add or update the file with: - -``` -{ - "dns": ["1.1.1.1", "8.8.8.8"] -} -``` - - If this file already exists, merge the `dns` key into the existing JSON - instead of replacing the entire file. - - If your environment does not allow public resolvers, replace `1.1.1.1` and - `8.8.8.8` with DNS servers approved by your network. - -2. Restart Docker: - -``` -sudo systemctl restart docker -``` - -3. Verify DNS works inside containers: - -``` -docker run --rm busybox nslookup registry.npmjs.org -``` - -4. Retry starting nostream: - -``` -nostream start -``` - -Note: avoid `127.0.0.53` in Docker DNS settings because it points to the host's -local resolver stub and is often unreachable from containers. +The standalone path needs PostgreSQL 14, Redis and Node 24. For the full +walkthrough, see the development quick start in +[CONTRIBUTING.md](CONTRIBUTING.md#development-quick-start-standalone). ## Configuration @@ -719,3 +252,13 @@ I'm Cameri on most social networks. You can find me on Nostr by npub1qqqqqqyz0la ## License This project is MIT licensed. + +## Star History + + + + + + Star History Chart + + diff --git a/docker-compose.yml b/docker-compose.yml index d640b0232..719832a9c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -56,6 +56,8 @@ services: OPENNODE_API_KEY: ${OPENNODE_API_KEY} # Lnbits LNBITS_API_KEY: ${LNBITS_API_KEY} + # Nostr Wallet Connect + NWC_URL: ${NWC_URL} # OpenTelemetry metrics OTEL_SERVICE_NAME: ${OTEL_SERVICE_NAME:-nostream} OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md new file mode 100644 index 000000000..c20d5ec22 --- /dev/null +++ b/docs/OPERATIONS.md @@ -0,0 +1,250 @@ +# Operations + +Running, backing up and maintaining a relay after it is set up. + +## Running as a service + +By default this server will run continuously until you stop it with Ctrl+C or until the system restarts. + +To have it start again whenever the system restarts, install it as a systemd service. For example: + +``` +$ nano /etc/systemd/system/nostream.service + +# Note: replace "User=..." with your username, and +# "/home/nostr/nostream" with the directory where you cloned the repo. + +[Unit] +Description=Nostr TS Relay +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=5 +User=nostr +WorkingDirectory=/home/nostr/nostream +ExecStart=/usr/bin/env bash -lc 'cd /home/nostr/nostream && nostream start' +ExecStop=/usr/bin/env bash -lc 'cd /home/nostr/nostream && nostream stop' + +[Install] +WantedBy=multi-user.target +``` + +And then: + +``` +systemctl enable nostream +systemctl start nostream +``` + +The logs can be viewed with: + +``` +journalctl -u nostream +``` + +## Importing events +You can import NIP-01 events from `.jsonl` (JSON Lines) or `.json` (JSON array) files directly into the relay database. + +Under Docker Compose, Postgres is not published to the host, so run the import inside the relay container and give it a path the container can see: + +``` +docker compose exec nostream node src/cli/index.js import /home/node/.nostr/events.jsonl +``` + +Compressed `.jsonl` files are also supported and decompressed on-the-fly: + +- `.jsonl.gz` (Gzip) +- `.jsonl.xz` (XZ) + +Basic import: +``` +nostream import ./events.jsonl +``` + +Equivalent alias form: +``` +nostream import --file ./events.jsonl +``` + +Import from a JSON array file (compatible with `nostream export --format json`): +``` +nostream import --file ./events.json +``` + +Import a compressed backup: +``` +nostream import ./events.jsonl.gz +nostream import ./events.jsonl.xz +``` + +Set a custom batch size (default: `1000`): +``` +nostream import ./events.jsonl --batch-size 500 +``` + +The importer: + +- Processes the file line-by-line to keep memory usage bounded. +- Streams JSON array items one by one to keep memory usage bounded. +- Validates NIP-01 schema, event id hash, and Schnorr signature before insertion. +- Writes each flush as two statements: one multi-row insert for regular events, then one upsert for replaceable ones. A kind `5` delete flushes first, so one batch can become several flushes. There is no transaction spanning them, and a statement that fails inserts nothing and counts its own events as skipped, which is why `Skipped` above can include events that were valid on their own. The insert runs first, so a failed upsert leaves that flush's regular events already written. +- A request to vanish has no effect on an import. The importer builds its writer without a user repository (`src/import-events.ts:222`), so the branch that would delete the author's older events and mark them vanished never runs: the request is stored like any other event. Peering sync does pass one, and its imports do apply it. +- Skips duplicates through `ON CONFLICT DO NOTHING`, without failing the import. +- Upserts replaceable events (kinds `0`, `3`, `41`, `10000`–`19999` and `30000`–`39999`) on `(event_pubkey, event_kind, event_deduplication)`, keeping the newer one. Two replaceable events sharing a key within one upsert can make PostgreSQL refuse the statement (`ON CONFLICT DO UPDATE command cannot affect row a second time`), and that upsert's events count as skipped. A batch dense in competing replaceable events is therefore the case to watch, and `--batch-size 1` avoids it at the cost of one round trip per event. +- Prints progress in the format: + `[Processed: 50,000 | Inserted: 45,000 | Skipped: 5,000 | Errors: 0]` + +## Exporting events +Export all stored events to either [JSON Lines](https://jsonlines.org/) (`.jsonl`) or JSON array (`.json`) format. The export streams rows from the database using cursors, so it works safely on relays with millions of events without loading them into memory. + +Optional compression is supported for lower storage and transfer costs: + +- Gzip via Node's native `zlib` +- XZ via `lzma-native` + +``` +nostream export # writes to events.jsonl +nostream export --output backup-2024-01-01.jsonl # custom filename +nostream export --output backup.jsonl.gz --compress --format=gzip +nostream export --output backup.jsonl.xz --compress --format=xz +nostream export --output backup-2024-01-01.jsonl # alias form +nostream export --output backup-2024-01-01.json --format json # JSON array output +``` + +Flags: + +- `--compress` / `-z`: enable compression. +- `--format `: compression format. If omitted while compression is enabled, + format is inferred from file extension (`.gz` / `.xz`) and defaults to `gzip`. + +After completion, the exporter prints a summary with: + +- Raw bytes generated from JSONL lines +- Output bytes written to disk +- Compression delta (smaller/larger) +- Throughput in events/sec and bytes/sec + +Optional XZ tuning (environment variables): + +- `NOSTREAM_XZ_THREADS`: max worker threads for XZ compression. + Defaults to `4` and is automatically capped to available CPU cores minus one. +- `NOSTREAM_XZ_PRESET`: compression preset from `0` (fastest, larger output) + to `9` (slowest, smallest output). Default is `6`. + +The script reads the same `DB_*` environment variables used by the relay (see [CONFIGURATION.md](../CONFIGURATION.md)). + +## Benchmarking database queries + +Run the read-only query benchmark to record the planner's choices and timings for the relay's hot-path queries (REQ subscriptions, vanish checks, purge scans, pending-invoice polls): + +``` +pnpm db:benchmark +pnpm db:benchmark --runs 5 --kind 1 --limit 500 +``` + +The benchmark only issues `EXPLAIN (ANALYZE, BUFFERS)` and `SELECT` statements against your configured database — it never writes. It loads `DB_*` variables from `.env` automatically (via `node --env-file-if-exists=.env`), so no extra setup is required beyond the one you already need to run the relay. Use it to confirm the `events_active_pubkey_kind_created_at_idx`, `events_deleted_at_partial_idx`, and `invoices_pending_created_at_idx` indexes are being picked up. + +For a reproducible before/after proof on a throwaway dataset, run: + +``` +pnpm db:verify-index-impact +``` + +It seeds ~200k synthetic events, drops the hot-path indexes, runs EXPLAIN (ANALYZE, BUFFERS) for each hot query, recreates the indexes, and prints a BEFORE/AFTER table. See the *Database indexes and benchmarking* section of [CONFIGURATION.md](../CONFIGURATION.md). + +Point `DB_*` at a scratch database before running it: it inserts event rows and drops the indexes it is measuring, so against a live relay it both pollutes the store and leaves the hot paths unindexed while it runs. + +## Relay maintenance + +Use `nostream dev db:clean` to wipe or prune `events` table data. This also removes +corresponding data from the derived `event_tags` table when present. + +Dry run (no deletion): + +``` +nostream dev db:clean --all --dry-run +``` + +Full wipe: + +``` +nostream dev db:clean --all --force +``` + +Delete events older than N days: + +``` +nostream dev db:clean --older-than=30 --force +``` + +Delete only selected kinds: + +``` +nostream dev db:clean --kinds=1,7,4 --force +``` + +Delete only selected kinds older than N days: + +``` +nostream dev db:clean --older-than=30 --kinds=1,7,4 --force +``` + +By default, the command asks for explicit confirmation (`Type 'DELETE' to confirm`). +Use `--force` to skip the prompt. + + +## Troubleshooting +### Linux: Docker DNS resolution failures (`EAI_AGAIN`) + +On some Linux environments (especially rolling-release distros or setups using +`systemd-resolved`), `docker compose` builds can fail with DNS errors such as: + +- `getaddrinfo EAI_AGAIN registry.npmjs.org` +- `Temporary failure in name resolution` + +To fix this, configure Docker daemon DNS in `/etc/docker/daemon.json`. + +1. Create or update `/etc/docker/daemon.json`: + +``` +sudo mkdir -p /etc/docker +sudo nano /etc/docker/daemon.json +``` + + Add or update the file with: + +``` +{ + "dns": ["1.1.1.1", "8.8.8.8"] +} +``` + + If this file already exists, merge the `dns` key into the existing JSON + instead of replacing the entire file. + + If your environment does not allow public resolvers, replace `1.1.1.1` and + `8.8.8.8` with DNS servers approved by your network. + +2. Restart Docker: + +``` +sudo systemctl restart docker +``` + +3. Verify DNS works inside containers: + +``` +docker run --rm busybox nslookup registry.npmjs.org +``` + +4. Retry starting nostream: + +``` +nostream start +``` + +Note: avoid `127.0.0.53` in Docker DNS settings because it points to the host's +local resolver stub and is often unreachable from containers. diff --git a/docs/PAYMENTS.md b/docs/PAYMENTS.md new file mode 100644 index 000000000..5b7573568 --- /dev/null +++ b/docs/PAYMENTS.md @@ -0,0 +1,117 @@ +# Payments + +Nostream can charge an admission fee before it accepts a pubkey's events. +Set `payments.enabled`, choose one processor, and restart the relay. + +## Accepting payments + +1. Before you begin + - Complete the [Production Setup Guide](https://nostream.dev/docs/setup) or the [quick start](../README.md#quick-start-docker-compose) + - Create a `.env` file + - On `.nostr/settings.yaml` file make the following changes: + - Set `payments.enabled` to `true` + - Set `payments.feeSchedules.admission[0].enabled` to `true`. The schedules are a list and `[0]` is the entry you edit; the relay charges the sum of every enabled schedule whose pubkey whitelist does not cover the payer, so more than one entry costs more than one fee. The invoice page quotes `[0]` alone (`get-invoice-controller.ts:56`), so with two enabled schedules it shows less than the invoice charges + - Set `limits.event.pubkey.minBalance` to the minimum balance in msats required to accept events (i.e. `1000000` to require a balance of `1000` sats) + - Choose one of the following payment processors: `zebedee`, `nodeless`, `opennode`, `lnbits`, `lnurl`, `nwc` + +Each processor step ends with `nostream stop` and `nostream start`, which is the quick start's CLI. A host deployed with Docker Compose has no such command: recreate the relay instead, with `./deploy/recreate-relay.sh /opt/nostream` from a checkout or the host copy described in [DEPLOY-RUNBOOK.md](DEPLOY-RUNBOOK.md), which also lists the manual equivalent. Run it as the user who ran `deploy/bootstrap.sh`, since that user owns `/opt/nostream/.env` and mode `600` keeps everyone else out. Bootstrap does not install the script, so read that section before relying on it. + +2. [ZEBEDEE](https://zebedee.io) + - Complete the step "Before you begin" + - [Sign up for a ZEBEDEE Developer Dashboard account](https://dashboard.zebedee.io/signup), create a new LIVE Project, and get that Project's API Key + - Set `ZEBEDEE_API_KEY` environment variable with the API Key above on your `.env` file + +``` + ZEBEDEE_API_KEY={YOUR_ZEBEDEE_API_KEY_HERE} +``` + + - Follow the required steps for all payments processors + - On `.nostr/settings.yaml` file make the following changes: + - `payments.processor` to `zebedee` + - `paymentsProcessors.zebedee.callbackBaseURL` to match your Nostream URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/zebedee`) + - Restart Nostream (`nostream stop` followed by `nostream start`) + - Read the in-depth guide for more information: [Set Up a Paid Nostr Relay with ZEBEDEE API](https://docs.zbdpay.com/payments/nostr/nostr-relay) + +3. Nodeless + - Complete the step "Before you begin" + - The processor is not usable as shipped: `resources/default-settings.yaml` points `paymentsProcessors.nodeless.baseURL` at `https://nodeless.io`, and that domain no longer resolves, so invoice creation and checks fail at the network. The steps below apply if you have a working host to point that setting at + - Go to Profile > API Tokens and generate a new key and take note of it + - Create a store webhook with your Nodeless callback URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/nodeless`) and make sure to enable all of the events. Grab the generated store webhook secret + - Set `NODELESS_API_KEY` and `NODELESS_WEBHOOK_SECRET` environment variables with generated API key and webhook secret, respectively + +``` + NODELESS_API_KEY={YOUR_NODELESS_API_KEY} + NODELESS_WEBHOOK_SECRET={YOUR_NODELESS_WEBHOOK_SECRET} +``` + + - On your `.nostr/settings.yaml` file make the following changes: + - Set `payments.processor` to `nodeless` + - Set `paymentsProcessors.nodeless.storeId` to your store ID + - Restart Nostream (`nostream stop` followed by `nostream start`) + +4. [OpenNode](https://www.opennode.com/) + - Complete the step "Before you begin" + - Sign up for a new account and get verified + - Go to Developers > Integrations and setup two-factor authentication + - Create a new API Key with Invoices permission + - Set `OPENNODE_API_KEY` environment variable on your `.env` file + + ``` + OPENNODE_API_KEY={YOUR_OPENNODE_API_KEY} + ``` + + - On your `.nostr/settings.yaml` file make the following changes: + - Set `payments.processor` to `opennode` + - Set `paymentsProcessors.opennode.callbackBaseURL` to match your Nostream URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/opennode`) + - Restart Nostream (`nostream stop` followed by `nostream start`) + +5. [LNBITS](https://lnbits.com/) + - Complete the step "Before you begin" + - Create a new wallet on you public LNbits instance + - [Demo](https://legend.lnbits.com/) server must not be used for production + - Your instance must be accessible from the internet and have a valid SSL/TLS certificate + - Get wallet Invoice/read key (in Api docs section of your wallet) + - set `LNBITS_API_KEY` environment variable with the Invoice/read key Key above on your `.env` file + + ``` + LNBITS_API_KEY={YOUR_LNBITS_API_KEY_HERE} + ``` + - On your `.nostr/settings.yaml` file make the following changes: + - Set `payments.processor` to `lnbits` + - set `paymentsProcessors.lnbits.baseURL` to your LNbits instance URL (e.g. `https://{YOUR_LNBITS_DOMAIN_HERE}/`) + - Set `paymentsProcessors.lnbits.callbackBaseURL` to match your Nostream URL (e.g. `https://{YOUR_DOMAIN_HERE}/callbacks/lnbits`) + - Restart Nostream (`nostream stop` followed by `nostream start`) + +6. [Alby](https://getalby.com/), or another LNURL-pay provider that serves its callback at `/callback`. That path is a Nostream requirement, not something [LUD-06](https://github.com/lnurl/luds/blob/luds/06.md) guarantees, since a provider may advertise any callback it likes. [LNURL-verify](https://github.com/lnurl/luds/issues/182) support is also needed + - Complete the step "Before you begin" + - [Create a new account](https://getalby.com/) if you don't have an LNURL + - On your `.nostr/settings.yaml` file make the following changes: + - Set `payments.processor` to `lnurl` + - Set `paymentsProcessors.lnurl.invoiceURL` to your LNURL-pay address up to but excluding `/callback` (e.g. `https://getalby.com/lnurlp/your-username`, with your own username) + - Restart Nostream (`nostream stop` followed by `nostream start`) + +7. Nostr Wallet Connect (NIP-47 / NWC) + - Complete the step "Before you begin" + - Create an app connection in your NWC-compatible wallet and copy the generated NWC URL + - Set `NWC_URL` environment variable on your `.env` file + + ``` + NWC_URL={NOSTR_WALLET_CONNECT_URL} + ``` + + + - On your `.nostr/settings.yaml` file make the following changes: + - Set `payments.processor` to `nwc` + - Restart Nostream (`nostream stop` followed by `nostream start`) + +8. Ensure payments are required for your public key + - Visit https://{YOUR-DOMAIN}/ + - You should be presented with a form requesting an admission fee to be paid + - Fill out the form and take the necessary steps to pay the invoice + - Wait until the screen indicates that payment was received + - Add your relay URL to your favorite Nostr client (wss://{YOUR-DOMAIN}) and wait for it to connect + - Send a couple notes to test + - Go to https://websocketking.com/ and connect to your relay (wss://{YOUR_DOMAIN}) + - Convert your npub to hexadecimal using a [Key Converter](https://damus.io/key/) + - Send the following JSON message: `["REQ", "payment-test", {"authors":["your-pubkey-in-hexadecimal"]}]` + - You should get back the few notes you sent earlier diff --git a/docs/SETUP.md b/docs/SETUP.md index 5e1c221c8..6487f36af 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -571,6 +571,6 @@ Test a restore before you need one. ## Next Steps -- **Monetize with Admission Fees:** See [`Accepting Payments`](../README.md#accepting-payments) to enable Lightning / LNURL / Zebedee pay-to-relay features. +- **Monetize with Admission Fees:** See [`Accepting Payments`](PAYMENTS.md) to enable Lightning / LNURL / Zebedee pay-to-relay features. - **Onion & I2P Hidden Services:** See [`CLI Reference & Common Workflows`](../CLI.md#common-workflows) to expose your relay anonymously. - **Admin Console & Operations:** See [`Configuration`](../CONFIGURATION.md) to enable the web-based Operator Console at `/admin`.