prefix . "lockerpad_" . $suffix; } public static function crypto() { static $crypto; return $crypto ?: ($crypto = new Crypto()); } public static function activate() { if (is_multisite()) { wp_die( "LockerPad currently supports single-site WordPress installations. Multisite support is not yet available.", ); } if (!is_ssl() && wp_get_environment_type() !== "local") { wp_die("LockerPad requires HTTPS."); } try { self::crypto(); } catch (\Throwable $e) { wp_die(esc_html($e->getMessage())); } global $wpdb; require_once ABSPATH . "wp-admin/includes/upgrade.php"; $collate = "ENGINE=InnoDB " . $wpdb->get_charset_collate(); // Old untyped vaults were media vaults. Keep that upgrade default; every new page lock sets its purpose explicitly. dbDelta( "CREATE TABLE " . self::table("vaults") . " ( id bigint unsigned NOT NULL AUTO_INCREMENT, public_id varchar(34) DEFAULT NULL, title varchar(180) NOT NULL, purpose varchar(10) NOT NULL DEFAULT 'media', directories longtext NULL, body longtext NOT NULL, files longtext NOT NULL, scripts longtext NULL, script_height smallint NOT NULL DEFAULT 500, enabled tinyint NOT NULL DEFAULT 1, mode varchar(32) NOT NULL DEFAULT 'both', dial_count tinyint NOT NULL DEFAULT 4, phrase_count tinyint NOT NULL DEFAULT 8, absolute_hours smallint NOT NULL DEFAULT 0, compact tinyint NOT NULL DEFAULT 0, version bigint NOT NULL DEFAULT 1, PRIMARY KEY (id), UNIQUE KEY public_id (public_id) ) $collate;", ); dbDelta( "CREATE TABLE " . self::table("clients") . " ( id bigint unsigned NOT NULL AUTO_INCREMENT, label varchar(180) NOT NULL, login varchar(80) NOT NULL, mode varchar(32) NOT NULL, dial_count tinyint NOT NULL, phrase_count tinyint NOT NULL, dial_hash varchar(255) NOT NULL, phrase_hash varchar(255) NOT NULL, vaults text NOT NULL, expires bigint NOT NULL, revoked tinyint NOT NULL DEFAULT 0, access_count bigint unsigned NOT NULL DEFAULT 0, access_limit bigint unsigned NOT NULL DEFAULT 0, last_access bigint NOT NULL DEFAULT 0, version bigint NOT NULL DEFAULT 1, PRIMARY KEY (id), UNIQUE KEY login (login) ) $collate;", ); dbDelta( "CREATE TABLE " . self::table("sessions") . " ( token char(64) NOT NULL, client bigint unsigned NOT NULL, vault bigint unsigned NOT NULL DEFAULT 0, vault_version bigint NOT NULL DEFAULT 0, hard_expires bigint NOT NULL DEFAULT 0, version bigint NOT NULL, expires bigint NOT NULL, PRIMARY KEY (token), KEY expires (expires) ) $collate;", ); dbDelta( "CREATE TABLE " . self::table("rates") . " ( bucket char(64) NOT NULL, attempts int NOT NULL DEFAULT 0, expires bigint NOT NULL, PRIMARY KEY (bucket), KEY expires (expires) ) $collate;", ); dbDelta( "CREATE TABLE " . self::table("access") . " ( client bigint unsigned NOT NULL, vault bigint unsigned NOT NULL, dial_count tinyint NOT NULL, phrase_count tinyint NOT NULL, dial_hash varchar(255) NOT NULL, phrase_hash varchar(255) NOT NULL, dial_lookup char(64) NOT NULL DEFAULT '', phrase_lookup char(64) NOT NULL DEFAULT '', password_hash varchar(255) NOT NULL DEFAULT '', password_lookup char(64) NOT NULL DEFAULT '', PRIMARY KEY (client,vault), KEY vault (vault) ) $collate;", ); foreach ( ["vaults", "clients", "access", "sessions", "rates"] as $table ) { $status = $wpdb->get_row( $wpdb->prepare( "SHOW TABLE STATUS WHERE Name=%s", self::table($table), ), ); if (!$status || strtolower($status->Engine) !== "innodb") { wp_die( "LockerPad requires InnoDB database tables for safe access and recovery updates. Ask your host to enable InnoDB.", ); } } if (get_option("lockerpad_schema") !== self::VERSION) { // Internal IDs remain stable for encryption contexts, shortcodes, and grants. $missing = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE public_id IS NULL OR public_id=''", self::table("vaults"), ), ); if ($wpdb->last_error) { wp_die( "LockerPad could not initialize public vault identifiers.", ); } foreach ($missing as $vid) { $saved = false; for ($attempt = 0; $attempt < 3; $attempt++) { if ( $wpdb->update( self::table("vaults"), ["public_id" => self::new_public_id()], ["id" => (int) $vid], ) === 1 ) { $saved = true; break; } } if (!$saved) { wp_die( "LockerPad could not assign a public vault identifier.", ); } } // Preserve existing grants and hashes. No decrypted passwords are needed. if (!get_option("lockerpad_access_migrated")) { $clients = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i ORDER BY revoked ASC,id ASC", self::table("clients"), ), ); $configured = []; foreach ($clients as $c) { foreach (json_decode($c->vaults, true) ?: [] as $vid) { $vid = (int) $vid; if ( !$wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE id=%d", self::table("vaults"), $vid, ), ) ) { continue; } if (!isset($configured[$vid])) { $wpdb->update( self::table("vaults"), [ "mode" => $c->mode, "dial_count" => $c->dial_count, "phrase_count" => $c->phrase_count, ], ["id" => $vid], ); $configured[$vid] = true; } $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO %i (client,vault,dial_count,phrase_count,dial_hash,phrase_hash) VALUES (%d,%d,%d,%d,%s,%s)", self::table("access"), $c->id, $vid, $c->dial_count, $c->phrase_count, $c->dial_hash, $c->phrase_hash, ), ); } } update_option("lockerpad_access_migrated", 1, false); } try { Pages::separate_legacy_vaults(); } catch (\Throwable $e) { wp_die(esc_html($e->getMessage())); } $wpdb->query( $wpdb->prepare( "UPDATE %i SET absolute_hours=0", self::table("vaults"), ), ); $wpdb->query( $wpdb->prepare("DELETE FROM %i", self::table("sessions")), ); update_option("lockerpad_schema", self::VERSION, false); if (function_exists("sg_cachepress_purge_cache")) { sg_cachepress_purge_cache(); } } if (!wp_next_scheduled("lockerpad_cleanup")) { wp_schedule_event(time() + 3600, "hourly", "lockerpad_cleanup"); } } public static function boot($file) { self::$file = $file; add_action( "init", function () { if (get_option("lockerpad_schema") !== self::VERSION) { self::activate(); } }, 1, ); // Old media shortcodes fail closed; no media decoder is bundled in this edition. add_shortcode("lockerpad", [self::class, "legacy_shortcode"]); foreach (["unlock", "logout", "session", "extend"] as $action) { add_action("wp_ajax_lockerpad_" . $action, [self::class, $action]); add_action("wp_ajax_nopriv_lockerpad_" . $action, [ self::class, $action, ]); } add_action("lockerpad_cleanup", function () { global $wpdb; foreach (["sessions", "rates"] as $table) { $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE expires < %d", self::table($table), time(), ), ); } }); Admin::boot(); Pages::boot(); Targets::boot(); Maintenance::boot(); } public static function assets() { // Called only by a rendered lock, page gate, or admin design preview. $url = plugin_dir_url(self::$file); wp_enqueue_style( "lockerpad", $url . "assets/vault.css", [], self::VERSION, ); wp_enqueue_script( "lockerpad-audio", $url . "assets/vault-audio.js", [], self::VERSION, true, ); wp_enqueue_script( "lockerpad-math", $url . "assets/vault-math.js", [], self::VERSION, true, ); wp_enqueue_script( "lockerpad-password", $url . "assets/password-entry.js", [], self::VERSION, true, ); wp_enqueue_script( "lockerpad-cards", $url . "assets/dial-cards.js", [], self::VERSION, true, ); wp_enqueue_script( "lockerpad", $url . "assets/vault.js", [ "lockerpad-audio", "lockerpad-math", "lockerpad-password", "lockerpad-cards", ], self::VERSION, true, ); } public static function vault($id) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id=%d AND enabled=1 AND purpose='page'", self::table("vaults"), $id, ), ); } public static function new_public_id() { return "v_" . bin2hex(random_bytes(16)); } public static function public_vault($publicId) { if ( !is_string($publicId) || !preg_match('/^v_[a-f0-9]{32}$/D', $publicId) ) { return null; } global $wpdb; return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE public_id=%s AND enabled=1 AND purpose='page'", self::table("vaults"), $publicId, ), ); } public static function legacy_shortcode() { return '

This protected content is unavailable. Please contact the website owner.

'; } public static function render_lock($vault, $preview = false) { ob_start(); self::print_lock($vault, $preview); return ob_get_clean(); } public static function print_lock($vault, $preview = false) { self::assets(); // Builders and templates can render shortcodes after wp_head. Print the // stylesheet before the first lock; WordPress prevents duplicate output. // Scripts remain queued for the footer, after all locks are in the DOM. if (!wp_style_is("lockerpad", "done")) { wp_print_styles(["lockerpad"]); } $dial = in_array("dial", Policy::methods($vault->mode), true); $phrase = in_array("phrase", Policy::methods($vault->mode), true); ?>
" data-vault="public_id); ?>" data-preview="" data-nonce="" data-mode="mode); ?>" data-dial-count="dial_count; ?>" data-phrase-count="phrase_count; ?>" data-endpoint="" aria-label="title); ?>">
" alt="LockerPad combination lock dial" width="900" height="900">

compact ) ? "Your code" : "Enter your combination"; ?>

mode), true, ) ): ?>

$message], $code); } private static function request() { self::headers(); if ( !is_ssl() || sanitize_text_field( wp_unslash($_SERVER["REQUEST_METHOD"] ?? ""), ) !== "POST" || sanitize_text_field( wp_unslash($_SERVER["HTTP_X_LOCKERPAD"] ?? ""), ) !== "1" ) { self::deny(); } $origin = sanitize_text_field( wp_unslash($_SERVER["HTTP_ORIGIN"] ?? ""), ); $site = wp_parse_url(home_url()); $expected = $site["scheme"] . "://" . $site["host"] . (isset($site["port"]) ? ":" . $site["port"] : ""); if (!hash_equals($expected, $origin)) { self::deny( 403, "The request origin does not match the WordPress site address.", ); } $nonce = sanitize_text_field(wp_unslash($_POST["nonce"] ?? "")); if (!wp_verify_nonce($nonce, "lockerpad_visitor")) { self::deny(403, "Refresh the page to renew its security token."); } if (absint(wp_unslash($_SERVER["CONTENT_LENGTH"] ?? 0)) > 8192) { self::deny(413); } } private static function rate($label, $max) { global $wpdb; $window = (int) floor(time() / 900); $bucket = hash_hmac("sha256", $label . ":" . $window, wp_salt("auth")); $table = self::table("rates"); $ok = $wpdb->query( $wpdb->prepare( "INSERT INTO %i (bucket,attempts,expires) VALUES (%s,1,%d) ON DUPLICATE KEY UPDATE attempts=attempts+1", $table, $bucket, ($window + 2) * 900, ), ); if ($ok === false) { self::deny(503); } $attempts = $wpdb->get_var( $wpdb->prepare( "SELECT attempts FROM %i WHERE bucket=%s", $table, $bucket, ), ); if ( $wpdb->last_error || !is_numeric($attempts) || (int) $attempts < 1 ) { self::deny(503); } $n = (int) $attempts; if ($n > $max) { header("Retry-After: 900"); self::deny( 429, "Too many attempts. Wait for the next 15-minute window.", ); } } public static function lookup($vault, $kind, $normal) { return Access::lookup(self::crypto(), $vault, $kind, $normal); } // Visitor actions use a fresh WordPress nonce, an exact Origin check and a custom header. // A nonce is not authorization: protected actions also require the per-lock session/grant. // phpcs:disable WordPress.Security.NonceVerification -- request() verifies lockerpad_visitor before every action. public static function unlock() { self::request(); global $wpdb; $vault = self::public_vault( sanitize_text_field(wp_unslash($_POST["vault"] ?? "")), ); $id = $vault ? (int) $vault->id : 0; self::rate( "ip:" . sanitize_text_field( wp_unslash($_SERVER["REMOTE_ADDR"] ?? "unknown"), ), 30, ); self::rate( "vault-ip:" . $id . ":" . sanitize_text_field( wp_unslash($_SERVER["REMOTE_ADDR"] ?? "unknown"), ), 12, ); // No global vault lockout: one source must not block other users. if (!$vault) { self::deny(); } try { $dial = Policy::dial( substr( sanitize_text_field(wp_unslash($_POST["dial"] ?? "")), 0, 30, ), $vault->dial_count, ); $phrase = Policy::phrase( substr( sanitize_text_field(wp_unslash($_POST["phrase"] ?? "")), 0, 500, ), $vault->phrase_count, ); // Preserve exact password characters; Policy validates type, Unicode and length. $password = Policy::password( isset($_POST["password"]) && is_string($_POST["password"]) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Policy::password validates the exact secret; text sanitization would change valid credentials. ? wp_unslash($_POST["password"]) : null, ); $pw = self::lookup($id, "password", $password ?? "invalid"); $dl = self::lookup($id, "dial", $dial ?? "invalid"); $pl = self::lookup($id, "phrase", $phrase ?? "invalid"); // Keyed indexes keep anonymous lookup bounded without exposing a public client identifier. // Empty indexes are pre-upgrade hashes; populate only after successful verification. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT a.*,c.id,c.label,c.login,c.expires,c.revoked,c.version FROM %i a INNER JOIN %i c ON c.id=a.client WHERE a.vault=%d AND (a.dial_lookup=%s OR a.phrase_lookup=%s OR a.password_lookup=%s OR (a.dial_hash<>'' AND a.dial_lookup='') OR (a.phrase_hash<>'' AND a.phrase_lookup='') OR (a.password_hash<>'' AND a.password_lookup=''))", self::table("access"), self::table("clients"), $id, $dl, $pl, $pw, ), ); $resolved = Access::resolve( self::crypto(), $vault, $rows, $dial, $phrase, time(), $password, ); if (!$resolved) { $detail = ""; if (current_user_can("manage_options")) { $checks = []; foreach ($rows as $row) { $d = $dial !== null && (int) $row->dial_count === (int) $vault->dial_count && password_verify( self::crypto()->credential("dial:" . $dial), $row->dial_hash, ); $p = $phrase !== null && (int) $row->phrase_count === (int) $vault->phrase_count && password_verify( self::crypto()->credential("phrase:" . $phrase), $row->phrase_hash, ); if ($d || $p) { $checks[] = $row->label . ": combination " . ($d ? "matched" : "did not match") . "; seed words " . ($p ? "matched" : "did not match") . "; " . ($row->revoked ? "revoked" : ($row->expires <= time() ? "expired" : "active")); } } $detail = $checks ? implode(". ", $checks) : "No invited user matched these credentials."; } self::deny(403, $detail); } $match = $resolved["client"]; $verified = $resolved; $indexes = []; if ($verified["dial"]) { $indexes["dial_lookup"] = $dl; } if ($verified["phrase"]) { $indexes["phrase_lookup"] = $pl; } if ($verified["password"]) { $indexes["password_lookup"] = $pw; } if ($indexes) { $wpdb->update(self::table("access"), $indexes, [ "client" => $match->client, "vault" => $id, ]); } $token = bin2hex(random_bytes(32)); $hard = Policy::hard_expiry(time(), (int) $match->expires, 0); $expires = Policy::session_expiry(time(), $hard); if ($wpdb->query("START TRANSACTION") === false) { self::deny(503); } $recorded = $wpdb->query( $wpdb->prepare( "UPDATE %i SET access_count=access_count+1,last_access=%d WHERE id=%d AND version=%d AND revoked=0 AND expires>%d AND (access_limit=0 OR access_countclient, $match->version, time(), ), ); if ($recorded !== 1) { $wpdb->query("ROLLBACK"); self::deny( 403, "Credentials matched, but the user is expired, revoked, changed, or at the unlock limit.", ); } if ( !$wpdb->insert(self::table("sessions"), [ "token" => hash("sha256", $token), "client" => $match->client, "vault" => $id, "vault_version" => $vault->version, "hard_expires" => $hard, "version" => $match->version, "expires" => $expires, ]) ) { $wpdb->query("ROLLBACK"); self::deny(503); } if ($wpdb->query("COMMIT") === false) { $wpdb->query("ROLLBACK"); self::deny(503); } self::cookie($token, $expires, $id); wp_send_json_success(["expires" => $expires]); } catch (\Throwable $e) { $wpdb->query("ROLLBACK"); self::deny(503, "The server could not complete the unlock."); } } public static function cookie_name($vault) { return "__Host-lockerpad-v" . (int) $vault; } private static function token($vault) { return sanitize_text_field( wp_unslash( $_COOKIE[self::cookie_name($vault)] ?? ($_COOKIE["__Host-lockerpad"] ?? ""), ), ); } private static function cookie($value, $expires, $vault) { setcookie(self::cookie_name($vault), $value, [ "expires" => $expires, "path" => "/", "secure" => true, "httponly" => true, "samesite" => "Strict", ]); } public static function authorize($vault) { global $wpdb; $token = self::token($vault); if ( !is_ssl() || !is_string($token) || !preg_match('/^[a-f0-9]{64}$/D', $token) ) { return null; } $s = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE token=%s", self::table("sessions"), hash("sha256", $token), ), ); if ( !$s || (int) $s->expires <= time() || ((int) $s->hard_expires && (int) $s->hard_expires <= time()) ) { return null; } $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id=%d", self::table("clients"), $s->client, ), ); $v = self::vault($vault); $grant = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE client=%d AND vault=%d", self::table("access"), $s->client, $vault, ), ); if ( !$c || (int) $c->revoked || (int) $c->expires <= time() || !$v || !$grant || (int) $s->vault !== (int) $vault || (int) $s->vault_version !== (int) $v->version || (int) $c->version !== (int) $s->version ) { return null; } return [ "client" => $c, "expires" => min( (int) $s->expires, (int) $c->expires, (int) $s->hard_expires ?: (int) $c->expires, ), "hardExpires" => (int) $s->hard_expires ?: (int) $c->expires, ]; } private static function session_data($auth) { return [ "expires" => (int) $auth["expires"], "serverTime" => time(), "clientExpires" => min( (int) $auth["client"]->expires, (int) $auth["hardExpires"], ), ]; } public static function session() { self::request(); $vault = self::public_vault( sanitize_text_field(wp_unslash($_POST["vault"] ?? "")), ); $auth = $vault ? self::authorize($vault->id) : null; if (!$auth) { self::deny(); } wp_send_json_success(self::session_data($auth)); } public static function extend() { self::request(); global $wpdb; $vault = self::public_vault( sanitize_text_field(wp_unslash($_POST["vault"] ?? "")), ); $id = $vault ? (int) $vault->id : 0; $auth = $vault ? self::authorize($id) : null; if (!$auth) { self::deny(); } $now = time(); $token = self::token($id); // Apply each click atomically, while rechecking expiry and revocation. $updated = $wpdb->query( $wpdb->prepare( "UPDATE %i s INNER JOIN %i c ON c.id=s.client INNER JOIN %i v ON v.id=s.vault INNER JOIN %i a ON a.client=s.client AND a.vault=s.vault SET s.expires=LEAST(s.expires+600,%d,c.expires,IF(s.hard_expires=0,c.expires,s.hard_expires)) WHERE s.token=%s AND s.vault=%d AND s.expires>%d AND c.expires>%d AND (s.hard_expires=0 OR s.hard_expires>UNIX_TIMESTAMP()) AND c.revoked=0 AND c.version=s.version AND v.version=s.vault_version AND v.enabled=1", self::table("sessions"), self::table("clients"), self::table("vaults"), self::table("access"), $now + 3600, hash("sha256", $token), $id, $now, $now, ), ); if ($updated === false) { self::deny(503); } $auth = self::authorize($id); if (!$auth) { self::deny(); } self::cookie($token, $auth["expires"], $id); wp_send_json_success(self::session_data($auth)); } public static function logout() { self::request(); global $wpdb; $v = self::public_vault( sanitize_text_field(wp_unslash($_POST["vault"] ?? "")), ); if (!$v) { self::deny(); } $id = (int) $v->id; $token = self::token($id); if (is_string($token) && preg_match('/^[a-f0-9]{64}$/D', $token)) { if ( $wpdb->delete(self::table("sessions"), [ "token" => hash("sha256", $token), "vault" => $id, ]) === false ) { self::deny(503); } } self::cookie("", time() - 3600, $id); wp_send_json_success(); } // phpcs:enable WordPress.Security.NonceVerification }