Chapter 9. Service Workers: Other Applications

Using service workers to control the delivery of third party content or even monitor third party performance is critical. But what about first party resources? Or frontend techniques to improve the performance and security with base page content in general? Service workers can be leveraged in many different ways, including through input validation and geo content control, which are discussed briefly below.

Input Validation

Input validation strategies typically involve client-side JavaScript, server-side logic, or other content delivery network/origin logic in an effort to not only prevent incorrect inputs or entries, but also to prevent malicious content from being injected that could potentially impact a site overall. The problem with some of the above strategies is that a site still remains vulnerable to attacks.

With client-side JavaScript, anyone can look to see what input validation strategies are in place and find a way to work around them for different attacks such as SQL injections, which could impact the end user’s experience. With server-side logic or other content delivery network/origin features, the request has to go to the network before being validated, which could impact performance for the end user.

How can service workers mitigate some of these vulnerabilities? Let’s use the service worker fetch handler to validate the input field and determine whether to forward or block a resource request. Of course service workers can be disabled, as with JavaScript, but it is up to the developer to put backup sever-side strategies in place as a preventative measure.

Benefits of using service workers:

  • Remove the need to have the request go to the network, server, content delivery network, or origin, which removes additional validation delay.

  • Reduce the risk of those requests being intercepted if we block them before even forwarding to the network.

  • Service workers have no DOM access so malicious content is likely not going to be injected to change the page and how it validates form fields.

The below pseudocode in Example 9-1 helps demonstrate how to implement input validation via a service worker. The fetch event can catch the POST request and analyze the fields before submission.

Example 9-1. Fetch event handler for form submission
self.onfetch = function(event) {
    event.respondWith(
    		// get POST request from form submission
    		// analyze fields before submitting to network
    		if input field is valid
    			submit fetch(event.request)
    		else block
    );
};

Geo Content Control

Delivering content to end users based on their specific geography has been critical to business growth. Advanced technology available at the content delivery network or origin has allowed businesses to target end users with content based on their geo locations. But what if we could make that determination at the browser, and then forward the request based on an end user’s geo location? Service workers can help by leveraging the GeoFencing API, which allows web applications to create geographic boundaries around specific locations.

Push notifications can then be leveraged when a user or device enters those areas. But being a browser-specific technique, there is the security concern in spoofing a geo location. With this in mind, it is critical to maintain server-side logic for comparison purposes, whether it exists at the origin or content delivery network, to ensure that geo location data is not tampered with.

This functionality is still relatively new because of the different caveats when accessing an end user’s geo location. But the idea of moving this functionality to the browser, with possible access to an offline cache for geo-specific content, can help eliminate the need to make a decision at the content delivery network or origin, which could help improve performance.

A Closer Look

Let’s take a look at Example 9-2. During service worker registration, different GeoFence regions would be added, along with any additional offline caches for content.

Example 9-2. Register event handler: Adding GeoFences
navigator.serviceWorker.register('serviceworker.js')
    .then((swRegistration) => {
    let region = new CircularGeofenceRegion({
        name: 'myfence',
        latitude: 37.421999,
        longitude: -122.084015,
        radius: 1000
    });
    let options = {
        includePosition: true
    };
swRegistration.geofencing.add(region, options).then(
    // log registration
);
// setup offline cache for geo-specific content
});

Once the service worker is active, it can start listening for users or devices entering or leaving the GeoFence we set up during registration (Example 9-3).

Example 9-3. GeoFence enter event listener
self.ongeofenceenter = (event) => {
    console.log(event.geofence.region.name);
    //if offline cache has region resources -> serve content
};

Because service workers can be disabled, having backend solutions in place is critical. As an additional preventative measure, content delivery networks or the origin can validate geo location and geo-specific content being served back to the end user.

Last Thoughts

Input validation and geo content control are just a couple more service worker applications, but the use cases and applications will continue to increase as we advance with this technology. The idea is to take backend solutions and bring them to the browser in an effort to mitigate some of the common security and performance issues we see today.