npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

auth-worker

v2.0.1

Published

OAuth2 Service Worker handler

Downloads

18

Readme

auth-worker

OAuth2 Service Worker handler

Vulnerabilities Reliability Rating CodeQL npm

Motivation

When it comes to saving credentials in the browser, HttpOnly Cookies are often the preferred method as they are not vulnerable to cross-site scripting (XSS) attacks. However, when using Single Sign-On (SSO), the credentials are usually provided in the form of tokens that are intended to be sent via the Authorization header.

While it may be tempting to simply store these tokens in the browser's localStorage, this can introduce security risks if any third-party code is present or if a user is able to add custom JavaScript to the application. Storing the tokens in regular Cookies may also not be the best solution as it defeats the purpose of using Cookies in the first place.

This library is an implementation of the OAuth2 recommendations for Single Page Applications that uses a Service Worker to store the tokens in SW cache, which is inaccessable to the main app.

Getting started

  1. Installation
  2. Create the service worker
  3. Load the service worker
  4. Use the auth

Installation

npm install auth-worker

Create the service worker

Note: This example shows usage with Google, but the lib supports multiple providers out of the box and custom providers can also be defined.

// service-worker.ts
import { initAuthServiceWorker } from 'auth-worker/worker';
import { google } from 'auth-worker/providers';

initAuthServiceWorker({ google }, '/auth', ['/allowed', '/routes']);

Parameters

| Name | Type | Description | | ----------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | providers | Record<string, IProvider> | The providers that should be used. | | path | string | The path that will be used for the auth endpoints. This should be a path that isn't used for anythin else, so altrough /auth might be the obvious choice, you might need to use something else in your app. | | allowlist | Array<RegExp \| string \| { url: RegExp \| string; methods: Array<'GET' \| 'POST' \| 'PATCH' \| 'PUT' \| 'HEAD' \| 'DELETE'> }> | The allowlist of URLs. Everything is allowed if the array is not passed. | | secret | string? | The secret that will be used as an base for the storage encription. If not set, nothing will be persisted and the login will only work while the service worker is active (in-memory storage). This is the only secure option. If you want better UX and can afford a bit weaker security (basically, security trough obscurity), you can define a secret key here that will be used to encrypt data when writing it to IndexedDB |

Load the service worker

// index.ts
import { loadAuthServiceWorker } from 'auth-worker';

loadAuthServiceWorker({
	google: {
		clientId: 'example-client-id',
		scopes: 'https://www.googleapis.com/auth/userinfo.profile',
	},
}).catch(console.error);

Parameters

| Name | Type | Description | | --------------------- | --------- | ----------------------------------------------------------------------- | | config | IConfig | The providers that should be used. | | options.workerPath? | string | The location of the service worker. Defaults to "./service-worker.js" | | options.scope? | string | The scope opf the service worker. Defaults to "/" | | options.debug? | boolean | Whether to enable debug mode. Defaults to false |

Use the auth

Note: The examples here are using the /auth prefix, but this can be changed in the initAuthServiceWorker function.

  • To log in, use the link in format /auth/login/{provider}. For example, /auth/login/google. After the successful login, the user will be redirected to /.
  • To log out, use the /auth/logout link. After the successful logout, the user will be redirected to /.
  • To get the user info, use the getUserInfo function. For example:
import { getUserInfo } from 'auth-worker';

const userInfo = await getUserInfo();
  • To make an authenticated API call, make sure the wanted API endpoint is allowed in the initAuthServiceWorker function and add the X-Use-Auth header to the request. For example:
const response = await fetch('https://example.com/api', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json',
		'X-Use-Auth': 'true',
	},
	body: JSON.stringify({
		foo: 'bar',
	}),
});

Security considerations

By default, this library will not persist the tokens in the browser. Instead, it will just keep them in memory while the service worker is active. This is the most secure option, but it also means that the user will be logged out when the service worker is terminated (for example, when the browser is closed).

If you want to persist the tokens, you can pass a secret key to the initAuthServiceWorker function. This will enable the storage in IndexedDB, but it will also mean that the tokens will be stored in the browser and it will be accessible to any script that is able to run in the context of your app. This is a bit safer than just keeping it in plaintext, since the encryption key is hardcoded in the service worker and is not accessible to the main app, but it is still not as secure as the in-memory storage because the key can be extracted (e.g., manually by reading the source code of the page).

Credits

Published under the MIT License.

Maintained and sponsored by Infinum.