From e8b44ac1a9d2bb22a47454ecdca5d928ba20913c Mon Sep 17 00:00:00 2001 From: Daniel Winzen Date: Sun, 25 Oct 2026 15:27:08 +0100 Subject: [PATCH] Add invite code system --- README.md | 2 ++ common_config.php | 56 +++++++++++++++++++++++++++++++++++++++++- cron.php | 2 ++ setup.php | 1 + www/admin.php | 55 ++++++++++++++++++++++++++++++++++++++--- www/manage_account.php | 46 +++++++++++++++++++++++++++++++--- www/register.php | 54 +++++++++++++++++++++++++++++++++++++--- 7 files changed, 205 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index bb821dd..e3fb129 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,8 @@ Mailbox owners can add identity addresses on their mailbox domain from account s Registering a mailbox on `CLEARNET_SERVER` automatically creates its matching `local_part@ONION_SERVER` identity. The database upgrade backfills this identity for existing clearnet mailboxes. +When `INVITE_CODES_ENABLED` is true, public mailbox registration requires an unused invite code and admins can generate unlimited codes from the admin interface. User accounts can generate up to `INVITE_CODE_LIMIT` codes after `INVITE_WAIT_PERIOD_MONTHS` months; each redeemed user-generated code makes one replacement available after the same wait from its redemption date. Set `INVITE_CODE_LIMIT` to 0 to hide user invite management while retaining admin-generated codes and invite-required registration. Set `INVITE_CODES_ENABLED` to false to hide invite management and allow registration without an invite. These settings are in `common_config.php`. Running `php setup.php` creates the invite-code table on existing installations. + Rspamd rejects unauthenticated inbound messages using a hosted envelope-sender domain unless SPF passes or DMARC passes for a hosted From domain. Configure the hosted-domain map URL and token in `/etc/rspamd/rspamd.local.lua` alongside the other Rspamd map settings. Create a password used for your TURN server and replace all `YOUR_SECRET` in `/etc/prosody/prosody.cfg.lua` with it. diff --git a/common_config.php b/common_config.php index 832188a..7ae38f9 100644 --- a/common_config.php +++ b/common_config.php @@ -9,7 +9,7 @@ const DBHOST = 'localhost'; // Database host const DBUSER = 'postfix'; // Database user const DBPASS = 'YOUR_PASSWORD'; // Database password const DBNAME = 'postfix'; // Database -const DBVERSION = 13; // Database schema version +const DBVERSION = 14; // Database schema version const INACTIVITY_PERIOD_MONTHS = [1, 6, 12, 24]; // Allowed inactivity periods in months - don't forget to update get_inactivity_period_options on changes here and if an option is removed, you should also update accounts in the database mailbox table const DEFAULT_INACTIVITY_PERIOD = 12; // Default inactivity period in months const ALLOW_ACCOUNT_NEVER_DELETE = false; // Whether to allow users to set their inactivity period to "never delete" @@ -40,6 +40,10 @@ const DEFAULT_QUOTA = 50 * 1024 * 1024; // Default mailbox quota in bytes const POSTMASTER_EMAIL = 'postmaster@danwin1210.de'; // Email address of the postmaster account receiving TLS and DMARC reports const POSTMASTER_PASSWORD = 'YOUR_PASSWORD'; // Password of the postmaster account receiving TLS and DMARC reports const ADMIN_LIST_PAGE_SIZE = 50; // Number of entries per page in the admin list +const INVITE_CODES_ENABLED = false; // Require invite codes for public registration and enable invite management +const INVITE_CODE_LIMIT = 3; // Number of invite codes a user may have generated before replacements become available +const INVITE_WAIT_PERIOD_MONTHS = 1; // Months to wait after account creation and invite redemption +const INVITE_CODE_EXPIRATION_MONTHS = 6; // Months after which an invite code expires and is removed from the database const LANGUAGES = [ 'cs' => ['name' => 'čeΕ‘tina', 'locale' => 'cs_CZ', 'flag' => 'πŸ‡¨πŸ‡Ώ', 'show_in_menu' => true, 'dir' => 'ltr'], @@ -113,6 +117,56 @@ function generate_feedback_id( PDO $db ): string return $feedback_id; } +function get_user_invite_status( PDO $db, string $username ): array +{ + if ( ! INVITE_CODES_ENABLED || INVITE_CODE_LIMIT <= 0 ) { + return [ 'available' => 0, 'eligible' => false ]; + } + $stmt = $db->prepare( 'SELECT created <= DATE_SUB(NOW(), INTERVAL ' . (int) INVITE_WAIT_PERIOD_MONTHS . ' MONTH) FROM mailbox WHERE username = ? AND active = 1;' ); + $stmt->execute( [ $username ] ); + $eligible = (bool) $stmt->fetchColumn(); + if ( $eligible === false ) { + return [ 'available' => 0, 'eligible' => false ]; + } + + $stmt = $db->prepare( 'SELECT COUNT(*), SUM(redeemed_at <= DATE_SUB(NOW(), INTERVAL ' . (int) INVITE_WAIT_PERIOD_MONTHS . ' MONTH)) FROM invite_codes WHERE generated_by = ?;' ); + $stmt->execute( [ $username ] ); + $counts = $stmt->fetch( PDO::FETCH_NUM ); + $total = (int) $counts[ 0 ]; + $matured_redemptions = (int) ( $counts[ 1 ] ?? 0 ); + + return [ + 'available' => $eligible ? max( 0, INVITE_CODE_LIMIT + $matured_redemptions - $total ) : 0, + 'eligible' => $eligible, + ]; +} + +function create_user_invite_code( PDO $db, string $username ): ?string +{ + if ( ! INVITE_CODES_ENABLED || INVITE_CODE_LIMIT <= 0 ) { + return null; + } + $status = get_user_invite_status( $db, $username ); + if( ! $status[ 'eligible' ] || $status[ 'available' ] <= 0 ) { + return null; + } + $code = bin2hex( random_bytes( 24 ) ); + $stmt = $db->prepare( 'INSERT INTO invite_codes (code, generated_by, created_at) VALUES (?, ?, NOW());' ); + $stmt->execute( [ $code, $username ] ); + return $code; +} + +function create_admin_invite_code( PDO $db, string $admin ): ?string +{ + if ( ! INVITE_CODES_ENABLED ) { + return null; + } + $code = bin2hex( random_bytes( 24 ) ); + $stmt = $db->prepare( 'INSERT INTO invite_codes (code, generated_by_admin, created_at) VALUES (?, ?, NOW());' ); + $stmt->execute( [ $code, $admin ] ); + return $code; +} + function get_db_instance(): PDO { static $db = null; diff --git a/cron.php b/cron.php index f2da814..b52dbb0 100644 --- a/cron.php +++ b/cron.php @@ -85,6 +85,8 @@ while ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { $del_domain->execute( [ $tmp[ 'domain' ] ] ); } } +// delete expired invite codes +$db->exec( 'DELETE FROM invite_codes WHERE created_at <= DATE_SUB(NOW(), INTERVAL ' . (int) INVITE_CODE_EXPIRATION_MONTHS . ' MONTH);' ); // delete squirrelmail attachments older than an hour exec( 'find /var/local/squirrelmail/attach/ -type f -cmin +60 -delete' ); try { diff --git a/setup.php b/setup.php index 2c39290..7d04202 100644 --- a/setup.php +++ b/setup.php @@ -30,6 +30,7 @@ $createTableStatements = [ 'alias' => "CREATE TABLE IF NOT EXISTS `alias` (`address` varchar(255) NOT NULL, `goto` text NOT NULL, `domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `enforce_tls_in` tinyint(1) NOT NULL DEFAULT 1, `identity` varchar(255) DEFAULT NULL, PRIMARY KEY (`address`), KEY `domain` (`domain`), KEY `active` (`active`), KEY `identity` (`identity`), CONSTRAINT `alias_ibfk_1` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON UPDATE CASCADE, CONSTRAINT `alias_identity_ibfk_1` FOREIGN KEY (`identity`) REFERENCES `mailbox` (`username`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'alias_domain' => "CREATE TABLE IF NOT EXISTS `alias_domain` (`alias_domain` varchar(255) NOT NULL DEFAULT '', `target_domain` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`alias_domain`), KEY `active` (`active`), KEY `target_domain` (`target_domain`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'captcha' => "CREATE TABLE IF NOT EXISTS `captcha` (`id` bigint(20) NOT NULL AUTO_INCREMENT, `time` int(11) NOT NULL, `code` char(5) NOT NULL, PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;", + 'invite_codes' => "CREATE TABLE IF NOT EXISTS `invite_codes` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, `generated_by` varchar(255) DEFAULT NULL, `generated_by_admin` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `redeemed_by` varchar(255) DEFAULT NULL, `redeemed_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `code` (`code`), KEY `generated_by_redeemed_at` (`generated_by`,`redeemed_at`), KEY `generated_by_admin` (`generated_by_admin`), KEY `redeemed_by` (`redeemed_by`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'dmarc_report' => "CREATE TABLE IF NOT EXISTS `dmarc_report` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `report_id` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `org_name` varchar(255) NOT NULL, `begin` datetime NOT NULL, `end` datetime NOT NULL, `domain` varchar(255) NOT NULL, `adkim` char(1) NOT NULL, `aspf` char(1) NOT NULL, `policy` varchar(10) NOT NULL, `subdomain_policy` varchar(10) NOT NULL, `pct` tinyint(3) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `report_id_org_name` (`report_id`,`org_name`), KEY `begin_end` (`begin`,`end`), KEY `domain` (`domain`), CONSTRAINT `dmarc_report_ibfk_1` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON DELETE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'dmarc_report_errors' => "CREATE TABLE IF NOT EXISTS `dmarc_report_errors` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `report_id` bigint(20) unsigned NOT NULL, `error` text NOT NULL, PRIMARY KEY (`id`), KEY `report_id` (`report_id`), CONSTRAINT `dmarc_report_errors_ibfk_1` FOREIGN KEY (`id`) REFERENCES `dmarc_report` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'dmarc_report_records' => "CREATE TABLE IF NOT EXISTS `dmarc_report_records` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `report_id` bigint(20) unsigned NOT NULL, `source_ip` varchar(255) NOT NULL, `count` int(11) NOT NULL, `policy_evaluated_disposition` varchar(10) NOT NULL, `policy_evaluated_dkim` char(4) NOT NULL, `policy_evaluated_spf` char(4) NOT NULL, `identifier_envelope_to` varchar(255) NOT NULL, `identifier_envelope_from` varchar(255) NOT NULL, `identifier_header_from` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `report_id` (`report_id`), CONSTRAINT `dmarc_report_records_ibfk_2` FOREIGN KEY (`report_id`) REFERENCES `dmarc_report` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", diff --git a/www/admin.php b/www/admin.php index 14e7a64..f182bb8 100644 --- a/www/admin.php +++ b/www/admin.php @@ -109,7 +109,14 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $msg .= ''; } } elseif ( ! empty( $_SESSION[ 'email_admin_user' ] ) ) { - if ( $_POST[ 'action' ] === 'update_alias' ) { + if ( INVITE_CODES_ENABLED && $_POST[ 'action' ] === 'create_admin_invite_code' ) { + $invite_code = create_admin_invite_code( $db, $_SESSION[ 'email_admin_user' ] ); + if( $invite_code === null ) { + $msg .= ''; + } else { + $msg .= '
'.sprintf(htmlspecialchars(_('Invite code created: %s')), ''.htmlspecialchars( $invite_code ).'').'
'; + } + } elseif ( $_POST[ 'action' ] === 'update_alias' ) { $alias_goto = ''; if ( isset( $_POST[ 'alias_keep_copy' ] ) ) { $alias_goto .= $_SESSION[ 'email_admin_user' ] . ','; @@ -523,6 +530,9 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { ?> | | | | | |
-
+
@@ -546,7 +556,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {
-
+
@@ -562,6 +572,8 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {

query( 'SELECT COUNT(*) FROM invite_codes;' )->fetchColumn(); + $totalPages = max( 1, (int) ceil( $total / ADMIN_LIST_PAGE_SIZE ) ); + $stmt = $db->prepare( 'SELECT code, generated_by, generated_by_admin, created_at, redeemed_by, redeemed_at FROM invite_codes ORDER BY created_at DESC, id DESC LIMIT :limit OFFSET :offset;' ); + $stmt->bindValue( ':limit', ADMIN_LIST_PAGE_SIZE, PDO::PARAM_INT ); + $stmt->bindValue( ':offset', $offset, PDO::PARAM_INT ); + $stmt->execute(); + ?> +

+
+ + +
+ fetch( PDO::FETCH_ASSOC ) ) { + $creator = $invite[ 'generated_by' ] ?? $invite[ 'generated_by_admin' ]; + ?> +

β€” + () + + β€” () + + β€” + +

+ '.htmlspecialchars(_('Incorrect username or password')).'
'; } } + } elseif ( INVITE_CODES_ENABLED && INVITE_CODE_LIMIT > 0 && ! empty( $_SESSION[ 'email_user' ] ) && $_POST[ 'action' ] === 'create_invite_code' ) { + $invite_code = create_user_invite_code( $db, $_SESSION[ 'email_user' ] ); + if ( $invite_code === null ) { + $msg .= ''; + } else { + $msg .= '
'.sprintf(htmlspecialchars(_('Invite code created: %s')), ''.htmlspecialchars( $invite_code ).'').'
'; + } } elseif ( ! empty( $_SESSION[ 'email_user' ] ) && $_POST[ 'action' ] === 'update_settings' ) { $alias_goto = ''; if ( isset( $_POST[ 'alias_keep_copy' ] ) ) { @@ -310,7 +317,7 @@ if ( isset( $_SESSION[ 'user_totp_pending' ] ) ) {
-
+
@@ -352,7 +359,7 @@ if ( isset( $_SESSION[ 'user_totp_pending' ] ) ) {
-
+
@@ -387,7 +394,7 @@ if ( empty( $_SESSION[ 'email_user' ] ) ) { ?>
-
@@ -450,6 +457,39 @@ if ( empty( $_SESSION[ 'email_user' ] ) ) { ?>
+ 0 ) { + $invite_status = get_user_invite_status( $db, $_SESSION[ 'email_user' ] ); + $inviteStmt = $db->prepare( 'SELECT code, created_at, redeemed_by, redeemed_at FROM invite_codes WHERE generated_by = ? ORDER BY created_at DESC;' ); + $inviteStmt->execute( [ $_SESSION[ 'email_user' ] ] ); + ?> +

+

0 ) { + printf( htmlspecialchars(_('You can create %d invite code(s).')), $invite_status[ 'available' ] ); + } elseif ( ! $invite_status[ 'eligible' ] ) { + printf( htmlspecialchars(_('You can generate up to %d invite codes after your account has been active for %d month(s).')), INVITE_CODE_LIMIT, INVITE_WAIT_PERIOD_MONTHS ); + } else { + printf( htmlspecialchars(_('You can create more invite codes %d month(s) after one of your existing codes is used.')), INVITE_WAIT_PERIOD_MONTHS ); + } + ?>

+ 0 ) { ?> +
+ + +
+ fetch( PDO::FETCH_ASSOC ) ) { ?> +

β€” + : + + β€” () + + β€” + +

+ + +

'.htmlspecialchars(_('Invalid captcha')).'
'; } $db = get_db_instance(); + $invite_code = is_string( $_POST[ 'invite_code' ] ?? null ) ? strtolower( trim( $_POST[ 'invite_code' ] ) ) : ''; + if ( INVITE_CODES_ENABLED ) { + if ( $invite_code === '' ) { + $ok = false; + $msg .= ''; + } else { + $stmt = $db->prepare( 'SELECT null FROM invite_codes WHERE code = ? AND redeemed_by IS NULL;' ); + $stmt->execute( [ $invite_code ] ); + if ( ! $stmt->fetchColumn() ) { + $ok = false; + $msg .= ''; + } + } + } if ( ! preg_match( '/^([^+\/\'"]+?)(@([^@]+))?$/iu', $_POST[ 'user' ], $match ) ) { $ok = false; $msg .= ''; @@ -67,7 +81,21 @@ if ( isset( $_POST[ 'user' ] ) ) { } if ( $ok ) { $hash = password_hash( $_POST[ 'pwd' ], PASSWORD_ARGON2ID ); - $db->beginTransaction(); + if ( INVITE_CODES_ENABLED ) { + $db->beginTransaction(); + $stmt = $db->prepare( 'SELECT id FROM invite_codes WHERE code = ? AND redeemed_by IS NULL FOR UPDATE;' ); + $stmt->execute( [ $invite_code ] ); + $invite_id = $stmt->fetchColumn(); + if ( ! $invite_id ) { + $db->rollBack(); + $ok = false; + $msg .= ''; + } + } else { + $db->beginTransaction(); + } + } + if ( $ok ) { $stmt = $db->prepare( 'INSERT INTO alias (address, goto, domain, created, modified) VALUES (?, ?, ?, NOW(), NOW());' ); $stmt->execute( [ "$user@$domain", "$user@$domain", $domain ] ); $stmt = $db->prepare( 'INSERT INTO mailbox (username, password, quota, local_part, domain, created, modified, password_hash_type, openpgpkey_wkd, feedback_id) VALUES(?, ?, ?, ?, ?, NOW(), NOW(), ?, ?, ?);' ); @@ -75,8 +103,20 @@ if ( isset( $_POST[ 'user' ] ) ) { if ( ! create_clearnet_onion_identity( $db, "$user@$domain", $msg ) ) { $db->rollBack(); } else { - $db->commit(); - $msg .= ''; + if ( INVITE_CODES_ENABLED ) { + $stmt = $db->prepare( 'UPDATE invite_codes SET redeemed_by = ?, redeemed_at = NOW() WHERE id = ? AND redeemed_by IS NULL;' ); + $stmt->execute( [ "$user@$domain", $invite_id ] ); + if ( $stmt->rowCount() !== 1 ) { + $db->rollBack(); + $msg .= ''; + } else { + $db->commit(); + $msg .= ''; + } + } else { + $db->commit(); + $msg .= ''; + } } } } @@ -112,8 +152,14 @@ if( ! REGISTRATION_ENABLED ) {
-
+
+ +
+
+
+
+