This commit is contained in:
Javier Casares 2026-06-08 11:13:10 +00:00
commit 38520b2ba7
9 changed files with 1044 additions and 13 deletions

View file

@ -1,5 +1,34 @@
== Changelog == == Changelog ==
= 1.5.2 =
_Release date: 2026-06-06_
**Added**
* OTP import tool (2FA > Import) — import authenticator secrets from third-party 2FA plugins without requiring users to reconfigure their app:
* Two Factor (community) — plain Base32 from `_two_factor_totp_key` user meta.
* WP 2FA (Melapress) — plain or encrypted Base32 from `wp_2fa_totp_key` user meta; decrypted if WP 2FA is active.
* Wordfence Login Security — raw binary from `wfls_2fa_secrets` table, Base32-encoded on import.
* Admin notice banner when importable secrets are detected; dismissible per-admin for 7 days or permanently via Import page preference.
* Import correctly skips users who already have OTP actively configured in our plugin; only imports for users who have not yet activated OTP here.
**Fixed**
* Deactivating the Authenticator App method from the profile no longer pre-generates a new OTP secret immediately. The secret is deleted cleanly and a fresh QR code is generated lazily the next time the user views their profile. This ensures the import tool can correctly detect these users as candidates.
**Compatibility**
* WordPress: 6.4 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.5 / WPCS 3.3.0
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.34 — 42 tests, 109 assertions
= 1.5.1 = = 1.5.1 =
_Release date: 2026-06-06_ _Release date: 2026-06-06_

View file

@ -189,8 +189,10 @@ class Dashboard_Page {
?> ?>
</form> </form>
<?php // @phpstan-ignore-next-line -- redundant but kept for defence in depth; render_page() already gates on manage_options. <?php
if ( current_user_can( 'manage_options' ) ) : ?> // @phpstan-ignore-next-line -- redundant but kept for defence in depth; render_page() already gates on manage_options.
if ( current_user_can( 'manage_options' ) ) :
?>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:1em;"> <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:1em;">
<input type="hidden" name="action" value="robotstxt_2fa_export_users" /> <input type="hidden" name="action" value="robotstxt_2fa_export_users" />
<?php wp_nonce_field( 'robotstxt_2fa_export_users' ); ?> <?php wp_nonce_field( 'robotstxt_2fa_export_users' ); ?>

View file

@ -0,0 +1,971 @@
<?php
/**
* OTP secret migration tool — imports authenticator secrets from third-party 2FA plugins.
*
* Supports:
* - Two Factor (community plugin) — user meta `_two_factor_totp_key`, plain Base32.
* - WP 2FA (Melapress) — user meta `wp_2fa_totp_key`, plain or OpenSSL-encrypted Base32.
* - Wordfence Login Security — custom table `{prefix}wfls_2fa_secrets`, raw binary.
*
* @package Robotstxt_2FA
*/
namespace Robotstxt\TwoFA\Admin;
use Robotstxt\TwoFA\User\User_Settings_Repository;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Detects and imports OTP secrets from third-party 2FA plugins.
*
* @since 1.5.2
*/
class Migration_Page {
/**
* Admin submenu page slug.
*/
public const PAGE_SLUG = 'robotstxt-2fa-migrate';
/**
* Our plugin's TOTP secret meta key (destination).
*/
private const DEST_META_KEY = 'robotstxt_2fa_otp_secret';
/**
* Option key for migration preferences.
*/
private const PREFS_OPTION = 'robotstxt_2fa_migration_prefs';
/**
* Transient key prefix for per-user temporary notice dismissal.
*/
private const DISMISS_TRANSIENT_PREFIX = 'robotstxt_2fa_dismiss_notice_';
/**
* Nonce action for the dismiss-notice handler.
*/
private const DISMISS_NONCE_ACTION = 'robotstxt_2fa_dismiss_notice';
/**
* Nonce action for the import handler.
*/
private const IMPORT_NONCE_ACTION = 'robotstxt_2fa_import_otp';
/**
* Nonce action for saving migration preferences.
*/
private const PREFS_NONCE_ACTION = 'robotstxt_2fa_migration_prefs';
/**
* Source plugin identifiers.
*/
private const SOURCE_TWO_FACTOR = 'two_factor';
private const SOURCE_WP_2FA = 'wp_2fa';
private const SOURCE_WORDFENCE = 'wordfence';
/**
* Meta key used by the Two Factor (community) plugin.
*/
private const META_TWO_FACTOR = '_two_factor_totp_key';
/**
* Meta key used by WP 2FA (Melapress).
*/
private const META_WP_2FA = 'wp_2fa_totp_key';
/**
* Wordfence secrets table name (without DB prefix).
*/
private const WORDFENCE_TABLE = 'wfls_2fa_secrets';
/**
* User settings repository.
*
* @var User_Settings_Repository
*/
private User_Settings_Repository $repository;
/**
* Constructor.
*/
public function __construct() {
$this->repository = new User_Settings_Repository();
}
/**
* Register WordPress hooks.
*
* @since 1.5.2
*
* @return void
*/
public function register_hooks(): void {
// Priority 11: appear after Settings and Documentation (both registered at 10).
add_action( 'admin_menu', array( $this, 'register_menu' ), 11 );
add_action( 'admin_notices', array( $this, 'maybe_show_notice' ) );
add_action( 'admin_init', array( $this, 'maybe_handle_dismiss' ) );
add_action( 'admin_post_robotstxt_2fa_import_otp', array( $this, 'handle_import' ) );
add_action( 'admin_post_robotstxt_2fa_save_migration_prefs', array( $this, 'handle_save_prefs' ) );
}
/**
* Register the Import submenu page.
*
* @since 1.5.2
*
* @return void
*/
public function register_menu(): void {
add_submenu_page(
Dashboard_Page::PAGE_SLUG,
__( 'Import / Migration — 2FA', 'robotstxt-2fa' ),
__( 'Import', 'robotstxt-2fa' ),
'manage_options',
self::PAGE_SLUG,
array( $this, 'render_page' )
);
}
/**
* Show an admin banner when importable secrets are found.
*
* Suppressed when permanently hidden in preferences or temporarily dismissed.
*
* @since 1.5.2
*
* @return void
*/
public function maybe_show_notice(): void {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$prefs = $this->get_prefs();
if ( ! empty( $prefs['hide_notice'] ) ) {
return;
}
$user_id = get_current_user_id();
if ( get_transient( self::DISMISS_TRANSIENT_PREFIX . $user_id ) ) {
return;
}
$count = count( $this->get_all_candidates() );
if ( 0 === $count ) {
return;
}
$dismiss_url = wp_nonce_url(
add_query_arg( 'action', 'robotstxt_2fa_dismiss_notice', admin_url( 'admin.php' ) ),
self::DISMISS_NONCE_ACTION
);
$import_url = admin_url( 'admin.php?page=' . self::PAGE_SLUG );
?>
<div class="notice notice-warning">
<p>
<strong><?php esc_html_e( '2FA (by ROBOTSTXT):', 'robotstxt-2fa' ); ?></strong>
<?php
$msg = sprintf(
/* translators: %d: number of users */
_n(
'%d user has an authenticator app secret from another 2FA plugin. Import it so they keep using the same app without reconfiguring.',
'%d users have authenticator app secrets from another 2FA plugin. Import them so they keep using the same app without reconfiguring.',
$count,
'robotstxt-2fa'
),
absint( $count )
);
echo esc_html( $msg );
?>
&nbsp;<a href="<?php echo esc_url( $import_url ); ?>"><?php esc_html_e( 'Go to import tool →', 'robotstxt-2fa' ); ?></a>
</p>
<p style="margin-top:0;">
<a href="<?php echo esc_url( $dismiss_url ); ?>" style="font-size:0.875em;"><?php esc_html_e( 'Dismiss for 7 days', 'robotstxt-2fa' ); ?></a>
</p>
</div>
<?php
}
/**
* Handle the dismiss-notice GET request.
*
* @since 1.5.2
*
* @return void
*/
public function maybe_handle_dismiss(): void {
if ( ! isset( $_GET['action'] ) || 'robotstxt_2fa_dismiss_notice' !== $_GET['action'] ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$nonce_raw = isset( $_GET['_wpnonce'] ) && is_string( $_GET['_wpnonce'] )
? wp_unslash( $_GET['_wpnonce'] )
: '';
if ( '' === $nonce_raw || ! wp_verify_nonce( sanitize_text_field( $nonce_raw ), self::DISMISS_NONCE_ACTION ) ) {
return;
}
$user_id = get_current_user_id();
set_transient( self::DISMISS_TRANSIENT_PREFIX . $user_id, true, 7 * DAY_IN_SECONDS );
wp_safe_redirect( remove_query_arg( array( 'action', '_wpnonce' ) ) );
exit;
}
/**
* Render the Import / Migration admin page.
*
* @since 1.5.2
*
* @return void
*/
public function render_page(): void {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
}
$prefs = $this->get_prefs();
$candidates = $this->get_all_candidates();
$result = $this->get_result_from_query();
?>
<div class="wrap">
<h1><?php esc_html_e( 'Import — Two-Factor Authentication', 'robotstxt-2fa' ); ?></h1>
<?php $this->render_result_notice( $result ); ?>
<?php $this->render_prefs_section( $prefs ); ?>
<h2><?php esc_html_e( 'Importable users', 'robotstxt-2fa' ); ?></h2>
<?php if ( empty( $candidates ) ) : ?>
<p><?php esc_html_e( 'No importable secrets found. Either no supported plugin is installed, no users have a configured authenticator app, or all secrets have already been imported.', 'robotstxt-2fa' ); ?></p>
<?php else : ?>
<p>
<?php
$msg_found = sprintf(
/* translators: %d: number of users */
_n(
'Found %d user with an authenticator app secret that has not yet been imported.',
'Found %d users with authenticator app secrets that have not yet been imported.',
count( $candidates ),
'robotstxt-2fa'
),
count( $candidates )
);
echo esc_html( $msg_found );
?>
</p>
<p class="description"><?php esc_html_e( 'The secret key is transferred directly — users will not need to reconfigure their authenticator app.', 'robotstxt-2fa' ); ?></p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="robotstxt_2fa_import_otp" />
<?php wp_nonce_field( self::IMPORT_NONCE_ACTION ); ?>
<table class="widefat striped" style="margin:1em 0;max-width:800px;">
<thead>
<tr>
<th style="width:32px;">
<input type="checkbox" id="robotstxt-2fa-select-all" />
</th>
<th><?php esc_html_e( 'User', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Email', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Role', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Source plugin', 'robotstxt-2fa' ); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ( $candidates as $row ) : ?>
<tr>
<td>
<input
type="checkbox"
name="users[<?php echo absint( $row['user']->ID ); ?>]"
value="<?php echo esc_attr( $row['source'] ); ?>"
checked
class="robotstxt-2fa-import-cb"
/>
</td>
<td>
<strong><?php echo esc_html( $row['user']->user_login ); ?></strong>
<?php if ( '' !== $row['user']->display_name && $row['user']->display_name !== $row['user']->user_login ) : ?>
<br /><span class="description"><?php echo esc_html( $row['user']->display_name ); ?></span>
<?php endif; ?>
</td>
<td><?php echo esc_html( $row['user']->user_email ); ?></td>
<td><?php echo esc_html( implode( ', ', $row['user']->roles ) ); ?></td>
<td><?php echo esc_html( $this->get_source_label( $row['source'] ) ); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>
<?php
submit_button(
sprintf(
/* translators: %d: number of users */
__( 'Import selected (%d)', 'robotstxt-2fa' ),
count( $candidates )
),
'primary',
'submit',
false
);
?>
</p>
</form>
<script>
(function () {
var selectAll = document.getElementById( 'robotstxt-2fa-select-all' );
var checkboxes = document.querySelectorAll( '.robotstxt-2fa-import-cb' );
if ( ! selectAll ) { return; }
selectAll.addEventListener( 'change', function () {
checkboxes.forEach( function ( cb ) { cb.checked = selectAll.checked; } );
} );
checkboxes.forEach( function ( cb ) {
cb.addEventListener( 'change', function () {
var total = checkboxes.length;
var checked = document.querySelectorAll( '.robotstxt-2fa-import-cb:checked' ).length;
selectAll.indeterminate = checked > 0 && checked < total;
selectAll.checked = checked === total;
} );
} );
}());
</script>
<?php endif; ?>
</div>
<?php
}
/**
* Handle the OTP import admin-post action.
*
* @since 1.5.2
*
* @return void
*/
public function handle_import(): void {
check_admin_referer( self::IMPORT_NONCE_ACTION );
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to perform this action.', 'robotstxt-2fa' ) );
}
$raw_users = isset( $_POST['users'] ) && is_array( $_POST['users'] )
? wp_unslash( $_POST['users'] )
: array();
$imported = 0;
$skipped = 0;
$failed = 0;
$valid_sources = array( self::SOURCE_TWO_FACTOR, self::SOURCE_WP_2FA, self::SOURCE_WORDFENCE );
foreach ( $raw_users as $raw_id => $raw_source ) {
$user_id = absint( (string) $raw_id );
$source = is_string( $raw_source ) ? sanitize_key( $raw_source ) : '';
if ( 0 === $user_id || ! in_array( $source, $valid_sources, true ) ) {
++$failed;
continue;
}
$secret = $this->read_secret( $user_id, $source );
if ( '' === $secret ) {
++$failed;
continue;
}
update_user_meta( $user_id, self::DEST_META_KEY, $secret );
$settings = $this->repository->get_user_settings( $user_id );
$settings['enabled'] = true;
if ( ! in_array( 'otp', $settings['methods'], true ) ) {
$settings['methods'][] = 'otp';
}
$this->repository->save_user_settings( $user_id, $settings );
++$imported;
}
wp_safe_redirect(
add_query_arg(
array(
'page' => self::PAGE_SLUG,
'robotstxt_imported' => $imported,
'robotstxt_skipped' => $skipped,
'robotstxt_failed' => $failed,
),
admin_url( 'admin.php' )
)
);
exit;
}
/**
* Handle saving migration preferences.
*
* @since 1.5.2
*
* @return void
*/
public function handle_save_prefs(): void {
check_admin_referer( self::PREFS_NONCE_ACTION );
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to perform this action.', 'robotstxt-2fa' ) );
}
$hide_notice = isset( $_POST['hide_notice'] ) && '1' === $_POST['hide_notice'];
update_option(
self::PREFS_OPTION,
array( 'hide_notice' => $hide_notice ),
false
);
wp_safe_redirect(
add_query_arg( 'page', self::PAGE_SLUG, admin_url( 'admin.php' ) )
);
exit;
}
// -------------------------------------------------------------------------
// Candidate discovery
// -------------------------------------------------------------------------
/**
* Return all importable users across all supported source plugins.
*
* Deduplicates by user ID: if a user appears in multiple sources, the first
* detected source wins (priority: Two Factor → WP 2FA → Wordfence).
*
* @since 1.5.2
*
* @return array<int, array{user: \WP_User, source: string}>
*/
private function get_all_candidates(): array {
$candidates = array();
foreach ( $this->get_candidates_from_meta( self::META_TWO_FACTOR, self::SOURCE_TWO_FACTOR ) as $row ) {
$candidates[ $row['user']->ID ] = $row;
}
foreach ( $this->get_candidates_from_meta( self::META_WP_2FA, self::SOURCE_WP_2FA ) as $row ) {
if ( ! isset( $candidates[ $row['user']->ID ] ) ) {
$candidates[ $row['user']->ID ] = $row;
}
}
foreach ( $this->get_candidates_from_wordfence() as $row ) {
if ( ! isset( $candidates[ $row['user']->ID ] ) ) {
$candidates[ $row['user']->ID ] = $row;
}
}
return array_values( $candidates );
}
/**
* Find users who have a source secret but have NOT activated OTP in our plugin.
*
* A user is excluded when 'otp' appears in their active methods list — that
* means they deliberately set up OTP in our plugin and should not be overwritten.
* Users with a lazily generated secret (secret exists but OTP never activated)
* are treated as candidates: the un-activated secret will be replaced with the
* imported one.
*
* @since 1.5.2
*
* @param string $source_meta_key Meta key to check for the source secret.
* @param string $source Source plugin identifier.
*
* @return array<int, array{user: \WP_User, source: string}>
*/
private function get_candidates_from_meta( string $source_meta_key, string $source ): array {
$query = new \WP_User_Query(
array(
'meta_key' => $source_meta_key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Admin-only, intentional.
'meta_compare' => 'EXISTS',
'fields' => 'all',
'number' => -1,
)
);
/** @var array<int, mixed> $results */
$results = $query->get_results();
$rows = array();
foreach ( $results as $user ) {
if ( ! $user instanceof \WP_User ) {
continue;
}
// Skip users who already have OTP actively configured in our plugin.
if ( $this->user_has_otp_active( $user->ID ) ) {
continue;
}
$rows[] = array(
'user' => $user,
'source' => $source,
);
}
return $rows;
}
/**
* Find users who have a Wordfence 2FA secret but not yet our secret.
*
* @since 1.5.2
*
* @return array<int, array{user: \WP_User, source: string}>
*/
private function get_candidates_from_wordfence(): array {
global $wpdb;
$table = $wpdb->prefix . self::WORDFENCE_TABLE;
// Silently skip if the Wordfence table does not exist.
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name built from trusted prefix constant.
$exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
if ( $table !== $exists ) {
return array();
}
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names are trusted constants.
$rows = $wpdb->get_results(
"SELECT s.user_id, s.secret FROM `{$table}` s",
ARRAY_A
);
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! is_array( $rows ) ) {
return array();
}
$candidates = array();
foreach ( $rows as $row ) {
if ( ! is_array( $row ) || ! isset( $row['user_id'] ) || ! is_numeric( $row['user_id'] ) ) {
continue;
}
$user_id = (int) $row['user_id'];
$src_binary = isset( $row['secret'] ) && is_string( $row['secret'] ) ? $row['secret'] : '';
$src = '' !== $src_binary ? $this->base32_encode( $src_binary ) : '';
if ( '' === $src ) {
continue;
}
// Skip users who already have OTP actively configured in our plugin.
if ( $this->user_has_otp_active( $user_id ) ) {
continue;
}
$user = get_user_by( 'ID', $user_id );
if ( $user instanceof \WP_User ) {
$candidates[] = array(
'user' => $user,
'source' => self::SOURCE_WORDFENCE,
);
}
}
return $candidates;
}
// -------------------------------------------------------------------------
// Secret readers
// -------------------------------------------------------------------------
/**
* Read and return the Base32-encoded TOTP secret for a user from a given source.
*
* Returns an empty string when the secret cannot be retrieved or decoded.
*
* @since 1.5.2
*
* @param int $user_id User identifier.
* @param string $source Source plugin identifier.
*
* @return string Base32-encoded secret, or empty string on failure.
*/
private function read_secret( int $user_id, string $source ): string {
switch ( $source ) {
case self::SOURCE_TWO_FACTOR:
return $this->read_two_factor_secret( $user_id );
case self::SOURCE_WP_2FA:
return $this->read_wp_2fa_secret( $user_id );
case self::SOURCE_WORDFENCE:
return $this->read_wordfence_secret( $user_id );
default:
return '';
}
}
/**
* Read a plain-Base32 secret stored by the Two Factor (community) plugin.
*
* @since 1.5.2
*
* @param int $user_id User identifier.
*
* @return string
*/
private function read_two_factor_secret( int $user_id ): string {
$raw = get_user_meta( $user_id, self::META_TWO_FACTOR, true );
if ( ! is_string( $raw ) || '' === $raw ) {
return '';
}
return strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $raw ) ?? '' );
}
/**
* Read the TOTP secret stored by WP 2FA (Melapress).
*
* The value may be plain Base32 or encrypted with an `lsc_`, `ssl_`, or `wps_`
* prefix. When WP 2FA is still installed and its classes are available the
* decrypted secret is returned directly. When WP 2FA is not installed, only
* plain-text (unencrypted) secrets can be imported.
*
* @since 1.5.2
*
* @param int $user_id User identifier.
*
* @return string
*/
private function read_wp_2fa_secret( int $user_id ): string {
$raw = get_user_meta( $user_id, self::META_WP_2FA, true );
if ( ! is_string( $raw ) || '' === $raw ) {
return '';
}
$encrypted_prefixes = array( 'lsc_', 'ssl_', 'wps_' );
$is_encrypted = false;
foreach ( $encrypted_prefixes as $prefix ) {
if ( str_starts_with( $raw, $prefix ) ) {
$is_encrypted = true;
break;
}
}
if ( $is_encrypted ) {
// Try to decrypt via WP 2FA's own class if the plugin is still active.
if ( class_exists( 'WP2FA\Admin\Methods\TOTP' ) ) {
$user = get_user_by( 'ID', $user_id );
if ( ! $user instanceof \WP_User ) {
return '';
}
try {
$decrypted = \WP2FA\Admin\Methods\TOTP::get_totp_decrypted( $user );
return is_string( $decrypted ) ? strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $decrypted ) ?? '' ) : '';
} catch ( \Throwable $e ) {
return '';
}
}
// WP 2FA not available — cannot decrypt.
return '';
}
// Plain text — validate and return.
return strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $raw ) ?? '' );
}
/**
* Read the TOTP secret stored by Wordfence Login Security.
*
* Wordfence stores the raw 20-byte secret as a binary blob. We Base32-encode
* it to produce the standard representation expected by authenticator apps and
* our plugin's OTP_Manager.
*
* @since 1.5.2
*
* @param int $user_id User identifier.
*
* @return string
*/
private function read_wordfence_secret( int $user_id ): string {
global $wpdb;
$table = $wpdb->prefix . self::WORDFENCE_TABLE;
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted constant.
$secret_binary = $wpdb->get_var( $wpdb->prepare( "SELECT `secret` FROM `{$table}` WHERE `user_id` = %d LIMIT 1", $user_id ) );
if ( ! is_string( $secret_binary ) || '' === $secret_binary ) {
return '';
}
return $this->base32_encode( $secret_binary );
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
/**
* Base32-encode binary data using the RFC 4648 alphabet.
*
* Wordfence stores the raw TOTP secret as binary; this produces the Base32
* string that authenticator apps and our OTP_Manager expect.
*
* @since 1.5.2
*
* @param string $data Raw binary string.
*
* @return string
*/
private function base32_encode( string $data ): string {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$bits = '';
for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) {
$bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT );
}
$chunks = str_split( $bits, 5 );
$encoded = '';
foreach ( $chunks as $chunk ) {
if ( strlen( $chunk ) < 5 ) {
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
}
$encoded .= $alphabet[ (int) bindec( $chunk ) ];
}
return $encoded;
}
/**
* Check whether the user has OTP actively configured in our plugin.
*
* Returns true when 'otp' appears in the stored methods list, meaning the user
* has deliberately set up and confirmed an OTP secret in our plugin. A lazily
* generated secret that was never activated does NOT qualify.
*
* @since 1.5.2
*
* @param int $user_id User identifier.
*
* @return bool
*/
private function user_has_otp_active( int $user_id ): bool {
$settings = $this->repository->get_user_settings( $user_id );
return in_array( 'otp', $settings['methods'], true );
}
/**
* Return a human-readable label for a source plugin identifier.
*
* @since 1.5.2
*
* @param string $source Source identifier.
*
* @return string
*/
private function get_source_label( string $source ): string {
$labels = array(
self::SOURCE_TWO_FACTOR => __( 'Two Factor (community)', 'robotstxt-2fa' ),
self::SOURCE_WP_2FA => __( 'WP 2FA (Melapress)', 'robotstxt-2fa' ),
self::SOURCE_WORDFENCE => __( 'Wordfence Login Security', 'robotstxt-2fa' ),
);
return $labels[ $source ] ?? $source;
}
/**
* Retrieve migration preferences.
*
* @since 1.5.2
*
* @return array{hide_notice: bool}
*/
private function get_prefs(): array {
$raw = get_option( self::PREFS_OPTION, array() );
if ( ! is_array( $raw ) ) {
$raw = array();
}
return array(
'hide_notice' => ! empty( $raw['hide_notice'] ),
);
}
/**
* Read and sanitize import result query args set after an import redirect.
*
* @since 1.5.2
*
* @return array{imported: int, skipped: int, failed: int}|null
*/
private function get_result_from_query(): ?array {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only display; nonce verified in handle_import().
if ( ! array_key_exists( 'robotstxt_imported', $_GET ) ) {
return null;
}
return array(
'imported' => absint( isset( $_GET['robotstxt_imported'] ) && is_scalar( $_GET['robotstxt_imported'] ) ? $_GET['robotstxt_imported'] : 0 ),
'skipped' => absint( isset( $_GET['robotstxt_skipped'] ) && is_scalar( $_GET['robotstxt_skipped'] ) ? $_GET['robotstxt_skipped'] : 0 ),
'failed' => absint( isset( $_GET['robotstxt_failed'] ) && is_scalar( $_GET['robotstxt_failed'] ) ? $_GET['robotstxt_failed'] : 0 ),
);
// phpcs:enable WordPress.Security.NonceVerification.Recommended
}
/**
* Render the notice preferences section.
*
* @since 1.5.2
*
* @param array{hide_notice: bool} $prefs Current preferences.
*
* @return void
*/
private function render_prefs_section( array $prefs ): void {
?>
<h2><?php esc_html_e( 'Notice preferences', 'robotstxt-2fa' ); ?></h2>
<p class="description"><?php esc_html_e( 'Control how the migration banner behaves in the admin area.', 'robotstxt-2fa' ); ?></p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-bottom:2em;">
<input type="hidden" name="action" value="robotstxt_2fa_save_migration_prefs" />
<?php wp_nonce_field( self::PREFS_NONCE_ACTION ); ?>
<table class="form-table" role="presentation">
<tr>
<th scope="row"><?php esc_html_e( 'Admin notice', 'robotstxt-2fa' ); ?></th>
<td>
<input type="hidden" name="hide_notice" value="0" />
<label>
<input
type="checkbox"
name="hide_notice"
value="1"
<?php checked( $prefs['hide_notice'] ); ?>
/>
<?php esc_html_e( 'Permanently hide the migration notice in the admin area.', 'robotstxt-2fa' ); ?>
</label>
<p class="description"><?php esc_html_e( 'When unchecked, the notice appears until all importable secrets have been processed. Use the "Dismiss for 7 days" link in the notice for a temporary hide.', 'robotstxt-2fa' ); ?></p>
</td>
</tr>
</table>
<?php submit_button( __( 'Save preferences', 'robotstxt-2fa' ), 'secondary' ); ?>
</form>
<?php
}
/**
* Render an import result notice when redirect query args are present.
*
* @since 1.5.2
*
* @param array{imported: int, skipped: int, failed: int}|null $result Import result data.
*
* @return void
*/
private function render_result_notice( ?array $result ): void {
if ( null === $result ) {
return;
}
$type = $result['failed'] > 0 ? 'notice-warning' : 'notice-success';
$imported = $result['imported'];
$skipped = $result['skipped'];
$failed = $result['failed'];
?>
<div class="notice <?php echo esc_attr( $type ); ?>">
<p>
<?php if ( $imported > 0 ) : ?>
<?php
$msg = sprintf(
/* translators: %d: number of secrets imported */
_n(
'✓ %d secret imported and OTP method activated.',
'✓ %d secrets imported and OTP method activated.',
$imported,
'robotstxt-2fa'
),
absint( $imported )
);
echo esc_html( $msg );
?>
<?php endif; ?>
<?php if ( $skipped > 0 ) : ?>
<?php if ( $imported > 0 ) : ?>
&nbsp;
<?php endif; ?>
<?php
$msg = sprintf(
/* translators: %d: number of users skipped */
_n(
'%d user skipped (secret already present).',
'%d users skipped (secret already present).',
$skipped,
'robotstxt-2fa'
),
absint( $skipped )
);
echo esc_html( $msg );
?>
<?php endif; ?>
<?php if ( $failed > 0 ) : ?>
<?php if ( $imported > 0 || $skipped > 0 ) : ?>
&nbsp;
<?php endif; ?>
<?php
$msg = sprintf(
/* translators: %d: number of users that could not be imported */
_n(
'✗ %d user could not be imported (invalid, encrypted, or missing secret).',
'✗ %d users could not be imported (invalid, encrypted, or missing secret).',
$failed,
'robotstxt-2fa'
),
absint( $failed )
);
echo esc_html( $msg );
?>
<?php endif; ?>
<?php if ( 0 === $imported && 0 === $skipped && 0 === $failed ) : ?>
<?php esc_html_e( 'No users were selected for import.', 'robotstxt-2fa' ); ?>
<?php endif; ?>
</p>
</div>
<?php
}
}

View file

@ -8,6 +8,7 @@
namespace Robotstxt\TwoFA; namespace Robotstxt\TwoFA;
use Robotstxt\TwoFA\Admin\Dashboard_Page; use Robotstxt\TwoFA\Admin\Dashboard_Page;
use Robotstxt\TwoFA\Admin\Migration_Page;
use Robotstxt\TwoFA\Admin\Settings_Page; use Robotstxt\TwoFA\Admin\Settings_Page;
use Robotstxt\TwoFA\Cli\Cli_Command; use Robotstxt\TwoFA\Cli\Cli_Command;
use Robotstxt\TwoFA\Login\Login_Form_Manager; use Robotstxt\TwoFA\Login\Login_Form_Manager;
@ -118,6 +119,13 @@ class Plugin {
*/ */
private Dashboard_Page $dashboard_page; private Dashboard_Page $dashboard_page;
/**
* Migration / import page.
*
* @var Migration_Page
*/
private Migration_Page $migration_page;
/** /**
* Get singleton instance. * Get singleton instance.
* *
@ -149,6 +157,7 @@ class Plugin {
$this->ip_restrictions = new IP_Restrictions( $config ); $this->ip_restrictions = new IP_Restrictions( $config );
$this->geo_restrictions = new Geo_Restrictions( $config ); $this->geo_restrictions = new Geo_Restrictions( $config );
$this->dashboard_page = new Dashboard_Page( $this->attempts_log, $config, $repository ); $this->dashboard_page = new Dashboard_Page( $this->attempts_log, $config, $repository );
$this->migration_page = new Migration_Page();
} }
/** /**
@ -163,6 +172,7 @@ class Plugin {
$this->ip_restrictions->register_hooks(); $this->ip_restrictions->register_hooks();
$this->geo_restrictions->register_hooks(); $this->geo_restrictions->register_hooks();
$this->dashboard_page->register_hooks(); $this->dashboard_page->register_hooks();
$this->migration_page->register_hooks();
$this->login_manager->register_hooks(); $this->login_manager->register_hooks();
$this->profile_settings->register_hooks(); $this->profile_settings->register_hooks();
$this->recovery_codes->register_hooks(); $this->recovery_codes->register_hooks();

View file

@ -884,13 +884,15 @@ class Profile_Settings {
if ( $otp_requested ) { if ( $otp_requested ) {
$otp_should_remain_enabled = true; $otp_should_remain_enabled = true;
} else { } else {
// Delete the secret entirely — do not pre-generate a replacement.
// A fresh secret is generated lazily when the user next views the OTP section,
// which also prevents the import tool from skipping this user as "already configured".
$this->otp_manager->delete_secret( $user_id ); $this->otp_manager->delete_secret( $user_id );
$this->otp_manager->ensure_secret( $user );
$this->focus_section = true; $this->focus_section = true;
add_settings_error( add_settings_error(
'robotstxt-2fa', 'robotstxt-2fa',
'robotstxt-2fa-otp-disabled', 'robotstxt-2fa-otp-disabled',
__( 'Authenticator app disabled. A new QR code is ready below if you want to reconnect it.', 'robotstxt-2fa' ), __( 'Authenticator app disabled. Scan a new QR code below to reconnect it.', 'robotstxt-2fa' ),
'updated' 'updated'
); );
} }

View file

@ -4,7 +4,7 @@ Tags: security, two-factor authentication, login, otp
Requires at least: 6.4 Requires at least: 6.4
Tested up to: 7.0 Tested up to: 7.0
Requires PHP: 8.0 Requires PHP: 8.0
Stable tag: 1.5.1 Stable tag: 1.5.2
License: GPLv3 or later License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html License URI: https://www.gnu.org/licenses/gpl-3.0.html
@ -59,6 +59,23 @@ Yes. Activate the plugin at the network level. Network administrators can set an
== Changelog == == Changelog ==
= 1.5.2 =
_Release date: 2026-06-06_
**Added**
* OTP secret import tool (2FA > Import) — detects authenticator app secrets from three supported plugins and lets administrators import them with one click, without users needing to reconfigure their authenticator app:
* **Two Factor** (community plugin) — reads `_two_factor_totp_key` user meta (plain Base32, direct import).
* **WP 2FA** (Melapress) — reads `wp_2fa_totp_key` user meta; decrypts if WP 2FA is still active, imports plain-text secrets otherwise.
* **Wordfence Login Security** — reads from the `wfls_2fa_secrets` database table (raw binary, Base32-encoded on import).
* Import skips users who already have OTP actively configured in our plugin.
* Admin notice banner when importable secrets are detected — shows count and link to import tool; dismissible per-admin for 7 days or permanently via a setting on the Import page.
**Fixed**
* Deactivating the Authenticator App from the profile no longer immediately pre-generates a new OTP secret. The secret is now deleted cleanly, and a fresh QR code is generated lazily on the next profile view.
= 1.5.1 = = 1.5.1 =
_Release date: 2026-06-06_ _Release date: 2026-06-06_

View file

@ -3,7 +3,7 @@
* Plugin Name: 2FA (by ROBOTSTXT) * Plugin Name: 2FA (by ROBOTSTXT)
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/ * Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
* Description: Adds two-factor authentication to the WordPress login flow. * Description: Adds two-factor authentication to the WordPress login flow.
* Version: 1.5.1 * Version: 1.5.2
* Author: ROBOTSTXT * Author: ROBOTSTXT
* Author URI: https://www.robotstxt.es/ * Author URI: https://www.robotstxt.es/
* Text Domain: robotstxt-2fa * Text Domain: robotstxt-2fa
@ -23,7 +23,7 @@ if ( ! defined( 'ABSPATH' ) ) {
} }
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) { if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
define( 'ROBOTSTXT_2FA_VERSION', '1.5.1' ); define( 'ROBOTSTXT_2FA_VERSION', '1.5.2' );
} }
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) { if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {

View file

@ -1,8 +1,8 @@
{ {
"name": "2FA (by ROBOTSTXT)", "name": "2FA (by ROBOTSTXT)",
"slug": "robotstxt-2fa", "slug": "robotstxt-2fa",
"version": "1.5.1", "version": "1.5.2",
"download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/releases/download/1.5.1/robotstxt-2fa-1.5.1.zip", "download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/releases/download/1.5.2/robotstxt-2fa-1.5.2.zip",
"requires": "6.4", "requires": "6.4",
"requires_php": "8.0", "requires_php": "8.0",
"tested": "7.1", "tested": "7.1",
@ -11,10 +11,10 @@
"author_profile": "https://www.robotstxt.es/", "author_profile": "https://www.robotstxt.es/",
"homepage": "https://www.robotstxt.es/plugins/robotstxt-2fa/", "homepage": "https://www.robotstxt.es/plugins/robotstxt-2fa/",
"description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.", "description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.",
"changelog": "<h3>1.5.1 - 2026-06-06</h3><ul><li><strong>Security:</strong> CSV exports now use RFC 4180 encoding instead of addslashes()</li><li><strong>Security:</strong> GeoIP path validated with is_file() and !is_link() to block symlinks</li><li><strong>Security:</strong> App Password window filter validated as positive integer</li><li><strong>Fixed:</strong> Export CSV button only rendered for manage_options users</li></ul>", "changelog": "<h3>1.5.2 - 2026-06-06</h3><ul><li><strong>Added:</strong> OTP import tool — import authenticator secrets from Two Factor, WP 2FA, and Wordfence without users reconfiguring their app</li><li><strong>Added:</strong> Admin notice banner when importable secrets are detected, dismissible per-admin or permanently</li><li><strong>Fixed:</strong> Deactivating OTP from profile now deletes the secret cleanly without pre-generating a replacement</li></ul>",
"sections": { "sections": {
"description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.", "description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.",
"changelog": "<h3>1.5.1 - 2026-06-06</h3><ul><li><strong>Security:</strong> CSV exports now use RFC 4180 encoding instead of addslashes()</li><li><strong>Security:</strong> GeoIP path validated with is_file() and !is_link() to block symlinks</li><li><strong>Security:</strong> App Password window filter validated as positive integer</li><li><strong>Fixed:</strong> Export CSV button only rendered for manage_options users</li></ul>" "changelog": "<h3>1.5.2 - 2026-06-06</h3><ul><li><strong>Added:</strong> OTP import tool — import authenticator secrets from Two Factor, WP 2FA, and Wordfence without users reconfiguring their app</li><li><strong>Added:</strong> Admin notice banner when importable secrets are detected, dismissible per-admin or permanently</li><li><strong>Fixed:</strong> Deactivating OTP from profile now deletes the secret cleanly without pre-generating a replacement</li></ul>"
}, },
"banners": { "low": "", "high": "" }, "banners": { "low": "", "high": "" },
"icons": { "1x": "", "2x": "" } "icons": { "1x": "", "2x": "" }

View file

@ -3,7 +3,7 @@
'name' => 'robotstxt/robotstxt-2fa', 'name' => 'robotstxt/robotstxt-2fa',
'pretty_version' => 'dev-main', 'pretty_version' => 'dev-main',
'version' => 'dev-main', 'version' => 'dev-main',
'reference' => '61d65485a74e176946a79a5f6879fb8cd1f006a6', 'reference' => 'cba155cf16825862a2862ab315c62321cb1e5987',
'type' => 'wordpress-plugin', 'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
@ -40,7 +40,7 @@
'robotstxt/robotstxt-2fa' => array( 'robotstxt/robotstxt-2fa' => array(
'pretty_version' => 'dev-main', 'pretty_version' => 'dev-main',
'version' => 'dev-main', 'version' => 'dev-main',
'reference' => '61d65485a74e176946a79a5f6879fb8cd1f006a6', 'reference' => 'cba155cf16825862a2862ab315c62321cb1e5987',
'type' => 'wordpress-plugin', 'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),