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

+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';
}