'ID','number'=>100,'paged'=>$page]);
foreach($users as $user_id){
foreach([('wp' . 's_totp_secret')=>'hidefy_totp_secret',('wp' . 's_pin_hash')=>'hidefy_pin_hash',('wp' . 's_recovery')=>'hidefy_recovery'] as $old=>$new){
if(metadata_exists('user',$user_id,$old)&&!metadata_exists('user',$user_id,$new)){
update_user_meta($user_id,$new,get_user_meta($user_id,$old,true));
}
}
}
++$page;
}while(count($users)===100);
}
update_option('hidefy_legacy_migrated',1,false);
}
static function defaults(){return ['login'=>0,'slug'=>'secure-login','turnstile'=>0,'turnstile_environment'=>'production','turnstile_test_mode'=>'pass','sandbox_confirmed'=>0,'site_key'=>'','secret_key'=>'','twofa'=>0,'twofa_roles'=>['administrator'],'pin'=>0,'pin_roles'=>['editor','author'],'credit_widget'=>0,'credit_widget_area'=>'','delete_data_on_uninstall'=>0];}
static function opt($k){
if($k==='turnstile' && !empty(self::$o['turnstile']) && (self::$o['turnstile_environment']??'production')==='sandbox'
&& !self::sandbox_allowed())return 0;
return self::$o[$k]??null;
}
/** Recognize actual loopback installations even when WP_ENVIRONMENT_TYPE is unset. */
static function is_local_site(){
$host=wp_parse_url(home_url('/'),PHP_URL_HOST);
if(!is_string($host))return false;
$host=strtolower(trim($host,'[]'));
return in_array($host,['localhost','127.0.0.1','::1'],true);
}
/** Only explicitly configured non-production environments or loopback installs can test Turnstile. */
static function is_test_environment(){
return self::is_local_site() || in_array(wp_get_environment_type(),['local','development','staging'],true);
}
/** Sandbox is permitted only in non-production WordPress environments after an explicit admin opt-in. */
static function sandbox_allowed(){
return self::is_test_environment()
&& !empty(self::$o['sandbox_confirmed']);
}
static function boot(){
// Register hooks only. User APIs and role APIs are not guaranteed to be ready
// while WordPress is including active plugin files.
add_action('init',[__CLASS__,'initialize_after_wp_load'],0);
self::$o=wp_parse_args(get_option(self::OPTION,[]),self::defaults());
add_action('admin_menu',[__CLASS__,'menu']);add_action('admin_init',[__CLASS__,'settings']);
add_filter('login_url',[__CLASS__,'login_url'],10,3);add_filter('site_url',[__CLASS__,'site_url'],10,4);
add_filter('wp_redirect',[__CLASS__,'registration_redirect'],10,2);
add_action('init',[__CLASS__,'hide_admin_login_redirect'],0);add_action('init',[__CLASS__,'custom_login'],0);add_action('login_init',[__CLASS__,'block_default_login'],0);
add_action('login_form',[__CLASS__,'turnstile_form']);add_filter('authenticate',[__CLASS__,'turnstile_check'],25,3);
add_action('register_form',[__CLASS__,'turnstile_form']);add_filter('registration_errors',[__CLASS__,'turnstile_registration_check'],25,3);
add_filter('authenticate',[__CLASS__,'twofa_intercept'],99,3);
add_action('init',[__CLASS__,'challenge'],1);
add_filter('wp_is_application_passwords_available_for_user',[__CLASS__,'application_passwords'],10,2);
add_filter('xmlrpc_enabled',[__CLASS__,'xmlrpc']);
add_action('admin_post_hidefy_reset_pins',[__CLASS__,'reset_pins']);add_action('admin_post_hidefy_save_pin',[__CLASS__,'save_pin']);add_action('admin_post_hidefy_unlock_pin',[__CLASS__,'unlock_pin']);
add_filter('rest_pre_insert_post',[__CLASS__,'rest_pin'],10,2);add_filter('rest_pre_insert_page',[__CLASS__,'rest_pin'],10,2);
add_filter('rest_pre_dispatch',[__CLASS__,'rest_guard'],10,3);
add_action('pre_post_update',[__CLASS__,'pre_update_pin'],10,2);
add_filter('pre_delete_post',[__CLASS__,'delete_pin'],10,3);
add_action('admin_notices',[__CLASS__,'pin_notice']);add_action('admin_init',[__CLASS__,'pin_first_setup_gate'],1);add_action('admin_init',[__CLASS__,'pin_editor_gate'],2);add_action('admin_enqueue_scripts',[__CLASS__,'admin_styles']);
add_filter('wp_insert_post_data',[__CLASS__,'post_pin'],10,4);
add_action('pre_trash_post',[__CLASS__,'trash_pin'],10,2);
// Quick Edit submits through admin-ajax.php?action=inline-save.
// Validate server-side before WordPress's AJAX handler executes.
add_action('wp_ajax_inline-save',[__CLASS__,'quick_edit_guard'],0);
add_action('admin_enqueue_scripts',[__CLASS__,'quick_edit_ui']);
add_action('widgets_init',[__CLASS__,'register_credit_widget']);
add_action('wp_loaded',[__CLASS__,'sync_credit_widget'],20);
add_action('admin_notices',[__CLASS__,'sandbox_notice']);
}
static function initialize_after_wp_load(){
// init runs after the WordPress user API is available. Migrate once, then
// reload options so legacy settings are effective in this same request.
self::migrate_legacy_data();
if($role=get_role('administrator')){
if(!$role->has_cap('manage_hidefy_security'))$role->add_cap('manage_hidefy_security');
}
self::$o=wp_parse_args(get_option(self::OPTION,[]),self::defaults());
}
static function sandbox_notice(){if(current_user_can('manage_options')&&self::opt('turnstile')&&self::opt('turnstile_environment')==='sandbox')echo '
Hidefy: Cloudflare Turnstile is in SANDBOX mode. This is not bot protection. Switch to Production with real keys before launch.
'; }
static function activate(){if(is_multisite())wp_die('Hidefy only supports single-site WordPress.');if($admin=get_role('administrator'))$admin->add_cap('manage_hidefy_security');add_option(self::OPTION,self::defaults());flush_rewrite_rules();}
static function deactivate(){flush_rewrite_rules();}
static function menu(){add_menu_page('Hidefy','Hidefy','manage_hidefy_security','hidefy',[__CLASS__,'page'],'dashicons-shield-alt',80);add_submenu_page('hidefy','Security Settings','Security Settings','manage_hidefy_security','hidefy',[__CLASS__,'page']);if(self::pin_required()){add_submenu_page('profile.php','My Security PIN','My Security PIN','read','hidefy-my-pin',[__CLASS__,'my_pin_page']);add_submenu_page('hidefy','My Security PIN','My Security PIN','read','hidefy-my-pin',[__CLASS__,'my_pin_page']);}}
static function settings(){add_filter('option_page_capability_hidefy_group',static function(){return 'manage_hidefy_security';});register_setting('hidefy_group',self::OPTION,['type'=>'array','sanitize_callback'=>[__CLASS__,'sanitize']]);}
static function sanitize($in){$old=self::$o;$out=$old; if(!is_array($in))return $old; if(current_user_can('hidefy_demo_account')){ $in['turnstile_environment']='sandbox'; $in['site_key']=$old['site_key']; $in['secret_key']=''; }
foreach(['login','turnstile','twofa','pin','credit_widget'] as $key)$out[$key]=empty($in[$key])?0:1;
$slug=sanitize_title($in['slug']??'');if(!preg_match('/^[a-z0-9][a-z0-9-]{2,60}$/',$slug)||in_array($slug,['wp-admin','wp-login','wp-json','feed','admin','login'],true)){$slug=$old['slug'];add_settings_error(self::OPTION,'slug','Invalid or reserved login slug.');}
// Only real site administrators can change the uninstall data policy.
$out['delete_data_on_uninstall']=current_user_can('manage_options') && !current_user_can('hidefy_demo_account')
? (!empty($in['delete_data_on_uninstall'])?1:0)
: (int)($old['delete_data_on_uninstall']??0);
$out['slug']=$slug;
$env=sanitize_key($in['turnstile_environment']??'production');$out['turnstile_environment']=in_array($env,['production','sandbox'],true)?$env:'production';
$out['sandbox_confirmed']=!empty($in['sandbox_confirmed'])?1:0;
if($out['turnstile'] && $out['turnstile_environment']==='sandbox'){
if(!self::is_test_environment()){
$out['turnstile']=0;
$out['sandbox_confirmed']=0;
add_settings_error(self::OPTION,'sandbox_production','Sandbox is blocked on production websites. Select Production and enter your Cloudflare keys.');
}elseif(!$out['sandbox_confirmed']){
$out['turnstile']=0;
add_settings_error(self::OPTION,'sandbox_confirmation','Confirm that Sandbox does not protect against bots before enabling it.');
}
}
$test=sanitize_key($in['turnstile_test_mode']??'pass');$out['turnstile_test_mode']=in_array($test,['pass','fail','interactive'],true)?$test:'pass';
foreach(['site_key','secret_key'] as $key){$v=trim((string)($in[$key]??''));$out[$key]=$v===''?$old[$key]:sanitize_text_field($v);}
unset($out['credit']); // Remove legacy admin-sidebar attribution option.
$out['credit_widget_area']=sanitize_key($in['credit_widget_area']??'');
if($out['credit_widget'] && $out['credit_widget_area']===''){ $out['credit_widget']=0; add_settings_error(self::OPTION,'credit_widget','Select a widget area before enabling automatic attribution.'); }
$roles=array_keys(wp_roles()->roles);foreach(['twofa_roles','pin_roles'] as $key)$out[$key]=array_values(array_intersect($roles,(array)($in[$key]??[])));
if($out['turnstile']&&$out['turnstile_environment']==='production'&&(!$out['site_key']||!$out['secret_key'])){$out['turnstile']=0;add_settings_error(self::OPTION,'turnstile','Turnstile requires both keys.');}
return $out;
}
static function page(){
if(!current_user_can('manage_hidefy_security'))return;
$o=self::$o;
$url=home_url('/'.$o['slug'].'/');
require __DIR__.'/admin-page.php';
}
/** Reset another user's PIN or every non-administrator PIN; never disclose the old PIN. */
static function reset_pins(){
if(!current_user_can('manage_options')||!current_user_can('manage_hidefy_security'))wp_die('Unauthorized', 'Forbidden',['response'=>403]);
check_admin_referer('hidefy_reset_pins');
$mode=isset($_POST['reset_mode'])?sanitize_key(wp_unslash($_POST['reset_mode'])):'';
$ids=[];
if($mode==='user'){
$uid=isset($_POST['reset_user_id'])?absint($_POST['reset_user_id']):0;
$user=$uid?get_userdata($uid):false;
if(!$user||in_array('administrator',(array)$user->roles,true))wp_die('Select a valid non-administrator account.','Invalid user',['response'=>400]);
$ids=[$uid];
}elseif($mode==='all'){
$page=1;
do{
$users=get_users(['number'=>100,'paged'=>$page,'fields'=>'all']);
foreach($users as $user){
if(!in_array('administrator',(array)$user->roles,true))$ids[]=$user->ID;
}
++$page;
}while(count($users)===100);
}else{
wp_die('Invalid reset operation.','Invalid request',['response'=>400]);
}
foreach($ids as $uid){
delete_user_meta($uid,self::PIN);
delete_transient('hidefy_pin_fail_'.$uid);
}
wp_safe_redirect(add_query_arg(['page'=>'hidefy','hidefy_tab'=>'content','hidefy_pin_reset'=>count($ids)],admin_url('admin.php')));exit;
}
static function role_checkboxes($key,$selected){foreach(wp_roles()->roles as $id=>$role){echo '';}}
static function admin_styles($hook){if(str_contains((string)$hook,'hidefy-my-pin')||$hook==='toplevel_page_hidefy')wp_enqueue_style('hidefy-security',plugins_url('assets/security.css',HIDEFY_FILE),[],HIDEFY_VERSION);
if($hook==='toplevel_page_hidefy'){wp_enqueue_style('hidefy-admin',plugins_url('assets/admin.css',HIDEFY_FILE),[],HIDEFY_VERSION);wp_enqueue_script('hidefy-admin',plugins_url('assets/admin.js',HIDEFY_FILE),[],HIDEFY_VERSION,true);}}
/** Read-only return URL. No state changes are performed from this request parameter. */
static function pin_target(){
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation parameter, validated as an admin URL.
$url=isset($_REQUEST['hidefy_return'])?esc_url_raw(wp_unslash($_REQUEST['hidefy_return'])):'';
if(!$url)return '';
$target=wp_validate_redirect($url,'');
$admin=admin_url();
return $target&&str_starts_with($target,$admin)&&!str_contains($target,'hidefy-my-pin')?$target:'';
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
/** Require a first-time PIN before protected users use the dashboard. */
static function pin_first_setup_gate(){
if(!self::pin_required()||get_user_meta(get_current_user_id(),self::PIN,true)||wp_doing_ajax()||wp_doing_cron())return;
global $pagenow;
if(in_array($pagenow,['admin-post.php','admin-ajax.php','async-upload.php'],true))return;
// Do not interfere with the PIN enrollment screen itself.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin page routing, not a form submission.
if(isset($_GET['page'])&&sanitize_key(wp_unslash($_GET['page']))==='hidefy-my-pin')return;
$target='';
if(in_array($pagenow,['edit.php','post.php','post-new.php'],true)){
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only post type routing for the first-time PIN enrollment redirect.
$post_type=isset($_GET['post_type'])?sanitize_key(wp_unslash($_GET['post_type'])):'post';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only editor URL inspection.
if($pagenow==='post.php' && isset($_GET['post'])){
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only post ID lookup; no mutation.
$post=get_post(absint($_GET['post']));
if($post)$post_type=$post->post_type;
}
if(in_array($post_type,['post','page'],true))$target=admin_url('edit.php'.($post_type==='page'?'?post_type=page':''));
}
$url=admin_url('profile.php?page=hidefy-my-pin');
if($target)$url=add_query_arg('hidefy_return',$target,$url);
wp_safe_redirect($url);exit;
}
static function pin_editor_gate(){
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- WordPress editor navigation is a GET request, not a state-changing form.
if(!self::pin_required()||self::pin_unlocked()||wp_doing_ajax()||wp_doing_cron())return;
global $pagenow;
if(!in_array($pagenow,['post-new.php','post.php'],true))return;
if($pagenow==='post.php'){
$post_id=isset($_GET['post'])?absint($_GET['post']):0;
$post=$post_id?get_post($post_id):null;
if(!$post||!in_array($post->post_type,['post','page'],true))return;
}elseif(isset($_GET['post_type'])&&!in_array(sanitize_key(wp_unslash($_GET['post_type'])),['post','page'],true))return;
// Return to the relevant content list after PIN verification, not to a blocked editor.
$post_type='post';
if($pagenow==='post.php'){
$post_id=isset($_GET['post'])?absint($_GET['post']):0;
$post=$post_id?get_post($post_id):null;
if($post && $post->post_type==='page')$post_type='page';
}elseif(isset($_GET['post_type']) && sanitize_key(wp_unslash($_GET['post_type']))==='page'){
$post_type='page';
}
$target=admin_url('edit.php'.($post_type==='page'?'?post_type=page':''));
wp_safe_redirect(add_query_arg('hidefy_return',$target,admin_url('profile.php?page=hidefy-my-pin')));exit;
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
static function pin_forms(){
$has=(bool)get_user_meta(get_current_user_id(),self::PIN,true);
$return=self::pin_target();
$unlocked=self::pin_unlocked();
echo '
🔒
CONTENT PROTECTION';
if(!$has){
echo '
Create your security PIN
First time here? Set an individual 8–32 digit PIN to protect your posts and pages.
Your content editing access is currently unlocked. You can update your PIN below.
Content editing is unlocked for this session.
';
echo '';
}else{
echo '
Verify your security PIN
Confirm your current PIN before editing content or managing your PIN.
';
echo '';
}
echo '
Forgot your security PIN? Contact your website administrator to reset it.
';
echo '
';
}
static function my_pin_page(){
if(!is_user_logged_in()||!self::pin_required())wp_die('PIN protection is not enabled for this account.');
if(self::pin_unlocked() && self::pin_target()){wp_safe_redirect(self::pin_target());exit;}
echo '
Hidefy
';self::pin_forms();echo '
';
}
static function pin_notice(){
global $pagenow;
if(!in_array($pagenow,['post.php','post-new.php','edit.php'],true)||!self::pin_required()||self::pin_unlocked())return;
$post_type='post';
if($pagenow==='post.php'){
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only editor navigation.
$post_id=isset($_GET['post'])?absint($_GET['post']):0;
$post=$post_id?get_post($post_id):null;
if($post && $post->post_type==='page')$post_type='page';
}else{
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only post type selection.
if(isset($_GET['post_type']) && sanitize_key(wp_unslash($_GET['post_type']))==='page')$post_type='page';
}
$target=admin_url('edit.php'.($post_type==='page'?'?post_type=page':''));
$url=add_query_arg('hidefy_return',$target,admin_url('profile.php?page=hidefy-my-pin'));
echo '
';
}
static function has_role($u,$key){return $u instanceof WP_User && (bool)array_intersect($u->roles,(array)self::opt($key));}
static function login_url($url,$redirect,$force){if(!self::opt('login'))return $url;$url=home_url('/'.self::opt('slug').'/');if($redirect)$url=add_query_arg('redirect_to',$redirect,$url);return $url;}
static function site_url($url,$path,$scheme,$blog_id){if(!self::opt('login')||!in_array($scheme,['login','login_post'],true))return $url;if(str_starts_with(ltrim($path,'/'),'wp-login.php')){ $query=wp_parse_url($url,PHP_URL_QUERY);return home_url('/'.self::opt('slug').'/').($query?'?'.$query:'');}return $url;}
/** Return a genuine 404 for unauthenticated visits to the dashboard entry point.
* Keep AJAX, admin-post, REST and other endpoints available for WordPress compatibility.
* The login URL must be enabled first; otherwise WordPress keeps its normal behavior.
*/
static function hide_admin_login_redirect(){
if(!self::opt('login') || is_user_logged_in() || (defined('WP_CLI') && WP_CLI))return;
$path=(string)wp_parse_url(esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']??'')),PHP_URL_PATH);
$base=(string)wp_parse_url(home_url('/'),PHP_URL_PATH);
$prefix=rtrim($base,'/');
if($prefix!=='' && !str_starts_with($path,$prefix.'/'))return;
$relative=ltrim(substr($path,strlen($prefix)),'/');
// Match only the admin dashboard entry, including /wp-admin (without trailing slash).
if(!in_array($relative,['wp-admin','wp-admin/','wp-admin/index.php'],true))return;
status_header(404);
nocache_headers();
header('X-Robots-Tag: noindex, nofollow',true);
wp_die(esc_html__('Page not found.','hidefy'),esc_html__('404 Not Found','hidefy'),['response'=>404]);
}
static function custom_login(){if(!self::opt('login'))return;$path=trim((string)wp_parse_url(esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']??'')),PHP_URL_PATH),'/');$homepath=trim((string)wp_parse_url(home_url('/'),PHP_URL_PATH),'/');if($homepath&&str_starts_with($path,$homepath.'/'))$path=substr($path,strlen($homepath)+1);
if($path!==self::opt('slug'))return;
if(defined('HIDEFY_CUSTOM_LOGIN'))return;
define('HIDEFY_CUSTOM_LOGIN',true);
// WordPress wp-login.php normally runs in the global script scope. Because
// this plugin loads it inside a callback, explicitly initialize variables
// that core login templates expect in their local scope. Otherwise PHP 8+
// prints warnings and may leak them into the login form's input values.
$user_login = '';
$error = '';
require ABSPATH.'wp-login.php';
exit;
}
/** WordPress core uses a relative wp-login.php URL after successful registration.
* Rewrite only that specific destination, preserving its success notice.
* Do not expose the normal login endpoint or rewrite unrelated redirects.
*/
static function registration_redirect($location,$status){
if(!self::opt('login') || !is_string($location))return $location;
$parts=wp_parse_url($location);
if(!is_array($parts))return $location;
$path=(string)($parts['path']??'');
if(basename($path)!=='wp-login.php')return $location;
parse_str((string)($parts['query']??''),$query);
if(($query['checkemail']??'')!=='registered')return $location;
// Only rewrite WordPress's own relative path or the current site's login URL.
if(isset($parts['host'])){
$host=wp_parse_url(home_url('/'),PHP_URL_HOST);
if(!is_string($host)||strcasecmp((string)$parts['host'],$host)!==0)return $location;
}
return add_query_arg('checkemail','registered',home_url('/'.self::opt('slug').'/'));
}
// WordPress core login action and post-registration redirect are read-only here.
// phpcs:disable WordPress.Security.NonceVerification.Recommended
static function block_default_login(){if(!self::opt('login')||defined('HIDEFY_CUSTOM_LOGIN')|| (defined('WP_SECURE_RECOVERY')&&WP_SECURE_RECOVERY))return;
$action=sanitize_key($_REQUEST['action']??'login');if(in_array($action,['logout','postpass'],true))return;
// Fallback for old bookmarks or cached post-registration redirects.
if(self::request_method()==='GET' && isset($_GET['checkemail']) && $_GET['checkemail']==='registered'){
wp_safe_redirect(add_query_arg('checkemail','registered',home_url('/'.self::opt('slug').'/')),302);exit;
}
status_header(404);nocache_headers();wp_die('Not found','Not found',['response'=>404]);}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
static function request_method(){return isset($_SERVER['REQUEST_METHOD']) ? strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))) : '';}
static function turnstile_keys(){
if(self::opt('turnstile_environment')!=='sandbox')return [self::opt('site_key'),self::opt('secret_key')];
$mode=self::opt('turnstile_test_mode');
$sites=['pass'=>'1x00000000000000000000AA','fail'=>'2x00000000000000000000AB','interactive'=>'3x00000000000000000000FF'];
$secrets=['pass'=>'1x0000000000000000000000000000000AA','fail'=>'2x0000000000000000000000000000000AA','interactive'=>'1x0000000000000000000000000000000AA'];
return [$sites[$mode]??$sites['pass'],$secrets[$mode]??$secrets['pass']];
}
static function turnstile_form(){
if(!self::opt('turnstile'))return;
[$site,]=self::turnstile_keys();
// Turnstile's official browser API is hosted by Cloudflare; it cannot be bundled locally.
// Only request it when the site administrator has explicitly enabled Turnstile.
if (!wp_script_is('hidefy-turnstile', 'registered')) {
wp_register_script('hidefy-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js', [], '1.0', ['in_footer' => false, 'strategy' => 'defer']);
}
wp_enqueue_script('hidefy-turnstile');
echo '';
// The login and registration hooks run inside WordPress's login form markup.
wp_print_scripts('hidefy-turnstile');
}
/** Verify a Turnstile response on the server; never trust the browser widget alone. */
/** WordPress core login/registration POSTs have no Hidefy nonce field.
* The Cloudflare response is an external one-time challenge, not a CSRF nonce.
* We only verify it here and never mutate settings or user data.
*/
static function verify_turnstile(){
// phpcs:disable WordPress.Security.NonceVerification.Missing -- WordPress core login/registration form verification.
$token=isset($_POST['cf-turnstile-response']) && is_string($_POST['cf-turnstile-response']) ? sanitize_text_field(wp_unslash($_POST['cf-turnstile-response'])) : '';
if($token==='')return new WP_Error('hidefy_turnstile','Complete the security challenge.');
if(strlen($token)>2048)return new WP_Error('hidefy_turnstile','Invalid security challenge token.');
[, $secret]=self::turnstile_keys();
if(!$secret)return new WP_Error('hidefy_turnstile','Security challenge is not configured.');
$body=['secret'=>$secret,'response'=>$token];
if(!empty($_SERVER['REMOTE_ADDR']) && filter_var(sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])),FILTER_VALIDATE_IP))$body['remoteip']=sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
$resp=wp_remote_post('https://challenges.cloudflare.com/turnstile/v0/siteverify',['timeout'=>8,'body'=>$body]);
if(is_wp_error($resp))return new WP_Error('hidefy_turnstile','Security challenge verification unavailable.');
if(wp_remote_retrieve_response_code($resp)!==200)return new WP_Error('hidefy_turnstile','Security challenge verification unavailable.');
$json=json_decode(wp_remote_retrieve_body($resp),true);
return is_array($json)&&!empty($json['success'])?true:new WP_Error('hidefy_turnstile','Security challenge failed.');
}
static function turnstile_check($user,$username,$password){
if(!self::opt('turnstile')||!isset($_POST['log'],$_POST['pwd'])||is_wp_error($user))return $user;
$result=self::verify_turnstile();return is_wp_error($result)?$result:$user;
}
static function turnstile_registration_check($errors,$sanitized_user_login,$user_email){
if(!self::opt('turnstile'))return $errors;
// WordPress calls this filter during actual registration submission, not on page display.
$result=self::verify_turnstile();
if(is_wp_error($result))foreach($result->get_error_codes() as $code)$errors->add($code,$result->get_error_message($code));
return $errors;
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- WordPress core login POST; 2FA issues a random short-lived one-time challenge token.
static function twofa_intercept($user,$username,$password){if(!self::opt('twofa')||!$user instanceof WP_User||!self::has_role($user,'twofa_roles'))return $user;
if(!isset($_POST['log'],$_POST['pwd']))return new WP_Error('hidefy_2fa','Use the standard login form to complete 2FA.');
$token=bin2hex(random_bytes(32));$hash=hash('sha256',$token);set_transient('hidefy_pending_'.$hash,['user'=>$user->ID,'created'=>time(),'tries'=>0,'redirect'=>esc_url_raw(wp_unslash($_REQUEST['redirect_to']??admin_url()))],5*MINUTE_IN_SECONDS);
$url=add_query_arg(['hidefy_challenge'=>'1','token'=>$token],home_url('/'));wp_safe_redirect($url);exit;
}
// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
static function application_passwords($available,$user){return self::opt('twofa')&&self::has_role($user,'twofa_roles')?false:$available;}
static function xmlrpc($enabled){return self::opt('twofa')?false:$enabled;}
static function base32($bytes){$alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';$bits='';foreach(str_split($bytes) as $c)$bits.=str_pad(decbin(ord($c)),8,'0',STR_PAD_LEFT);$out='';foreach(str_split($bits,5) as $chunk)$out.=$alphabet[bindec(str_pad($chunk,5,'0'))];return $out;}
static function decode32($s){$alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';$bits='';foreach(str_split(strtoupper($s)) as $c){$n=strpos($alpha,$c);if($n===false)return ''; $bits.=str_pad(decbin($n),5,'0',STR_PAD_LEFT);} $out='';foreach(str_split($bits,8) as $b)if(strlen($b)===8)$out.=chr(bindec($b));return $out;}
static function totp($secret,$counter){$key=self::decode32($secret);$hi=intdiv($counter,4294967296);$lo=$counter%4294967296;$h=hash_hmac('sha1',pack('N2',$hi,$lo),$key,true);$offset=ord(substr($h,-1))&15;$n=(unpack('N',substr($h,$offset,4))[1]&0x7fffffff)%1000000;return str_pad((string)$n,6,'0',STR_PAD_LEFT);}
static function valid_totp($secret,$code){if(!preg_match('/^\d{6}$/',$code))return false;$step=intdiv(time(),30);for($i=-1;$i<=1;$i++)if(hash_equals(self::totp($secret,$step+$i),$code))return true;return false;}
/** The GET request only displays a challenge. Its POST is verified with _hidefy_nonce below. */
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- GET uses a random one-time bearer token; POST requires wp_verify_nonce().
static function challenge(){if(empty($_GET['hidefy_challenge']))return;
$token=isset($_REQUEST['token'])?sanitize_text_field(wp_unslash($_REQUEST['token'])):'';if(!preg_match('/^[a-f0-9]{64}$/',$token))wp_die('Invalid challenge token.');$key='hidefy_pending_'.hash('sha256',$token);$state=get_transient($key);
if(!is_array($state)||($state['tries']??0)>=5)wp_die('Challenge expired. Please log in again.');$user=get_user_by('id',(int)$state['user']);if(!$user)wp_die('Invalid user.');
nocache_headers();$secret=get_user_meta($user->ID,self::TOTP,true);$enrolling=!$secret;
if($enrolling){$secret=get_transient('hidefy_enroll_'.hash('sha256',$token));if(!$secret){$secret=self::base32(random_bytes(20));set_transient('hidefy_enroll_'.hash('sha256',$token),$secret,5*MINUTE_IN_SECONDS);}}
$error='';if(self::request_method()==='POST'){
if(!isset($_POST['_hidefy_nonce'])||!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_hidefy_nonce'])),'hidefy_challenge_'.$token))wp_die('Invalid request.');
$code=isset($_POST['code'])?sanitize_text_field(wp_unslash($_POST['code'])):'';$recovery=get_user_meta($user->ID,'hidefy_recovery',true);
$valid=self::valid_totp($secret,$code);$used_recovery=false;
if(!$enrolling&&!$valid&&is_array($recovery))foreach($recovery as $i=>$hash){if(wp_check_password($code,$hash,$user->ID)){$valid=true;$used_recovery=true;unset($recovery[$i]);break;}}
if($valid){delete_transient($key);delete_transient('hidefy_enroll_'.hash('sha256',$token));if($enrolling){update_user_meta($user->ID,self::TOTP,$secret);$backup=bin2hex(random_bytes(8));update_user_meta($user->ID,'hidefy_recovery',[wp_hash_password($backup)]);set_transient('hidefy_backup_'.hash('sha256',$token),['user_id'=>$user->ID,'code'=>$backup],2*MINUTE_IN_SECONDS);}if($used_recovery)update_user_meta($user->ID,'hidefy_recovery',array_values($recovery));
wp_set_current_user($user->ID);wp_set_auth_cookie($user->ID,false,is_ssl());
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- wp_login is a WordPress core action and must retain its official name for compatibility.
do_action('wp_login',$user->user_login,$user);
$dest=wp_validate_redirect($state['redirect'],admin_url());if($enrolling){$dest=add_query_arg('hidefy_backup',hash('sha256',$token),admin_url('index.php'));}wp_safe_redirect($dest);exit;
}$state['tries']++;set_transient($key,$state,5*MINUTE_IN_SECONDS);$error='Invalid code.';
}
header('Content-Type: text/html; charset='.get_option('blog_charset'));echo 'Hidefy | Two-factor authentication';wp_enqueue_style('hidefy-auth',plugins_url('assets/security.css',HIDEFY_FILE),[],HIDEFY_VERSION);wp_print_styles('hidefy-auth');echo '
🛡
HIDEFY · ACCOUNT PROTECTION
'.($enrolling?'Set up your authenticator':'Two-factor verification').'
'.($enrolling?'Scan the QR code with Google Authenticator, then enter the 6-digit code to activate 2FA.':'Enter the 6-digit code from your authenticator app to finish signing in.').'