Category: Client-Side Security

Safeguarding React Native Apps With Advanced Methods

With the rising popularity of React Native, the need for robust security grows equally urgent. Traditional security practices are essential, but are they enough? Advanced techniques like code obfuscation, white-box cryptography, and MAST platforms offer additional protection. Whether you’re a seasoned developer or just starting, this guide empowers you to secure your React Native apps and ensure user data protection.

The Importance of Application Security in Today’s Digital Landscape


In today’s interconnected world, where sensitive information is increasingly stored and accessed through applications, application security has become more crucial than ever. As the reliance on digital services grows, so does the potential impact of security breaches and attacks.

Reasons why application security is critical in today’s digital landscape:

  1. Protection of Sensitive Data

  2. Maintaining Business Continuity

  3. Ensuring User Trust and Confidence

  4. Compliance with Regulations

  5. Protection of Critical Infrastructure


Common Security Vulnerabilities in React Native Applications


Injection attacks (SQL injection, cross-site scripting) 

Injection attacks are a serious threat to web applications, allowing attackers to inject malicious code into a website and potentially gain unauthorized access to sensitive information, disrupt website functionality, or even take control of the server.

There are two main types of injection attacks:

  • SQL injection (SQLi): injects malicious SQL code into website input fields, such as login forms or search bars, allowing attackers to manipulate the database and steal data or grant themselves access.

  • Cross-site scripting (XSS) injects malicious scripts into website content, such as comments or user profiles, allowing attackers to steal user information, execute unwanted actions on their behalf, or redirect them to phishing websites.


Injection attacks can have severe consequences, including data theft, website defacement, loss of control, and denial of service. They can expose sensitive information, disrupt your website’s functionality, and even allow attackers to take control of your system.

Insecure data storage and handling 

Insecure data storage and handling refers to the practice of storing sensitive information without adequate safeguards in place. This can leave your data vulnerable to unauthorized access, theft, and misuse. Insecure data storage and handling pose a significant risk of data breaches, identity theft, financial loss, and reputational damage. Hackers can steal your data, exposing your personal information and leading to financial losses. This can severely damage your company’s reputation and erode customer trust.

Weak authentication and authorization mechanisms 

Weak authentication and authorization mechanisms are major vulnerabilities that can leave your systems and data exposed to unauthorized access, manipulation, and theft. These weaknesses can provide attackers with a foothold in your environment, allowing them to escalate their privileges, steal sensitive information, and disrupt critical operations.

Types of weak authentication and authorization mechanisms

  • Weak passwords: easy-to-guess passwords or password reuse across multiple accounts.

  • Lack of multi-factor authentication (MFA): Reliance solely on passwords for authentication.

  • Unencrypted credentials: storing passwords in plain text or using weak encryption methods.

  • Insecure access controls: granting excessive permissions to users or allowing unauthorized access to resources.

  • Missing authorization checks: failing to verify user permissions before allowing access to sensitive data or functionality.

  • Improper session management: not invalidating sessions or using weak session tokens.

Insecure network communication (lack of HTTPS, insufficient encryption) 

Insecure network communication leaves your data vulnerable to interception and manipulation as it travels between devices. This lack of security can lead to various attacks, compromising your data and privacy. Insecure network communication occurs when:

  • Data is transmitted without encryption, which means anyone can eavesdrop on the communication and steal sensitive information, such as passwords, credit card numbers, and personal information.

  • Weak encryption protocols are used: Even if encryption is used, older or weak encryption protocols can be easily cracked by hackers.

  • Websites are not using HTTPS: This means the communication between your browser and the website is not encrypted, leaving it vulnerable to eavesdropping.

  • Unsecured Wi-Fi networks are used: Public Wi-Fi networks are often not secure, making it easy for hackers to intercept data transmitted over these networks.

Third-party library vulnerabilities

Third-party libraries are essential building blocks for modern software development, offering ready-made functionality and saving developers time and effort. However, these libraries can also introduce hidden vulnerabilities that put your software at risk. These libraries can be used in various ways, such as adding features and functionality, saving development time, and promoting code reuse.

Third-party libraries are not always perfect. They may contain security vulnerabilities that could allow attackers to gain access to your systems, steal your data, or disrupt your operations.


Best Practices for Securing React Native Applications


Secure coding practices are paramount. By incorporating these practices into your development process, you can significantly reduce the risk of vulnerabilities and security exploits in your applications. Key aspects of secure coding:

1. Input Validation

Never trust user input blindly. Always validate and sanitize all user input before processing it. This helps to prevent attackers from injecting malicious code into your application.

2. Output Encoding

Encode all output before displaying it to the user. This helps to prevent cross-site scripting (XSS) attacks, where attackers can inject malicious scripts into your application and steal user information or redirect them to phishing websites.

3. Use prepared statements

When using SQL queries, always use prepared statements instead of directly embedding SQL code into your application. This helps to prevent SQL injection attacks, where attackers can inject malicious SQL code into your application and steal data from your database.

Utilize secure data storage solutions (e.g., encrypted storage):

Ensuring the confidentiality, integrity, and availability of your data is crucial for maintaining business continuity and protecting sensitive information. Secure data storage solutions play a key role in achieving this objective.

Effective methods for secure data storage:

1. Encryption: unreadable data without a key, preventing unauthorized access. 

2. Data Loss Prevention (DLP): monitors data traffic to identify and prevent leaks of sensitive information. 

3. Access Control: Restricts access to data based on user roles and permissions. 

4. Data Backup and Recovery: Ensures data restoration in case of disasters or breaches, minimizing disruptions. 

5. Cloud Storage: Offers secure and scalable storage solutions for global accessibility. 

6. Hardware Security Modules (HSMs): Dedicated hardware for enhanced security of sensitive data and cryptographic operations. 

7. Tokenization: Replaces sensitive data with non-sensitive tokens for increased protection against breaches. 

8. Data Minimization: Collects and stores only necessary data, reducing breach risk and simplifying data privacy compliance.

These solutions offer varying levels of security and cater to different needs. Choosing the right combination ensures optimal protection for your critical data.

Implement robust authentication and authorization mechanisms (e.g., OAuth2, JWT): 

Robust authentication and authorization mechanisms are essential for protecting your valuable assets and ensuring the security of your applications and systems. These mechanisms ensure that only authorized users can access sensitive information and resources.

Types of robust authentication and authorization mechanisms:

1. OAuth2: Provides secure third-party application access to user data without revealing passwords. Widely used and popular. 

2. JWT: Securely transmits information between parties in a compact, self-contained token. Popular for Single Sign-On (SSO) and API access. 

3. Multi-factor authentication (MFA): Adds an extra layer of security by requiring additional verification factors (fingerprint, token, OTP) beyond username and password. 

4. Single sign-on (SSO): Enables access to multiple applications with one set of credentials, improving user experience and reducing password fatigue. 

5. Role-based access control (RBAC): Grants permission to resources based on users’ organizational roles, ensuring access only to necessary information and resources.

These mechanisms offer varying degrees of security and address different needs. Choosing the right combination ensures optimal user experience and robust access control for your systems.

Encrypt sensitive data in transit (HTTPS, TLS): 

Encrypting sensitive data in transit is a vital security practice that ensures confidentiality and integrity during communication.

Methods for encrypting data in transit:

  • HTTPS: This is the secure version of the HTTP protocol and uses Transport Layer Security (TLS) to encrypt communication between a web browser and a web server. All websites should use HTTPS to protect user data.

  • TLS (formerly known as SSL): This is a cryptographic protocol that provides secure communication between two applications. TLS is used to secure various communications, including email, messaging apps, and file transfers.

  • VPNs: Virtual private networks create a secure tunnel over a public network, encrypting all data traffic between the user and the VPN server. VPNs are particularly useful for protecting data on public Wi-Fi networks.

Validate user inputs and sanitize data: 

Malicious actors can inject harmful code or manipulate data through user input, leading to serious security threats like data breaches, SQL injection attacks, and cross-site scripting (XSS).

Techniques for user input validation and data sanitization:

  • Input masking: Restricts the types of characters that users can input.

  • Regular expressions: Used to match specific patterns in user input.

  • Whitelisting: Allows only specific values for user input.

  • Blacklisting: Blocks specific characters or sequences that are considered harmful.

  • HTML entity encoding: Converts special characters into their HTML entity equivalents, preventing them from being interpreted as code.

  • URL encoding: Encodes special characters in URLs to prevent them from being interpreted as part of the URL path.

Regularly audit and update third-party libraries: 

Regularly auditing and updating third-party libraries is a crucial security practice that helps mitigate these risks and protect your software from cyberattacks.

How to audit and update third-party libraries:

  • Use a Software Composition Analysis (SCA) tool: SCA tools can help you identify all the libraries used in your codebase, their versions, and any known vulnerabilities.

  • Review security advisories: Regularly check for security advisories issued by library developers and update libraries as needed to address vulnerabilities.

  • Utilize automated update tools: Several tools can automate the process of updating libraries, saving you time and effort.

  • Prioritize critical libraries: Focus on updating libraries that are used extensively or have known vulnerabilities.

  • Test updates: Before deploying library updates to production, test them thoroughly to ensure they do not introduce any regressions or compatibility issues.

Implement a secure development lifecycle (SDLC):

The Secure Development Lifecycle (SDLC) is a structured approach to integrating security into every stage of the software development process. By incorporating security practices throughout the process, organizations can significantly reduce the risk of vulnerabilities and build more secure software applications.

SDLC phases and security considerations

1. Planning and Requirements:

  • Identify security requirements

  • Conduct threat modeling

  • Select secure libraries and frameworks

2. Design and Architecture:

  • Implement secure design principles

  • Use secure coding practices

  • Perform static code analysis

3. Implementation and Development:

  • Implement secure coding techniques

  • Use secure APIs and libraries

  • Perform unit and integration testing

4. Testing and Deployment:

  • Perform penetration testing

  • Security configuration review

  • Vulnerability scanning

5. Monitoring and Maintenance:

  • Monitor security logs and alerts

  • Perform regular security audits and assessments.

  • Update software regularly

Tools and Techniques for Securing React Native Applications


Linting and static analysis tools 

Linting and static analysis tools are essential allies in the software development process. They help developers identify potential issues with their code early on, leading to more robust and reliable applications. Linting tools examine the source code and identify pre-defined coding rules and conventions violations. This can include syntax errors, e.g., missing semicolons; style violations, e.g., inconsistent indentation; and potential problems, e.g., unused variables.

Static analysis is a broader category of tools that goes beyond linting. They perform a deeper code analysis, looking for potential logical errors, security vulnerabilities, and performance issues. This can include:

  • Dead code

  • Unreachable code

  • Security vulnerabilities

  • Performance bottlenecks

Popular linting and static analysis tools:

  • Linting: ESLint, JSLint, Pylint, Flake8, Rubocop

  • Static analysis: SonarQube, Fortify, Coverity, FindBugs, and CodeQL

The best linting and static analysis tool for your project will depend on the programming language you are using, your team’s preferences, and the specific needs of your project.

Penetration testing and vulnerability scanning 

Cyber threats are constantly evolving, so proactive security measures are crucial. Penetration testing and vulnerability scanning are two essential tools that help organizations identify and address security weaknesses before attackers can exploit them.

Penetration testing:

Penetration testing simulates a real-world attack on your systems and applications. Ethical hackers, also known as penetration testers, attempt to exploit vulnerabilities in your defenses to gain unauthorized access to your data and systems. This provides valuable insights into your security posture and helps you identify and fix vulnerabilities before attackers can find them.

Vulnerability scanning:

Vulnerability scanning uses automated tools to identify known vulnerabilities in your systems and applications. These tools compare your software to databases of known vulnerabilities and identify matches. While not as comprehensive as penetration testing, vulnerability scanning can provide a quick and efficient way to identify common weaknesses.

While penetration testing and vulnerability scanning offer valuable benefits, they are most effective when used together. Vulnerability scanning provides a broad overview of potential weaknesses, while penetration testing provides a deeper understanding of how these weaknesses can be exploited.

Code obfuscation and white-box cryptography and white-box cryptography are two techniques used to protect software from unauthorized access and modification. While they share some similarities, they have distinct purposes and approaches.

Code obfuscation is the process of transforming code into a form that is difficult to understand and analyze but still retains its original functionality. This makes it harder for attackers to reverse engineer the code and steal intellectual property, exploit vulnerabilities, or inject malicious code.

Common code obfuscation techniques:

  • Control flow obfuscation: Modifying the code’s execution flow to make it harder to follow.

  • Data obfuscation: encoding data to make it unreadable without the decryption key.

  • String encryption: encrypting strings to hide sensitive information.

  • Symbol renaming: renaming variables and functions to make them less meaningful.

  • Dead code insertion: Adding unnecessary code to confuse attackers.

White-box cryptography is a cryptographic technique where the encryption key is embedded within the software itself. This allows the software to perform cryptographic operations without needing to store the key in a separate location, which can be vulnerable to attack.

The best approach for your software depends on your specific needs and security requirements. Code obfuscation is a good option for protecting intellectual property and preventing tampering, while white-box cryptography is a good option for protecting sensitive data and enabling secure execution in untrusted environments.

Mobile application security testing (MAST) platforms 

MAST platforms are specialized tools designed to analyze and test mobile applications for security vulnerabilities. They offer a range of features, including static code analysis, dynamic analysis, fuzzing, penetration testing, and vulnerability management. Popular MAST platforms are Appknox, Checkmarx SAST, esChecker, NowSecure Platform, Synopsys, Data Theorem Mobile Secure, and AppScan. 

The best MAST platform for your needs will depend on your budget, the type of mobile applications you develop, and your security requirements. Some factors to consider include:

  • The features offered by the platform.

  • The ease of use of the platform.

  • The platform’s integration with your existing development tools.

  • The cost of the platform.

Application firewalls and intrusion detection systems (IDS)

In the landscape of cybersecurity, safeguarding applications from malicious attacks is crucial. Two essential tools in this fight are application firewalls (WAFs) and intrusion detection systems (IDS). While they have overlapping functionality, they offer distinct approaches to security.

Application Firewalls (WAFs):

Application firewalls act as gatekeepers, controlling and filtering traffic to and from web applications. They analyze incoming traffic based on pre-defined rules and block any requests that are deemed malicious or suspicious. This helps prevent attacks like SQL injection, cross-site scripting, and denial-of-service (DoS) attacks.

Types of WAFs:

  • Network-based WAFs: deployed at the network level, inspecting traffic flowing between the internet and the application.

  • Host-based WAFs: installed directly on the web server, offering granular control over application-specific traffic.

  • Cloud-based WAFs: offered as a service, providing scalability and centralized management.

Intrusion Detection Systems (IDS):

Intrusion detection systems monitor network traffic and application activity for signs of suspicious or malicious behavior. They analyze packets, logs, and other data to identify potential attacks, notifying administrators and taking automated actions if necessary.

Types of IDS:

  • Network-based IDS (NIDS): monitors traffic flowing through the network, detecting threats across various applications.

  • Host-based IDS (HIDS): installed on individual systems, focusing on detecting attacks targeting specific applications or operating systems.

  • Wireless IDS (WIDS): monitors wireless networks for suspicious activities.

WAFs and IDS play crucial roles in securing applications; they offer complementary functionality. Using them together provides a layered defense against various threats. WAFs act as a first line of defense, filtering out known attack patterns, while IDS provide deeper analysis and detection of more sophisticated attacks. By prioritizing security and embracing advanced techniques, React Native developers can build secure, trustworthy, and future-proof applications.

Customer Data Doesn’t Go On Vacation: Managing Third-Party Tags in the Hospitality Industry

As the hospitality industry recovers from the challenges posed by the COVID-19 pandemic, global tourism has mostly returned to pre-pandemic levels, with many high-income regions seeing robust travel and hotel demand. This has forced hotel chains, restaurants, travel, and entertainment to adjust to shifting travel patterns including the resurgence of leisure travel and more seasonal demand which has complicated staffing and scheduling.


While the industry had already adopted digital tools during the pandemic to maintain safety, efficiency, and customer engagement, they continued their investment in digital platforms for improved revenue management, as data-driven tools enabled businesses to monitor changes to customer behavior and demand fluctuations to adjust pricing, staffing, and resource strategies accordingly. 

To support this digital transformation hospitality became more reliant on third-party services, from booking platforms to marketing and analytics tools. While these services bring undeniable benefits, they also come with hidden dangers, particularly in the form of third-party tags.

Third-party services, such as online booking engines, chatbots, customer review tools, and digital marketing solutions, have become essential to the modern website. These tools offer the ability to streamline operations, enhance customer experience, and provide valuable customer insights. However, this doesn’t come without risks.

The essentials of using third-party tags


In the hospitality industry, global companies like Marriott, Wyndham, Hilton, Intercontinental, Hyatt, Melia Hotels, Radisson, MGM, and Caesars use these third-party services to understand customer behavior, facilitate bookings, and help manage customer relationships. A hotel website might include a third-party booking system for their accommodations and social media share buttons. A restaurant chain usually features a third-party reservation form and review gatherer on its website. A travel agency adds a third-party tag to handle their car hire services online on their page and accept payments. These are just a few examples. 

The benefits of using third-party tags such as the ones listed above are numerous: increased customer visibility, improved customer engagement, and the ability to offer personalized experiences. Third-party services can also help businesses manage reviews, run targeted advertising campaigns, and analyze customer behavior to optimize product and service offerings.

What data is being collected on the client side?


The use of third-party scripts enables the collection of extensive data on the client side, often unknown to the end-user. These scripts can track a variety of information, including:

  • User behavior: Information on how users interact with a website, including pages visited, time spent on each page, and actions taken (e.g., clicks, form submissions).

  • Demographic information: Data such as age, gender, location, and language preferences, which can be used to tailor marketing efforts.

  • Device and browser information: Details about the device and browser visitors use, which can inform website optimization efforts (including IP address).

  • Purchase history: Records of user transactions, including items purchased, the amount spent, payment methods used, and payment data.

data collected by tags


The dangers of third-party tags in the hospitality industry


While the collection of such data can offer numerous benefits, it also presents significant risks that businesses in the hospitality industry need to be aware of:


Analytics & Personalization Tags

Analytics and personalization tags include Google Analytics, Adobe Analytics, Hotjar, LogRocket, and Fullstory which are used to track user interactions on websites and apps. They help hotels understand customer preferences, booking patterns, and website navigation behavior, allowing for a personalized guest experience. Some of the above also replay sessions to identify and analyze drop-off points, but in the process collect sensitive user information which comes at a risk. For instance, by recording and replaying a payment session, these third-party tags may inadvertently record and store payment card data outside the Cardholder Data Environment (CDE), placing it in a non-PCI DSS-compliant environment. Additionally, other tags could collect credit card information beyond their intended scope or outside of PCI DSS compliance, raising security and regulatory concerns.

Marketing & Retargeting Tags

Marketing and retargeting tags from ad networks including Facebook Pixel, Google Ads, and TikTok, are commonly used to gather metrics and support marketing efforts, particularly for retargeting campaigns. These allow hospitality brands to reach out to guests who have previously interacted with their site but didn’t complete a booking, providing targeted offers and reminders. They’re also designed to collect an extensive set of guest data, including sensitive credit cards, rewards, check-in/check-out dates, passports, credentials, and booking reference information. This raises questions about what data is being accessed or shared by third-party tags, since to effectively retarget users, marketing tags will attempt to capture all data available on a page to identify the user. Therefore, it is crucial to establish clear policies on what data should be collected and ensure the protection of user privacy.

Customer Support & Chatbot Tags

Example support and chatbot scripts include LiveChat and Zendesk enabling customer service automation, allowing guests to receive assistance 24×7. AI-driven chatbots also use tags to record interactions to improve future interactions. To be effective chatbots must collect as much guest information as possible, which is often sensitive, and quite often outside of the intended form field. Hospitality companies must ensure these third-party tags are only allowing access to the forms and data necessary to support the support interaction. 

Know Your Customer (KYC) Tags

Example KYC solution providers include Jumio, Onfido, Trulioo, Authenteq, and Persona. KYC tags become important for luxury hotels, resorts, and rental properties where verifying identity is important. They’re also used for payment security, regulatory compliance, and guest personalization and loyalty. However, there are potential risks associated with this use. To complete the authentication process, some tags may collect sensitive information, such as passport numbers, driver’s license numbers, and photos. Proper safeguards are necessary to ensure that only the required data is collected and securely handled to protect user privacy.

Booking & Payment Processing Tags

Examples of booking engines (like Sabre and Amadeus) and payment gateways (like Stripe and PayPal) as well as buy now pay later (BNPL) services like Afterpay and Klarna, ensure guests have seamless, secure booking and payment experiences including the ability to support real-time pricing adjustments.  However, these third-party tags are vulnerable to tampering by other scripts, which may manipulate the payment process or introduce malicious changes to the page. This poses significant risks, including the potential for attackers to steal user credentials or disrupt the payment flow, emphasizing the need for robust security measures to protect transaction integrity. In addition, all hospitality companies that process credit card transactions must comply with PCI DSS.  Effective March 31, 2025 merchants must comply with new requirements 6.4.3 and 11.6.1. These new requirements intend to protect merchants including hospitality from digital skimming attacks, a continued and growing threat to hospitality websites. 

Tag Managers 

Google Tag Manager and Adobe Launch are tag management systems (TMS) that offer a convenient way to embed tags on a website without needing direct involvement from the development team. These applications allow non-technical teams, such as marketing, digital, or the business, to add scripts independently, which can be resource-efficient and straightforward. However, this ease of access can introduce security risks, as scripts may be added without adhering to the company’s security policies, potentially exposing the site to third-party data risks.

Mitigating third-party tag risks


To mitigate the risks mentioned above, businesses in the hospitality industry must take a proactive approach that balances security with customer-centricity. Here is some guidance:

  • Audit third-party tags regularly: Regularly review and audit third-party scripts in use to ensure they are necessary, secure, and compliant with current policies.

  • Implement strong data management: Establish clear policies outlining how data is accessed, collected, used, and protected. Ensure that third-party services adhere to these policies.

  • Educate hospitality guests: Be transparent with guests about data collection practices. Clearly explain what data is being collected, and how it is used, and give them control over their data.

  • Opt for privacy-focused third-party tag solutions: Consider using third-party services that prioritize privacy and security while enabling businesses to run and innovate. Opt for services that are transparent about their data practices and are compliant with standards and regulations.

Comprehensive control with security and compliance expertise 

The hospitality industry’s reliance on third-party online services is a double-edged sword. While these services offer essential capabilities to improve guest experiences, manage revenue, and coordinate resource demand in a post-pandemic world, they also introduce data privacy, security, and customer trust risks. By understanding the potential dangers and taking steps to mitigate them, businesses can harness the benefits of third-party scripts while protecting themselves and their customers from harm. 

The crucial question becomes…How can hospitality providers effectively protect guest data while continuing to innovate?

When evaluating security solutions to meet these needs, every hospitality provider should consider a client-side protection solution based on the following criteria:

1. Comprehensive platform
  • First-party data encryption and protection

The platform should enable state-of-the-art data protection for all guest information collected throughout the customer journey, from reservation to checkout.

  • Fine-grained control over third-party vendors

The platform should offer consistent, fine-grained visibility and control over the behavior and data usage of all third-party services and software integrated into the hospitality ecosystem.

2. Flexible hybrid deployment 

Given how a hospitality provider may have a lot of domains, login pages, and payment pages that collect personal data, it is essential to choose a provider that has flexible deployment options with a convenient dashboard that aggregates data in one place. 

With the PCI DSS v4 compliance deadline approaching, it is worth checking whether a potential compliance provider can help you quickly bring many payment pages into compliance with a deployment option that doesn’t require configuration. That can significantly make your life easier and remove the need to get approval from various stakeholders or allocate additional team resources to manage the new solution. 

3. Peak season performance

The platform selected must also be capable of scaling up to support the largest and most demanding operations without causing any slowdown or disruption to the guest experience, particularly during peak seasons like holidays or large events.

Given the hospitality industry’s seasonal fluctuations, it’s crucial that the solution can scale up or down based on operational needs.

4. Comprehensive data security and compliance policies

A key feature should also be its ability to support the development of a centralized security policy by all involved teams (e.g., operations, IT, guest services, marketing, governance, risk, and compliance). This policy should encompass all client-side risks and regulatory compliance requirements, such as PCI DSS v4 compliance. It should offer assessment-ready reports for Qualified Security Assessors (QSAs)

5. Client-side & PCI DSS expertise

Client-side protection and compliance vendors should possess years of expertise in protecting JavaScript, with deep knowledge in guiding organizations through PCI DSS compliance. For third-party services, skilled consultants should be available to assist in setting up the best risk mitigation strategies, including data access controls. A fully managed service should also be an option if desired. A vendor with the right level of expertise will empower business operations while fostering customer trust. 

In conclusion, it can be said that by adopting a proactive approach to security, hospitality companies can strengthen their defenses against evolving threats, ensuring a safer, more secure, and trusted guest experience.

The third-party tags, or the vast majority of them, serve a purpose and support the business, and thus cannot be removed. Nor should they be. By monitoring them and understanding the job of each tag or script, businesses can better control them and keep their digital platforms safe for their customers.


This is where Jscrambler can help, with a client-side protection and compliance platform that mitigates third-party tag risks while ensuring compliance with the new anti-skimming requirements in PCI DSS v4. With Jscrambler, businesses not only adopt a unified, fine-grained client-side security approach but also gain access to the top PCI DSS experts in the industry that accelerates compliance ahead of the impending March 31, 2025 deadline. Book a demo to see Jscrambler’s solution in action today.

Google Announces Third-Party Cookies are Here to Stay

On 14 January 2020, Google published a blog post detailing a shock announcement that was lauded as a victory in the battle for greater user privacy. Entitled ‘Building a more private web: A path towards making third-party cookies obsolete,’ Google outlined its plan to phase out support for the divisive tracking technology in Chrome—a move that will be made once it has worked out how to address the “needs of users, publishers, and advertisers” and has developed tools to “mitigate workarounds.”

Fast-forward to 22 July 2024, following years of delays to its proposed two-year deprecation timeline, Google released another blog post that caught the world’s attention: ‘A new path for Privacy Sandbox on the web’. Contained within was the startling announcement that Google is abandoning its long-standing plan to block third-party cookies in Chrome after all.

Let’s explore Google’s revised plans, third-party cookies, their benefits and pitfalls for client-side security and compliance, and reactions to the announcement.

Third-party cookies: Google’s new path


Having announced its U-turn, the tech behemoth said it’s pursuing an updated approach that will “introduce a new experience in Chrome that lets people make an informed choice that applies across their web browsing, and they’d be able to adjust that choice at any time.”

While Google already gives users the option to disable third-party cookies within the browser, it recognizes that it could do more to make the option more transparent – and used the blog to communicate that it’s “discussing this new path with regulators and will engage with the industry as we roll this out”.

With the bombshell dropped, Google appeared to have learned from the series of delays to its initial plans by remaining coy about what comes next – particularly a timeline for implementing the new controls.

What are third-party cookies?


Third-party cookies are small pieces of data, stored in the browser, that are inserted on a user’s device by a website other than the one they are currently visiting. Advertisers and data analytics companies usually use them to track users across multiple websites, enabling them to gather information about browsing habits, preferences, and behaviors.

Unlike first-party cookies, created by the website the user is visiting for functionality like remaining logged in, third-party cookies are set by a domain that’s separate from the one in the browser’s address bar. For example, if you visit a site that contains an advertisement or embedded social media content, that ad or social media service may set a cookie to track you across different sites.


Benefits and pitfalls of third-party cookies


While third-party cookies have revolutionized digital advertising this century, they are increasingly being scrutinized for data privacy and security concerns.

Benefits


Personalized advertising

They allow advertisers to track users across multiple websites, enabling them to create highly targeted ads based on their behavior, preferences, and interests. They also provide the opportunity to show retargeted ads to users who have previously visited their websites by tracking their browser history, increasing conversion rates by reminding users of products they’ve already browsed.

Cross-site analytics

They provide third parties, like marketers and website owners, with insights into user activity across different websites by gathering data about how they interact with them. This is known as cross-site analytics and includes techniques like behavior profiling based on interests, demographics, or browsing habits.

The resulting data can be harnessed to help businesses understand the broader customer journey and refine their marketing strategies.

Improved user experience

Their power to drive retargeting and personalization allows users to see more relevant ads and recommendations, improving the browsing experience by aligning it with their interests.

Storing data on third-party platforms gives users a better and more consistent experience across multiple devices. For example, if you’re browsing a website on your phone before switching to your laptop later, cookies allow the website to remember your preferences, making for a seamless experience.

Improved marketing

They help advertisers and marketers to segment users into different groups based on browsing history, enabling more efficient and tailored marketing campaigns that can be synchronized across platforms and devices. This ensures that ads seen on social media, search engines, and other channels are part of a coherent and integrated campaign strategy, elevating their impact.


Pitfalls

Privacy concerns

By enabling extensive tracking across multiple websites, they can be leveraged to build detailed user profiles – including behavior, preferences, and interests – without their knowledge or explicit consent. The pervasive nature of this online tracking technology prompted Safari and Firefox to block third-party cookies in 2020 and to robust data privacy regulations like the GDPR (General Data Protection Regulation) in the EU.

Data security risks

The vast amounts of user data collected by these cookies could be vulnerable to hacks, leaks, or misuse by third parties, putting sensitive information at risk. Hackers can exploit vulnerabilities to track users, verify stolen data, or impersonate them by hijacking session data, resulting in data breaches. This compromises an overwhelming amount of sensitive information, much of it collected and stored using third-party cookies without the user’s knowledge or permission.

Regulatory challenges

The regulatory screw has been tightened amid the introduction of rigorous data privacy regulations like the GDPR and the California Consumer Privacy Act (CCPA) that impose strict restrictions on how user data can be collected and used. Companies that fail to comply with these laws can be hit with hefty fines and experience reputational damage. Third-party cookies can complicate regulatory compliance, as users must be informed and consent tracking.

Lack of transparency

Users usually don’t know who is tracking them, for what purpose, and how their data is used. When they learn about the extent of data collected via third-party cookies, it can lead to a lack of trust in websites and online platforms, potentially damaging brand reputation.



Google’s U-turn


The reaction to Google’s sudden announcement was both swift and mixed. Some think getting rid of third-party cookies would have been a strategic mistake for Google. Others were more measured, believing that allowing users to “make an informed choice” is a good idea, provided they have all the necessary information to decide about sharing data. Meanwhile, many were concerned, claiming that Google, which makes over 77% of its revenue from tracker-driven, behaviourally targeted ads, put profits before privacy.

For instance, the Information Commissioner’s Office (ICO), the UK’s data privacy watchdog, said it was “disappointed” by the decision. Stephen Bonner of the ICO said: “It has been our view that blocking third-party cookies would be a positive step for consumers”. This backlash underscores that Google’s decision represents a blow to improving data privacy and security online amid the ubiquity and all-encompassing nature of third-party cookie tracking.

While other search engines didn’t renege on their promise to phase third-party cookies out, Google’s domination of the worldwide search engine market, 92% share, means their privacy and security implications are here to stay for businesses and their online customers.  

New Jscrambler Research Reveals 97% of Organizations Know JavaScript Tags Collect Private and Sensitive Data

PORTO, Portugal – October 23, 2024


A global report published today by Jscrambler, the pioneering platform for client-side protection, and conducted by Dimensional Research, outlines the risks and exposure created by third-party JavaScript tags. While businesses understand that third-party tags collect information, only 13% are confident they understand what information they collect and only 26% are aware that tags leaked their private user data to other organizations. Full details are available in the report The Perils of Third-Party Tags: Examining the Client-Side Security Risks and Compliance Challenges of JavaScript

“Today, virtually all websites use JavaScript to seamlessly integrate third-party services and transform their online operations by leveraging analytics, user tracking, payments, social media, communications, support chat functions and chatbots, performance measurement, and more,” said Rui Ribeiro, CEO and co-founder, Jscrambler. “But this adoption comes at a price. Most businesses have no idea what information these tags are collecting and what highly sensitive customer data may be being leaked. Companies must invest in client-side protection and compliance solutions to continue benefiting from these tags while protecting user data from being collected, skimmed, or leaked by third parties.”

Key findings of the report include: 

Third-Party Tags Collect Sensitive Information, Creating Significant Compliance and Security Risks

Nearly every respondent (97%) indicates that they know that third-party tags collect sensitive or private information regularly. Additionally, 49% admit that in the previous 12 months, these tags collected data they were not supposed to, including site traffic, website form data, login, order, social media information, customer account details, and more. And it doesn’t stop with data collection – 26% of respondents realize sensitive data has been leaked to another organization. 

The Case of Google Tag Manager

Google Tag Manager (GTM) may present the best illustration of the value of tag usage while also highlighting users’ limited understanding of the potential risks involved. According to the research, while more than 90% of respondents are familiar with GTM, only 33% recognize that teams can autonomously add more third-party tags and code without additional authorization, creating major compliance and security risks. Slightly more encouraging is that 47% confirm that GTM creates privacy and compliance risks.

Digital Skimming Prevention and Tag Audits are Crucial as March Compliance Deadlines Draw Closer

As compliance implications for third-party vendor tag use become more pronounced, it is promising that 61% of respondents state that a tool that prevents digital skimming is key to achieving PCI DSS compliance. This is especially important regarding PCI DSS requirements 6.4.3 and 11.6.1, designed to prevent digital skimming attacks on websites that capture payment card data. The deadline to comply with these two requirements is March 31, 2025. 

What’s encouraging is that 57% of respondents audit third-party tags to ensure data collection authorization and compliance. Gaining control over the behavior and data consumption of third-party tags is instrumental in helping organizations comply with various standards, regulations, and laws, including PCI DSS, DORA, GDPR, and HIPAA.

Critical Need for Client-Side Protection

Although data protection policies require strict enforcement and scalability, only 36% of respondents’ companies have policies and tools to prevent data skimming. For example, one-quarter of respondents cannot ensure that sensitive data in their company’s chatbot is not shared with another third party. 

When it comes to addressing the issue, 68% of respondents agree that a client-side protection and compliance solution should be deployed to protect user data from being collected, skimmed, or leaked by third parties. Furthermore, an overwhelming 97% indicate that a client-side protection and compliance solution would be valuable to their company. This consensus highlights the critical need for enhanced client-side protection measures. 

Download a full copy of the new market research


Methodology


The report includes findings from a July 2024 global survey of 327 professionals with website responsibilities at medium-size and enterprise companies including IT, cybersecurity, product management, marketing, etc. The survey was administered electronically by Dimensional Research on behalf of Jscrambler. Participants spanned five continents, represented all seniority levels, and had roles across IT, cybersecurity, product management, and marketing. Of the respondents, 74% had responsibility for the technical aspects of their organizations’ websites.  


About Jscrambler


Jscrambler is the leader in Client-Side Protection and Compliance. Jscrambler is the first to merge advanced polymorphic JavaScript obfuscation with fine-grained third-party tag protection in a unified Client-Side Protection and Compliance Platform.

Jscrambler’s integrated solution ensures a robust defense against current and emerging client-side cyber threats, data leaks, misconfigurations, and IP theft, empowering software development and digital teams to securely innovate online with JavaScript. Jscrambler’s Code Integrity product safeguards first-party JavaScript through state-of-the-art obfuscation and exclusive runtime protection. Jscrambler’s Webpage Integrity product mitigates threats and risks posed by third-party tags, all while ensuring compliance with the new version 4 of PCI DSS.

With Jscrambler, businesses adopt a unified, future-proof client-side security policy, all while achieving compliance with emerging security standards.  Jscrambler serves a diverse range of customers, including top Fortune 500 companies, online retailers, airlines, media outlets, and financial services firms whose success depends on safely engaging with their customers online.

How do JavaScript frameworks impact the security of applications?

With almost 14 million active developers and 98% of all websites using it, JavaScript provides the building blocks for web applications – and it’s easy to see why it’s so popular. This fundamental programming language offers the flexibility to create interactive web apps that bring online applications to life. While this ubiquity has led to the development of intuitive, streamlined frameworks that make it even easier to build dynamic web applications, it’s also JavaScript’s Achilles heel.


The JavaScript framework’s popularity attracted the attention of cybercriminals who target their innate vulnerabilities on an industrial scale, compromising the security of the applications they underpin.
 

JavaScript frameworks 


Building complex, interactive web applications from scratch can be overwhelming without an in-depth understanding of coding. JavaScript frameworks break down technical barriers by providing access to a pre-written, reusable code set. This standardized structure creates a blueprint for building web applications using predefined tools, components, and best practices. Novice developers can leverage these frameworks to create robust, scalable, and maintainable applications without learning how to code.

Hybrid mobile app frameworks – such as React Native, NativeScript, Apache Cordova, and Ionic – illustrate how JavaScript can be leveraged to build powerful apps that run on Android and iOS without extra effort. For instance, NativeScript apps are built using JavaScript or any language that converts to JavaScript, such as TypeScript.

JavaScript framework vulnerabilities


Applications built using JavaScript frameworks are executed on the client side, exposing them to vulnerabilities that can be exploited to execute malicious code, steal cookies, session tokens, or other sensitive information that leads to identity theft or hijacking. Let’s explore ten of the most common vulnerabilities and how to avoid them using client-side practices and policies:

Cross-Site Scripting (XSS)

Malicious scripts are injected into trusted applications and executed by unsuspecting users’ browsers. There are three different types of XSS attacks:

  • Stored XSS: Once injected, the malicious script is permanently stored on the target server.

  • Reflected XSS: The user unknowingly sends a malicious script to a web server via a URL.

  • DOM-based XSS: The client-side scripts in a web page modify the DOM and execute the attacker’s payload.


Mitigation: Validate and sanitize all client-side user input used as part of HTML output and encode user-generated content before displaying it on web pages to stop the browser from interpreting it as executable code or active web links.

Cross-Site Request Forgery (CSRF)

Attackers transmit unauthorized commands from a user that the web application trusts, such as changing account details or making purchases. A malicious script or link forces the user to perform actions like submitting a form or making a request without their knowledge or consent.

Mitigation: Use anti-CSRF tokens to ensure requests originate from the correct source and implement same-site cookies to restrict cookies to requests from the same domain. Cross-Origin Resource Sharing (CORS) policies restrict which domains can send requests to a web server, ensuring only trusted origins can interact with sensitive endpoints. For critical operations, users should always be required to re-authenticate.

Security Misconfiguration

Poor security settings in the application can make it easier for attackers to exploit vulnerabilities. For instance, improperly configured Content Security Policies (CSP) intended to prevent XSS attacks may be too permissive, or failure to disable unnecessary JavaScript functions or expose sensitive information can create attack vectors.

Mitigation: Proper configuration requires robust CSPs, diligent management of security settings, and regular reviews and updates to align with best practices and minimize exposure to attacks.

Flawed Code via JavaScript Supply Chain

Web applications typically incorporate code from diverse sources, including third-party libraries – any flaw in this source code heightens the risk of a cyber-attack. Once these flawed packages are included in a development project, the vulnerabilities can propagate throughout the application, potentially compromising security, performance, and functionality. Attackers exploit these flaws to gain unauthorized access, steal sensitive data, or disrupt services.

Mitigation: Enforce strong code and webpage integrity policies that include endpoints, networks, the cloud, and mobile devices, so only known and reliable third-party code can run. Gain client-side visibility by using webpage inventory technology that actively monitors this angle.  Use automated tools to ensure the reliability of third-party dependencies by actively monitoring them.

Intentional Code Alterations by Threat Actors

By manipulating JavaScript code, attackers can exploit web applications by executing malicious activity, including harvesting user credentials, redirecting users to phishing sites, or installing malware. These modifications can be introduced using techniques like XSS attacks and compromising third-party libraries or supply chains. 

Mitigation: Implement resilient source code protection that obfuscates the code, such as code integrity checks, secure coding standards, and regular audits of the codebase and third-party dependencies.

Web Skimming

These client-side attacks occur when cybercriminals inject malicious JavaScript code onto a web application to compromise sensitive data – typically payment card data – inputted by users into checkout pages and other online forms. Applications are compromised by targeting assets originating outside their security perimeter, including all client-side web assets – the files and resources that are downloaded and executed by a user’s web browser when they use an app.

Mitigation: To securely collect data from users via web forms, they must be designed to incorporate proactive security measures, including data encryption, multi-factor authentication (MFA), spam protection, and secure communication protocols like HTTPS and SSL/TLS.

Formjacking

Malicious JavaScript code is inserted into a web application, hijacking its form functionalities, such as checkout or login forms, to siphon off user data. Formjacking exploits the trust that users have in well-known, legitimate web applications. Consequently, the attack can often go undetected for a prolonged period.

Mitigation: Regularly patch and update the app’s software, plugins, and extensions, ensure it uses a secure connection to keep data safe during transmission, and regularly scan the app and server logs for vulnerabilities and suspicious activities.

Magecart

This is a form of e-skimming attack focused on injecting digital credit card skimmers into e-commerce and payment applications to compromise sensitive payment data. Attackers typically exploit vulnerabilities in third-party scripts or gain access to the app’s infrastructure to plant malicious code. Once embedded, it silently intercepts and exfiltrates payment data to servers controlled by the attackers.

Mitigation: Gain client-side visibility using webpage inventory technology that actively monitors the client side, looking for signs of malicious behavior.

Session Hijacking

Attackers gain unauthorized access to a user’s active session with a web application by exploiting vulnerabilities to steal cookies and other session tokens to impersonate legitimate users. This can occur through methods like man-in-the-middle attacks whereby, without adequate encryption, data exchanged between the user and the server can be intercepted and altered by attackers.

Mitigation: Implement strong encryption to secure cookies and ensure proper input sanitization.

JavaScript Sniffers

JavaScript sniffers are malicious scripts (malware) injected into a web application’s code to intercept and steal sensitive information. They exploit vulnerabilities in the app’s security, such as unpatched software, weak access controls, or insecure third-party integrations, allowing attackers to inject the malware directly or through compromised third-party scripts. Once deployed, the malware silently captures transactional data from forms or other input fields as users interact with the compromised app.

Mitigation: Conduct regular code audits, patch and update the app’s software consistently, ensure secure handling of third-party resources, and use CSPs to limit the execution of untrusted scripts.

Fortifying Frameworks: JavaScript Client-side Security


JavaScript’s well-deserved reputation as the programming language of choice for web application development has been achieved despite innate vulnerabilities that can lead to severe consequences – from unauthorized access to sensitive data to manipulation of application functionality. 

Amid this wide client-side attack surface, the fundamental JavaScript frameworks that streamline web application development can compromise their security. Effective mitigation of this multidimensional threat requires robust client-side security practices and policies that reinforce these frameworks by constantly patching and updating software, regularly monitoring script behaviors and web pages for changes, and being diligent when selecting and implementing third and fourth-party scripts.

MAC: Message Authentication Code

In cybersecurity, ensuring the integrity and authenticity of messages is paramount. One of the critical tools used to achieve this is the Message Authentication Code (MAC). This article delves into the concept of MAC, its types, how it works, and its applications in modern digital communication.

What is a Message Authentication Code (MAC)?

A Message Authentication Code (MAC) is a short piece of information used to authenticate a message and ensure its integrity. Essentially, it provides a way to check that a message has not been altered during transmission and verifies the sender’s identity. A MAC is generated using a secret key and a cryptographic algorithm, producing a fixed-size output, commonly known as a tag or checksum.

Importance of MAC in Digital Communication

  1. Data Integrity: MACs ensure that the data received is exactly what was sent, with no alterations or corruption during transit. Any modification in the message would result in a different MAC, alerting the recipient to the potential tampering.

  2. Authentication: By using a secret key known only to the sender and the receiver, MACs authenticate the source of the message, ensuring it comes from a trusted sender.

  3. Security: In secure communication protocols, MACs play a crucial role in maintaining confidentiality and preventing unauthorized access to data.


The Core Principles of MACs

At its heart, a MAC operates on a foundation of shared secrecy and cryptographic transformations. Here’s a breakdown of the core principles:

  • Shared Secret Key: The cornerstone of MAC security is a secret key, known only to the sender and receiver. This key serves as a cryptographic password used in the MAC generation process. The strength of the key directly impacts the overall security of the system.

  • Cryptographic Hash Function: A MAC leverages a cryptographic hash function, a one-way mathematical operation that transforms an arbitrary message into a fixed-size string of bits, known as a hash digest. This digest acts as a fingerprint of the message, capturing its essence in a condensed form. Hash functions possess crucial properties like collision resistance (meaning it’s computationally infeasible to find two different messages with the same hash) and avalanche effect (a minor change in the message drastically alters the hash digest).


How Does MAC Work?

The process of generating and verifying a MAC involves several steps:

  • Message Preparation: The sender prepares the message that needs to be transmitted.

  • Key Generation: A secret key, known only to the sender and the receiver, is used. This key must be securely shared between the parties beforehand.

  • MAC Generation: The sender uses a MAC algorithm (such as HMAC, CMAC, etc.) to combine the message with the secret key, generating a unique MAC value.

  • Transmission: The original message and the MAC are sent to the receiver.

  • Verification: Upon receiving the message and the MAC, the receiver uses the same secret key and MAC algorithm to generate a new MAC for the received message. The receiver then compares the newly generated MAC with the received MAC. If they match, the message is authenticated and considered intact.


Types of MAC Algorithms

There are several types of MAC algorithms, each with its specific use cases and security properties:

  1. HMAC (Hash-based Message Authentication Code):

    • Description: HMAC uses a cryptographic hash function (e.g., SHA-256) along with a secret key to generate a MAC.

    • Advantages: HMAC is widely used due to its simplicity, efficiency, and resistance to certain types of attacks, such as length-extension attacks.

    • Applications: HMAC is used in various Internet protocols, including TLS (Transport Layer Security) and IPsec (Internet Protocol Security).

  2. CMAC (Cipher-based Message Authentication Code):

    • Description: CMAC uses a block cipher (e.g., AES) with a secret key to generate a MAC.

    • Advantages: CMAC provides a high level of security and is suitable for environments where a block cipher is already in use.

    • Applications: CMAC is used in network security protocols and secure messaging systems.

  3. GMAC (Galois/Counter Mode MAC):

    • Description: GMAC is a variant of the GCM (Galois/Counter Mode) block cipher mode, optimized for generating MACs.

    • Advantages: GMAC provides both authentication and encryption, making it efficient for secure communication.

    • Applications: GMAC is used in secure communication protocols, such as TLS and SSH (Secure Shell).

  4. PMAC (Parallelizable Message Authentication Code):

    • Description: PMAC is designed to take advantage of parallel processing, allowing faster MAC generation.

    • Advantages: PMAC is efficient in environments with parallel processing capabilities.

    • Applications: PMAC is used in high-performance computing and network security applications.


Advanced Applications of MACs


Beyond their fundamental role in securing communication channels, MACs have found applications in various advanced security scenarios:

  • Digital Signatures: MACs can be used as building blocks for digital signatures. By combining a message with a private key using a MAC algorithm, a digital signature can be created. This signature can then be verified using the corresponding public key, ensuring the authenticity and integrity of the signed message.

  • Data Integrity Verification: MACs play a crucial role in data integrity verification. They can be used to ensure that stored data on a disk or transmitted data packets haven’t been modified without authorization. This is critical for maintaining data consistency and preventing security breaches.

  • Message Replay Protection: MACs can offer a degree of protection against message replay attacks. Since a valid MAC value is tied to a specific message and secret key, an attacker cannot simply capture and replay a message with the same MAC as it won’t match the independently generated MAC at the receiver’s end. However, it’s important to note that additional mechanisms like sequence numbers might be necessary for robust replay protection.


Challenges and Considerations


While MACs are essential for secure communication, there are challenges and considerations to keep in mind:

  1. Key Management: Securely sharing and storing the secret key is crucial. If the key is compromised, the security of the MAC is also compromised.

  2. Algorithm Selection: Choosing the right MAC algorithm depends on the specific use case and security requirements. For instance, HMAC is suitable for most general purposes, while CMAC may be preferred in environments using block ciphers.

  3. Performance: The performance of MAC algorithms can vary. In high-performance environments, algorithms like PMAC, which leverage parallel processing, may be more suitable.

  4. Security: Ensuring the cryptographic strength of the MAC algorithm is vital. Using weak or outdated algorithms can expose the system to attacks.


Conclusion


Message Authentication Codes (MACs) are fundamental to ensuring data integrity and authenticity in digital communication. By providing a secure way to verify that messages have not been altered and that they originate from a trusted source, MACs play a crucial role in maintaining the security of modern communication systems.

Understanding the different types of MAC algorithms and their applications helps choose the right solution for specific security needs.

BYOI: Bring Your Own Identity

Identity management has become a cornerstone of digital interactions. From logging into social media accounts to accessing corporate resources, how we manage, and authenticate, our digital identities plays a critical role in ensuring security and convenience.

One emerging concept is Bring Your Own Identity (BYOI). This approach allows individuals to use a single identity across multiple platforms and services, enhancing user experience and streamlining identity management.

Understanding BYOI


BYOI, or Bring Your Own Identity, is a concept where users can authenticate themselves using an identity provider (IdP) of their choice rather than relying on the authentication mechanisms provided by each service or application they use. This can be achieved through federated identity management, where different systems trust and accept credentials from common identity providers like Google, Facebook, or enterprise identity systems.

The Evolution of Identity Management

Traditionally, users had to create separate credentials for each service they accessed. This not only led to a proliferation of passwords but also increased the risk of security breaches due to weak or reused passwords. The advent of single sign-on (SSO) solutions marked a significant improvement, allowing users to log in once and access multiple services. BYOI takes this a step further by allowing users to bring their preferred identity provider into the mix.


Benefits of BYOI

1. Enhanced User Experience

One of the primary advantages of BYOI is the improved user experience. By allowing users to authenticate using their preferred identity provider, BYOI eliminates the need to remember multiple usernames and passwords. This seamless experience leads to higher user satisfaction and engagement.

2. Improved Security

BYOI leverages the security measures implemented by major identity providers. These providers typically have robust security protocols, including multi-factor authentication (MFA), anomaly detection, and regular security updates. By relying on these trusted providers, organizations can enhance their overall security posture.

3. Cost Efficiency

Managing user identities can be resource-intensive. BYOI can reduce the burden on IT departments by offloading the authentication process to third-party providers. This can result in cost savings in terms of both infrastructure and personnel.

4. Scalability

As organizations grow, so does the complexity of managing user identities. BYOI offers a scalable solution by allowing organizations to integrate with existing identity providers. This can simplify the onboarding process for new users and make it easier to manage a growing user base.


Implementing BYOI


Implementing BYOI requires careful planning and consideration. Here are some key steps to consider:

1. Choose the Right Identity Provider: The first step is to select a reliable identity provider that supports the necessary authentication protocols (e.g., OAuth, OpenID Connect). The choice of provider will depend on factors such as security features, user base, and integration capabilities.

2. Integrate with Existing Systems: Once the identity provider is chosen, the next step is to integrate it with existing systems. This may involve configuring applications to accept tokens from the identity provider and setting up federated trust relationships.

3. Ensure Compliance: Organizations must ensure that their BYOI implementation complies with relevant regulations and standards. This may include data protection laws, industry standards, and internal policies.

4. Educate Users: User education is crucial for the successful adoption of BYOI. Users need to understand how to use their chosen identity provider for authentication and be aware of the security benefits it offers.


Challenges of BYOI


While BYOI offers numerous benefits, it is not without its challenges. Some of the key challenges include:

  • Interoperability: Ensuring interoperability between different identity providers and applications can be complex. Organizations must ensure that their systems can accept and process tokens from various providers.

  • Security Risks: While BYOI can enhance security, it also introduces new risks. For example, if an identity provider is compromised, the impact could extend to all connected services. Organizations must implement robust security measures to mitigate these risks.

  • User Privacy: BYOI involves sharing user data between different entities. Organizations must ensure that they handle this data responsibly and in compliance with privacy regulations.


Decentralized Identity and Beyond


The BYOI landscape is a dynamic tapestry constantly being woven with advancements in digital identity management. Decentralized identity (DID) solutions are emerging as a potential paradigm shift, challenging the traditional IdP model. DIDs empower users with greater autonomy over their identities.

Users store their identity data on their own devices or secure vaults, granting access to specific attributes to SPs as needed. This mitigates reliance on centralized IdPs and fosters data privacy. Imagine a world where you carry your digital identity on a secure key fob, granting access selectively.

Here’s a glimpse into potential future developments that could redefine the BYOI landscape:

  • Adaptive Authentication: Context-aware authentication based on factors like location, device, and time can enhance security and user experience. For instance, fingerprint recognition might be required for high-value transactions, while location verification could be used for geographically restricted access.

  • Biometric Authentication: Integrating biometric factors like fingerprints or facial recognition for user verification can offer added security. This eliminates the vulnerability of passwords being stolen or forgotten.

  • Continual Improvement of Standards: Continued efforts to establish and refine open standards like OpenID Connect and SAML are crucial for seamless BYOI implementation across diverse platforms. This fosters interoperability, akin to ensuring all airlines utilize compatible ticketing systems.

  • Regulatory Frameworks: As BYOI and DID solutions evolve, robust regulatory frameworks are essential to address data privacy concerns and ensure responsible data handling practices. This necessitates collaboration between governments, technology companies, and user advocacy groups.


Conclusion


BYOI presents a compelling vision for a more streamlined and potentially more secure authentication landscape. As the technology matures and security concerns are addressed, BYOI can potentially revolutionize how we access online services. However, the future of authentication likely lies in a hybrid approach, leveraging the strengths of both centralized and decentralized models.

BYOI can coexist with DIDs, offering users a choice based on the specific context and desired level of control. Ultimately, the goal is to empower users with a secure and user-friendly authentication experience, allowing them to navigate the digital world with confidence and control.

The Mongolian Skimmer: different vests, all equally dangerous

with Pedro Marrucho and David Alves


A few weeks ago, while consulting skimming threat intel sources Jscrambler researchers stumbled across a new skimming campaign that, at first glance, stood out because of the JavaScript obfuscation it exhibits. Some people raised the question if this was a new obfuscation technique, probably because the code is using weird accented characters.

As part of a company that makes a JavaScript obfuscation tool, the team could tell immediately that it is not. The obfuscation author just used unusual Unicode characters for variables and function names. But that has been done before and it’s hardly an obstacle.

The Jscrambler researchers went over the obfuscation, retrieved the details of the attack, and affected victims and we even saw a strange interaction between different skimming actors chatting through comments in the code. Read everything below.



source-code-example

Mongolian Skimmer


Obfuscation


Jscrambler researchers learned about this skimming campaign from Sansec threat intel. No details were available on it, but the team did a full analysis. At first glance, the thing that stood out was the script’s obfuscation, which seemed a bit bizarre because of all the accented characters. Some people online were saying it could be a new obfuscation technique. The heavy use of Unicode characters, many of them invisible, does make the code very hard to read for humans.
 

But the minute Jscrambler researchers started looking at the obfuscation, they realized immediately that it wasn’t a new fancy technique — it was simply leveraging a well-known JavaScript language capability: the ability to use any Unicode character in identifiers (e.g. variable names), as per the ECMAScript Standard.

The added obfuscation does introduce confusion (we call this obfuscation potency) but it does not add any resiliency (how hard it is to reverse engineer, using manual or automated methods). A simple method to remove these characters is to pass the code through a JS transformer that renames all identifiers to simple names (e.g. ‘a’, ‘b’, ‘c’, …). But that’s only useful if a human needs to look at it. A fully automated JS obfuscation reverse engineering engine will not mind what unicode characters are being used. The tooling has been available and fully automated at Jscrambler for years. It’s one of the things Jscrambler researchers use to find skimmers in our products and research.

Using Jscrambler’s own Code Integrity product, the team quickly renamed all the identifiers to much shorter and more readable ones.mongolian-skimmer-obfuscation-exampleAfter renaming the variables the code resulted in a bunch of string concatenations, including a few String.fromCharCode(…) statements, which contain a hidden skimmer, to be passed to an eval function call.


jscrambler-code-integrity

The eval-ed string reveals a script that was also obfuscated using a common obfuscation tool. Once the eval runs, it loads a skimmer designed to steal sensitive information.

steal-sensitive-information-example


Once Jscrambler researchers reversed the JS, they quickly confirmed that this was a pretty standard skimmer.

standard-skimmer-revelation

Naming the Skimmer


When they analyzed the first variable assigned in the script, its initial character was represented by the hex value “E1A0A5”, which corresponds to a Unicode character named “Mongolian Letter OE”. Such an unusual character being used by an identifier inspired the team to name the skimmer the Mongolian Skimmer.

Mongolian-Letter-OE

Skimmer Analysis


The skimmer follows a typical skimming structure Jscrambler researchers have seen countless times in the past:

  • DOM Monitoring for Changes
    The script continuously monitors changes in specific DOM elements like <input>, <select>, and <textarea> fields. These are prime targets for stealing user data, such as personal information or payment details. It extracts the name or ID attributes and fetches the value of these elements when users interact with them.

  • Data Exfiltration
    The skimmer checks the page URL for keywords such as “checkout” or “admin” to identify pages handling sensitive data. Once identified, it encodes the data using window.btoa() for base64 encoding and sends it to a remote server via a tracking pixel (constructed with new Image()) – a classic skimming technique.

  • Developer Tools Detection
    The script actively detects whether the browser developer tools (DevTools) are open. If detected, the skimmer disables certain functions—likely an attempt to evade detection during debugging or dynamic analysis phases.

  • Data Collection Before Page Unload
    The skimmer ensures no data is lost by capturing any last-minute data entries before the page is closed or refreshed using the beforeunload event.

  • Cross-Browser Compatibility
    The skimmer uses well-known techniques to ensure compatibility across different browsers by employing both modern and legacy event-handling techniques. This guarantees it can target a wide range of users, regardless of their browser version.

  • Anti-Debugging
    The skimmer employs an interesting anti-debugging technique by checking its formatting through string conversion and regex tests to detect tampering. This is a standard trick used by skimmers to prevent debugging by detecting code beautification or any other type of formatting changes.


Loader Analysis


Most of the Mongolian skimmer instances the team found used an inline script on the homepage, which asynchronously fetched the skimmer script from an external source. However, they did encounter one peculiar instance where a different loader was being used that is worth highlighting.

Unusual Loader Variant

unsual-loader-variant


This loader script appears to have been added to the loader of a Magento plugin named “Magento 2 Google Tag Manager” built by MageFan. It dynamically loads Google Tag Manager and the skimmer script, but only if it detects user interactions, such as:

  • Scroll

  • Mouse movement

  • Touchstart


This approach may not only serve as an effective anti-bot measure but also as a way to make extra sure that the script loading is not visibly impacting page load performance.

Cyber Chit-Chat Using the Victims’ Code

In one compromised Magento site, Jscrambler researchers found not just one, but two skimmer instances: the familiar “’Google’+’Analytics’+’Object’” loader which we talked about some time ago here, and the Mongolian skimmer. 

cyber-chit-chat-using-the-victim-codeIt’s not uncommon for compromised sites to be targeted by multiple malicious actors exploiting the same vulnerabilities. What made this case special was that Jscrambler researchers found the two threat actors casually chatting by leaving code comments in the source code to each other. This developed into an active conversation where the two threat actors agreed to split the profits of the skimming activity.


Take a look at their exchange:

Date

Message

24/09/2024

<!– 50/50 maybe? -–>

27/09/2024

<!– I agree 50/50, you can add your code 🙂 –>

30/09/2024

<!– Alright ) so how can I contact you though? U have acc on exploit? –>

We can’t say that cybercriminals don’t follow a code ?.

Conclusion


The obfuscation techniques found on this skimmer may have looked to the untrained eye as a new obfuscation method, but that was not the case. It was just another Tuesday in cyberspace. It used old techniques to appear more obfuscated, but they are just as easy to reverse. A simple code transformer can remove all the weird characters automatically for you. Underneath the skin, it was just a very common type of skimmer code, commonly found in misconfigured or vulnerable Magento installations in the wild.

Indicators of Compromise (IOCs): Malicious Domains

common[.]gifcache[.]com

Skimmer

191[.]96[.]56[.]171

Hostinger

USA

cache[.]cdn-core[.]com

Skimmer

198[.]187[.]29[.]127

Namecheap

USA

widget[.]statictool[.]com

Skimmer

82[.]197[.]83[.]18

Hostinger

USA

widget[.]useonline[.]org

Skimmer

82[.]197[.]83[.]18

Hostinger

USA

process[.]services[.]bz

Exfil

82[.]180[.]138[.]247

Hostinger

USA

stat[.]mystatpal[.]com

Exfil

82[.]197[.]83[.]29

Hostinger

USA

seomgr[.]com

Exfil

62[.]72[.]7[.]8

Hostinger

USA

mdn[.]safecontentdelivery[.]com

Exfil

217[.]21[.]77[.]96

Hostinger

USA

Save Your Data Like a Pro: The Power of Multi-Factor Authentication (MFA)

Multi-factor authentication (MFA) is a security system that requires users to provide two or more forms of identification (factors) before accessing a digital resource. These factors can include something the user knows (e.g., a password), something the user has (e.g., a smartphone), and something the user is (e.g., a fingerprint).

MFA enhances security by making it harder for unauthorized users to access accounts, even if they have obtained one factor (e.g., a password) through phishing or other means.

Our digital world is under siege! Cyber threats are on the rise, with attackers growing more sophisticated all the time. Traditional passwords are like flimsy fences – easily breached through data leaks, phishing attacks, or even just weak choices. This puts our data and privacy at risk.

Here’s where stronger authentication comes in as a knight in shining armor. By requiring multiple verification factors, like a password and a code from your phone, it makes it much harder for attackers to break in. Even if they steal your password, they’d still need your phone or your fingerprint to gain access. It’s like adding a moat and guard dogs to your digital castle!

The Importance of Multi-Factor Authentication Adoption


Multi-factor authentication offers a powerful shield for your online accounts. Here are some key benefits of adopting MFA:

  • Fortress-like Security: MFA adds an extra layer on top of passwords, making it significantly harder for attackers to breach your defenses. Even if your password is compromised, they’d still need your phone, a security key, or your fingerprint to gain access.

  • Reduced Phishing Risk: Phishing scams often trick people into revealing their passwords. MFA throws a wrench into these plans. Without the additional verification factor, stolen passwords become useless to attackers.

  • Enhanced Data Protection: Many organizations deal with sensitive information. MFA safeguards this data by requiring stronger authentication, making it much harder for unauthorized access and potential data breaches.

  • Compliance Advantage: Certain industries have regulations requiring strong authentication measures. MFA compliance can help organizations avoid hefty fines and legal hassles.

  • Surprisingly Convenient: While offering robust security, MFA doesn’t have to be a hassle. Many user-friendly options exist, like verification codes on your phone or fingerprint scanners.

  • Cost-Effective Security: Compared to other security solutions, MFA is a relatively inexpensive way to improve your online security posture significantly.


Current State of MFA Adoption


MFA adoption is increasing, driven by growing awareness of security risks and regulations mandating its use in some industries. Industry leaders in technology and finance are leading in adoption rates, with advancements in user-friendly MFA methods contributing to this growth. However, adoption is uneven across industries, with smaller businesses and individual consumers lagging.


Despite its benefits, MFA is not foolproof, and certain advanced attacks can bypass it, particularly SMS-based methods. User inertia and cost considerations also present challenges to wider adoption. While significant progress has been made, efforts to improve awareness, enhance user-friendliness, and focus on stronger MFA methods are crucial for broader adoption.

Methods of MFA Authentication


There are several methods for MFA authentication, each offering varying levels of security and convenience. Here’s a breakdown of some common methods:

  • Something You Know:

    • Knowledge-based Authentication: This relies on information only the user knows, like answering pre-set security questions (e.g., childhood pet’s name). It’s considered a weaker MFA method due to its vulnerability to social engineering attacks.

  • Something You Have:

    • SMS Verification: A one-time code is sent via text message to the user’s registered phone for login verification. It’s convenient but susceptible to SIM-swapping attacks.

    • Authenticator Apps (TOTP/HOTP): These apps generate time-based or counter-based one-time codes that the user enters during login. They offer better security than SMS verification.

    • Hardware Security Keys: Physical tokens that connect to a device’s USB port or use Bluetooth to provide a secure login experience. They are considered the most secure MFA method.

  • Something You Are:

    • Biometric Authentication: Uses unique physical characteristics like fingerprints, facial recognition, or iris scans for verification. Offers strong security but may have limitations depending on the technology used.


Challenges of Implementing MFA


Implementing MFA can be a two-edged sword. While it offers significant security benefits, there are challenges to consider:

  • User Resistance: People may find the extra login step inconvenient or cumbersome. Some might worry about the security of their device used for MFA.

  • Technical Complexity: Integrating MFA with various applications and legacy systems can be complex. Choosing an MFA solution that works seamlessly across your tech stack is crucial.

  • Cost and Time Investment: Implementing MFA requires an initial investment in time and resources for setup, training, and potentially ongoing support.

  • Limited User Support: Without clear instructions and proper user support, a smooth rollout can be hampered. People may need help understanding or using MFA effectively.

  • Security Gaps: Not all MFA methods are created equal. SMS-based verification, for instance, can be vulnerable to SIM-swapping attacks. Choosing a more secure MFA method like security keys can mitigate this risk.


Best Practices for Successful MFA Adoption


Here are some best practices to ensure successful adoption of Multi-Factor Authentication.

Prioritize User Experience:

  • Convenience is Key: Offer multiple MFA methods (push notifications, phone calls, authenticator apps) to cater to user preferences and accessibility needs.

  • Seamless Integration: Choose an MFA solution that integrates smoothly with your existing login processes to minimize disruption.

  • Clear Communication: Educate users about the benefits of MFA, address security concerns, and provide step-by-step instructions for setup and use.


Balance Security and Usability:

  • MFA Strength Matters: Not all MFA methods are equal. While SMS offers convenience, security keys, and biometrics provide stronger protection.

  • Risk-Based Approach: Consider implementing adaptive authentication that adjusts MFA requirements based on login attempts or user risk profiles (e.g., higher risk for access from a new device).


Planning and Implementation:

  • Phased Rollout: Start with a pilot group to identify and address any technical issues or user concerns before wider deployment.

  • User Training and Support: Provide comprehensive training materials and ongoing support to ensure users understand and feel comfortable using MFA.

  • Regular Review and Updates: Monitor MFA usage and user feedback. Stay updated on evolving threats and adapt your MFA strategy accordingly.


The Future of MFA


The future of MFA is all about going beyond passwords and static verification methods, aiming for a more secure and user-friendly experience. Here are some key trends to watch:

  • Biometric Authentication: Fingerprint scanners, facial recognition, and iris scans will likely become more commonplace, offering a convenient and secure way to verify identity.

  • Continuous Authentication: Imagine a system that constantly analyzes your behavior (typing patterns, device location) to identify anomalies and prevent unauthorized real-time access. This eliminates the need for constant login prompts.

  • Passwordless Authentication: Passwords might fade away altogether. Security keys, built-in device authenticators, and even behavioral biometrics could become the primary methods for verifying your identity.

  • Integration with Zero Trust: MFA will likely become seamlessly integrated with the Zero Trust security model, which assumes constant verification and grants access based on least privilege principles.

  • Focus on User Experience: Expect advancements in user-friendly interfaces and intuitive workflows that make MFA even more invisible and frictionless in the background.

  • Standardization and Interoperability: Universal standards for MFA protocols and methods will likely emerge, enabling smoother integration across different platforms and applications.


Conclusion


Multi-factor authentication (MFA) has emerged as a critical shield for our online accounts in a world increasingly plagued by cyber threats. While challenges like user resistance and technical complexities exist, the benefits of MFA are undeniable.

Organizations can overcome these hurdles by prioritizing user experience, implementing a balanced security approach, embracing new technologies, and ensuring successful MFA adoption.

As we look towards the future, MFA’s evolution promises a world beyond passwords, with seamless authentication methods that are both secure and user-friendly. This paves the way for a more secure digital landscape for everyone.

Understanding Generator Function in Javascript

The generator function has been a special function in Javascript since 2015, but developers have overlooked or rarely used it,  perhaps due to its infrequent utilization or lack of familiarity. These special functions, capable of pausing and restarting execution, make handling async iteration and sequence easier. From lazy loading to custom iterables, animation to the beloved `await` keyword in asynchronous programming, generators are advanced concepts made simple.

This article will introduce beginners to generator functions, explain their importance, and explore how they streamline complex tasks like lazy evaluation and creating custom iterables. 

To fully grasp generator functions, let’s take a quick refresher on regular functions in JavaScript.  This foundation will help us understand each step in this article and identify the key differences between the two.

What is a Javascript Function?

In programming, a function is a reusable block of code that performs a specific task. You can call it multiple times with different inputs (if needed) to achieve the desired functionality, and it can optionally return a result.

Declaring a Function:

    function functionName() {
    }

Let’s define a simple function: 

    function calcRectArea(length, width) {
        return length * width;
    }
    let result = calcRectArea(50, 80)

The above function `calcRectArea` takes two parameters: length and width, which represent the length and width of a rectangle, respectively. It calculates the area of the rectangle by multiplying the length and width together and returns the result.

A standard function starts, runs, and returns when the function is finished, while a generator function can be paused and resumed multiple times. Great! We just mentioned generator functions. Now, let’s learn what they are and how they differ from regular functions in JavaScript.

What is a Generator Function in JavaScript?

Generator functions in JavaScript are powerful tools for generating sequences of values. They don’t return a single value like a regular function when called. Instead, they return a Generator object following the ES6 Iterable Protocol. This offers a simple way to handle large datasets or create custom iterators. It uses the yield keyword to pause execution and return values one at a time. This allows them to remember their state and resume execution from the exact pause point when called again.

In JavaScript, generator functions are defined using an asterisk (*) placed after the function keyword. The code syntax of a generator function declaration.

    function* functionName(){
    }

We can also declare a generator function in an expression like a regular function, as seen in the code below:

    const generatorFunction = function*() {}

The generator function does not return a value immediately; instead, it returns a certain type of object, known as the Generator object

The generator object manages function execution through its `next()` method. The `yield` keyword within the generator function pauses execution and remembers its state. This allows the function to resume later, continuing from the pause point until completion.

Yield keyword :

    function* functionName(){
     yeild 'Name'
     yeild 'Age'
     yeild 'Employment status'
    }

Next () method:

    generator.next()

When we invoke the next() function, it yields an object comprising two properties:

* Value: This signifies the actual value of the object at the current iterator position.

* Done: This Boolean state indicates whether the iteration is complete or not.

    {value: name, done: false|true}

Calling a Generator Function

To understand the concept further, let’s examine a basic code example with accurate data demonstrating how the generator function works. We will update the previous code with the accurate info we need. 

    function* profileInfo() {
      yield 'Jane Smith';
      yield 29;
      yield 'Employed';
    }
    const generator = profileInfo()
    generator.next()
    generator.next()
    generator.next()

The `profileInfo` function acts like a step-by-step information provider in our code example. It uses the `yield` keyword like a pause button, holding onto the information. When we call `profileInfo()`, it doesn’t reveal everything at once. Instead, it creates a special object that remembers its place and is ready to continue. We use the `next()` method to retrieve the information piece by piece. Each time we call it, the function resumes from where it left off and delivers the next yielded value.

If we log the generator object on our console, here’s what we will see:

    { value: 'Jane Smith', done: false }
    { value: 29, done: false }
    { value: 'Employed', done: false }

Calling the generator the fourth time will result in the value undefined and a true boolean value, indicating that there are no more elements to yield:

    { value: 'Jane Smith', done: false }
    { value: 29, done: false }
    { value: 'Employed', done: false }
    { value: undefined, done: true }

So, how does this all work together? Imagine you are interviewing someone and want to collect their information piece by piece. The first `next()` call would be like asking for their name, and the generator would yield ‘Jane Smith’. The second `next()` call would be like asking for their age, and it would yield 34. Finally, the third `next()` call might be for their employment status, and it would yield ‘Employed’.

Passing Arguments to Generator Functions for Dynamic Control

    function* addNewEmpoyee(name, age, gender, department) {
      yield `Creating new employee profile name: ${name}`;
      yield `Setting age to: ${age}`;
      yield `Setting gender to: ${gender}`;
      yield `Selecting department to: ${department}`;
      return `Employee profile: ${name}, age: ${age}, gender: ${gender}, department:${department} created.`;
    }
    const generator = addNewEmpoyee("John Doe", 30, "Male", "Technical"); // Pass arguments during creation
    
    console.log(generator.next().value); 
    console.log(generator.next().value); 
    console.log(generator.next().value);  
    console.log(generator.next().value); 
    console.log(generator.next().value);  

We define a generator function called `addNewEmployee`, which accepts four arguments:  `name`,  `age` ,  `gender`,  `department` . Inside the function, we utilize four yield statements to yield each argument. Subsequently, we use the `return`  keyword to return the four arguments. During instantiation, we pass the arguments, such as John Doe for the employee’s name, and so forth, until all four arguments are provided. Finally, we invoke the generator function in our console using `generator.next()` The output below is what we will get.

    Creating new employee profile name: John Doe

    Setting age to: 30

    Setting gender to: Male

    Selecting department to: Technical

    Employee profile: John Doe, age: 30, gender: Male, department: Technical created.

In the previous code, we used the `return` keyword to return the final statement of the arguments. Let’s provide a brief explanation of what the return keyword does.

Return keyword

The return statement is one of the methods used for the generator object. When a return statement is encountered within a generator function, it exits the generator’s execution and returns a specific value. This effectively ends the generator’s ability to yield further values.

    function* greetUser(name) {
        yield "Hello!";
        return name;
        yield "How are you";
    }
    const generator = greetUser("John Doe");
    
    console.log(generator.next());
    console.log(generator.next());
    console.log(generator.next());

Code output

  { value: 'Hello!', done: false }
 
  { value: 'John Doe', done: true }

We noticed that we have two yield statements and a return statement. When we invoke the generator function three times, we will receive a boolean statement that is true, indicating that the yield argument is complete. However, we won’t receive the last yield statement, which is “How are you?” Instead, we will get a response of `{ value: undefined, done: true }`

    { value: 'Hello!', done: false }
    { value: 'John Doe', done: true }
    { value: undefined, done: true }

This is because the returned value becomes the result of the next call on the generator object. Subsequent calls to .next() after the initial return will simply return a `{ value: undefined, done: true }` object, indicating the generator is finished, as seen in the code above. Therefore, when handling the return statement, it is crucial to exercise caution, as its purpose is to terminate the function and return the current value.

Lazy loading data with Generator Function

Generator functions in JavaScript provide an effective way to implement lazy loading by yielding values on demand. This pattern can improve performance, especially when dealing with large data sets or asynchronous data sources (API). 

    function* lazyLoadFunc(data) {
        for (let item of data) {
            yield item * 3;
        }
    }
    // data array
    const numbers = [1, 2, 3, 4, 5];
    
    const lazyData = lazyLoadFunc(numbers);
    
    // process the generator lazily
    for (let printValues of lazyData) {
        console.log(printValues); 
    }

Output 

    3
    6
    9
    12
    15

Creating a custom iterable object with Generator

The Generator function can be used to define an iterable object.

    function* TrackeeEmployeeIterator(employees) {
        for (let employee of employees) {
            yield employee;
        }
    }
    const TrackeeEmployeeDatabase = {
        employees: [
            { id: 1, name: 'Gabriel', role: 'Backend Developer' },
            { id: 2, name: 'Emmanuel', role: 'Graphic Designer' },
            { id: 3, name: 'Jane', role: 'Community Manager' },
            { id: 4, name: 'Lora', role: 'Front-end Developer' },
        ],
        [Symbol.iterator]: function() {
            return TrackeeEmployeeIterator(this.employees);
        }
    };
    
    for (let employee of TrackeeEmployeeDatabase ) {
        console.log(employee);
    }

We start by creating a function `TrackeeEmployeeIterator` that takes an argument for employees. This function is a generator, indicated by the function* syntax. We use a for loop inside this function to iterate over each employee in the employees’ array. The yield keyword returns each employee individually, allowing the generator to produce a sequence of employee objects.

Next, we define an array of employee objects, each with properties: `id, name, and role`. These objects represent individual employees.

To make the object iterable, we add a method `[Symbol.iterator]` to it. This special method returns an iterator created by the `TrackeeEmployeeIterator` generator function, passing in the employees array.

Finally, we use a `for…of` loop to iterate over the `TrackeeEmployeeDatabase` object. This loop utilizes the iterator to access and print each employee object to the console. The output is as shown below:

    { id: 1, name: 'Gabriel', role: 'Backend Developer' }
    { id: 2, name: 'Emmanuel', role: 'Graphic Designer' }
    { id: 3, name: 'Jane', role: 'Community Manager' }
    { id: 4, name: 'Lora', role: 'Front-end Developer' }

There are other useful examples to explore using generator functions, as demonstrated in the MDN Web Docs.

Conclusion 

The generator function offers many advantages to help you write a better function. Let’s illustrate this: Think of a generator function like GraphQL. If you have a compiled list of data and need to display only a few items, GraphQL will help you filter the queried data you need instead of displaying the entire compiled list.

Similarly, the generator function helps you collect data piece by piece. If you have a long list of data and only need the first three items, you can pick them out. If you want to continue with the fourth one, you can resume, as the generator function pauses the data and continues from where you left off.