registry = $registry; foreach ( array( 'add_option_altlumen_keys', 'update_option_altlumen_keys', 'delete_option_altlumen_keys' ) as $hook ) { add_action( $hook, array( __CLASS__, 'clear_decrypt_cache' ), 10, 0 ); } } /** * Register the two options in a single Settings API group. * * @return void */ public function register() { register_setting( 'altlumen', 'altlumen_settings', array( 'type' => 'array', 'sanitize_callback' => array( $this, 'sanitize_settings' ), 'show_in_rest' => false, ) ); register_setting( 'altlumen', 'altlumen_keys', array( 'type' => 'array', 'sanitize_callback' => array( $this, 'sanitize_keys' ), 'show_in_rest' => false, ) ); } /** * Prefer a locally configured core client without making provider requests. * * @return string */ private function default_provider(): string { $provider = $this->registry->get( strtolower( 'WordPress' ) ); return $provider && true === $provider->test_connection( '' ) ? $provider->id() : 'anthropic'; } /** * Read public settings. * * @return array */ public function get(): array { $values = wp_parse_args( (array) get_option( 'altlumen_settings', array() ), array( 'provider' => $this->default_provider(), 'model' => '', 'custom_model' => '', 'language' => 'site', 'max_length' => 125, 'approval_mode' => 'review', 'overwrite' => false, 'batch_rate' => 30, 'privacy_consent' => false, 'privacy_consent_provider' => '', 'remove_data' => false, ) ); if ( ! $this->registry->get( $values['provider'] ) ) { $values['provider'] = $this->default_provider(); } return $values; } /** * Sanitize every public field; unknown fields cannot enter the option. * * @param mixed $input Submitted settings. * @return array */ public function sanitize_settings( $input ): array { $input = is_array( $input ) ? $input : array(); $output = array(); foreach ( $this->get() as $field => $default ) { $callback = in_array( $field, array( 'overwrite', 'privacy_consent', 'remove_data' ), true ) ? 'sanitize_boolean' : 'sanitize_' . $field; if ( is_callable( array( $this, $callback ) ) ) { $output[ $field ] = $this->$callback( $input[ $field ] ?? ( is_bool( $default ) ? false : $default ) ); } } $provider = $this->registry->get( $output['provider'] ); if ( $provider && ! array_key_exists( $output['model'], $provider->models() ) ) { $output['model'] = $provider->default_model(); } $output['privacy_consent'] = $output['privacy_consent'] && $output['privacy_consent_provider'] === $output['provider']; $output['privacy_consent_provider'] = $output['privacy_consent'] ? $output['provider'] : ''; return $output; } /** * Require explicit consent bound to the current provider. * * @return bool */ public function has_consent(): bool { $settings = $this->get(); return null !== $this->registry->get( $settings['provider'] ) && true === $settings['privacy_consent'] && $settings['privacy_consent_provider'] === $settings['provider']; } /** * Sanitize the provider named in the consent assertion. * * @param mixed $value Submitted provider. * @return string */ public function sanitize_privacy_consent_provider( $value ): string { return is_string( $value ) && $this->registry->get( $value ) ? $value : ''; } /** * Validate a provider. * * @param mixed $value Input value. * @return string */ public function sanitize_provider( $value ): string { return is_string( $value ) && $this->registry->get( $value ) ? $value : 'anthropic'; } /** * Validate a model identifier. * * @param mixed $value Input value. * @return string */ public function sanitize_model( $value ): string { return is_string( $value ) ? substr( preg_replace( '/[^a-zA-Z0-9._:\/-]/', '', $value ), 0, 150 ) : ''; } /** * Sanitize a custom model identifier. * * @param mixed $value Input value. * @return string */ public function sanitize_custom_model( $value ): string { return $this->sanitize_model( $value ); } /** * Validate the language or locale. * * @param mixed $value Input value. * @return string */ public function sanitize_language( $value ): string { return is_string( $value ) && ( 'site' === $value || preg_match( '/^[a-z]{2,3}(?:[_-][A-Za-z]{2,8}){0,2}$/', $value ) ) ? $value : 'site'; } /** * Bound the maximum output length. * * @param mixed $value Input value. * @return int */ public function sanitize_max_length( $value ): int { return is_scalar( $value ) ? min( 250, max( 80, absint( $value ) ) ) : 125; } /** * Validate the approval mode. * * @param mixed $value Input value. * @return string */ public function sanitize_approval_mode( $value ): string { return 'auto' === $value ? 'auto' : 'review'; } /** * Allow only explicit checkbox values. * * @param mixed $value Input value. * @return bool */ public function sanitize_boolean( $value ): bool { return in_array( $value, array( true, 1, '1' ), true ); } /** * Validate the batch speed. * * @param mixed $value Input value. * @return int */ public function sanitize_batch_rate( $value ): int { return is_scalar( $value ) && in_array( (int) $value, array( 10, 30, 60 ), true ) ? (int) $value : 30; } /** * Get the supported configuration constant name. * * @param string $provider Provider identifier. * @return string */ private function constant_name( string $provider ): string { $names = array( 'openai' => 'ALTLUMEN_OPENAI_KEY', 'anthropic' => 'ALTLUMEN_ANTHROPIC_KEY', 'gemini' => 'ALTLUMEN_GEMINI_KEY', ); return $names[ $provider ] ?? ''; } /** * Check whether configuration locks the key field. * * @param string $provider Provider identifier. * @return bool */ public function is_locked( string $provider ): bool { $name = $this->constant_name( $provider ); return '' !== $name && defined( $name ); } /** * Get a key only for a server-side request. * * @param string $provider Provider identifier. * @return string */ public function get_key( string $provider ): string { if ( $this->is_locked( $provider ) ) { $value = constant( $this->constant_name( $provider ) ); return is_string( $value ) ? $value : ''; } $keys = (array) get_option( 'altlumen_keys', array() ); return isset( $keys[ $provider ] ) && is_string( $keys[ $provider ] ) ? $this->decrypt( $keys[ $provider ] ) : ''; } /** * Return only a masked key state, never plaintext. * * @param string $provider Provider identifier. * @return string */ public function key_state( string $provider ): string { if ( $this->is_locked( $provider ) ) { return __( 'Defined in wp-config.php', 'altlumen' ); } $key = $this->get_key( $provider ); if ( '' !== $key ) { return '••••' . substr( $key, -4 ); } $keys = (array) get_option( 'altlumen_keys', array() ); return ! empty( $keys[ $provider ] ) ? __( 'Re-enter the API key. The saved key can no longer be decrypted.', 'altlumen' ) : __( 'No key saved', 'altlumen' ); } /** * Validate a submitted secret without making it public. * * @param mixed $value Input secret. * @return string */ public function sanitize_secret( $value ): string { $value = is_string( $value ) ? trim( $value ) : $value; return is_string( $value ) && strlen( $value ) >= 8 && strlen( $value ) <= 512 && ! preg_match( '/[\x00-\x20\x7f]/', $value ) ? $value : ''; } /** * Warn about an obvious provider mismatch without blocking custom key formats. * * @param string $provider Provider ID. * @param string $key Submitted key, used only for local validation. * @return string */ public function key_warning( string $provider, string $key ): string { $mismatch = ( 'anthropic' === $provider && 0 !== strpos( $key, 'sk-ant-' ) ) || ( 'openai' === $provider && ( 0 !== strpos( $key, 'sk-' ) || 0 === strpos( $key, 'sk-ant-' ) ) ) || ( 'gemini' === $provider && 0 !== strpos( $key, 'AIza' ) ); return $mismatch ? __( 'This key format looks unusual for the selected provider. Check the provider; saving is still allowed.', 'altlumen' ) : ''; } /** * Apply explicit key actions. Empty or masked values never overwrite a key. * * @param mixed $input Submitted action map. * @return array */ public function sanitize_keys( $input ): array { self::clear_decrypt_cache(); $keys = (array) get_option( 'altlumen_keys', array() ); foreach ( $this->registry->all() as $id => $provider ) { if ( isset( $input[ $id ] ) && is_string( $input[ $id ] ) && '' !== $this->decrypt( $input[ $id ] ) && ! $this->is_locked( $id ) ) { $keys[ $id ] = $input[ $id ]; continue; } if ( $this->is_locked( $id ) || ! isset( $input[ $id ] ) || ! is_array( $input[ $id ] ) ) { continue; } $action = $input[ $id ]['action'] ?? 'keep'; if ( 'remove' === $action ) { unset( $keys[ $id ] ); } if ( 'replace' === $action ) { $key = $this->sanitize_secret( $input[ $id ]['value'] ?? '' ); $encrypted = '' !== $key ? $this->encrypt( $key ) : ''; if ( '' !== $encrypted ) { $keys[ $id ] = $encrypted; /* translators: %s: provider name. */ add_settings_error( 'altlumen', 'altlumen_key_saved_' . $id, sprintf( __( 'Saved for %s', 'altlumen' ), $provider->label() ), 'success' ); $warning = $this->key_warning( $id, $key ); if ( '' !== $warning ) { add_settings_error( 'altlumen', 'altlumen_key_format_' . $id, $warning, 'warning' ); } } else { add_settings_error( 'altlumen', 'altlumen_key', __( 'The API key could not be saved. Enter a valid key and try again.', 'altlumen' ) ); } } } self::clear_decrypt_cache(); return $keys; } /** * Encrypt with authenticated encryption and a fresh random nonce. * * @param string $plaintext Secret key. * @return string Empty on failure. */ public function encrypt( string $plaintext ): string { try { $nonce = random_bytes( 24 ); $key = hash( 'sha256', wp_salt( 'auth' ) . 'altlumen', true ); $cipher = function_exists( 'sodium_crypto_secretbox' ) ? sodium_crypto_secretbox( $plaintext, $nonce, $key ) : \ParagonIE_Sodium_Compat::crypto_secretbox( $plaintext, $nonce, $key ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Encodes authenticated ciphertext data, never code. return 'v1:' . base64_encode( $nonce . $cipher ); } catch ( \Throwable $error ) { return ''; } } /** * Decrypt safely. Salt rotation and tampering require key re-entry. * * @param string $envelope Versioned ciphertext. * @return string Empty on failure. */ public function decrypt( string $envelope ): string { if ( 0 !== strpos( $envelope, 'v1:' ) ) { return ''; } // This decodes authenticated ciphertext data, never executable code. // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decodes authenticated ciphertext data, never code. $bytes = base64_decode( substr( $envelope, 3 ), true ); if ( false === $bytes || strlen( $bytes ) < 40 ) { return ''; } try { $key = hash( 'sha256', wp_salt( 'auth' ) . 'altlumen', true ); $cache_id = hash( 'sha256', $envelope ); $salt_hash = hash( 'sha256', $key ); if ( isset( self::$decrypt_cache[ $cache_id ] ) && self::$decrypt_cache[ $cache_id ]['salt_hash'] === $salt_hash ) { return self::$decrypt_cache[ $cache_id ]['plain']; } $plain = function_exists( 'sodium_crypto_secretbox_open' ) ? sodium_crypto_secretbox_open( substr( $bytes, 24 ), substr( $bytes, 0, 24 ), $key ) : \ParagonIE_Sodium_Compat::crypto_secretbox_open( substr( $bytes, 24 ), substr( $bytes, 0, 24 ), $key ); $plain = is_string( $plain ) ? $plain : ''; self::$decrypt_cache[ $cache_id ] = array( 'salt_hash' => $salt_hash, 'plain' => $plain, ); return $plain; } catch ( \Throwable $error ) { return ''; } } }