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

Storing information using the DateRangePicker feature from rsuite - a step-by-step guide

Currently, I am working on storing a date range into an array using DateRangePicker from rsuite. Although my application is functioning correctly, I am encountering some TypeScript errors. How can I resolve this issue? import { DateRangePicker } from " ...

Storing data in a TypeBuffer and then retrieving it from a file can lead to surprising outcomes

Upon executing the following code: var list = new Uint32Array(16); for (var i=0; i<16; ++i) list[i] = i; fs.writeFileSync("list", new Uint8Array(list).buffer); console.log([].slice.call(new Uint32Array(fs.readFileSync("list")))); We anticipate the out ...

Breaking down types in Typescript: Extracting individual types from an object containing multiple objects

Having a query: const queries = { light: { a... b... }, dark: { a... b... c... d... }, The react element requires a colors parameter that corresponds to one of the themes in the above object, with each theme containing a un ...

The issue with MaterialUI Select's set value is that it consistently falls outside the expected

I'm currently working on a MaterialUI Select component where I am dynamically handling the value parameter. However, I'm facing an issue where even though I set a valid value from the available options, it always shows as out of range. SelectInp ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Is CefSharp compatible with JavaScript promises?

I noticed that when I run the JavaScript code below in the console of my browser, it works perfectly fine. However, when I try to use this code in CefSharp, it returns null. I am currently using CefSharp version 100.0.120-pre. Does CefSharp 100.0.120-pre s ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

Getting the error message ""Cannot return null for non-nullable field" while trying to subscribe in NestJS using GraphQL"

I have developed a Node.js backend using Nestjs and incorporating Graphql, with my frontend built on Ionic/Angular utilizing Apollo-angular for graphql functionalities. However, I am encountering difficulties in subscribing to data additions or changes. St ...

Using Vue3 to set attributes on web components

I recently developed a self-contained web component using Vite and Vue3 to replace outdated jQuery libraries. When this component is rendered in HTML, it appears like this: <custom-datepicker id="deliveryTime"> #shadow-root <div> ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

MTG Life counter. Display fluctuations in count

I am currently working on a fun project creating an MTG (Magic The Gathering) life tracker, even though the code is quite messy. Despite its flaws, it still gets the job done. Click here to view the MTG life tracker https://i.stack.imgur.com/Su17J.png ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Experiencing challenges in integrating fundamental Javascript elements on a chat page

My chat page skeleton is in place, but I'm facing challenges in connecting all the pieces. My goal is to send messages to the server whenever a user clicks 'send', and to update the displayed messages every 3 seconds. Any insights, tips, or ...

Using parameters in routes in Angular 4

all I have created a new auxiliary website. Users will be directed to this site from the main site using a reference link like: I have set up the AppRoutingModule as follows: import { NgModule } from '@angular/core'; import { RouterMod ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...

ExtJs encounters missing files in directory - Error: Module '<path>modern-app-3 ode_modules@senchaextpackage.json' not found

I am currently in the process of setting up a new ExtJs project by following the instructions provided here. Upon completing the installation of ext-gen, I proceeded to create a new app using the command ext-gen app -a -t moderndesktop -n ModernApp3, but ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

The website is having trouble reading the local json file accurately

Currently, I have developed an HTML site that utilizes JavaScript/jQuery to read a .json file and PHP to write to it. In addition, there is a C++ backend which also reads and writes to the same .json file. My goal is to transmit the selected button informa ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...