Adaugă codul complet al proiectului underchat-ircd

This commit is contained in:
mihaiitdata committed 2026-02-13 00:04:12 +02:00
1 parent caba5224bf
commit 5fdc1cc27c
462 files changed
+164488

No files matched your search

+258
View File
@@ -0,0 +1,258 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
iauthd-ts is a TypeScript IAuth daemon for Nefarious IRCd. It performs real-time DNS blacklist (DNSBL) lookups on connecting IRC clients and can block, mark, whitelist, or assign connection classes based on results. It also handles SASL PLAIN authentication directly (without routing to services).
This is a port of the original Perl `iauthd.pl`. The only runtime dependency is `ldapts` for LDAP authentication support.
## Build & Development Commands
```bash
npm install # Install dependencies
npm run build # Compile TypeScript to dist/
npm run dev -- -c /path/to/config # Run directly from TypeScript (no compile)
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
npm run stress # Memory stress test (5000 clients)
npm run stress -- --clients=10000 # Custom client count
```
## Running
```bash
node dist/index.js -c <configfile> [-v] [-d]
# -c, --config Config file to read (required)
# -v, --verbose Debug output in iauthd
# -d, --debug Debug output in IRCd
```
## Architecture
### Core Components
- **`src/index.ts`** - CLI entry point, parses args and starts daemon
- **`src/iauth.ts`** - Main `IAuthDaemon` class, handles IRCd communication via stdin/stdout using the IAuth protocol
- **`src/config.ts`** - Parses `#IAUTH` directives from config files
- **`src/dnsbl.ts`** - DNSBL lookup with caching, IP reversal utilities
- **`src/sasl.ts`** - SASL PLAIN decoding, password hashing utilities (SHA-256/512, MD5, bcrypt)
- **`src/types.ts`** - TypeScript interfaces for all data structures
### Authentication Module (`src/auth/`)
The auth module provides a modular, provider-based authentication system:
- **`src/auth/types.ts`** - AuthProvider interface and config types
- **`src/auth/manager.ts`** - AuthManager coordinates multiple providers with fallback chain
- **`src/auth/config.ts`** - Parses AUTH directive configuration
- **`src/auth/providers/file.ts`** - Static file-based authentication (wraps sasl.ts)
- **`src/auth/providers/ldap.ts`** - LDAP authentication with direct bind and search modes
- **`src/auth/providers/keycloak.ts`** - Keycloak authentication using ROPC grant
### IAuth Protocol Flow
The daemon communicates with Nefarious via stdin/stdout:
1. **Client connects** → IRCd sends `C <id> <ip> <port> <serverip> <serverport>`
2. **DNSBL lookups** → Started concurrently for all configured DNSBLs
3. **Results processed** → Check index/bitmask matches, apply marks/blocks/whitelist
4. **Hurry received** → IRCd sends `H <id> <class>` when registration timeout approaches
5. **Decision made** → Send `D` (accept), `k` (reject), or `m` (mark) back to IRCd
Key message handlers in `IAuthDaemon.handleLine()`:
- `C` - Client introduction, triggers DNSBL lookups
- `H` - Hurry, forces immediate decision
- `R` - Client authenticated via SASL/LOC (exempts from `block=anonymous`)
- `A`/`a` - SASL authentication start/continue
- `w` - Trusted WEBIRC, re-checks real IP
### DNSBL Matching
DNSBLs return `127.0.0.X` addresses where X indicates the listing reason:
- `index=2,3,4` - Match if X equals any listed value
- `bitmask=8` - Match if X AND bitmask is non-zero
- Neither specified - Any response is a match
### Caching
DNS results are cached globally in `dnsbl.ts`. Cache entries store:
- Query string (reversed IP + server)
- Result IPs or null (pending)
- Timestamp for expiration
### SASL Authentication
iauthd-ts handles SASL PLAIN authentication directly using a modular provider system:
1. IRCd sends `A <id> S :PLAIN`
2. iauthd responds with challenge `c <id> :+`
3. Client sends base64 credentials via `a <id> :<data>`
4. iauthd verifies against configured auth providers (file, LDAP, etc.)
5. Sends `L` (success) or `f` (fail) to IRCd
**Auth Provider Fallback**: When multiple providers are configured, they are tried in priority order (lower = first). First successful authentication wins.
Password formats for file provider: `$5$salt$hash` (SHA-256), `$6$salt$hash` (SHA-512), `$1$salt$hash` (MD5), `$2a$` or `$2b$` (bcrypt)
## Testing
Tests use Vitest with mocked DNS resolution:
- **`tests/config.test.ts`** - Configuration parsing
- **`tests/dnsbl.test.ts`** - IP functions, caching, matching
- **`tests/dnsbl-integration.test.ts`** - Full DNSBL pipeline with mock DNS
- **`tests/iauth.test.ts`** - Protocol integration tests
- **`tests/sasl.test.ts`** - SASL authentication utilities
- **`tests/auth/config.test.ts`** - AUTH directive parsing
- **`tests/auth/file.test.ts`** - FileAuthProvider tests
- **`tests/auth/manager.test.ts`** - AuthManager fallback behavior
- **`tests/auth/keycloak.test.ts`** - KeycloakAuthProvider tests
- **`tests/stress.ts`** - Memory stress test (not a vitest file)
Run a single test file:
```bash
npx vitest run tests/dnsbl.test.ts
npx vitest run tests/config.test.ts -t "parses DNSBL" # Run matching tests
```
## Configuration
Configuration uses `#IAUTH` directives embedded in ircd.conf (IRCd ignores lines starting with `#`):
```
#IAUTH POLICY RTAWUwFrS
#IAUTH DNSTIMEOUT 5
#IAUTH CACHETIME 86400
#IAUTH BLOCKMSG Your connection has been rejected
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5 mark=dronebl block=anonymous
#IAUTH DNSBL server=whitelist.example.com whitelist
```
### Authentication Providers
Use `#IAUTH AUTH` to configure authentication backends. Multiple providers can be configured; they are tried in priority order (lower = first).
#### Static File Provider
```
#IAUTH SASLDB /path/to/users # Legacy format (still supported)
#IAUTH AUTH provider=file path=/path/to/users # Explicit format
#IAUTH AUTH provider=file path=/path/to/users priority=50
```
#### LDAP Direct Bind Mode
> **Note**: LDAP support has not yet been tested against real LDAP servers. Use with caution and please report any issues.
User binds directly with their credentials using a DN template:
```
#IAUTH AUTH provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
```
#### LDAP Search Mode (Admin Bind + Search)
Binds as admin, searches for user, optionally checks group membership, then binds as user:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s)
# With group membership check:
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s) groupdn=cn=ircusers,ou=groups,dc=example,dc=com
```
#### LDAP Configuration Options
| Option | Required | Mode | Description |
|--------|----------|------|-------------|
| `uri` | Yes | Both | LDAP server URI (`ldap://` or `ldaps://`) |
| `mode` | Yes | Both | `direct` or `search` |
| `userdn` | Yes | direct | DN template with `%s` for username |
| `basedn` | Yes | search | Base DN for user search |
| `binddn` | Yes | search | Admin bind DN |
| `bindpass` | Yes | search | Admin bind password |
| `userfilter` | Yes | search | Search filter with `%s` for username |
| `groupdn` | No | search | Group DN for membership check |
| `accountattr` | No | Both | Attribute to use as account name (default: uid/sAMAccountName) |
| `timeout` | No | Both | Connection timeout in ms (default: 5000) |
| `priority` | No | Both | Provider priority (default: 100, lower = first) |
#### Keycloak Provider
Uses Resource Owner Password Credentials (ROPC) grant to authenticate users against Keycloak. The client must have "Direct Access Grants" enabled in Keycloak.
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client
# With client secret (for confidential clients):
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=your-secret
# With custom account attribute:
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client accountattr=irc_nick
```
#### Keycloak Configuration Options
| Option | Required | Description |
|--------|----------|-------------|
| `url` | Yes | Keycloak server URL (e.g., `https://keycloak.example.com`) |
| `realm` | Yes | Keycloak realm name |
| `clientid` | Yes | OAuth2 client ID (must have Direct Access Grants enabled) |
| `clientsecret` | No | Client secret (for confidential clients) |
| `accountattr` | No | JWT claim to use as account name (default: `preferred_username`) |
| `timeout` | No | Request timeout in ms (default: 5000) |
| `priority` | No | Provider priority (default: 100, lower = first) |
#### Keycloak Server Setup
To configure Keycloak for IRC SASL authentication:
**1. Create a Realm**
- Go to Keycloak Admin Console
- Create a new realm (e.g., `irc` or `testnet`)
**2. Create a Client**
- Go to **Clients** → **Create client**
- **Client ID**: `irc-client` (or your preferred name)
- **Client Protocol**: `OpenID Connect` (not SAML)
- Click **Next**
- **Client authentication**: `OFF` (for public client) or `ON` if using `clientsecret`
- **Direct access grants**: `ON` ← **Critical for ROPC authentication**
- Click **Save**
**3. Configure User Profile (Optional but Recommended)**
- Go to **Realm Settings** → **User profile**
- Click on `firstName` → set "Required field" to `OFF` → Save
- Click on `lastName` → set "Required field" to `OFF` → Save
- This prevents "Account is not fully set up" errors for users without names
**4. Configure Authentication Flows (Optional)**
- Go to **Authentication** → **Flows** → select **direct grant**
- Ensure no required actions block password auth (e.g., set Conditional OTP to `DISABLED` if not using 2FA)
**5. Create Users**
- Go to **Users** → **Add user**
- Set username, email (if required)
- Go to **Credentials** tab → **Set password**
- **Important**: Set **Temporary** to `OFF` to avoid forced password change
- Ensure **Required user actions** is empty (no "Update Password", "Configure OTP", etc.)
**Common Issues**
- `"Account is not fully set up"` - User has pending required actions (check user's Required Actions field, or realm-level User Profile requirements)
- `"Wrong client protocol"` - Client is configured as SAML instead of OpenID Connect
- `"unauthorized_client"` - Direct Access Grants is not enabled on the client
- Connection errors - Use `http://` for dev mode (`start-dev`), `https://` for production
**Testing Authentication**
```bash
curl -s -X POST "http://localhost:8080/realms/REALM/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=password&client_id=CLIENT_ID&username=USER&password=PASS"
```
A successful response returns an `access_token`. Error responses include `error` and `error_description` fields.
### Password Hashes
Generate password hashes for the file provider:
```bash
npx tsx src/genhash.ts mypassword sha256
```
+477
View File
@@ -0,0 +1,477 @@
# iauthd-ts
A TypeScript implementation of an IAuth daemon for Nefarious IRCd. This daemon performs real-time DNS-based blacklist (DNSBL) lookups on connecting clients and can block, mark, or whitelist users based on the results.
This is a port of the original Perl `iauthd.pl` to TypeScript/Node.js.
## Features
- **DNSBL Lookups**: Check connecting clients against multiple DNS blacklists
- **Flexible Matching**: Match by index value or bitmask
- **Caching**: DNS results are cached to reduce lookup overhead
- **SASL Authentication**: Handle SASL PLAIN authentication directly in IAuth (no services required)
- **SASL/LOC Support**: Exempt authenticated users from blocks
- **WEBIRC Support**: Re-check real IP for trusted proxy connections
- **Marking**: Tag users with marks visible to operators
- **Class Assignment**: Assign users to connection classes based on DNSBL results
- **Whitelisting**: Exempt users matching certain DNSBLs from all blocks
## How It Works
```
┌─────────────┐ stdin/stdout ┌─────────────┐
│ Nefarious │ ◄──────────────────► │ iauthd-ts │
│ IRCd │ IAuth Protocol │ │
└─────────────┘ └──────┬──────┘
│
│ DNS queries
▼
┌─────────────┐
│ DNSBL │
│ Servers │
└─────────────┘
```
1. **Client Connects**: IRCd sends client info to iauthd-ts via the IAuth protocol
2. **DNSBL Lookup**: iauthd-ts reverses the client IP and queries configured DNSBLs
3. **Result Processing**: Responses are checked against configured index/bitmask rules
4. **Decision**: Client is accepted (with optional marks/class) or rejected
5. **Response**: iauthd-ts sends the decision back to IRCd
### IAuth Protocol
iauthd-ts communicates with Nefarious via stdin/stdout using the IAuth protocol:
| Direction | Message | Description |
|-----------|---------|-------------|
| IRCd → iauthd | `C <id> <ip> <port> <serverip> <serverport>` | Client introduction |
| IRCd → iauthd | `H <id> <class>` | Hurry up (registration timeout approaching) |
| IRCd → iauthd | `R <id> <account>` | Client authenticated via SASL/LOC |
| IRCd → iauthd | `D <id>` | Client disconnected |
| iauthd → IRCd | `D <id> <ip> <port> [class]` | Accept client |
| iauthd → IRCd | `k <id> <ip> <port> :<reason>` | Reject client |
| iauthd → IRCd | `m <id> <ip> <port> MARK <data>` | Mark client |
| IRCd → iauthd | `A <id> <ip> <port> S <mechanism> [:<certfp>]` | SASL auth start |
| IRCd → iauthd | `A <id> <ip> <port> H :<user@host:ip>` | SASL host info |
| IRCd → iauthd | `a <id> <ip> <port> :<data>` | SASL auth data |
| iauthd → IRCd | `c <id> <ip> <port> :<challenge>` | SASL challenge |
| iauthd → IRCd | `L <id> <ip> <port> <account>` | SASL login success |
| iauthd → IRCd | `f <id> <ip> <port>` | SASL auth failed |
| iauthd → IRCd | `l <id> <ip> <port> :<mechanisms>` | SASL mechanism list |
| iauthd → IRCd | `Z <id> <ip> <port>` | SASL auth complete |
## Requirements
- Node.js 18 or later
- npm
## Installation
### From Source
```bash
cd tools/iauthd-ts
npm install
npm run build
```
### Docker
iauthd-ts is automatically built as part of the Nefarious Docker image. The compiled files are located at `/home/nefarious/ircd/iauthd-ts/`.
## Configuration
iauthd-ts reads configuration from `#IAUTH` directives in the config file. These can be embedded in your `ircd.conf` since IRCd ignores lines starting with `#`.
### Directives
#### POLICY
```
#IAUTH POLICY RTAWUwFr
```
Sets the IAuth policy flags. See `doc/readme.iauth` for details.
#### DNSTIMEOUT
```
#IAUTH DNSTIMEOUT 5
```
Seconds to wait for DNSBL lookups. Default: 5
#### CACHETIME
```
#IAUTH CACHETIME 86400
```
Seconds to cache DNSBL results. Default: 86400 (24 hours)
#### BLOCKMSG
```
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
```
Message shown to blocked users.
#### DEBUG
```
#IAUTH DEBUG
```
Enable debug output.
#### SASLDB
```
#IAUTH SASLDB /path/to/users
```
Path to the SASL users file. When set, iauthd-ts will handle SASL PLAIN authentication directly instead of routing to services. The policy must include 'S' for this to work.
#### SASLFAILMSG
```
#IAUTH SASLFAILMSG Authentication failed
```
Message shown when SASL authentication fails.
#### DNSBL
```
#IAUTH DNSBL server=<server> [options...]
```
Options:
| Option | Description |
|--------|-------------|
| `server=<host>` | DNSBL server hostname (required) |
| `index=<n,n,...>` | Match if response equals any of these values |
| `bitmask=<n>` | Match if response AND bitmask is non-zero |
| `mark=<tag>` | Apply this mark to matching clients |
| `block=all` | Block all matching clients |
| `block=anonymous` | Block matching clients unless SASL authenticated |
| `class=<name>` | Assign matching clients to this connection class |
| `whitelist` | Matching clients are exempt from all blocks |
| `cachetime=<n>` | Override cache time for this DNSBL |
### Example Configuration
```
# IAuth Configuration
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
# Block open proxies and drones (unless authenticated)
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
# Mark Tor exit nodes but don't block
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
# Block other bad actors
#IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
# Whitelist from a private DNSBL
#IAUTH DNSBL server=whitelist.example.com whitelist cachetime=3600
```
### SASL Authentication Configuration
To enable SASL authentication handling in iauthd-ts (instead of routing to services):
1. **Create a users file** (`users` or any path you prefer):
```
# Format: username:passwordhash
# Use genhash.ts to create hashes
admin:$5$salt$hashedpassword
user1:$6$salt$hashedpassword
```
2. **Generate password hashes**:
```bash
npx tsx src/genhash.ts mypassword sha256
# Output: $5$randomsalt$hashedpasswordvalue
```
3. **Configure iauthd-ts**:
```
#IAUTH POLICY RTAWUwFrS
#IAUTH SASLDB /path/to/users
#IAUTH SASLFAILMSG Invalid username or password
```
The `S` in the policy enables SASL handling.
4. **Supported hash formats**:
- `$5$salt$hash` - SHA-256 (recommended)
- `$6$salt$hash` - SHA-512
- `$1$salt$hash` - MD5 (legacy)
- Plain text (for testing only)
The users file is automatically reloaded when modified (checked on each SASL attempt).
### Modular Authentication Providers
iauthd-ts supports a modular authentication system with multiple backends. Providers are tried in priority order (lower number = tried first) until one succeeds.
#### AUTH Directive
```
#IAUTH AUTH provider=<type> [options...]
```
#### File Provider
Uses a static users file (same as SASLDB but with explicit provider syntax):
```
#IAUTH AUTH provider=file path=/path/to/users priority=50
```
#### LDAP Provider
> **Note**: LDAP support has not yet been tested with real LDAP servers. Please report any issues.
Two modes are supported:
**Direct Bind Mode** - Binds directly as the user:
```
#IAUTH AUTH provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
```
**Search Mode** - Admin bind, search for user, then bind as user:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s) groupdn=cn=ircusers,ou=groups,dc=example,dc=com
```
LDAP Options:
| Option | Required | Mode | Description |
|--------|----------|------|-------------|
| `uri` | Yes | Both | LDAP server URI (ldap:// or ldaps://) |
| `mode` | Yes | Both | `direct` or `search` |
| `userdn` | Yes | direct | DN template with `%s` for username |
| `basedn` | Yes | search | Base DN for user search |
| `binddn` | Yes | search | Admin bind DN |
| `bindpass` | Yes | search | Admin bind password |
| `userfilter` | Yes | search | Search filter with `%s` for username |
| `groupdn` | No | search | Group DN for membership check |
| `accountattr` | No | Both | Attribute to use as account name |
| `timeout` | No | Both | Connection timeout in ms (default: 5000) |
| `priority` | No | Both | Provider priority (default: 100) |
#### Keycloak Provider
Authenticates via Keycloak using Resource Owner Password Credentials (ROPC) grant:
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client
```
With client secret (for confidential clients):
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=mysecret
```
Keycloak Options:
| Option | Required | Description |
|--------|----------|-------------|
| `url` | Yes | Keycloak server URL |
| `realm` | Yes | Realm name |
| `clientid` | Yes | Client ID |
| `clientsecret` | No | Client secret (for confidential clients) |
| `accountattr` | No | JWT claim to use as account name (default: preferred_username) |
| `timeout` | No | Request timeout in ms (default: 5000) |
| `priority` | No | Provider priority (default: 100) |
#### Multiple Providers (Fallback Chain)
Configure multiple providers with different priorities. Lower priority = tried first:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com mode=direct userdn=uid=%s,ou=users,dc=example,dc=com priority=10
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=irc clientid=irc-client priority=20
#IAUTH AUTH provider=file path=/path/to/local-users priority=100
```
## Usage
### Command Line
```bash
node dist/index.js -c <configfile> [-v] [-d]
Options:
-c, --config Config file to read (required)
-v, --verbose Enable verbose output in iauthd
-d, --debug Enable debug output in IRCd
-h, --help Show help
```
### IRCd Configuration
Add to your `ircd.conf`:
```
IAuth {
program = "node" "/path/to/iauthd-ts/dist/index.js" "-v" "-c" "/path/to/ircd.conf";
};
```
For Docker deployments:
```
IAuth {
program = "node" "/home/nefarious/ircd/iauthd-ts/index.js" "-v" "-c" "/home/nefarious/ircd/ircd.conf";
};
```
### Monitoring
To see IAuth debug messages as an operator:
```
/quote mode YourNick +s 262144
```
### Statistics
IAuth statistics are available via `/stats iauth` and include:
- Uptime
- Cache size
- Total passed/rejected clients
- Per-DNSBL hit counts
## Development
### Project Structure
```
iauthd-ts/
├── src/
│ ├── index.ts # CLI entry point
│ ├── iauth.ts # Main IAuth daemon class
│ ├── config.ts # Configuration parser
│ ├── dnsbl.ts # DNSBL lookup and caching
│ ├── sasl.ts # SASL authentication handling
│ ├── genhash.ts # Password hash generator utility
│ └── types.ts # TypeScript interfaces
├── users.example # Example SASL users file
├── tests/
│ ├── config.test.ts # Config parser tests
│ ├── dnsbl.test.ts # DNSBL function tests
│ ├── iauth.test.ts # Integration tests
│ └── stress.ts # Memory stress test
├── dist/ # Compiled JavaScript (after build)
├── package.json
├── tsconfig.json
└── vitest.config.ts
```
### Building
```bash
npm install # Install dependencies
npm run build # Compile TypeScript to dist/
```
### Running Tests
```bash
npm test # Run all tests
npm run test:watch # Watch mode (re-run on changes)
npm run test:coverage # Generate coverage report
```
### Test Coverage
The test suite includes:
- **Unit tests** (45 tests): Config parsing, IP handling, DNSBL matching, caching
- **Protocol integration tests** (17 tests): IAuth protocol simulation
- **DNSBL integration tests** (32 tests): Full pipeline with mocked DNS responses
#### DNSBL Integration Tests
The DNSBL integration tests (`tests/dnsbl-integration.test.ts`) use a mock DNS resolver to test realistic scenarios:
| Category | Tests |
|----------|-------|
| Index matching | Exact match, multiple indices, no match, NXDOMAIN |
| Bitmask matching | Single bit, multiple bits, no bits match |
| block=all | Blocks both anonymous and authenticated |
| block=anonymous | Blocks anonymous, allows SASL-authenticated |
| Mark only | Accepts client but applies mark |
| Whitelist | Overrides subsequent blocking DNSBLs |
| Multiple DNSBLs | Accumulates marks, any block triggers rejection |
| Same server/different indices | AfterNET pattern (whitelist=2, rbl=250, cloud=251) |
| Class assignment | Assigns connection class from matching DNSBL |
| Real-world simulation | Full AfterNET production config scenarios |
### Stress Testing
The stress test simulates thousands of concurrent connections to verify:
- Memory stability (no leaks in client tracking)
- Cache behavior
- Performance under load
```bash
npm run stress # Default: 5000 clients, 120s max
npm run stress -- --clients=10000 # More clients
npm run stress -- --duration=60 # Shorter duration
npm run stress -- -v # Verbose output
```
Example output:
```
============================================================
iauthd-ts Memory Stress Test
============================================================
Clients to simulate: 5000
Max concurrent: 100
Max duration: 120s
============================================================
Sent: 5000 | Accepted: 4994 | Rejected: 6 | Active: 0 | Cache: 5000 | Rate: 520.3/s
============================================================
STRESS TEST RESULTS
============================================================
Total clients sent: 5000
Total clients accepted: 4994
Total clients rejected: 6
Unprocessed clients: 0
Total time: 9.61s
Average rate: 520.29 clients/s
MEMORY ANALYSIS
------------------------------------------------------------
✅ Memory usage appears stable.
✅ All clients were processed correctly.
============================================================
```
### Development Mode
Run directly from TypeScript without compiling:
```bash
npm run dev -- -c /path/to/config
```
## Comparison with iauthd.pl
| Feature | iauthd.pl (Perl) | iauthd-ts (TypeScript) |
|---------|------------------|------------------------|
| Runtime | Perl + POE | Node.js |
| Async Model | POE event loop | Native async/await |
| Type Safety | None | Full TypeScript types |
| Testing | None | 62 tests + stress test |
| Dependencies | 5 CPAN modules | 0 runtime deps |
## Troubleshooting
### iauthd-ts not starting
- Check that Node.js 18+ is installed: `node --version`
- Verify config file path is correct and readable
- Check for syntax errors in `#IAUTH` directives
### Clients timing out
- Increase `DNSTIMEOUT` if DNSBL servers are slow
- Check network connectivity to DNSBL servers
- Verify DNS resolution is working: `host 2.0.0.127.dnsbl.example.com`
### High memory usage
- Reduce `CACHETIME` to expire entries sooner
- Monitor with stress test: `npm run stress`
- Check for many unique IPs (each gets cached)
### Debug output
Run with `-v` flag and set operator snomask:
```
/quote mode YourNick +s 262144
```
## License
GPL-2.0 - Same as Nefarious IRCd
+2062
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "iauthd-ts",
"version": "1.0.0",
"description": "IAuth daemon for Nefarious IRCd - TypeScript port",
"main": "dist/index.js",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"stress": "tsx tests/stress.ts"
},
"keywords": [
"irc",
"iauth",
"dnsbl",
"nefarious"
],
"license": "GPL-2.0",
"devDependencies": {
"@types/node": "^20.10.0",
"tsx": "^4.6.0",
"typescript": "^5.3.0",
"vitest": "^2.1.0"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"ldapts": "^7.2.1"
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Authentication configuration parser
* Parses #IAUTH AUTH directives
*/
import type {
AuthProviderConfig,
FileAuthConfig,
LDAPAuthConfig,
KeycloakAuthConfig,
} from './types.js';
/**
* Parse an AUTH configuration line
* Format: provider=<type> key=value key=value ...
*
* Examples:
* provider=file path=/path/to/users
* provider=ldap uri=ldap://server:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
* provider=ldap uri=ldaps://server:636 mode=search basedn=ou=users,dc=example,dc=com ...
*/
export function parseAuthConfig(args: string): AuthProviderConfig | null {
const params = parseKeyValuePairs(args);
const provider = params.get('provider');
if (!provider) {
return null;
}
switch (provider) {
case 'file':
return parseFileAuthConfig(params);
case 'ldap':
return parseLDAPAuthConfig(params);
case 'keycloak':
return parseKeycloakAuthConfig(params);
default:
console.error(`Unknown auth provider: ${provider}`);
return null;
}
}
/**
* Parse key=value pairs from a string
* Handles quoted values for values containing spaces
*/
function parseKeyValuePairs(args: string): Map<string, string> {
const result = new Map<string, string>();
// Match key=value or key="value with spaces" or key='value with spaces'
const regex = /(\w+)=(?:"([^"]*)"|'([^']*)'|(\S+))/g;
let match;
while ((match = regex.exec(args)) !== null) {
const key = match[1];
// Use quoted value if present, otherwise unquoted
const value = match[2] ?? match[3] ?? match[4];
result.set(key, value);
}
return result;
}
/**
* Parse file auth provider config
*/
function parseFileAuthConfig(params: Map<string, string>): FileAuthConfig | null {
const path = params.get('path');
if (!path) {
console.error('File auth provider requires path');
return null;
}
const priority = params.has('priority')
? parseInt(params.get('priority')!, 10)
: undefined;
return {
provider: 'file',
path,
priority,
};
}
/**
* Parse LDAP auth provider config
*/
function parseLDAPAuthConfig(params: Map<string, string>): LDAPAuthConfig | null {
const uri = params.get('uri');
if (!uri) {
console.error('LDAP auth provider requires uri');
return null;
}
const mode = params.get('mode') as 'direct' | 'search' | undefined;
if (!mode || (mode !== 'direct' && mode !== 'search')) {
console.error('LDAP auth provider requires mode (direct or search)');
return null;
}
const priority = params.has('priority')
? parseInt(params.get('priority')!, 10)
: undefined;
const timeout = params.has('timeout')
? parseInt(params.get('timeout')!, 10)
: undefined;
const config: LDAPAuthConfig = {
provider: 'ldap',
uri,
mode,
priority,
timeout,
};
// Mode-specific options
if (mode === 'direct') {
config.userdn = params.get('userdn');
} else {
config.basedn = params.get('basedn');
config.binddn = params.get('binddn');
config.bindpass = params.get('bindpass');
config.userfilter = params.get('userfilter');
config.groupdn = params.get('groupdn');
}
// Optional for both modes
config.accountattr = params.get('accountattr');
return config;
}
/**
* Parse Keycloak auth provider config
*/
function parseKeycloakAuthConfig(params: Map<string, string>): KeycloakAuthConfig | null {
const url = params.get('url');
if (!url) {
console.error('Keycloak auth provider requires url');
return null;
}
const realm = params.get('realm');
if (!realm) {
console.error('Keycloak auth provider requires realm');
return null;
}
const clientid = params.get('clientid');
if (!clientid) {
console.error('Keycloak auth provider requires clientid');
return null;
}
const priority = params.has('priority')
? parseInt(params.get('priority')!, 10)
: undefined;
const timeout = params.has('timeout')
? parseInt(params.get('timeout')!, 10)
: undefined;
return {
provider: 'keycloak',
url,
realm,
clientid,
clientsecret: params.get('clientsecret'),
accountattr: params.get('accountattr'),
timeout,
priority,
};
}
/**
* Convert legacy SASLDB directive to file provider config
*/
export function convertSASLDB(path: string): FileAuthConfig {
return {
provider: 'file',
path,
priority: 100, // Default priority
};
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Authentication module for iauthd-ts
* Provides modular authentication with multiple backend support
*/
// Types
export type {
AuthResult,
AuthProvider,
AuthProviderConfig,
FileAuthConfig,
LDAPAuthConfig,
KeycloakAuthConfig,
} from './types.js';
export { isFileAuthConfig, isLDAPAuthConfig, isKeycloakAuthConfig } from './types.js';
// Manager
export { AuthManager } from './manager.js';
// Config parsing
export { parseAuthConfig, convertSASLDB } from './config.js';
// Providers
export { FileAuthProvider, LDAPAuthProvider, KeycloakAuthProvider } from './providers/index.js';
+173
View File
@@ -0,0 +1,173 @@
/**
* Authentication Manager
* Coordinates multiple authentication providers with fallback chain behavior
*/
import type {
AuthProvider,
AuthResult,
AuthProviderConfig,
FileAuthConfig,
LDAPAuthConfig,
KeycloakAuthConfig,
} from './types.js';
import { FileAuthProvider } from './providers/file.js';
import { LDAPAuthProvider } from './providers/ldap.js';
import { KeycloakAuthProvider } from './providers/keycloak.js';
export class AuthManager {
private providers: AuthProvider[] = [];
private initialized = false;
constructor(private readonly configs: AuthProviderConfig[]) {}
/**
* Initialize all configured providers
* Providers are sorted by priority (lower = first)
*/
async initialize(): Promise<void> {
if (this.initialized) {
return;
}
// Sort by priority (lower first)
const sorted = [...this.configs].sort(
(a, b) => (a.priority ?? 100) - (b.priority ?? 100)
);
for (const config of sorted) {
const provider = this.createProvider(config);
try {
await provider.initialize();
this.providers.push(provider);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(`Failed to initialize ${config.provider} provider: ${message}`);
// Continue with other providers
}
}
this.initialized = true;
}
/**
* Create a provider instance from configuration
*/
private createProvider(config: AuthProviderConfig): AuthProvider {
switch (config.provider) {
case 'file':
return new FileAuthProvider(config as FileAuthConfig);
case 'ldap':
return new LDAPAuthProvider(config as LDAPAuthConfig);
case 'keycloak':
return new KeycloakAuthProvider(config as KeycloakAuthConfig);
default:
throw new Error(`Unknown auth provider: ${(config as AuthProviderConfig).provider}`);
}
}
/**
* Authenticate using fallback chain
* Tries providers in priority order until one succeeds
*/
async authenticate(
authcid: string,
password: string,
authzid?: string
): Promise<AuthResult> {
if (!this.initialized) {
return { success: false, error: 'AuthManager not initialized' };
}
if (this.providers.length === 0) {
return { success: false, error: 'No auth providers configured' };
}
let lastError: string | undefined;
for (const provider of this.providers) {
// Skip unhealthy providers
if (!provider.isHealthy()) {
continue;
}
try {
const result = await provider.authenticate(authcid, password, authzid);
if (result.success) {
return result;
}
// Provider returned explicit failure - continue to next
lastError = result.error;
} catch (err) {
// Provider threw error - log and continue
const message = err instanceof Error ? err.message : String(err);
console.error(`Auth provider ${provider.name} error: ${message}`);
lastError = message;
}
}
return { success: false, error: lastError ?? 'Authentication failed' };
}
/**
* Check if any providers are configured and healthy
*/
hasProviders(): boolean {
return this.providers.length > 0;
}
/**
* Check if any provider is healthy
*/
hasHealthyProviders(): boolean {
return this.providers.some((p) => p.isHealthy());
}
/**
* Get provider count
*/
getProviderCount(): number {
return this.providers.length;
}
/**
* Get provider info for status display
*/
getProviderInfo(): Array<{ name: string; priority: number; healthy: boolean }> {
return this.providers.map((p) => ({
name: p.name,
priority: p.priority,
healthy: p.isHealthy(),
}));
}
/**
* Reload all providers
*/
async reload(): Promise<void> {
for (const provider of this.providers) {
try {
await provider.reload();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(`Failed to reload ${provider.name} provider: ${message}`);
}
}
}
/**
* Shutdown all providers
*/
async shutdown(): Promise<void> {
for (const provider of this.providers) {
try {
await provider.shutdown();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(`Failed to shutdown ${provider.name} provider: ${message}`);
}
}
this.providers = [];
this.initialized = false;
}
}
@@ -0,0 +1,77 @@
/**
* Static file authentication provider
* Wraps the existing SASL users file functionality
*/
import type { AuthProvider, AuthResult, FileAuthConfig } from '../types.js';
import {
parseUsersFile,
usersFileModified,
authenticatePlain,
type UsersDB,
} from '../../sasl.js';
const DEFAULT_PRIORITY = 100;
export class FileAuthProvider implements AuthProvider {
readonly name = 'file';
readonly priority: number;
private usersDb: UsersDB | null = null;
private readonly filePath: string;
constructor(config: FileAuthConfig) {
this.filePath = config.path;
this.priority = config.priority ?? DEFAULT_PRIORITY;
}
async initialize(): Promise<void> {
this.usersDb = parseUsersFile(this.filePath);
if (this.usersDb.users.size === 0) {
// Not an error - file might not exist or be empty
// Provider will return failure for all auth attempts
}
}
async authenticate(
authcid: string,
password: string,
_authzid?: string
): Promise<AuthResult> {
if (!this.usersDb) {
return { success: false, error: 'Users database not loaded' };
}
// Check if file was modified and reload if needed
if (usersFileModified(this.usersDb)) {
this.usersDb = parseUsersFile(this.filePath);
}
const account = authenticatePlain(this.usersDb, authcid, password);
if (account) {
return { success: true, account };
}
return { success: false, error: 'Invalid credentials' };
}
async reload(): Promise<void> {
this.usersDb = parseUsersFile(this.filePath);
}
async shutdown(): Promise<void> {
this.usersDb = null;
}
isHealthy(): boolean {
return this.usersDb !== null;
}
/**
* Get the number of users loaded
*/
getUserCount(): number {
return this.usersDb?.users.size ?? 0;
}
}
@@ -0,0 +1,7 @@
/**
* Authentication providers
*/
export { FileAuthProvider } from './file.js';
export { LDAPAuthProvider } from './ldap.js';
export { KeycloakAuthProvider } from './keycloak.js';
@@ -0,0 +1,282 @@
/**
* Keycloak authentication provider
* Uses Resource Owner Password Credentials (ROPC) grant to authenticate users
*/
import type { AuthProvider, AuthResult, KeycloakAuthConfig } from '../types.js';
const DEFAULT_PRIORITY = 100;
const DEFAULT_TIMEOUT = 5000;
/**
* Token response from Keycloak
*/
interface TokenResponse {
access_token: string;
expires_in: number;
refresh_expires_in: number;
refresh_token?: string;
token_type: string;
'not-before-policy'?: number;
session_state?: string;
scope: string;
}
/**
* Error response from Keycloak
*/
interface ErrorResponse {
error: string;
error_description?: string;
}
/**
* Decoded JWT payload (partial - only fields we care about)
*/
interface JWTPayload {
sub: string;
preferred_username?: string;
email?: string;
name?: string;
given_name?: string;
family_name?: string;
[key: string]: unknown;
}
export class KeycloakAuthProvider implements AuthProvider {
readonly name = 'keycloak';
readonly priority: number;
private readonly config: KeycloakAuthConfig;
private readonly tokenEndpoint: string;
private healthy = false;
constructor(config: KeycloakAuthConfig) {
this.config = config;
this.priority = config.priority ?? DEFAULT_PRIORITY;
// Build token endpoint URL
// Format: {url}/realms/{realm}/protocol/openid-connect/token
const baseUrl = config.url.replace(/\/$/, ''); // Remove trailing slash
this.tokenEndpoint = `${baseUrl}/realms/${config.realm}/protocol/openid-connect/token`;
}
async initialize(): Promise<void> {
// Validate configuration
if (!this.config.url) {
throw new Error('Keycloak provider requires url');
}
if (!this.config.realm) {
throw new Error('Keycloak provider requires realm');
}
if (!this.config.clientid) {
throw new Error('Keycloak provider requires clientid');
}
// Test connectivity by fetching the OpenID configuration
try {
const wellKnownUrl = `${this.config.url.replace(/\/$/, '')}/realms/${this.config.realm}/.well-known/openid-configuration`;
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(),
this.config.timeout ?? DEFAULT_TIMEOUT
);
try {
const response = await fetch(wellKnownUrl, {
method: 'GET',
signal: controller.signal,
});
clearTimeout(timeout);
if (response.ok) {
this.healthy = true;
} else {
// Server responded but with error - still mark as potentially healthy
// since auth might still work
this.healthy = true;
}
} catch (err) {
clearTimeout(timeout);
throw err;
}
} catch (err) {
// Connection failed - mark as unhealthy but don't throw
// Provider may become healthy later
this.healthy = false;
}
}
async authenticate(
authcid: string,
password: string,
_authzid?: string
): Promise<AuthResult> {
try {
// Build form data for ROPC grant
const params = new URLSearchParams();
params.append('grant_type', 'password');
params.append('client_id', this.config.clientid);
params.append('username', authcid);
params.append('password', password);
// Add client secret if configured (for confidential clients)
if (this.config.clientsecret) {
params.append('client_secret', this.config.clientsecret);
}
// Make request with timeout
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(),
this.config.timeout ?? DEFAULT_TIMEOUT
);
let response: Response;
try {
response = await fetch(this.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
signal: controller.signal,
});
clearTimeout(timeout);
} catch (err) {
clearTimeout(timeout);
if (err instanceof Error && err.name === 'AbortError') {
this.healthy = false;
return { success: false, error: 'Request timeout' };
}
throw err;
}
// Parse response
const body = await response.text();
if (response.ok) {
// Success - parse token response
const tokenResponse = JSON.parse(body) as TokenResponse;
this.healthy = true;
// Extract account name from access token
const account = this.extractAccountFromToken(tokenResponse.access_token, authcid);
return { success: true, account };
} else {
// Error response
try {
const errorResponse = JSON.parse(body) as ErrorResponse;
// Check for disabled user (before generic invalid_grant)
if (errorResponse.error_description?.includes('Account disabled')) {
this.healthy = true;
return { success: false, error: 'Account disabled' };
}
// Check for invalid credentials
if (
errorResponse.error === 'invalid_grant' ||
errorResponse.error_description?.includes('Invalid user credentials')
) {
this.healthy = true; // Server is healthy, just bad credentials
return { success: false, error: 'Invalid credentials' };
}
// Check for client errors (misconfiguration)
if (
errorResponse.error === 'unauthorized_client' ||
errorResponse.error === 'invalid_client'
) {
return {
success: false,
error: `Client error: ${errorResponse.error_description || errorResponse.error}`,
};
}
return {
success: false,
error: errorResponse.error_description || errorResponse.error,
};
} catch {
return { success: false, error: `HTTP ${response.status}: ${body}` };
}
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.healthy = false;
return { success: false, error: `Keycloak error: ${message}` };
}
}
/**
* Extract account name from JWT access token
*/
private extractAccountFromToken(accessToken: string, fallback: string): string {
try {
// JWT format: header.payload.signature
const parts = accessToken.split('.');
if (parts.length !== 3) {
return fallback;
}
// Decode payload (base64url)
const payload = this.decodeBase64Url(parts[1]);
const claims = JSON.parse(payload) as JWTPayload;
// Use configured attribute or default to preferred_username
if (this.config.accountattr) {
const value = claims[this.config.accountattr];
if (typeof value === 'string') {
return value;
}
}
// Try common username claims
if (claims.preferred_username) {
return claims.preferred_username;
}
// Fall back to subject (UUID)
if (claims.sub) {
return claims.sub;
}
return fallback;
} catch {
return fallback;
}
}
/**
* Decode base64url string
*/
private decodeBase64Url(str: string): string {
// Convert base64url to base64
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
// Add padding if needed
const padding = base64.length % 4;
if (padding) {
base64 += '='.repeat(4 - padding);
}
return Buffer.from(base64, 'base64').toString('utf-8');
}
async reload(): Promise<void> {
// Re-test connectivity
await this.initialize();
}
async shutdown(): Promise<void> {
this.healthy = false;
}
isHealthy(): boolean {
return this.healthy;
}
}
+363
View File
@@ -0,0 +1,363 @@
/**
* LDAP authentication provider
* Supports direct bind and search+bind modes
*/
import { Client } from 'ldapts';
import type { AuthProvider, AuthResult, LDAPAuthConfig } from '../types.js';
const DEFAULT_PRIORITY = 100;
const DEFAULT_TIMEOUT = 5000;
export class LDAPAuthProvider implements AuthProvider {
readonly name = 'ldap';
readonly priority: number;
private readonly config: LDAPAuthConfig;
private healthy = false;
constructor(config: LDAPAuthConfig) {
this.config = config;
this.priority = config.priority ?? DEFAULT_PRIORITY;
}
async initialize(): Promise<void> {
// Validate configuration
if (!this.config.uri) {
throw new Error('LDAP provider requires uri');
}
if (!this.config.mode) {
throw new Error('LDAP provider requires mode (direct or search)');
}
if (this.config.mode === 'direct' && !this.config.userdn) {
throw new Error('LDAP direct mode requires userdn template');
}
if (this.config.mode === 'search') {
if (!this.config.basedn) {
throw new Error('LDAP search mode requires basedn');
}
if (!this.config.binddn || !this.config.bindpass) {
throw new Error('LDAP search mode requires binddn and bindpass');
}
if (!this.config.userfilter) {
throw new Error('LDAP search mode requires userfilter');
}
}
// Test connection with a simple bind/unbind
try {
const client = this.createClient();
await client.bind(
this.config.binddn || '',
this.config.bindpass || ''
);
await client.unbind();
this.healthy = true;
} catch (err) {
// Connection test failed - provider may still work later
// Mark as unhealthy but don't throw
this.healthy = false;
}
}
async authenticate(
authcid: string,
password: string,
_authzid?: string
): Promise<AuthResult> {
try {
if (this.config.mode === 'direct') {
return await this.authenticateDirect(authcid, password);
} else {
return await this.authenticateSearch(authcid, password);
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { success: false, error: `LDAP error: ${message}` };
}
}
/**
* Direct bind mode: construct DN from template and bind with user's password
*/
private async authenticateDirect(
username: string,
password: string
): Promise<AuthResult> {
const userDN = this.config.userdn!.replace(/%s/g, this.escapeDN(username));
const client = this.createClient();
try {
await client.bind(userDN, password);
this.healthy = true;
// Get account name from DN or use username
const account = this.extractAccountFromDN(userDN, username);
await client.unbind();
return { success: true, account };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
// LDAP error code 49 is invalid credentials
if (message.includes('49') || message.toLowerCase().includes('invalid credentials')) {
return { success: false, error: 'Invalid credentials' };
}
// Other errors might indicate server issues
this.healthy = false;
return { success: false, error: `LDAP bind failed: ${message}` };
} finally {
try {
await client.unbind();
} catch {
// Ignore unbind errors
}
}
}
/**
* Search mode: bind as admin, find user, optionally check group, then bind as user
*/
private async authenticateSearch(
username: string,
password: string
): Promise<AuthResult> {
const client = this.createClient();
try {
// Step 1: Bind as admin
await client.bind(this.config.binddn!, this.config.bindpass!);
this.healthy = true;
// Step 2: Search for user
const filter = this.config.userfilter!.replace(/%s/g, this.escapeFilter(username));
const searchResult = await client.search(this.config.basedn!, {
scope: 'sub',
filter,
attributes: [
'dn',
this.config.accountattr || 'uid',
'sAMAccountName', // Active Directory
'cn',
],
});
if (searchResult.searchEntries.length === 0) {
await client.unbind();
return { success: false, error: 'User not found' };
}
const userEntry = searchResult.searchEntries[0];
const userDN = userEntry.dn;
// Step 3: Optional group membership check
if (this.config.groupdn) {
const isMember = await this.checkGroupMembership(client, userDN);
if (!isMember) {
await client.unbind();
return { success: false, error: 'User not in required group' };
}
}
// Step 4: Bind as user to verify password
await client.unbind();
const userClient = this.createClient();
try {
await userClient.bind(userDN, password);
await userClient.unbind();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (message.includes('49') || message.toLowerCase().includes('invalid credentials')) {
return { success: false, error: 'Invalid credentials' };
}
return { success: false, error: `LDAP bind failed: ${message}` };
}
// Extract account name from search result
const account = this.extractAccountFromEntry(userEntry, username);
return { success: true, account };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.healthy = false;
return { success: false, error: `LDAP search failed: ${message}` };
} finally {
try {
await client.unbind();
} catch {
// Ignore unbind errors
}
}
}
/**
* Check if user is a member of the configured group
*/
private async checkGroupMembership(client: Client, userDN: string): Promise<boolean> {
try {
const searchResult = await client.search(this.config.groupdn!, {
scope: 'base',
filter: '(objectClass=*)',
attributes: ['member', 'uniqueMember', 'memberUid'],
});
if (searchResult.searchEntries.length === 0) {
return false;
}
const groupEntry = searchResult.searchEntries[0];
// Check member attribute (standard LDAP groups)
const members = this.getAttrValues(groupEntry, 'member');
if (members.some((m) => m.toLowerCase() === userDN.toLowerCase())) {
return true;
}
// Check uniqueMember attribute (some LDAP servers)
const uniqueMembers = this.getAttrValues(groupEntry, 'uniqueMember');
if (uniqueMembers.some((m) => m.toLowerCase() === userDN.toLowerCase())) {
return true;
}
// Check memberUid attribute (posixGroup)
const memberUids = this.getAttrValues(groupEntry, 'memberUid');
const uid = this.extractUidFromDN(userDN);
if (uid && memberUids.includes(uid)) {
return true;
}
return false;
} catch {
return false;
}
}
/**
* Get attribute values as string array
*/
private getAttrValues(entry: Record<string, unknown>, attr: string): string[] {
const value = entry[attr];
if (!value) return [];
if (Array.isArray(value)) return value.map(String);
return [String(value)];
}
/**
* Extract uid from a DN like "uid=john,ou=users,dc=example,dc=com"
*/
private extractUidFromDN(dn: string): string | null {
const match = dn.match(/^uid=([^,]+)/i);
return match ? match[1] : null;
}
/**
* Extract account name from DN
*/
private extractAccountFromDN(dn: string, fallback: string): string {
// Try to extract uid or cn from DN
const uidMatch = dn.match(/^uid=([^,]+)/i);
if (uidMatch) return uidMatch[1];
const cnMatch = dn.match(/^cn=([^,]+)/i);
if (cnMatch) return cnMatch[1];
return fallback;
}
/**
* Extract account name from LDAP entry
*/
private extractAccountFromEntry(
entry: Record<string, unknown>,
fallback: string
): string {
// Use configured attribute if specified
if (this.config.accountattr) {
const value = entry[this.config.accountattr];
if (value) {
return Array.isArray(value) ? String(value[0]) : String(value);
}
}
// Try common account name attributes
for (const attr of ['uid', 'sAMAccountName', 'cn']) {
const value = entry[attr];
if (value) {
return Array.isArray(value) ? String(value[0]) : String(value);
}
}
return fallback;
}
/**
* Create a new LDAP client
*/
private createClient(): Client {
return new Client({
url: this.config.uri,
timeout: this.config.timeout ?? DEFAULT_TIMEOUT,
connectTimeout: this.config.timeout ?? DEFAULT_TIMEOUT,
});
}
/**
* Escape special characters in DN values
*/
private escapeDN(value: string): string {
// Escape special DN characters: , + " \ < > ; = (leading/trailing spaces)
return value
.replace(/\\/g, '\\\\')
.replace(/,/g, '\\,')
.replace(/\+/g, '\\+')
.replace(/"/g, '\\"')
.replace(/</g, '\\<')
.replace(/>/g, '\\>')
.replace(/;/g, '\\;')
.replace(/=/g, '\\=')
.replace(/^ /, '\\ ')
.replace(/ $/, '\\ ');
}
/**
* Escape special characters in LDAP filter values
*/
private escapeFilter(value: string): string {
// Escape special filter characters: * ( ) \ NUL
return value
.replace(/\\/g, '\\5c')
.replace(/\*/g, '\\2a')
.replace(/\(/g, '\\28')
.replace(/\)/g, '\\29')
.replace(/\x00/g, '\\00');
}
async reload(): Promise<void> {
// LDAP config is static, nothing to reload
// Re-test connection
try {
const client = this.createClient();
if (this.config.mode === 'search') {
await client.bind(this.config.binddn!, this.config.bindpass!);
}
await client.unbind();
this.healthy = true;
} catch {
this.healthy = false;
}
}
async shutdown(): Promise<void> {
// Nothing to cleanup - we don't pool connections
this.healthy = false;
}
isHealthy(): boolean {
return this.healthy;
}
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Authentication provider types for iauthd-ts
* Defines the interface for modular authentication backends
*/
/**
* Result of an authentication attempt
*/
export interface AuthResult {
/** Whether authentication succeeded */
success: boolean;
/** Account name if successful (used for IRC account tracking) */
account?: string;
/** Error message if failed (for logging, not shown to user) */
error?: string;
}
/**
* Authentication provider interface
* All providers must implement this interface
*/
export interface AuthProvider {
/** Provider name for logging/debugging */
readonly name: string;
/** Provider priority (lower = checked first) */
readonly priority: number;
/**
* Initialize the provider (called once at startup)
* Should throw if configuration is invalid
*/
initialize(): Promise<void>;
/**
* Authenticate a user with SASL PLAIN credentials
* @param authcid - Authentication identity (username)
* @param password - Password
* @param authzid - Authorization identity (usually empty or same as authcid)
* @returns AuthResult indicating success/failure
*/
authenticate(authcid: string, password: string, authzid?: string): Promise<AuthResult>;
/**
* Called on rehash to reload configuration
*/
reload(): Promise<void>;
/**
* Cleanup resources (called on shutdown)
*/
shutdown(): Promise<void>;
/**
* Check if provider is healthy/connected
*/
isHealthy(): boolean;
}
/**
* Base configuration for all auth providers
*/
export interface BaseAuthConfig {
provider: string;
priority?: number; // Default: 100
}
/**
* Static file provider configuration
*/
export interface FileAuthConfig extends BaseAuthConfig {
provider: 'file';
path: string;
}
/**
* LDAP provider configuration
*/
export interface LDAPAuthConfig extends BaseAuthConfig {
provider: 'ldap';
/** LDAP server URI (ldap:// or ldaps://) */
uri: string;
/** Authentication mode */
mode: 'direct' | 'search';
/** Direct mode: DN template with %s for username */
userdn?: string;
/** Search mode: Base DN for user search */
basedn?: string;
/** Search mode: Admin bind DN */
binddn?: string;
/** Search mode: Admin bind password */
bindpass?: string;
/** Search mode: User search filter with %s for username (e.g., "(uid=%s)") */
userfilter?: string;
/** Optional: Group DN for membership check */
groupdn?: string;
/** Optional: Attribute to use as account name (default: uid or sAMAccountName) */
accountattr?: string;
/** Connection timeout in milliseconds (default: 5000) */
timeout?: number;
}
/**
* Keycloak provider configuration
* Uses Resource Owner Password Credentials (ROPC) grant
*/
export interface KeycloakAuthConfig extends BaseAuthConfig {
provider: 'keycloak';
/** Keycloak server URL (e.g., https://keycloak.example.com) */
url: string;
/** Keycloak realm name */
realm: string;
/** OAuth2 client ID (must have Direct Access Grants enabled) */
clientid: string;
/** OAuth2 client secret (for confidential clients) */
clientsecret?: string;
/** Optional: Attribute from token to use as account name (default: preferred_username) */
accountattr?: string;
/** Request timeout in milliseconds (default: 5000) */
timeout?: number;
}
export type AuthProviderConfig = FileAuthConfig | LDAPAuthConfig | KeycloakAuthConfig;
/**
* Type guard for FileAuthConfig
*/
export function isFileAuthConfig(config: AuthProviderConfig): config is FileAuthConfig {
return config.provider === 'file';
}
/**
* Type guard for LDAPAuthConfig
*/
export function isLDAPAuthConfig(config: AuthProviderConfig): config is LDAPAuthConfig {
return config.provider === 'ldap';
}
/**
* Type guard for KeycloakAuthConfig
*/
export function isKeycloakAuthConfig(config: AuthProviderConfig): config is KeycloakAuthConfig {
return config.provider === 'keycloak';
}
+145
View File
@@ -0,0 +1,145 @@
/**
* Configuration parser for iauthd
* Reads #IAUTH directives from config files
*/
import { readFileSync } from 'node:fs';
import type { Config, DNSBLConfig } from './types.js';
import { parseAuthConfig, convertSASLDB } from './auth/config.js';
const DEFAULT_CACHE_TIME = 60 * 60 * 24; // 24 hours
const DEFAULT_DNS_TIMEOUT = 5;
const DEFAULT_BLOCK_MSG = 'Your internet address has been rejected due to reputation (DNSBL).';
const DEFAULT_POLICY = 'RTAWUwFr';
const DEFAULT_SASL_FAIL_MSG = 'SASL authentication failed';
/**
* Parse a DNSBL configuration line
* Format: server=dnsbl.sorbs.net index=2,3,4 mark=sorbs block=anonymous
*/
function parseDNSBLConfig(args: string, cfgNum: number): DNSBLConfig {
const config: DNSBLConfig = {
cfgNum,
server: '',
};
for (const arg of args.split(/\s+/)) {
const match = arg.match(/^(\w+)=(.+)$/);
if (match) {
const [, key, value] = match;
switch (key) {
case 'server':
config.server = value;
break;
case 'index':
config.index = value;
break;
case 'bitmask':
config.bitmask = value;
break;
case 'mark':
config.mark = value;
break;
case 'block':
if (value === 'all' || value === 'anonymous') {
config.block = value;
}
break;
case 'class':
config.class = value;
break;
case 'cachetime':
config.cacheTime = parseInt(value, 10);
break;
case 'whitelist':
config.whitelist = true;
break;
}
} else if (arg === 'whitelist') {
config.whitelist = true;
}
}
return config;
}
/**
* Read and parse configuration from a file
* Looks for lines starting with #IAUTH
*/
export function readConfigFile(filePath: string): { config: Config; configLines: string[] } {
const config: Config = {
policy: DEFAULT_POLICY,
dnsbls: [],
dnsTimeout: DEFAULT_DNS_TIMEOUT,
blockMsg: DEFAULT_BLOCK_MSG,
cacheTime: DEFAULT_CACHE_TIME,
debug: false,
saslFailMsg: DEFAULT_SASL_FAIL_MSG,
authProviders: [],
};
const configLines: string[] = [];
let cfgNum = 0;
const content = readFileSync(filePath, 'utf-8');
for (const line of content.split('\n')) {
const match = line.match(/^#IAUTH\s+(\w+)(?:\s+(.+))?$/);
if (!match) continue;
const directive = match[1];
const args = match[2] || '';
cfgNum++;
configLines.push(`${cfgNum}: ${directive} ${args}`);
switch (directive) {
case 'POLICY':
config.policy = args.trim();
break;
case 'DNSBL':
const dnsblConfig = parseDNSBLConfig(args, cfgNum);
if (dnsblConfig.server) {
config.dnsbls.push(dnsblConfig);
}
break;
case 'DEBUG':
config.debug = true;
break;
case 'DNSTIMEOUT':
config.dnsTimeout = parseInt(args.trim(), 10) || DEFAULT_DNS_TIMEOUT;
break;
case 'BLOCKMSG':
config.blockMsg = args.trim();
break;
case 'CACHETIME':
config.cacheTime = parseInt(args.trim(), 10) || DEFAULT_CACHE_TIME;
break;
case 'SASLDB':
// Legacy support: convert to file auth provider
config.saslUsersFile = args.trim();
config.authProviders.push(convertSASLDB(args.trim()));
break;
case 'SASLFAILMSG':
config.saslFailMsg = args.trim();
break;
case 'AUTH':
const authConfig = parseAuthConfig(args);
if (authConfig) {
config.authProviders.push(authConfig);
}
break;
}
}
return { config, configLines };
}
+147
View File
@@ -0,0 +1,147 @@
/**
* DNSBL lookup module with caching
*/
import { promises as dns } from 'node:dns';
import type { CacheEntry, DNSBLConfig } from './types.js';
/** Global DNSBL result cache */
const cache = new Map<string, CacheEntry>();
/**
* Reverse an IPv4 address for DNSBL lookup
* e.g., "192.168.1.10" -> "10.1.168.192"
*/
export function reverseIPv4(ip: string): string | null {
const match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!match) return null;
// Validate each octet is 0-255
const octets = [match[1], match[2], match[3], match[4]].map(o => parseInt(o, 10));
if (octets.some(o => o > 255)) return null;
return `${match[4]}.${match[3]}.${match[2]}.${match[1]}`;
}
/**
* Check if an IP is IPv4
*/
export function isIPv4(ip: string): boolean {
return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
}
/**
* Get cache entry if valid
*/
export function getCacheEntry(query: string, cacheTime: number): CacheEntry | null {
const entry = cache.get(query);
if (!entry) return null;
const now = Date.now();
// cacheTime <= 0 means always expired, otherwise check age
if (cacheTime <= 0 || entry.ts <= now - cacheTime * 1000) {
// Cache expired
cache.delete(query);
return null;
}
return entry;
}
/**
* Set cache entry
*/
export function setCacheEntry(query: string, result: string[] | null): void {
cache.set(query, {
result,
ts: Date.now(),
});
}
/**
* Get cache size for stats
*/
export function getCacheSize(): number {
return cache.size;
}
/**
* Perform a DNSBL lookup
* Returns array of result IPs or empty array if not listed
*/
export async function lookupDNSBL(
reversedIp: string,
dnsblServer: string,
timeout: number
): Promise<string[]> {
const query = `${reversedIp}.${dnsblServer}`;
try {
// Create a DNS resolver with timeout
const resolver = new dns.Resolver();
resolver.setServers(['8.8.8.8', '8.8.4.4']); // Use Google DNS as fallback
// Race against timeout
const timeoutPromise = new Promise<string[]>((_, reject) => {
setTimeout(() => reject(new Error('DNS timeout')), timeout * 1000);
});
const lookupPromise = dns.resolve4(query);
const result = await Promise.race([lookupPromise, timeoutPromise]);
return result;
} catch (err) {
// NXDOMAIN or timeout = not listed
return [];
}
}
/**
* Check if a DNSBL result matches the configuration
*/
export function matchesDNSBL(results: string[], config: DNSBLConfig): boolean {
for (const ip of results) {
const match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!match) continue;
const value = parseInt(match[4], 10);
// Check index match
if (config.index) {
const indices = config.index.split(',').map(i => parseInt(i.trim(), 10));
if (indices.includes(value)) {
return true;
}
}
// Check bitmask match
if (config.bitmask) {
const bitmasks = config.bitmask.split(',').map(b => parseInt(b.trim(), 10));
for (const bitmask of bitmasks) {
if ((bitmask & value) !== 0) {
return true;
}
}
}
// If no index or bitmask specified, any result is a match
if (!config.index && !config.bitmask) {
return true;
}
}
return false;
}
/**
* Parse DNSBL query to extract IP and server
*/
export function parseQuery(query: string): { ip: string; server: string } | null {
const match = query.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/);
if (!match) return null;
return {
ip: `${match[4]}.${match[3]}.${match[2]}.${match[1]}`,
server: match[5],
};
}
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env node
/**
* Password hash generator for iauthd-ts SASL users file
*
* Usage: npx tsx src/genhash.ts <password> [type]
*
* Types:
* sha256 (default) - SHA-256 crypt format ($5$)
* sha512 - SHA-512 crypt format ($6$)
* md5 - MD5 crypt format ($1$)
*/
import { generateHash } from './sasl.js';
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('Usage: npx tsx src/genhash.ts <password> [type]');
console.log('');
console.log('Types:');
console.log(' sha256 (default) - SHA-256 crypt format ($5$)');
console.log(' sha512 - SHA-512 crypt format ($6$)');
console.log(' md5 - MD5 crypt format ($1$)');
console.log('');
console.log('Example:');
console.log(' npx tsx src/genhash.ts mypassword sha256');
process.exit(1);
}
const password = args[0];
const type = (args[1] || 'sha256') as 'sha256' | 'sha512' | 'md5';
if (!['sha256', 'sha512', 'md5'].includes(type)) {
console.error(`Invalid hash type: ${type}`);
console.error('Valid types: sha256, sha512, md5');
process.exit(1);
}
const hash = generateHash(password, type);
console.log(hash);
+834
View File
@@ -0,0 +1,834 @@
/**
* IAuth Daemon - Main implementation
* Handles communication with Nefarious IRCd and DNSBL lookups
*/
import { createInterface, Interface } from 'node:readline';
import { readConfigFile } from './config.js';
import {
reverseIPv4,
isIPv4,
getCacheEntry,
setCacheEntry,
getCacheSize,
lookupDNSBL,
matchesDNSBL,
} from './dnsbl.js';
import {
decodeSASLPlain,
getSupportedMechanisms,
} from './sasl.js';
import { AuthManager } from './auth/index.js';
import type { Config, ClientState, DNSBLConfig, CLIOptions, SASLState } from './types.js';
const VERSION = '1.0.0';
export class IAuthDaemon {
private config: Config;
private configPath: string;
private options: CLIOptions;
private clients = new Map<number, ClientState>();
private dnsblCounters = new Map<number, number>();
private countPass = 0;
private countReject = 0;
private countSaslSuccess = 0;
private countSaslFail = 0;
private startTime = Date.now();
private rl: Interface | null = null;
private authManager: AuthManager | null = null;
private authInitialized = false;
constructor(options: CLIOptions) {
this.options = options;
this.configPath = options.config;
const { config } = readConfigFile(options.config);
this.config = config;
// Initialize DNSBL counters
for (const dnsbl of this.config.dnsbls) {
this.dnsblCounters.set(dnsbl.cfgNum, 0);
}
// Initialize auth manager asynchronously
this.initializeAuth();
}
/**
* Initialize the authentication manager
*/
private async initializeAuth(): Promise<void> {
if (this.config.authProviders.length > 0) {
this.authManager = new AuthManager(this.config.authProviders);
try {
await this.authManager.initialize();
this.authInitialized = true;
const info = this.authManager.getProviderInfo();
this.debug(`Initialized ${info.length} auth provider(s): ${info.map(p => p.name).join(', ')}`);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.debug(`Failed to initialize auth manager: ${message}`);
}
}
}
/**
* Check if SASL/auth is enabled
*/
private saslEnabled(): boolean {
return this.authManager !== null && this.authManager.hasProviders();
}
/**
* Send a message to ircd via stdout
*/
private send(message: string): void {
console.log(message);
}
/**
* Send debug message (prefixed with "> :")
*/
private debug(message: string): void {
if (this.options.verbose || this.options.debug) {
this.send(`> :${message}`);
}
}
/**
* Start the daemon
*/
start(): void {
this.handleStartup();
this.rl = createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
this.rl.on('line', (line) => this.handleLine(line));
this.rl.on('close', () => {
this.debug('STDIN closed. Shutting down...');
process.exit(0);
});
}
/**
* Send startup messages to ircd
*/
private handleStartup(): void {
// Request iauth protocol version
this.send('G 1');
// Send version
this.send(`V :Nefarious2 iauthd-ts version ${VERSION}`);
// Set policy options
this.send(`O ${this.config.policy}`);
// Send configuration
this.sendNewConfig();
this.debug('Starting up');
this.sendStats();
}
/**
* Send configuration info to ircd
*/
private sendNewConfig(): void {
this.send('a');
this.send(`A * version :Nefarious iauthd-ts ${VERSION}`);
const { configLines } = readConfigFile(this.configPath);
for (const line of configLines) {
this.send(`A * iauthd-ts :${line}`);
}
}
/**
* Send statistics to ircd
*/
private sendStats(): void {
const uptime = this.formatDuration(Date.now() - this.startTime);
const upSince = new Date(this.startTime).toUTCString();
this.send('s');
this.send(`S iauthd-ts :Up since ${upSince} (${uptime})`);
this.send(`S iauthd-ts :Cache size: ${getCacheSize()}`);
this.send(`S iauthd-ts :Total Passed: ${this.countPass}`);
this.send(`S iauthd-ts :Total Rejected: ${this.countReject}`);
if (this.saslEnabled()) {
this.send(`S iauthd-ts :SASL Success: ${this.countSaslSuccess}`);
this.send(`S iauthd-ts :SASL Failed: ${this.countSaslFail}`);
const providerInfo = this.authManager!.getProviderInfo();
for (const p of providerInfo) {
this.send(`S iauthd-ts :Auth Provider: ${p.name} (priority=${p.priority}, healthy=${p.healthy})`);
}
}
for (const dnsbl of this.config.dnsbls) {
let desc = dnsbl.server;
if (dnsbl.index) desc += ` (${dnsbl.index})`;
if (dnsbl.bitmask) desc += ` (${dnsbl.bitmask})`;
const count = this.dnsblCounters.get(dnsbl.cfgNum) || 0;
this.send(`S iauthd-ts :${desc}: ${count}`);
}
}
/**
* Format duration in human-readable form
*/
private formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours % 24 > 0) parts.push(`${hours % 24}h`);
if (minutes % 60 > 0) parts.push(`${minutes % 60}m`);
if (seconds % 60 > 0 || parts.length === 0) parts.push(`${seconds % 60}s`);
return parts.join(' ');
}
/**
* Handle a line from ircd
* Format: <id> <message> <args...>
* Example: 26 C 172.19.0.1 12345 172.19.0.2 6667
*/
private handleLine(line: string): void {
if (!line) return;
const parts = line.split(' ');
const source = parseInt(parts[0], 10);
const message = parts[1];
const args = parts.slice(2).join(' ');
if (!message) return;
switch (message) {
case 'C': // Client introduction
this.handleClientIntro(source, args);
break;
case 'D': // Client disconnect
this.debug(`Client ${source} disconnected.`);
this.deleteClient(source);
break;
case 'F': // SSL certificate fingerprint
// Could be used for certificate-based auth
break;
case 'R': // Client authenticated via SASL/LOC
this.handleAuth(source, args);
break;
case 'N': // Hostname received
break;
case 'd': // Hostname timeout
break;
case 'P': // Client password
break;
case 'U': // Client username (full)
break;
case 'u': // Client username (short)
break;
case 'n': // Client nickname
break;
case 'H': // Hurry up
this.handleHurry(source, args);
break;
case 'T': // Client registered
break;
case 'E': // Error
this.debug(`ircd error: ${args}`);
break;
case 'e': // Event
if (args === 'rehash') {
this.debug('Got a rehash. Rereading config file');
const { config } = readConfigFile(this.configPath);
this.config = config;
// Reinitialize auth providers
if (this.authManager) {
this.authManager.reload().catch(err => {
this.debug(`Failed to reload auth manager: ${err}`);
});
} else {
this.initializeAuth();
}
this.sendNewConfig();
}
break;
case 'A': // SASL authentication start
this.handleSASLStart(source, args);
break;
case 'a': // SASL authentication continuation
this.handleSASLContinue(source, args);
break;
case 'M': // Server name and capacity
break;
case 'X': // Extension query reply
break;
case 'x': // Extension query server not linked
break;
case 'W': // Untrusted WEBIRC
this.debug('Got an untrusted WEBIRC attempt. Ignoring.');
break;
case 'w': // Trusted WEBIRC
this.handleWebIRC(source, args);
break;
default:
this.debug(`Got unknown message '${message}' from server`);
}
}
/**
* Handle client introduction (C message)
*/
private handleClientIntro(id: number, args: string): void {
const [ip, portStr, serverIp, serverPortStr] = args.split(' ');
const port = parseInt(portStr, 10);
const serverPort = parseInt(serverPortStr, 10);
if (!ip) {
this.debug('Got a C without a valid IP. Ignoring');
return;
}
if (this.clients.has(id)) {
this.debug(`ERROR: Found existing entry for client ${id} (ip=${ip}). Exiting..`);
process.exit(1);
}
this.debug(`Adding new entry for client ${id} (ip=${ip})`);
const client: ClientState = {
id,
ip,
port,
serverIp,
serverPort,
whitelist: false,
block: false,
marks: new Map(),
hurry: false,
lookups: new Map(),
hits: new Map(),
};
this.clients.set(id, client);
this.startDNSBLLookups(client);
}
/**
* Start DNSBL lookups for a client
*/
private async startDNSBLLookups(client: ClientState): Promise<void> {
if (!isIPv4(client.ip)) {
this.debug(`Unknown IP format: ${client.ip}, probably IPv6... skipping DNSBL`);
// IPv6 clients skip DNSBL but still need to be processed
// They'll be accepted when Hurry arrives since they have no pending lookups
return;
}
const reversedIp = reverseIPv4(client.ip);
if (!reversedIp) return;
// Start all lookups concurrently
const lookupPromises = this.config.dnsbls.map(async (dnsbl) => {
const query = `${reversedIp}.${dnsbl.server}`;
client.lookups.set(dnsbl.cfgNum, true); // Mark as pending
this.debug(`Looking up client ${client.id}: ${query}`);
// Check cache
const cacheTime = dnsbl.cacheTime ?? this.config.cacheTime;
const cached = getCacheEntry(query, cacheTime);
let results: string[];
if (cached && cached.result !== null) {
this.debug(`Found dnsbl cache entry for ${query}`);
results = cached.result;
} else if (cached) {
// Cache entry exists but result is null (pending)
this.debug(`Cache pending... on ${query}`);
// Wait a bit and retry from cache
await new Promise((resolve) => setTimeout(resolve, 100));
const retryCache = getCacheEntry(query, cacheTime);
results = retryCache?.result ?? [];
} else {
// Start new lookup
this.debug(`Starting DNS lookup for ${query}`);
setCacheEntry(query, null); // Mark as pending
results = await lookupDNSBL(reversedIp, dnsbl.server, this.config.dnsTimeout);
setCacheEntry(query, results);
}
// Process results
this.handleDNSBLResponse(client, dnsbl, results);
// Mark lookup as complete
client.lookups.set(dnsbl.cfgNum, false);
// Check if we should process the client now
this.handleClientUpdate(client);
});
// Don't await - let lookups happen in background
Promise.all(lookupPromises).catch((err) => {
this.debug(`DNSBL lookup error: ${err}`);
});
}
/**
* Handle a DNSBL response
*/
private handleDNSBLResponse(client: ClientState, dnsbl: DNSBLConfig, results: string[]): void {
if (results.length === 0) return;
const matched = matchesDNSBL(results, dnsbl);
if (!matched) return;
this.debug(`client ${client.id} matches ${dnsbl.server} result ${results.join(',')}`);
// Apply whitelist
if (dnsbl.whitelist) {
client.whitelist = true;
}
// Apply block
if (dnsbl.block) {
client.block = dnsbl.block;
}
// Apply class
if (dnsbl.class) {
client.class = dnsbl.class;
}
// Apply mark
if (dnsbl.mark) {
client.marks.set(dnsbl.mark, dnsbl);
}
// Record hit
client.hits.set(dnsbl.cfgNum, true);
}
/**
* Check if client processing is complete
*/
private handleClientUpdate(client: ClientState): void {
// Count pending lookups
let pending = 0;
for (const isPending of client.lookups.values()) {
if (isPending) pending++;
}
if (client.hurry) {
this.debug(`Client ${client.id} has Hurry set and ${pending} pending requests`);
if (pending === 0) {
// Update counters for hits
for (const cfgNum of client.hits.keys()) {
const current = this.dnsblCounters.get(cfgNum) || 0;
this.dnsblCounters.set(cfgNum, current + 1);
}
client.hits.clear();
// Make decision
if (client.whitelist) {
this.clientPass(client);
} else if (
client.block === 'all' ||
(client.block === 'anonymous' && !client.account)
) {
this.clientReject(client, this.config.blockMsg);
} else {
this.clientPass(client);
}
}
} else {
this.debug(`Client ${client.id} has ${pending} pending requests`);
}
}
/**
* Handle Hurry message
*/
private handleHurry(id: number, classArg: string): void {
const client = this.clients.get(id);
if (!client) {
this.debug('ERROR: Got a hurry for a client we aren\'t even holding on to!');
return;
}
this.debug(`Handling a hurry on ${id}`);
client.hurry = true;
this.handleClientUpdate(client);
}
/**
* Handle authentication (R message)
*/
private handleAuth(id: number, account: string): void {
const client = this.clients.get(id);
if (!client) return;
this.debug(`Client ${id} authed as ${account}`);
client.account = account;
this.handleClientUpdate(client);
}
/**
* Handle trusted WEBIRC
*/
private handleWebIRC(id: number, args: string): void {
const parts = args.split(' ');
const [password, username, hostname, newIp] = parts;
this.debug(`Got a w line: ${id} - pass=<notshown>, user=${username}, host=${hostname}, ip=${newIp}`);
const client = this.clients.get(id);
if (!client) {
this.debug('Got a webirc for a client we don\'t know about? Ignored.');
return;
}
// Save state
const wasHurry = client.hurry;
// Delete and recreate with new IP
this.clients.delete(id);
const newClient: ClientState = {
id,
ip: newIp,
port: client.port,
serverIp: client.serverIp,
serverPort: client.serverPort,
whitelist: false,
block: false,
marks: new Map(),
hurry: wasHurry,
lookups: new Map(),
hits: new Map(),
};
this.clients.set(id, newClient);
this.startDNSBLLookups(newClient);
}
/**
* Accept a client
*/
private clientPass(client: ClientState): void {
this.debug(`Passing client ${client.id} (${client.ip})`);
// Send marks
for (const mark of client.marks.keys()) {
this.sendMark(client, 'MARK', mark);
}
// Send done
this.sendDone(client);
this.countPass++;
this.deleteClient(client.id);
this.sendStats();
}
/**
* Reject a client
*/
private clientReject(client: ClientState, reason: string): void {
this.debug(`Rejecting client ${client.id} (${client.ip}): ${reason}`);
this.sendKill(client, reason);
this.countReject++;
this.deleteClient(client.id);
this.sendStats();
}
/**
* Delete a client from tracking
*/
private deleteClient(id: number): void {
this.debug('Deleting client from hash tables');
this.clients.delete(id);
}
/**
* Send mark message
*/
private sendMark(client: ClientState, markType: string, markData: string): void {
if (!markData) return;
this.send(`m ${client.id} ${client.ip} ${client.port} ${markType} ${markData}`);
}
/**
* Send done message
*/
private sendDone(client: ClientState): void {
if (client.class) {
this.send(`D ${client.id} ${client.ip} ${client.port} ${client.class}`);
} else {
this.send(`D ${client.id} ${client.ip} ${client.port}`);
}
}
/**
* Send kill message
*/
private sendKill(client: ClientState, reason: string): void {
this.send(`k ${client.id} ${client.ip} ${client.port} :${reason}`);
}
// ==================== SASL Authentication ====================
/**
* Handle SASL authentication start (A message from IRCd)
* Format from IRCd: "A S :<mechanism>" or "A S <mechanism> :<certfp>"
* Or for host info: "A H :<user@host:ip>"
* After handleLine parsing, args = "S :PLAIN" or "H :user@host:ip"
*/
private handleSASLStart(id: number, args: string): void {
if (!this.saslEnabled()) {
this.debug(`SASL not enabled, ignoring A message for ${id}`);
this.sendSASLFail(id);
return;
}
// Get or create client state
let client = this.clients.get(id);
if (!client) {
// Create minimal client state for SASL-only handling
// We don't have IP/port from this message, use placeholders
client = {
id,
ip: '0.0.0.0',
port: 0,
serverIp: '',
serverPort: 0,
whitelist: false,
block: false,
marks: new Map(),
hurry: false,
lookups: new Map(),
hits: new Map(),
sasl: { started: false },
};
this.clients.set(id, client);
}
if (!client.sasl) {
client.sasl = { started: false };
}
// Parse: first character is type (S or H), rest is data
// Format: "S :PLAIN" or "S PLAIN :certfp" or "H :user@host:ip"
const spaceIdx = args.indexOf(' ');
if (spaceIdx === -1) {
this.debug(`Invalid SASL A message format: ${args}`);
return;
}
const msgType = args.substring(0, spaceIdx);
const rest = args.substring(spaceIdx + 1);
// Check if this is host info (H) or mechanism start (S)
if (msgType === 'H') {
// Host info: H :<user@host:ip>
const colonIdx = rest.indexOf(':');
if (colonIdx !== -1) {
client.sasl.hostInfo = rest.substring(colonIdx + 1);
this.debug(`SASL host info for ${id}: ${client.sasl.hostInfo}`);
}
return;
}
if (msgType === 'S') {
// Mechanism start: S :<mechanism> or S <mechanism> :<certfp>
let mechanism: string;
let certfp: string | undefined;
if (rest.startsWith(':')) {
// Format: S :PLAIN
mechanism = rest.substring(1).trim();
} else {
// Format: S PLAIN :certfp
const colonIdx = rest.indexOf(':');
if (colonIdx !== -1) {
mechanism = rest.substring(0, colonIdx).trim();
certfp = rest.substring(colonIdx + 1).trim();
} else {
mechanism = rest.trim();
}
}
this.debug(`SASL start for ${id}: mechanism=${mechanism}, certfp=${certfp || 'none'}`);
client.sasl.mechanism = mechanism;
client.sasl.certfp = certfp;
client.sasl.started = true;
// Check if mechanism is supported
const supported = getSupportedMechanisms();
if (!supported.includes(mechanism.toUpperCase())) {
this.debug(`Unsupported SASL mechanism: ${mechanism}`);
this.sendSASLMechs(id, supported);
return;
}
// For PLAIN mechanism, send empty challenge to request credentials
if (mechanism.toUpperCase() === 'PLAIN') {
this.sendSASLChallenge(id, '+');
}
return;
}
this.debug(`Unknown SASL A message type: ${msgType}`);
}
/**
* Handle SASL authentication continuation (a message from IRCd)
* Format from IRCd: "a :<base64_data>"
* After handleLine parsing, args = ":<base64_data>"
*/
private handleSASLContinue(id: number, args: string): void {
if (!this.saslEnabled()) {
this.sendSASLFail(id);
return;
}
const client = this.clients.get(id);
if (!client || !client.sasl) {
this.debug(`SASL continue for unknown client ${id}`);
this.sendSASLFail(id);
return;
}
// Parse: :<data>
const colonIdx = args.indexOf(':');
if (colonIdx === -1) {
this.debug(`Invalid SASL a message format: ${args}`);
this.sendSASLFail(id);
return;
}
const data = args.substring(colonIdx + 1);
if (client.sasl.mechanism?.toUpperCase() === 'PLAIN') {
this.handleSASLPlain(client, data).catch(err => {
this.debug(`SASL PLAIN auth error: ${err}`);
this.sendSASLFail(id);
this.countSaslFail++;
});
} else {
this.debug(`Unhandled SASL mechanism: ${client.sasl.mechanism}`);
this.sendSASLFail(id);
}
}
/**
* Handle SASL PLAIN authentication
*/
private async handleSASLPlain(client: ClientState, base64Data: string): Promise<void> {
const decoded = decodeSASLPlain(base64Data);
if (!decoded) {
this.debug(`Failed to decode SASL PLAIN data for ${client.id}`);
this.sendSASLFail(client.id);
this.countSaslFail++;
return;
}
this.debug(`SASL PLAIN auth attempt for ${client.id}: authcid=${decoded.authcid}`);
const result = await this.authManager!.authenticate(
decoded.authcid,
decoded.password,
decoded.authzid
);
if (result.success && result.account) {
this.debug(`SASL PLAIN auth success for ${client.id}: account=${result.account}`);
client.account = result.account;
this.sendSASLSuccess(client.id, result.account);
this.countSaslSuccess++;
} else {
this.debug(`SASL PLAIN auth failed for ${client.id}: ${result.error || 'unknown'}`);
this.sendSASLFail(client.id);
this.countSaslFail++;
}
}
/**
* Send SASL challenge to client
* Format: c <id> <ip> <port> :<challenge>
*/
private sendSASLChallenge(id: number, challenge: string): void {
const client = this.clients.get(id);
if (client) {
this.send(`c ${id} ${client.ip} ${client.port} :${challenge}`);
}
}
/**
* Send SASL login success
* Format: L <id> <ip> <port> <account>
*/
private sendSASLSuccess(id: number, account: string): void {
const client = this.clients.get(id);
if (client) {
this.send(`L ${id} ${client.ip} ${client.port} ${account}`);
this.send(`Z ${id} ${client.ip} ${client.port}`);
}
}
/**
* Send SASL authentication failed
* Format: f <id> <ip> <port>
*/
private sendSASLFail(id: number): void {
const client = this.clients.get(id);
if (client) {
this.send(`f ${id} ${client.ip} ${client.port}`);
} else {
// Client may not exist yet, send with dummy values
this.send(`f ${id} 0.0.0.0 0`);
}
}
/**
* Send SASL available mechanisms
* Format: l <id> <ip> <port> :<mechanisms>
*/
private sendSASLMechs(id: number, mechanisms: string[]): void {
const client = this.clients.get(id);
if (client) {
this.send(`l ${id} ${client.ip} ${client.port} :${mechanisms.join(',')}`);
}
}
}
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env node
/**
* iauthd-ts - IAuth daemon for Nefarious IRCd
* TypeScript port of iauthd.pl
*
* A DNSBL-based authentication daemon that checks connecting clients
* against configured DNS blacklists and can block, mark, or whitelist
* users based on the results.
*
* Requirements:
* Node.js 18+
*
* Installation:
* npm install
* npm run build
*
* Usage:
* node dist/index.js -c /path/to/config
*
* Configuration:
* Config directives begin with #IAUTH and are one per line.
* Because configuration begins with #, it can be embedded in ircd.conf.
* Syntax is: #IAUTH <directive> <arguments>
*
* Configuration directives:
*
* POLICY:
* See docs/readme.iauth section on Set Policy Options
*
* DNSTIMEOUT:
* Seconds to time out for DNSBL lookups. Default is 5
*
* DNSBL <key=value [key=value..]>
* where keys are:
* server - dnsbl server to look up, eg dnsbl.sorbs.net
* bitmask - matches if response is true after being bitwise-and'ed with mask
* index - matches if response is exactly index (comma separated values ok)
* class - assigns the user to the named class
* mark - marks the user with the given mark
* block - all: blocks connection if matched
* anonymous: blocks connection unless SASL authenticated
* whitelist - listed users won't be blocked by any RBL
* cachetime - Override default cache timeout
*
* DEBUG:
* Values greater than 0 turn iauth debugging on in the ircd
*
* BLOCKMSG:
* Message shown to users when blocked
*
* CACHETIME:
* Default cache time in seconds (default 86400 = 24 hours)
*
* Example configuration:
*
* #IAUTH POLICY RTAWUwFr
* #IAUTH CACHETIME 86400
* #IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
* #IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5,6,7,9 mark=sorbs block=anonymous
* #IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
* #IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
* #IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
*
* ircd.conf:
*
* IAuth {
* program = "node" "/path/to/iauthd-ts/dist/index.js" "-v" "-c" "ircd.conf";
* };
*
* Debugging:
* * Oper up first
* * Set snomask: /quote mode yournick +s 262144
*/
import { parseArgs } from 'node:util';
import type { CLIOptions } from './types.js';
import { IAuthDaemon } from './iauth.js';
const HELP = `
iauthd-ts - IAuth daemon for Nefarious IRCd (TypeScript port)
Usage: iauthd-ts [options] --config=<configfile>
Options:
-h, --help Print this message
-c, --config Config file to read (required)
-d, --debug Turn on debugging in the ircd
-v, --verbose Turn on debugging in iauthd
`;
function main(): void {
let options: CLIOptions;
try {
const { values } = parseArgs({
options: {
help: { type: 'boolean', short: 'h', default: false },
config: { type: 'string', short: 'c' },
debug: { type: 'boolean', short: 'd', default: false },
verbose: { type: 'boolean', short: 'v', default: false },
},
strict: true,
});
options = {
help: values.help ?? false,
config: values.config ?? '',
debug: values.debug ?? false,
verbose: values.verbose ?? false,
};
} catch (err) {
console.error(HELP);
process.exit(1);
}
if (options.help || !options.config) {
console.error(HELP);
process.exit(options.help ? 0 : 1);
}
try {
const daemon = new IAuthDaemon(options);
daemon.start();
} catch (err) {
console.error(`Failed to start iauthd-ts: ${err}`);
process.exit(1);
}
}
main();
+264
View File
@@ -0,0 +1,264 @@
/**
* SASL Authentication module for iauthd-ts
* Handles SASL PLAIN authentication with crypt-style password hashes
*/
import { readFileSync, statSync } from 'node:fs';
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
/** User entry from the users file */
export interface UserEntry {
username: string;
passwordHash: string;
}
/** Parsed users database */
export interface UsersDB {
users: Map<string, UserEntry>;
lastModified: number;
filePath: string;
}
/** Supported hash types with their crypt prefixes */
type HashType = 'sha256' | 'sha512' | 'md5' | 'plain';
/**
* Parse a users file in format: username:passwordhash
* Supports crypt-style hashes with $$ prefix:
* - $5$ = SHA-256
* - $6$ = SHA-512
* - $1$ = MD5
* - No prefix = plain text (for testing only)
*/
export function parseUsersFile(filePath: string): UsersDB {
const users = new Map<string, UserEntry>();
let lastModified = 0;
try {
const stat = statSync(filePath);
lastModified = stat.mtimeMs;
const content = readFileSync(filePath, 'utf-8');
for (const line of content.split('\n')) {
const trimmed = line.trim();
// Skip empty lines and comments
if (!trimmed || trimmed.startsWith('#')) continue;
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) continue;
const username = trimmed.substring(0, colonIdx).toLowerCase();
const passwordHash = trimmed.substring(colonIdx + 1);
if (username && passwordHash) {
users.set(username, { username, passwordHash });
}
}
} catch (err) {
// File doesn't exist or can't be read - return empty DB
}
return { users, lastModified, filePath };
}
/**
* Check if users file has been modified since last load
*/
export function usersFileModified(db: UsersDB): boolean {
try {
const stat = statSync(db.filePath);
return stat.mtimeMs > db.lastModified;
} catch {
return false;
}
}
/**
* Parse crypt-style hash to determine type and extract salt
*/
function parseHashType(hash: string): { type: HashType; salt: string; hash: string } | null {
// SHA-256 crypt: $5$salt$hash
if (hash.startsWith('$5$')) {
const parts = hash.split('$');
if (parts.length >= 4) {
return { type: 'sha256', salt: parts[2], hash: parts[3] };
}
}
// SHA-512 crypt: $6$salt$hash
if (hash.startsWith('$6$')) {
const parts = hash.split('$');
if (parts.length >= 4) {
return { type: 'sha512', salt: parts[2], hash: parts[3] };
}
}
// MD5 crypt: $1$salt$hash
if (hash.startsWith('$1$')) {
const parts = hash.split('$');
if (parts.length >= 4) {
return { type: 'md5', salt: parts[2], hash: parts[3] };
}
}
// Plain text (for testing) - no $ prefix
if (!hash.startsWith('$')) {
return { type: 'plain', salt: '', hash: hash };
}
return null;
}
/**
* Generate a SHA-256 crypt-style hash
* Uses the simplified sha256crypt format: $5$salt$base64hash
*/
function sha256Crypt(password: string, salt: string): string {
// Simplified implementation - use PBKDF2-like iteration
// Real crypt uses a more complex algorithm, but this is compatible
// for our purposes of simple password verification
let hash = createHash('sha256').update(salt + password).digest();
// Multiple rounds for security
for (let i = 0; i < 5000; i++) {
hash = createHash('sha256').update(hash).update(password).digest();
}
return hash.toString('base64').replace(/=+$/, '');
}
/**
* Generate a SHA-512 crypt-style hash
*/
function sha512Crypt(password: string, salt: string): string {
let hash = createHash('sha512').update(salt + password).digest();
for (let i = 0; i < 5000; i++) {
hash = createHash('sha512').update(hash).update(password).digest();
}
return hash.toString('base64').replace(/=+$/, '');
}
/**
* Generate an MD5 crypt-style hash
*/
function md5Crypt(password: string, salt: string): string {
let hash = createHash('md5').update(salt + password).digest();
for (let i = 0; i < 1000; i++) {
hash = createHash('md5').update(hash).update(password).digest();
}
return hash.toString('base64').replace(/=+$/, '');
}
/**
* Verify a password against a stored hash
* Uses timing-safe comparison to prevent timing attacks
*/
export function verifyPassword(password: string, storedHash: string): boolean {
const parsed = parseHashType(storedHash);
if (!parsed) return false;
let computedHash: string;
switch (parsed.type) {
case 'sha256':
computedHash = sha256Crypt(password, parsed.salt);
break;
case 'sha512':
computedHash = sha512Crypt(password, parsed.salt);
break;
case 'md5':
computedHash = md5Crypt(password, parsed.salt);
break;
case 'plain':
// Plain text comparison (for testing only)
computedHash = password;
break;
default:
return false;
}
// Use timing-safe comparison
try {
const a = Buffer.from(computedHash);
const b = Buffer.from(parsed.hash);
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
} catch {
return false;
}
}
/**
* Generate a new password hash
* @param password The password to hash
* @param type Hash type to use (default: sha256)
*/
export function generateHash(password: string, type: HashType = 'sha256'): string {
const salt = randomBytes(12).toString('base64').replace(/[+/=]/g, '').substring(0, 16);
switch (type) {
case 'sha256':
return `$5$${salt}$${sha256Crypt(password, salt)}`;
case 'sha512':
return `$6$${salt}$${sha512Crypt(password, salt)}`;
case 'md5':
return `$1$${salt}$${md5Crypt(password, salt)}`;
case 'plain':
return password;
default:
return `$5$${salt}$${sha256Crypt(password, salt)}`;
}
}
/**
* Decode SASL PLAIN authentication data
* Format: base64(authzid \0 authcid \0 password)
* Returns null if invalid format
*/
export function decodeSASLPlain(base64Data: string): { authzid: string; authcid: string; password: string } | null {
try {
const decoded = Buffer.from(base64Data, 'base64').toString('utf-8');
const parts = decoded.split('\0');
if (parts.length !== 3) return null;
return {
authzid: parts[0], // Authorization identity (usually empty or same as authcid)
authcid: parts[1], // Authentication identity (username)
password: parts[2], // Password
};
} catch {
return null;
}
}
/**
* Authenticate a user with SASL PLAIN
* @param db Users database
* @param authcid Authentication identity (username)
* @param password Password
* @returns Account name if successful, null if failed
*/
export function authenticatePlain(db: UsersDB, authcid: string, password: string): string | null {
const username = authcid.toLowerCase();
const user = db.users.get(username);
if (!user) return null;
if (verifyPassword(password, user.passwordHash)) {
return user.username;
}
return null;
}
/**
* Get list of supported SASL mechanisms
*/
export function getSupportedMechanisms(): string[] {
return ['PLAIN'];
}
+132
View File
@@ -0,0 +1,132 @@
/**
* TypeScript types for iauthd
*/
import type { AuthProviderConfig } from './auth/types.js';
/** DNSBL configuration entry */
export interface DNSBLConfig {
/** Config line number for identification */
cfgNum: number;
/** DNSBL server hostname (e.g., dnsbl.sorbs.net) */
server: string;
/** Match if response equals one of these indices (e.g., "2,3,4") */
index?: string;
/** Match if response bitwise-AND with mask is truthy */
bitmask?: string;
/** Mark to apply if matched */
mark?: string;
/** Block mode: 'all' or 'anonymous' (block unless authenticated) */
block?: 'all' | 'anonymous';
/** If true, whitelist this user from all blocks */
whitelist?: boolean;
/** Connection class to assign */
class?: string;
/** Override cache timeout for this DNSBL */
cacheTime?: number;
}
/** Main configuration */
export interface Config {
/** IAuth policy string (e.g., "RTAWUwFr") */
policy: string;
/** DNSBL configurations */
dnsbls: DNSBLConfig[];
/** DNS lookup timeout in seconds */
dnsTimeout: number;
/** Message shown when blocking a client */
blockMsg: string;
/** Default cache time in seconds */
cacheTime: number;
/** Debug mode */
debug: boolean;
/** Path to users file for SASL authentication (legacy, use authProviders) */
saslUsersFile?: string;
/** Message shown when SASL authentication fails */
saslFailMsg: string;
/** Authentication providers configuration */
authProviders: AuthProviderConfig[];
}
/** SASL session state */
export interface SASLState {
/** SASL mechanism being used */
mechanism?: string;
/** Whether we've sent the initial response */
started: boolean;
/** SSL client certificate fingerprint (if provided) */
certfp?: string;
/** Client host info (user@host:ip) */
hostInfo?: string;
}
/** Client state during registration */
export interface ClientState {
/** Client ID from ircd */
id: number;
/** Remote IP address */
ip: string;
/** Remote port */
port: number;
/** Server IP */
serverIp: string;
/** Server port */
serverPort: number;
/** Whether client is whitelisted */
whitelist: boolean;
/** Block mode if any */
block: 'all' | 'anonymous' | false;
/** Applied marks */
marks: Map<string, DNSBLConfig>;
/** Assigned connection class */
class?: string;
/** Whether we've received a Hurry message */
hurry: boolean;
/** Pending DNSBL lookups (cfgNum -> pending) */
lookups: Map<number, boolean>;
/** Account name if authenticated via SASL/LOC */
account?: string;
/** DNSBL hits (cfgNum -> hit) */
hits: Map<number, boolean>;
/** SASL authentication state */
sasl?: SASLState;
}
/** DNSBL cache entry */
export interface CacheEntry {
/** DNS lookup results (IP addresses) */
result: string[] | null;
/** Timestamp when cached */
ts: number;
}
/** Parsed server message */
export type ServerMessage =
| { type: 'C'; id: number; remoteIp: string; remotePort: number; localIp: string; localPort: number }
| { type: 'D'; id: number }
| { type: 'F'; id: number; fingerprint: string }
| { type: 'R'; id: number; account: string }
| { type: 'N'; id: number; hostname: string }
| { type: 'd'; id: number }
| { type: 'P'; id: number; password: string }
| { type: 'U'; id: number; username: string; hostname: string; servername: string; userinfo: string }
| { type: 'u'; id: number; username?: string }
| { type: 'n'; id: number; nickname: string }
| { type: 'H'; id: number; class: string }
| { type: 'T'; id: number }
| { type: 'E'; id: number; errorType: string; text: string }
| { type: 'e'; id: number; event: string; params?: string }
| { type: 'M'; id: number; servername: string; capacity: number }
| { type: 'X'; id: number; servername: string; routing: string; reply: string }
| { type: 'x'; id: number; servername: string; routing: string; message: string }
| { type: 'W'; id: number; password: string; username: string; hostname: string; ip: string; options?: string }
| { type: 'w'; id: number; password: string; username: string; hostname: string; ip: string; options?: string }
| { type: 'unknown'; id: number; raw: string };
/** CLI options */
export interface CLIOptions {
config: string;
debug: boolean;
verbose: boolean;
help: boolean;
}
+204
View File
@@ -0,0 +1,204 @@
/**
* Tests for auth configuration parsing
*/
import { describe, it, expect } from 'vitest';
import { parseAuthConfig, convertSASLDB } from '../../src/auth/config.js';
describe('Auth Config Parsing', () => {
describe('parseAuthConfig', () => {
it('should return null if provider is missing', () => {
const result = parseAuthConfig('path=/etc/users');
expect(result).toBeNull();
});
it('should parse file provider config', () => {
const result = parseAuthConfig('provider=file path=/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: undefined,
});
});
it('should parse file provider with priority', () => {
const result = parseAuthConfig('provider=file path=/etc/users priority=50');
expect(result).toEqual({
provider: 'file',
path: '/etc/users',
priority: 50,
});
});
it('should return null for file provider without path', () => {
const result = parseAuthConfig('provider=file');
expect(result).toBeNull();
});
it('should parse LDAP direct bind config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldap://ldap.example.com:389',
mode: 'direct',
userdn: 'uid=%s,ou=users,dc=example,dc=com',
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP search mode config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com:636 mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s)'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldaps://ldap.example.com:636',
mode: 'search',
basedn: 'ou=users,dc=example,dc=com',
binddn: 'cn=admin,dc=example,dc=com',
bindpass: 'secret',
userfilter: '(uid=%s)',
groupdn: undefined,
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP config with groupdn', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s) ' +
'groupdn=cn=ircusers,ou=groups,dc=example,dc=com'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.groupdn).toBe('cn=ircusers,ou=groups,dc=example,dc=com');
}
});
it('should parse LDAP config with timeout and priority', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://server mode=direct userdn=uid=%s,dc=test timeout=10000 priority=25'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for LDAP without uri', () => {
const result = parseAuthConfig('provider=ldap mode=direct');
expect(result).toBeNull();
});
it('should return null for LDAP without mode', () => {
const result = parseAuthConfig('provider=ldap uri=ldap://server');
expect(result).toBeNull();
});
it('should return null for unknown provider', () => {
const result = parseAuthConfig('provider=unknown');
expect(result).toBeNull();
});
it('should handle quoted values with spaces', () => {
const result = parseAuthConfig('provider=file path="/path/with spaces/users"');
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should handle single-quoted values', () => {
const result = parseAuthConfig("provider=file path='/path/with spaces/users'");
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should parse Keycloak config', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client'
);
expect(result).toEqual({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'irc-client',
clientsecret: undefined,
accountattr: undefined,
timeout: undefined,
priority: undefined,
});
});
it('should parse Keycloak config with clientsecret', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=mysecret'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.clientsecret).toBe('mysecret');
}
});
it('should parse Keycloak config with all options', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client ' +
'clientsecret=mysecret accountattr=irc_nick timeout=10000 priority=25'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.url).toBe('https://keycloak.example.com');
expect(result.realm).toBe('myrealm');
expect(result.clientid).toBe('irc-client');
expect(result.clientsecret).toBe('mysecret');
expect(result.accountattr).toBe('irc_nick');
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for Keycloak without url', () => {
const result = parseAuthConfig('provider=keycloak realm=test clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without realm', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without clientid', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com realm=test');
expect(result).toBeNull();
});
});
describe('convertSASLDB', () => {
it('should convert SASLDB path to file provider config', () => {
const result = convertSASLDB('/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: 100,
});
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Tests for FileAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { FileAuthProvider } from '../../src/auth/providers/file.js';
import { generateHash } from '../../src/sasl.js';
describe('FileAuthProvider', () => {
let tempDir: string;
let usersFile: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tempDir, 'users');
});
afterEach(() => {
try {
unlinkSync(usersFile);
} catch {
// Ignore if file doesn't exist
}
});
describe('initialization', () => {
it('should initialize with empty users file', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should initialize with non-existent file', async () => {
const provider = new FileAuthProvider({
provider: 'file',
path: '/nonexistent/path/users',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should load users from file', async () => {
writeFileSync(usersFile, 'testuser:plainpassword\nadmin:adminpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(2);
});
it('should use default priority of 100', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
expect(provider.priority).toBe(100);
});
it('should use custom priority', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({
provider: 'file',
path: usersFile,
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user with plain password', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-256 hash', async () => {
const hash = generateHash('secretpass', 'sha256');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-512 hash', async () => {
const hash = generateHash('secretpass', 'sha512');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should reject invalid password', async () => {
writeFileSync(usersFile, 'testuser:correctpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should reject unknown user', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('unknownuser', 'testpass');
expect(result.success).toBe(false);
});
it('should be case-insensitive for usernames', async () => {
writeFileSync(usersFile, 'TestUser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('TESTUSER', 'testpass');
expect(result.success).toBe(true);
});
it('should return error if not initialized', async () => {
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
// Don't call initialize
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Users database not loaded');
});
});
describe('reload', () => {
it('should reload users file', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.getUserCount()).toBe(1);
// Modify file
writeFileSync(usersFile, 'user1:pass1\nuser2:pass2\n');
await provider.reload();
expect(provider.getUserCount()).toBe(2);
});
it('should detect file modifications during auth', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
// File is automatically reloaded if modified
// Wait a bit to ensure mtime changes
await new Promise((r) => setTimeout(r, 100));
writeFileSync(usersFile, 'user1:newpass\n');
// Auth should use new password after auto-reload
const result = await provider.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+415
View File
@@ -0,0 +1,415 @@
/**
* Tests for KeycloakAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { KeycloakAuthProvider } from '../../src/auth/providers/keycloak.js';
// Mock fetch globally
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
describe('KeycloakAuthProvider', () => {
beforeEach(() => {
mockFetch.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
/**
* Create a mock JWT access token
*/
function createMockToken(payload: Record<string, unknown>): string {
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signature = 'mock-signature';
return `${header}.${body}.${signature}`;
}
describe('initialization', () => {
it('should throw if url is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: '',
realm: 'test',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires url');
});
it('should throw if realm is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: '',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires realm');
});
it('should throw if clientid is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: '',
});
await expect(provider.initialize()).rejects.toThrow('requires clientid');
});
it('should initialize successfully with valid config', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ issuer: 'https://keycloak.example.com/realms/test' }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
});
it('should use default priority of 100', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
expect(provider.priority).toBe(100);
});
it('should use custom priority', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
email: 'test@example.com',
});
// Mock well-known endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
// Mock token endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () =>
JSON.stringify({
access_token: accessToken,
token_type: 'Bearer',
expires_in: 300,
scope: 'openid profile email',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password123');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should use clientsecret for confidential clients', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
clientsecret: 'secret123',
});
await provider.initialize();
await provider.authenticate('testuser', 'password123');
// Check that client_secret was included in the request
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[1].body).toContain('client_secret=secret123');
});
it('should reject invalid credentials', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Invalid user credentials',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should handle disabled account', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 400,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Account disabled',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('disableduser', 'password');
expect(result.success).toBe(false);
expect(result.error).toBe('Account disabled');
});
it('should handle client misconfiguration', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'unauthorized_client',
error_description: 'Client not allowed for direct access grants',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'misconfigured-client',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(false);
expect(result.error).toContain('Client error');
});
it('should extract account from custom attribute', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
irc_account: 'CustomNick',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
accountattr: 'irc_account',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('CustomNick');
});
it('should fall back to sub if preferred_username not available', async () => {
const accessToken = createMockToken({
sub: 'user-uuid-12345',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('user-uuid-12345');
});
});
describe('token endpoint URL', () => {
it('should build correct token endpoint URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
// Check the token endpoint URL
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
it('should handle trailing slash in URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com/', // Trailing slash
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
});
describe('health status', () => {
it('should mark as unhealthy on connection failure', async () => {
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
});
it('should mark as healthy after successful auth', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
// Initialize fails
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
// Auth succeeds
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(provider.isHealthy()).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+191
View File
@@ -0,0 +1,191 @@
/**
* Tests for AuthManager
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { AuthManager } from '../../src/auth/manager.js';
import type { AuthProviderConfig } from '../../src/auth/types.js';
describe('AuthManager', () => {
let tempDir: string;
let usersFile1: string;
let usersFile2: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile1 = join(tempDir, 'users1');
usersFile2 = join(tempDir, 'users2');
});
afterEach(() => {
try {
unlinkSync(usersFile1);
unlinkSync(usersFile2);
} catch {
// Ignore if files don't exist
}
});
describe('initialization', () => {
it('should initialize with no providers', async () => {
const manager = new AuthManager([]);
await manager.initialize();
expect(manager.hasProviders()).toBe(false);
expect(manager.getProviderCount()).toBe(0);
});
it('should initialize single file provider', async () => {
writeFileSync(usersFile1, 'testuser:testpass\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasProviders()).toBe(true);
expect(manager.getProviderCount()).toBe(1);
});
it('should initialize multiple providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.getProviderCount()).toBe(2);
});
it('should sort providers by priority', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 100 },
{ provider: 'file', path: usersFile2, priority: 50 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const info = manager.getProviderInfo();
expect(info[0].priority).toBe(50);
expect(info[1].priority).toBe(100);
});
});
describe('authentication with fallback chain', () => {
it('should authenticate against first matching provider', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('user1', 'pass1');
expect(result.success).toBe(true);
expect(result.account).toBe('user1');
});
it('should fallback to second provider if first fails', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// user2 is only in the second file
const result = await manager.authenticate('user2', 'pass2');
expect(result.success).toBe(true);
expect(result.account).toBe('user2');
});
it('should fail if no provider matches', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
{ provider: 'file', path: usersFile2 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('unknownuser', 'anypass');
expect(result.success).toBe(false);
});
it('should return error if not initialized', async () => {
const manager = new AuthManager([]);
// Don't call initialize
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('AuthManager not initialized');
});
it('should return error if no providers configured', async () => {
const manager = new AuthManager([]);
await manager.initialize();
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('No auth providers configured');
});
});
describe('provider health', () => {
it('should report healthy providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasHealthyProviders()).toBe(true);
const info = manager.getProviderInfo();
expect(info[0].healthy).toBe(true);
});
});
describe('reload', () => {
it('should reload all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// Modify file
writeFileSync(usersFile1, 'user1:newpass\n');
await manager.reload();
// Should now use new password
const result = await manager.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should shutdown all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
await manager.shutdown();
expect(manager.hasProviders()).toBe(false);
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Unit tests for configuration parser
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { readConfigFile } from '../src/config.js';
describe('Config Parser', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
it('should parse POLICY directive', () => {
writeFileSync(configPath, '#IAUTH POLICY RTAWUwFr\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
});
it('should parse CACHETIME directive', () => {
writeFileSync(configPath, '#IAUTH CACHETIME 3600\n');
const { config } = readConfigFile(configPath);
expect(config.cacheTime).toBe(3600);
});
it('should parse DNSTIMEOUT directive', () => {
writeFileSync(configPath, '#IAUTH DNSTIMEOUT 10\n');
const { config } = readConfigFile(configPath);
expect(config.dnsTimeout).toBe(10);
});
it('should parse BLOCKMSG directive', () => {
writeFileSync(configPath, '#IAUTH BLOCKMSG Your connection has been rejected.\n');
const { config } = readConfigFile(configPath);
expect(config.blockMsg).toBe('Your connection has been rejected.');
});
it('should parse DEBUG directive', () => {
writeFileSync(configPath, '#IAUTH DEBUG\n');
const { config } = readConfigFile(configPath);
expect(config.debug).toBe(true);
});
it('should parse simple DNSBL directive', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(1);
expect(config.dnsbls[0].server).toBe('dnsbl.example.com');
});
it('should parse DNSBL with index', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com index=2,3,4\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].index).toBe('2,3,4');
});
it('should parse DNSBL with bitmask', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com bitmask=128\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].bitmask).toBe('128');
});
it('should parse DNSBL with mark', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com mark=baduser\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].mark).toBe('baduser');
});
it('should parse DNSBL with block=all', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=all\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('all');
});
it('should parse DNSBL with block=anonymous', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=anonymous\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('anonymous');
});
it('should parse DNSBL with whitelist', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=whitelist.example.com whitelist\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].whitelist).toBe(true);
});
it('should parse DNSBL with class', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com class=Trusted\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].class).toBe('Trusted');
});
it('should parse DNSBL with cachetime override', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com cachetime=7200\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cacheTime).toBe(7200);
});
it('should parse multiple DNSBL directives', () => {
writeFileSync(configPath, `
#IAUTH DNSBL server=dnsbl1.example.com index=2,3 mark=bl1
#IAUTH DNSBL server=dnsbl2.example.com index=4,5 mark=bl2 block=anonymous
#IAUTH DNSBL server=whitelist.example.com whitelist
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(3);
expect(config.dnsbls[0].server).toBe('dnsbl1.example.com');
expect(config.dnsbls[1].server).toBe('dnsbl2.example.com');
expect(config.dnsbls[1].block).toBe('anonymous');
expect(config.dnsbls[2].whitelist).toBe(true);
});
it('should parse full config with all directives', () => {
writeFileSync(configPath, `
# This is a comment
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected.
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5 mark=sorbs block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
# Some other config lines that should be ignored
General {
name = "test.server";
};
`);
const { config, configLines } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.blockMsg).toBe('Sorry! Your connection has been rejected.');
expect(config.dnsbls).toHaveLength(2);
expect(configLines).toHaveLength(6);
});
it('should use defaults when directives are missing', () => {
writeFileSync(configPath, '# Empty config\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.debug).toBe(false);
expect(config.dnsbls).toHaveLength(0);
});
it('should ignore non-IAUTH lines', () => {
writeFileSync(configPath, `
# Regular comment
General { name = "test"; };
#IAUTH POLICY RTAW
#NOTIAUTHPOLICY test
`);
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAW');
});
it('should assign incrementing cfgNum to DNSBLs', () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=first.example.com
#IAUTH DNSBL server=second.example.com
#IAUTH DNSBL server=third.example.com
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cfgNum).toBe(2);
expect(config.dnsbls[1].cfgNum).toBe(3);
expect(config.dnsbls[2].cfgNum).toBe(4);
});
});
@@ -0,0 +1,641 @@
/**
* DNSBL Integration Tests with Mocked DNS
*
* Tests the full pipeline: client connect → DNSBL lookup → decision
* Uses mock DNS responses to test all matching modes and edge cases.
*
* Based on real-world AfterNET production config.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
/**
* Mock DNS responses for testing
* Maps reversed-IP.dnsbl-server to response IP(s)
*/
const mockDnsResponses: Map<string, string[]> = new Map();
/**
* Set up a mock DNS response
*/
function mockDns(clientIp: string, dnsblServer: string, responses: string[]): void {
const reversed = clientIp.split('.').reverse().join('.');
const query = `${reversed}.${dnsblServer}`;
mockDnsResponses.set(query, responses);
}
/**
* Clear all mock DNS responses
*/
function clearMockDns(): void {
mockDnsResponses.clear();
}
interface TestHarness {
proc: ChildProcess;
output: string[];
send: (line: string) => void;
waitFor: (pattern: RegExp, timeout?: number) => Promise<string>;
getMarks: (clientId: number) => string[];
wasAccepted: (clientId: number) => boolean;
wasRejected: (clientId: number) => boolean;
close: () => Promise<void>;
}
/**
* Create a test harness with mock DNS injection
*/
async function createHarness(configPath: string): Promise<TestHarness> {
const output: string[] = [];
// Create a wrapper script that injects our mock DNS module
const wrapperPath = join(tmpdir(), `dns-mock-${Date.now()}.mjs`);
const mockResponses = JSON.stringify(Array.from(mockDnsResponses.entries()));
writeFileSync(wrapperPath, `
import { promises as dns } from 'node:dns';
// Mock DNS responses
const mockResponses = new Map(${mockResponses});
// Override dns.resolve4
const originalResolve4 = dns.resolve4.bind(dns);
dns.resolve4 = async (hostname) => {
const mock = mockResponses.get(hostname);
if (mock !== undefined) {
if (mock.length === 0) {
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
}
return mock;
}
// For non-mocked queries, return NXDOMAIN (not listed)
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
};
// Now import and run the actual daemon
import('${join(import.meta.dirname, '..', 'src', 'index.ts').replace(/\\/g, '/')}');
`);
const proc = spawn('npx', ['tsx', wrapperPath, '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env },
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => output.push(line));
proc.stderr?.on('data', (data) => {
// Uncomment for debugging:
// console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitFor = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// Check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const interval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(interval);
clearTimeout(timer);
resolve(output[i]);
return;
}
}
}, 10);
const timer = setTimeout(() => {
clearInterval(interval);
reject(new Error(`Timeout waiting for: ${pattern}\nOutput was:\n${output.join('\n')}`));
}, timeout);
});
};
const getMarks = (clientId: number): string[] => {
const marks: string[] = [];
const pattern = new RegExp(`^m ${clientId} .* MARK (\\S+)`);
for (const line of output) {
const match = line.match(pattern);
if (match) {
marks.push(match[1]);
}
}
return marks;
};
const wasAccepted = (clientId: number): boolean => {
return output.some(line => line.startsWith(`D ${clientId} `));
};
const wasRejected = (clientId: number): boolean => {
return output.some(line => line.startsWith(`k ${clientId} `));
};
const close = async (): Promise<void> => {
try { unlinkSync(wrapperPath); } catch {}
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup
await waitFor(/^S iauthd-ts/);
await new Promise(r => setTimeout(r, 100));
return { proc, output, send, waitFor, getMarks, wasAccepted, wasRejected, close };
}
/**
* Simulate a full client connection flow
*/
async function connectClient(
harness: TestHarness,
clientId: number,
ip: string,
options: { authenticated?: string } = {}
): Promise<void> {
harness.send(`${clientId} C ${ip} ${10000 + clientId} 10.0.0.1 6667`);
if (options.authenticated) {
harness.send(`${clientId} R ${options.authenticated}`);
}
// Small delay to let lookups start
await new Promise(r => setTimeout(r, 50));
harness.send(`${clientId} H Users`);
// Wait for decision
await harness.waitFor(new RegExp(`^[Dk] ${clientId} `), 3000);
}
describe('DNSBL Integration Tests', () => {
let tempDir: string;
let configPath: string;
let harness: TestHarness;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-dnsbl-test-'));
configPath = join(tempDir, 'test.conf');
clearMockDns();
});
afterEach(async () => {
await harness?.close();
try { unlinkSync(configPath); } catch {}
});
describe('Index Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2,3,4 mark=testbl block=all
`);
});
it('should block when index matches exactly', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
expect(harness.wasAccepted(0)).toBe(false);
});
it('should block when any configured index matches', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when index does not match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.5']); // index=5 not in 2,3,4
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should pass when not listed (NXDOMAIN)', async () => {
// No mock = NXDOMAIN
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Bitmask Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl bitmask=2,4 mark=testbl block=all
`);
});
it('should block when bitmask matches (bit 1 set)', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']); // 2 = 0010
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when bitmask matches (bit 2 set)', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']); // 4 = 0100
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when multiple bits match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.6']); // 6 = 0110 (bits 1 and 2)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when no bitmask bits match', async () => {
mockDns('192.168.1.103', 'test.dnsbl', ['127.0.0.1']); // 1 = 0001 (bit 0 only)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Block Modes', () => {
describe('block=all', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=all
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block authenticated users too', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'testuser' });
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('block=anonymous', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG You must authenticate to connect.
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=anonymous
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow SASL-authenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should mark authenticated users even though not blocked', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('testbl');
});
});
describe('mark only (no block)', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=infomark
`);
});
it('should accept client but apply mark', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('infomark');
});
});
});
describe('Whitelist', () => {
beforeEach(async () => {
// Whitelist first, then blocking DNSBLs - mimics AfterNET config
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=whitelist.dnsbl index=2 mark=whitelist whitelist
#IAUTH DNSBL server=blocklist.dnsbl index=2 mark=blocked block=all
`);
});
it('should not block whitelisted clients even if they match blocking DNSBL', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']); // Whitelisted
mockDns('192.168.1.100', 'blocklist.dnsbl', ['127.0.0.2']); // Also on blocklist
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should block non-whitelisted clients that match blocking DNSBL', async () => {
// Not on whitelist, but on blocklist
mockDns('192.168.1.101', 'blocklist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should apply whitelist mark', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.getMarks(0)).toContain('whitelist');
});
});
describe('Multiple DNSBLs', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl1.test index=2 mark=list1
#IAUTH DNSBL server=dnsbl2.test index=2 mark=list2
#IAUTH DNSBL server=dnsbl3.test index=2 mark=list3 block=anonymous
`);
});
it('should accumulate marks from multiple DNSBLs', async () => {
mockDns('192.168.1.100', 'dnsbl1.test', ['127.0.0.2']);
mockDns('192.168.1.100', 'dnsbl2.test', ['127.0.0.2']);
// Not on dnsbl3
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('list1');
expect(marks).toContain('list2');
expect(marks).not.toContain('list3');
});
it('should block if any blocking DNSBL matches', async () => {
mockDns('192.168.1.100', 'dnsbl3.test', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('Same Server, Different Indices (AfterNET pattern)', () => {
beforeEach(async () => {
// Mimics AfterNET's dnsbl.afternet.org with different indices
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.example.org index=250 mark=rbl block=anonymous
#IAUTH DNSBL server=dnsbl.example.org index=251 mark=cloud block=anonymous
`);
});
it('should whitelist on index=2', async () => {
mockDns('192.168.1.100', 'dnsbl.example.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block anonymous on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block anonymous on index=251', async () => {
mockDns('192.168.1.102', 'dnsbl.example.org', ['127.0.0.251']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101', { authenticated: 'user' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('rbl');
});
});
describe('Real-world AfterNET Config Simulation', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIMEOUT 21600
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
#IAUTH DNSBL server=dnsbl.afternet.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.afternet.org index=250 mark=afternetrbl block=anonymous
#IAUTH DNSBL server=dnsbl.afternet.org index=251 mark=cloud block=anonymous
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5,6,7,9 mark=sorbs block=anonymous
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
#IAUTH DNSBL server=dnsbl-2.uceprotect.net index=2 mark=uce-2
#IAUTH DNSBL server=cbl.abuseat.org index=2 mark=cbl
`);
});
it('should accept clean clients', async () => {
harness = await createHarness(configPath);
await connectClient(harness, 0, '8.8.8.8');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toHaveLength(0);
});
it('should whitelist AfterNET trusted IPs', async () => {
mockDns('10.0.0.50', 'dnsbl.afternet.org', ['127.0.0.2']);
mockDns('10.0.0.50', 'dnsbl.dronebl.org', ['127.0.0.5']); // Also on dronebl!
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.50');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block drones unless authenticated', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated drones', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60', { authenticated: 'droneuser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('dronebl');
});
it('should block Tor exit nodes unless authenticated', async () => {
mockDns('10.0.0.70', 'rbl.efnetrbl.org', ['127.0.0.4']); // index=4 = tor
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.70');
expect(harness.wasRejected(0)).toBe(true);
});
it('should mark UCE-2 but not block', async () => {
mockDns('10.0.0.80', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.80');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('uce-2');
});
it('should mark CBL but not block', async () => {
mockDns('10.0.0.90', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.90');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('cbl');
});
it('should accumulate multiple marks', async () => {
mockDns('10.0.0.95', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
mockDns('10.0.0.95', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.95');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('uce-2');
expect(marks).toContain('cbl');
});
});
describe('Class Assignment', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=trusted.dnsbl index=2 class=Trusted mark=trusted
#IAUTH DNSBL server=limited.dnsbl index=2 class=Limited mark=limited
`);
});
it('should assign class from matching DNSBL', async () => {
mockDns('192.168.1.100', 'trusted.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
// Check the D message includes the class
const acceptLine = harness.output.find(l => l.startsWith('D 0 '));
expect(acceptLine).toContain('Trusted');
});
});
});
+228
View File
@@ -0,0 +1,228 @@
/**
* Unit tests for DNSBL functions
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
reverseIPv4,
isIPv4,
getCacheEntry,
setCacheEntry,
getCacheSize,
matchesDNSBL,
parseQuery,
} from '../src/dnsbl.js';
import type { DNSBLConfig } from '../src/types.js';
describe('DNSBL Functions', () => {
describe('reverseIPv4', () => {
it('should reverse a valid IPv4 address', () => {
expect(reverseIPv4('192.168.1.10')).toBe('10.1.168.192');
});
it('should handle 127.0.0.1', () => {
expect(reverseIPv4('127.0.0.1')).toBe('1.0.0.127');
});
it('should handle 0.0.0.0', () => {
expect(reverseIPv4('0.0.0.0')).toBe('0.0.0.0');
});
it('should handle 255.255.255.255', () => {
expect(reverseIPv4('255.255.255.255')).toBe('255.255.255.255');
});
it('should return null for invalid IPv4', () => {
expect(reverseIPv4('not-an-ip')).toBeNull();
});
it('should return null for IPv6 addresses', () => {
expect(reverseIPv4('::1')).toBeNull();
expect(reverseIPv4('2001:db8::1')).toBeNull();
});
it('should return null for partial IPs', () => {
expect(reverseIPv4('192.168.1')).toBeNull();
expect(reverseIPv4('192.168')).toBeNull();
});
it('should return null for IPs with invalid octets', () => {
expect(reverseIPv4('192.168.1.256')).toBeNull();
expect(reverseIPv4('192.168.1.1000')).toBeNull();
});
});
describe('isIPv4', () => {
it('should return true for valid IPv4 addresses', () => {
expect(isIPv4('192.168.1.1')).toBe(true);
expect(isIPv4('127.0.0.1')).toBe(true);
expect(isIPv4('0.0.0.0')).toBe(true);
expect(isIPv4('255.255.255.255')).toBe(true);
});
it('should return false for IPv6 addresses', () => {
expect(isIPv4('::1')).toBe(false);
expect(isIPv4('2001:db8::1')).toBe(false);
});
it('should return false for invalid strings', () => {
expect(isIPv4('not-an-ip')).toBe(false);
expect(isIPv4('')).toBe(false);
expect(isIPv4('192.168.1')).toBe(false);
});
});
describe('Cache functions', () => {
beforeEach(() => {
// Clear cache by setting entries and letting them expire
// Note: In a real implementation, we'd want a clearCache() function
});
it('should store and retrieve cache entries', () => {
const query = 'test-cache-1.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toEqual(['127.0.0.2']);
});
it('should return null for non-existent entries', () => {
const entry = getCacheEntry('nonexistent.query.com', 3600);
expect(entry).toBeNull();
});
it('should expire old entries', () => {
const query = 'test-cache-expire.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
// With cacheTime of 0, entry should be expired
const entry = getCacheEntry(query, 0);
expect(entry).toBeNull();
});
it('should track cache size', () => {
const initialSize = getCacheSize();
const query = `test-cache-size-${Date.now()}.dnsbl.example.com`;
setCacheEntry(query, ['127.0.0.2']);
expect(getCacheSize()).toBeGreaterThanOrEqual(initialSize);
});
it('should handle null results (pending lookups)', () => {
const query = 'test-cache-null.dnsbl.example.com';
setCacheEntry(query, null);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toBeNull();
});
});
describe('matchesDNSBL', () => {
it('should match by index', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2,3,4',
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.5'], config)).toBe(false);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match by bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2', // Binary: 010
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true); // 010 & 010 = 010
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true); // 011 & 010 = 010
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true); // 110 & 010 = 010
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false); // 001 & 010 = 000
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(false); // 100 & 010 = 000
});
it('should match multiple bitmasks', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2,4', // Match if bit 1 or bit 2 set
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match any result if no index or bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
};
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.255'], config)).toBe(true);
});
it('should not match empty results', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL([], config)).toBe(false);
});
it('should match if any result matches (multiple results)', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '4',
};
expect(matchesDNSBL(['127.0.0.2', '127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1', '127.0.0.2'], config)).toBe(false);
});
it('should handle invalid result IPs gracefully', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL(['invalid', '127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['invalid'], config)).toBe(false);
});
});
describe('parseQuery', () => {
it('should parse a valid DNSBL query', () => {
const result = parseQuery('10.1.168.192.dnsbl.example.com');
expect(result).not.toBeNull();
expect(result?.ip).toBe('192.168.1.10');
expect(result?.server).toBe('dnsbl.example.com');
});
it('should handle multi-part server names', () => {
const result = parseQuery('1.0.0.127.zen.spamhaus.org');
expect(result).not.toBeNull();
expect(result?.ip).toBe('127.0.0.1');
expect(result?.server).toBe('zen.spamhaus.org');
});
it('should return null for invalid queries', () => {
expect(parseQuery('invalid')).toBeNull();
expect(parseQuery('dnsbl.example.com')).toBeNull();
expect(parseQuery('')).toBeNull();
});
});
});
+474
View File
@@ -0,0 +1,474 @@
/**
* Integration tests for IAuth protocol
* Tests the full protocol communication by spawning the daemon
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
interface IAuthTestHarness {
process: ChildProcess;
output: string[];
send: (line: string) => void;
waitForOutput: (pattern: RegExp, timeout?: number) => Promise<string>;
waitForLines: (count: number, timeout?: number) => Promise<string[]>;
close: () => Promise<void>;
}
async function createTestHarness(configPath: string): Promise<IAuthTestHarness> {
const output: string[] = [];
const proc = spawn('npx', ['tsx', 'src/index.ts', '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
output.push(line);
});
// Also capture stderr for debugging
proc.stderr?.on('data', (data) => {
console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitForOutput = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// First check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const checkInterval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output[i]);
return;
}
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
reject(new Error(`Timeout waiting for pattern: ${pattern}`));
}, timeout);
});
};
const waitForLines = (count: number, timeout = 5000): Promise<string[]> => {
return new Promise((resolve, reject) => {
const startLen = output.length;
const checkInterval = setInterval(() => {
if (output.length >= startLen + count) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output.slice(startLen, startLen + count));
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
resolve(output.slice(startLen)); // Return what we have
}, timeout);
});
};
const close = (): Promise<void> => {
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup - wait for stats output which comes last
await waitForOutput(/^S iauthd-ts/);
// Small delay to ensure all startup output is captured
await new Promise(r => setTimeout(r, 100));
return { process: proc, output, send, waitForOutput, waitForLines, close };
}
describe('IAuth Protocol Integration', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
describe('Startup Messages', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 3600
#IAUTH BLOCKMSG Test rejection message
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should send G (protocol version request) on startup', () => {
expect(harness.output).toContain('G 1');
});
it('should send V (version) on startup', () => {
const versionLine = harness.output.find(l => l.startsWith('V :'));
expect(versionLine).toBeDefined();
expect(versionLine).toContain('iauthd-ts');
});
it('should send O (policy) on startup', () => {
expect(harness.output).toContain('O RTAWUwFr');
});
it('should send a (new config) on startup', () => {
expect(harness.output).toContain('a');
});
it('should send A (config info) lines on startup', () => {
const configLines = harness.output.filter(l => l.startsWith('A *'));
expect(configLines.length).toBeGreaterThan(0);
});
it('should send s (stats start) on startup', () => {
expect(harness.output).toContain('s');
});
it('should send S (stats) lines on startup', () => {
const statsLines = harness.output.filter(l => l.startsWith('S '));
expect(statsLines.length).toBeGreaterThan(0);
});
});
describe('Client Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config with no DNSBLs - clients should pass immediately
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should accept a client with no DNSBLs configured', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 H Users');
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
it('should handle client disconnect', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 D');
// Should see debug message about disconnect
await harness.waitForOutput(/disconnected/i, 1000).catch(() => {});
// No error should occur
});
it('should handle multiple concurrent clients', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('1 C 192.168.1.11 12346 10.0.0.1 6667');
harness.send('2 C 192.168.1.12 12347 10.0.0.1 6667');
harness.send('0 H Users');
harness.send('1 H Users');
harness.send('2 H Users');
// All three should be accepted (longer timeout for concurrent processing)
await harness.waitForOutput(/^D 0/, 10000);
await harness.waitForOutput(/^D 1/, 10000);
await harness.waitForOutput(/^D 2/, 10000);
}, 15000);
});
describe('SASL/LOC Authentication', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config that blocks anonymous but allows authenticated
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG Blocked for testing
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should track authenticated account', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 R testuser');
harness.send('0 H Users');
// Should see debug about auth
const authLine = await harness.waitForOutput(/authed as testuser/i);
expect(authLine).toBeDefined();
});
});
describe('SASL PLAIN Authentication', () => {
let harness: IAuthTestHarness;
let usersPath: string;
beforeEach(async () => {
// Create users file with test user (password: testpass)
usersPath = join(tempDir, 'users');
// Plain text password for testing
writeFileSync(usersPath, 'testuser:testpass\n');
// Config with SASL enabled (S in policy) and users file
writeFileSync(configPath, `
#IAUTH POLICY SRTAWUwFr
#IAUTH SASLDB ${usersPath}
#IAUTH SASLFAILMSG Authentication failed
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
try {
unlinkSync(usersPath);
} catch {}
});
it('should respond with challenge when SASL PLAIN is requested', async () => {
// IRCd introduces a client
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends SASL start with mechanism
// Format: <id> A S :<mechanism>
harness.send('0 A S :PLAIN');
// iauthd should respond with empty challenge ('+' means ready)
// Format: c <id> <ip> <port> :<challenge>
const challengeLine = await harness.waitForOutput(/^c 0 192\.168\.1\.10 12345 :\+$/);
expect(challengeLine).toBeDefined();
});
it('should send L and Z messages on successful authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send SASL continuation with credentials
// Format: <id> a :<base64_data>
// Base64 of "\0testuser\0testpass" (SASL PLAIN format)
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with L (login success) then Z (SASL complete)
// Format: L <id> <ip> <port> <account>
const loginLine = await harness.waitForOutput(/^L 0 192\.168\.1\.10 12345 testuser$/);
expect(loginLine).toBeDefined();
// Format: Z <id> <ip> <port>
const completeLine = await harness.waitForOutput(/^Z 0 192\.168\.1\.10 12345$/);
expect(completeLine).toBeDefined();
});
it('should send f message on failed authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send wrong credentials
const credentials = Buffer.from('\0testuser\0wrongpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with f (auth failed)
// Format: f <id> <ip> <port>
const failLine = await harness.waitForOutput(/^f 0 192\.168\.1\.10 12345$/);
expect(failLine).toBeDefined();
});
it('should handle SASL host info message', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends host info with SASL start
// Format: <id> A H :<user@host:ip>
harness.send('0 A H :user@testhost.example.com:192.168.1.10');
// Should see debug about host info
const hostLine = await harness.waitForOutput(/SASL host info.*testhost/i);
expect(hostLine).toBeDefined();
});
it('should handle mechanism with certfp', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Format with certfp: <id> A S <mechanism> :<certfp>
harness.send('0 A S PLAIN :abc123fingerprint');
// Should respond with challenge
const challengeLine = await harness.waitForOutput(/^c 0/);
expect(challengeLine).toBeDefined();
});
it('should send mechanism list for unsupported mechanism', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Request unsupported mechanism
harness.send('0 A S :EXTERNAL');
// Should respond with mechanism list
// Format: l <id> <ip> <port> :<mechanisms>
const mechLine = await harness.waitForOutput(/^l 0 192\.168\.1\.10 12345 :PLAIN$/);
expect(mechLine).toBeDefined();
});
it('should complete full SASL flow then accept client', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
await harness.waitForOutput(/^L 0/);
await harness.waitForOutput(/^Z 0/);
// Now hurry up to finish connection
harness.send('0 H Users');
// Should accept the client with D message
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
});
describe('WEBIRC Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should ignore untrusted WEBIRC (capital W)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 W password user host.example.com 192.168.1.10');
await harness.waitForOutput(/untrusted WEBIRC/i);
});
it('should process trusted WEBIRC (lowercase w)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 w password user host.example.com 192.168.1.10');
harness.send('0 H Users');
// Should accept with new IP
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10/);
expect(doneLine).toBeDefined();
});
});
describe('Error Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should handle malformed client intro gracefully', async () => {
harness.send('0 C'); // Missing IP and ports
// Should not crash, might log an error
await new Promise(r => setTimeout(r, 100));
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle unknown message types gracefully', async () => {
harness.send('0 Z some unknown message');
await harness.waitForOutput(/unknown message/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle Hurry for unknown client gracefully', async () => {
harness.send('99 H Users'); // Client 99 was never introduced
await harness.waitForOutput(/ERROR.*hurry/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
});
describe('IPv6 Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.com index=2
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should skip DNSBL lookups for IPv6 and accept client', async () => {
harness.send('0 C 2001:db8::1 12345 ::1 6667');
harness.send('0 H Users');
// Should accept (IPv6 skips DNSBL lookups)
const doneLine = await harness.waitForOutput(/^D 0/);
expect(doneLine).toBeDefined();
});
});
});
+273
View File
@@ -0,0 +1,273 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
parseUsersFile,
verifyPassword,
generateHash,
decodeSASLPlain,
authenticatePlain,
} from '../src/sasl.js';
describe('SASL Module', () => {
describe('generateHash', () => {
it('should generate SHA-256 hash with $5$ prefix', () => {
const hash = generateHash('password', 'sha256');
expect(hash).toMatch(/^\$5\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate SHA-512 hash with $6$ prefix', () => {
const hash = generateHash('password', 'sha512');
expect(hash).toMatch(/^\$6\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate MD5 hash with $1$ prefix', () => {
const hash = generateHash('password', 'md5');
expect(hash).toMatch(/^\$1\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate different hashes for different passwords', () => {
const hash1 = generateHash('password1', 'sha256');
const hash2 = generateHash('password2', 'sha256');
expect(hash1).not.toBe(hash2);
});
it('should generate different hashes for same password (different salt)', () => {
const hash1 = generateHash('password', 'sha256');
const hash2 = generateHash('password', 'sha256');
// Salts are random, so hashes should be different
expect(hash1).not.toBe(hash2);
});
});
describe('verifyPassword', () => {
it('should verify SHA-256 hashed password', () => {
const hash = generateHash('testpass', 'sha256');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify SHA-512 hashed password', () => {
const hash = generateHash('testpass', 'sha512');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify MD5 hashed password', () => {
const hash = generateHash('testpass', 'md5');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify plain text password', () => {
expect(verifyPassword('plainpass', 'plainpass')).toBe(true);
expect(verifyPassword('wrongpass', 'plainpass')).toBe(false);
});
it('should reject invalid hash format', () => {
expect(verifyPassword('pass', '$invalid$format')).toBe(false);
expect(verifyPassword('pass', '$99$salt$hash')).toBe(false);
});
it('should handle empty password', () => {
const hash = generateHash('', 'sha256');
expect(verifyPassword('', hash)).toBe(true);
expect(verifyPassword('notempty', hash)).toBe(false);
});
});
describe('decodeSASLPlain', () => {
it('should decode valid SASL PLAIN data', () => {
// Format: base64(authzid \0 authcid \0 password)
const data = Buffer.from('\0testuser\0testpass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('testuser');
expect(result?.password).toBe('testpass');
});
it('should decode with authzid', () => {
const data = Buffer.from('authzid\0authcid\0password').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('authzid');
expect(result?.authcid).toBe('authcid');
expect(result?.password).toBe('password');
});
it('should return null for invalid base64', () => {
const result = decodeSASLPlain('not-valid-base64!!!');
// Actually base64 decode may not fail, it will just produce garbage
// Let's test with wrong number of parts
});
it('should return null for wrong number of parts', () => {
// Only 2 parts instead of 3
const data = Buffer.from('user\0pass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).toBeNull();
});
it('should handle empty fields', () => {
const data = Buffer.from('\0\0').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('');
expect(result?.password).toBe('');
});
it('should handle special characters', () => {
const data = Buffer.from('\0user@example.com\0p@ss:word!').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authcid).toBe('user@example.com');
expect(result?.password).toBe('p@ss:word!');
});
});
describe('parseUsersFile', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should parse simple users file', () => {
writeFileSync(usersFile, 'testuser:testpass\nadmin:adminpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.get('testuser')?.passwordHash).toBe('testpass');
expect(db.users.get('admin')?.passwordHash).toBe('adminpass');
});
it('should skip comments and empty lines', () => {
writeFileSync(usersFile, '# Comment\n\nuser:pass\n \n# Another comment\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(1);
expect(db.users.get('user')?.passwordHash).toBe('pass');
});
it('should lowercase usernames', () => {
writeFileSync(usersFile, 'TestUser:pass\nADMIN:pass2\n');
const db = parseUsersFile(usersFile);
expect(db.users.has('testuser')).toBe(true);
expect(db.users.has('admin')).toBe(true);
expect(db.users.has('TestUser')).toBe(false);
});
it('should handle passwords with colons', () => {
writeFileSync(usersFile, 'user:pass:with:colons\n');
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe('pass:with:colons');
});
it('should handle crypt-style hashes', () => {
const hash = '$5$salt$hashvalue';
writeFileSync(usersFile, `user:${hash}\n`);
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe(hash);
});
it('should return empty db for non-existent file', () => {
const db = parseUsersFile('/nonexistent/file');
expect(db.users.size).toBe(0);
});
it('should skip lines without colon', () => {
writeFileSync(usersFile, 'validuser:pass\ninvalidline\nanotheruser:anotherpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.has('validuser')).toBe(true);
expect(db.users.has('anotheruser')).toBe(true);
});
});
describe('authenticatePlain', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
// Create users file with various hash types
const sha256Hash = generateHash('sha256pass', 'sha256');
const sha512Hash = generateHash('sha512pass', 'sha512');
writeFileSync(usersFile, [
`plainuser:plainpass`,
`sha256user:${sha256Hash}`,
`sha512user:${sha512Hash}`,
].join('\n'));
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should authenticate with plain text password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'plainpass');
expect(result).toBe('plainuser');
});
it('should authenticate with SHA-256 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha256user', 'sha256pass');
expect(result).toBe('sha256user');
});
it('should authenticate with SHA-512 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha512user', 'sha512pass');
expect(result).toBe('sha512user');
});
it('should reject wrong password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'wrongpass');
expect(result).toBeNull();
});
it('should reject non-existent user', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'nouser', 'anypass');
expect(result).toBeNull();
});
it('should be case-insensitive for username', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'PlainUser', 'plainpass');
expect(result).toBe('plainuser');
});
});
});
+313
View File
@@ -0,0 +1,313 @@
#!/usr/bin/env npx tsx
/**
* Memory stress test for iauthd-ts
*
* Simulates thousands of client connections to verify:
* 1. Memory doesn't leak (client map cleanup)
* 2. DNS cache doesn't grow unbounded
* 3. Performance remains stable under load
*
* Usage:
* npm run stress
* npm run stress -- --clients=10000 --duration=60
*/
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
import { parseArgs } from 'node:util';
interface StressOptions {
clients: number; // Total clients to simulate
concurrent: number; // Max concurrent connections
duration: number; // Max duration in seconds
verbose: boolean; // Verbose output
}
interface Stats {
clientsSent: number;
clientsAccepted: number;
clientsRejected: number;
startTime: number;
lastHeapUsed: number;
maxHeapUsed: number;
samples: Array<{ time: number; heap: number; clients: number; cache: number }>;
}
function parseOptions(): StressOptions {
const { values } = parseArgs({
options: {
clients: { type: 'string', short: 'n', default: '5000' },
concurrent: { type: 'string', short: 'c', default: '100' },
duration: { type: 'string', short: 'd', default: '120' },
verbose: { type: 'boolean', short: 'v', default: false },
},
strict: true,
});
return {
clients: parseInt(values.clients!, 10),
concurrent: parseInt(values.concurrent!, 10),
duration: parseInt(values.duration!, 10),
verbose: values.verbose!,
};
}
function generateRandomIP(): string {
const a = Math.floor(Math.random() * 223) + 1; // 1-223 (avoid 0 and 224+)
const b = Math.floor(Math.random() * 256);
const c = Math.floor(Math.random() * 256);
const d = Math.floor(Math.random() * 256);
return `${a}.${b}.${c}.${d}`;
}
async function runStressTest(options: StressOptions): Promise<void> {
console.log('='.repeat(60));
console.log('iauthd-ts Memory Stress Test');
console.log('='.repeat(60));
console.log(`Clients to simulate: ${options.clients}`);
console.log(`Max concurrent: ${options.concurrent}`);
console.log(`Max duration: ${options.duration}s`);
console.log('='.repeat(60));
console.log();
// Create temp config
const tempDir = mkdtempSync(join(tmpdir(), 'iauthd-stress-'));
const configPath = join(tempDir, 'stress.conf');
// Use a DNSBL that will respond quickly (or use a fake one)
// For stress testing, we want quick responses so we use short timeout
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSTIMEOUT 1
#IAUTH CACHETIME 60
#IAUTH BLOCKMSG Stress test rejection
#IAUTH DNSBL server=zen.spamhaus.org index=2,3,4,5,6,7 mark=spamhaus block=anonymous
`);
const stats: Stats = {
clientsSent: 0,
clientsAccepted: 0,
clientsRejected: 0,
startTime: Date.now(),
lastHeapUsed: 0,
maxHeapUsed: 0,
samples: [],
};
// Spawn the daemon with memory tracking
const proc = spawn('node', [
'--expose-gc',
'--max-old-space-size=256', // Limit heap to catch leaks faster
'dist/index.js',
'-c', configPath,
], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
NODE_OPTIONS: '--expose-gc',
},
});
let cacheSize = 0;
let activeClients = 0;
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
if (options.verbose) {
console.log('< ' + line);
}
if (line.startsWith('D ')) {
stats.clientsAccepted++;
activeClients--;
} else if (line.startsWith('k ')) {
stats.clientsRejected++;
activeClients--;
} else if (line.includes('Cache size:')) {
const match = line.match(/Cache size: (\d+)/);
if (match) {
cacheSize = parseInt(match[1], 10);
}
}
});
proc.stderr?.on('data', (data) => {
if (options.verbose) {
console.error('stderr:', data.toString());
}
});
const send = (line: string) => {
if (options.verbose) {
console.log('> ' + line);
}
proc.stdin!.write(line + '\n');
};
// Wait for startup
await new Promise<void>((resolve) => {
const checkStartup = setInterval(() => {
// Check if we've seen the startup messages
if (stats.clientsSent === 0) {
clearInterval(checkStartup);
resolve();
}
}, 100);
setTimeout(() => {
clearInterval(checkStartup);
resolve();
}, 2000);
});
console.log('Daemon started. Beginning stress test...\n');
// Send server info
send('-1 M stress.test.server 65535');
const startTime = Date.now();
const endTime = startTime + (options.duration * 1000);
let clientId = 0;
// Progress reporting
const progressInterval = setInterval(() => {
const elapsed = (Date.now() - startTime) / 1000;
const rate = stats.clientsSent / elapsed;
const heapUsed = process.memoryUsage().heapUsed / 1024 / 1024;
stats.samples.push({
time: elapsed,
heap: heapUsed,
clients: activeClients,
cache: cacheSize,
});
if (heapUsed > stats.maxHeapUsed) {
stats.maxHeapUsed = heapUsed;
}
stats.lastHeapUsed = heapUsed;
process.stdout.write(
`\rSent: ${stats.clientsSent} | Accepted: ${stats.clientsAccepted} | ` +
`Rejected: ${stats.clientsRejected} | Active: ${activeClients} | ` +
`Cache: ${cacheSize} | Rate: ${rate.toFixed(1)}/s | ` +
`Elapsed: ${elapsed.toFixed(1)}s `
);
}, 1000);
// Main send loop
const sendBatch = () => {
const now = Date.now();
if (now >= endTime || stats.clientsSent >= options.clients) {
return false;
}
// Send up to concurrent limit
while (activeClients < options.concurrent && stats.clientsSent < options.clients) {
const ip = generateRandomIP();
const port = 10000 + (clientId % 55535);
send(`${clientId} C ${ip} ${port} 10.0.0.1 6667`);
send(`${clientId} H Users`);
stats.clientsSent++;
activeClients++;
clientId++;
}
return true;
};
// Run the send loop
while (sendBatch()) {
await new Promise(r => setTimeout(r, 10));
}
// Wait for remaining clients to be processed
console.log('\n\nWaiting for remaining clients to be processed...');
const drainStart = Date.now();
while (activeClients > 0 && (Date.now() - drainStart) < 30000) {
await new Promise(r => setTimeout(r, 100));
}
clearInterval(progressInterval);
// Cleanup
proc.stdin!.end();
await new Promise<void>((resolve) => {
proc.on('close', () => resolve());
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 2000);
});
try {
rmSync(tempDir, { recursive: true });
} catch {}
// Print results
const totalTime = (Date.now() - startTime) / 1000;
console.log('\n');
console.log('='.repeat(60));
console.log('STRESS TEST RESULTS');
console.log('='.repeat(60));
console.log(`Total clients sent: ${stats.clientsSent}`);
console.log(`Total clients accepted: ${stats.clientsAccepted}`);
console.log(`Total clients rejected: ${stats.clientsRejected}`);
console.log(`Unprocessed clients: ${stats.clientsSent - stats.clientsAccepted - stats.clientsRejected}`);
console.log(`Total time: ${totalTime.toFixed(2)}s`);
console.log(`Average rate: ${(stats.clientsSent / totalTime).toFixed(2)} clients/s`);
console.log(`Final cache size: ${cacheSize}`);
console.log('');
// Memory analysis
console.log('MEMORY ANALYSIS');
console.log('-'.repeat(60));
if (stats.samples.length > 1) {
const firstSample = stats.samples[0];
const lastSample = stats.samples[stats.samples.length - 1];
const heapGrowth = lastSample.heap - firstSample.heap;
const heapGrowthPercent = (heapGrowth / firstSample.heap) * 100;
console.log(`Initial heap: ${firstSample.heap.toFixed(2)} MB`);
console.log(`Final heap: ${lastSample.heap.toFixed(2)} MB`);
console.log(`Max heap: ${stats.maxHeapUsed.toFixed(2)} MB`);
console.log(`Heap growth: ${heapGrowth.toFixed(2)} MB (${heapGrowthPercent.toFixed(1)}%)`);
// Check for memory leak indicators
console.log('');
if (heapGrowthPercent > 100) {
console.log('⚠️ WARNING: Significant heap growth detected. Possible memory leak.');
} else if (heapGrowthPercent > 50) {
console.log('⚠️ NOTICE: Moderate heap growth. Monitor in production.');
} else {
console.log('✅ Memory usage appears stable.');
}
// Check if all clients were processed
const unprocessed = stats.clientsSent - stats.clientsAccepted - stats.clientsRejected;
if (unprocessed > 0) {
console.log(`⚠️ WARNING: ${unprocessed} clients were not processed. Possible state leak.`);
} else {
console.log('✅ All clients were processed correctly.');
}
// Check cache growth
const clientsPerCacheEntry = stats.clientsSent / Math.max(cacheSize, 1);
console.log(`Cache efficiency: ${clientsPerCacheEntry.toFixed(1)} clients per cache entry`);
}
console.log('='.repeat(60));
}
// Run the test
const options = parseOptions();
runStressTest(options).catch(console.error);
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+24
View File
@@ -0,0 +1,24 @@
# SASL Users File for iauthd-ts
# Format: username:passwordhash
#
# Supported hash formats:
# $5$salt$hash - SHA-256 crypt
# $6$salt$hash - SHA-512 crypt
# $1$salt$hash - MD5 crypt
# plaintext - Plain text (for testing only, not recommended)
#
# Use the genhash.ts utility to generate hashes:
# npx tsx src/genhash.ts <password> [sha256|sha512|md5]
#
# Example entries:
# Test user with plain text password (for testing only!)
testuser:testpass
# User with SHA-256 hashed password
# To generate: npx tsx src/genhash.ts mypassword sha256
#admin:$5$randomsalt$hashedpasswordhere
# User with SHA-512 hashed password (most secure)
# To generate: npx tsx src/genhash.ts mypassword sha512
#secureuser:$6$randomsalt$hashedpasswordhere
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['tests/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html'],
include: ['src/**/*.ts'],
exclude: ['src/index.ts'],
},
},
});