Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is

getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage()))
in typescript/javascript.

When implementing getSecureStorage, I used a static cipher key to encrypt every key/value pair added to local or session storage.

To enhance security, I decided to generate a new key dynamically after each expiration to prevent potential sharing of the key by users who may access it from the source. This approach requires storing a new cipher key for each unique key/value pair.

createSecureStorage(storage: Storage): Storage { 
    var cipherKeyMap = this.keyMapping;
    let privateState = function() {
        let cipherKey;
        this.encrypt = function(key: string, data: string): string {
          let entry = cipherKeyMap.find(entry => entry.key === key);
          if (entry) {
            cipherKey = entry.cipherKey;
          } else {
            cipherKey = Array.from({length: 16}, () => Math.floor(Math.random() * 90));
            cipherKeyMap.push({"key": key, "cipherKey": cipherKey});
          //...
        };

        this.decrypt = function(key: string, data: string): string {
          //...
        };
    }
    let state = new privateState();

    return {
      setItem(key: string, value: string) {
        //...
      },
      getItem(key: string) {
        //...
      },

      //is triggered from expirableSecureStorage
      removeItem(key: string) {
        storage.removeItem(key);
        cipherKeyMap.splice(cipherKeyMap.findIndex(r => r.key === key), 1);
      }
    } 
  }

This function is applicable for both localStorage and sessionStorage which are of type Storage and also exported as

//lib.dom.d.ts
declare var sessionStorage: Storage;
declare var localStorage: Storage;

This service will be utilized by multiple clients for storing values in these storage facilities.


During the implementation of the createSecureStorage function, I realized that if the passed storage is localStorage, the user's closure of the tab/window would result in wiping out the application state and losing the cipher keys while the related data remains encrypted with those keys in local storage.

Considering this situation, I have two options:

  1. Manage the persistence or clearance of randomly generated cipher keys in case of localStorage.
  2. Store only values encrypted with a static cipher key in localStorage and store the remaining values encrypted by dynamically generated keys in sessionStorage.

I opted for #2 to avoid persisting the cipher keys on the client side due to current security concerns.

In order to differentiate between sessionStorage and localStorage, how can I achieve this?

Answer №1

If you want to determine whether the object you passed is either localStorage or sessionStorage, you can simply compare them directly as objects are compared by reference.

function checkStorage(storage){console.log(storage === localStorage)};
checkStorage(localStorage);
checkStorage(sessionStorage);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Substitute an item with another -JavaScript

While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition ...

Attempting to display an HTML image utilizing data storage

I'm currently working on building a database for animals at an animal shelter. I have created tables containing species information and when a user selects a specific species, all available animals are displayed. Now, I want users to be able to click ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

AngularJS: default radio button selection

I'm currently working on creating a color configurator using AngularJS with radio buttons. Everything seems to be functioning properly - the data binds correctly, etc., but I'm encountering an issue setting the default color radio button as check ...

Utilize React Redux to send state as properties to a component

When my React Redux application's main page is loaded, I aim to retrieve data from an API and present it to the user. The data is fetched through an action which updates the state. However, I am unable to see the state as a prop of the component. It s ...

Problem with file organizer in Angular application - unable to see files and directories

I successfully integrated a file manager component following this tutorial. Despite no errors in vscode or chrome debug tool, my folders are not visible. Can anyone help me troubleshoot this issue? https://i.stack.imgur.com/ihEak.png I am unsure how to r ...

Is there a way to retrieve the widths of several <span> elements at once?

Having a few <span> elements generated dynamically, I need to find out their combined width. Wrapping them in a <div> and using alert($("#spanWrap").width()); resulted in the container's width instead of that of the <span> elements. ...

Tips for connecting data to an HTML page with Angular 2

My code is throwing an error message while I'm debugging: Error: Uncaught (in promise): TypeError: Unable to get property 'standard' of undefined or null reference Here is the relevant part of my code: student.component.ts: this._studentSe ...

Disable image loading for users who have javascript enabled

I find myself caught in a chicken-egg dilemma. The webpage I created contains numerous images that need to be loaded, and so I implemented a script that loads images as the user scrolls, similar to how Facebook or Google Images functions. When the user rea ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Is there a way to deactivate the Interceptor in a exported function?

Utilizing ngx-translator for localization has been a great help, but I've encountered an issue while attempting to access json-files for localization that are stored in a local folder. The error message I receive is HttpErrorResponse {headers: HttpHea ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

What steps can I take to prevent ng-bootstrap modal from automatically centering the content within the modal?

Looking for a solution to a UX issue with my Angular ng-bootstrap modal. The problem arises when displaying messages of varying lengths - if the message is longer than the screen's vertical resolution, it gets centered on the screen. This causes incon ...

Partially accessible Angular service within a callback function

I'm currently facing an issue in my Angular simple app related to a factory that is not fully available within a callback function. You can check out a simplified version of the application on this Plunkr link. Here's a snippet of the code: Th ...

Can Node.js Utilize AJAX, and if So, How?

Coming from a background in browser-based JavaScript, I am looking to dive into learning about node.js. From my current understanding, node.js utilizes the V8 engine as its foundation and offers server-side JavaScript capabilities along with pre-installed ...

JavaScript's search function is encountering issues when working with multidimensional arrays

I have an array containing city names and postal codes that I need to search through. I can successfully search for the city name and retrieve the result, but when I try to search for a postal code, it doesn't register. My question is: How can I modif ...

Mastering Angular: Tackling a Directive with Two Parts

I'm working on a directive that's responsible for embedding footnotes into a body of text while providing popover functionality. The text-notes directive is designed to be placed on a parent element, loading content and its related text notes dyn ...

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...