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

@rmg-dev/pkce-utils

v1.0.4

Published

A lightweight utility for implementing PKCE (Proof Key for Code Exchange) with Auth UI, designed for easy integration and secure OAuth flows

Downloads

345

Readme

pkce-utils

A lightweight utility for implementing PKCE (Proof Key for Code Exchange) with Auth UI, designed for easy integration and secure OAuth flows.

npm version license

Table of Contents

Features

  • Easy Integration: Simplifies the implementation of OAuth 2.0 Authorization Code Flow with PKCE in web applications.
  • Secure: Uses high-entropy cryptographic random strings and SHA-256 hashing to enhance security.
  • Lightweight: Minimal dependencies for ease of use and performance.

Installation

Install the package using npm:

npm install @rmg-dev/pkce-utils

Or with yarn:

yarn add @rmg-dev/pkce-utils

Usage

Importing the Library

import {
  redirectToLogin,
  handleCallback,
  Auth,
} from '@rmg-dev/pkce-utils';

Redirecting to the Identity Provider's Login Page

Use the redirectToLogin function to initiate the OAuth 2.0 authorization code flow by redirecting the user to the identity provider's login page.

await redirectToLogin({
  idpUrl: 'https://your-idp.com',
  clientId: 'your-client-id',
  redirectUri: 'https://your-app.com/callback',
  path: '/authorize', // Optional, defaults to '/login'
  scope: 'openid profile email', // Optional, defaults to 'openid'
});

This function will automatically redirect the user to the identity provider's login page with the appropriate query parameters.

Handling the Callback and Exchanging the Authorization Code

After the user authenticates, the identity provider will redirect back to your redirectUri. Use the handleCallback function to handle the callback and exchange the authorization code for tokens.

import { handleCallback, Auth } from '@rmg-dev/pkce-utils';

(async () => {
  try {
    const authData: Auth = await handleCallback({
      idpUrl: 'https://your-idp.com',
      clientId: 'your-client-id',
      redirectUri: 'https://your-app.com/callback',
    });
    console.log(authData);
    // Use authData to access protected resources
  } catch (error) {
    console.error(error);
  }
})();

API Reference

getChallenge

Generates a PKCE code challenge and state parameter for the OAuth 2.0 authorization code flow.

const challenge: Challenge = await getChallenge();

Returns

  • Promise<Challenge>: An object containing state, codeVerifier, and codeChallenge.

redirectToLogin

Initiates the OAuth 2.0 authorization code flow by redirecting the user to the identity provider's login page.

await redirectToLogin(params: RedirectToLogin): Promise<void>

Parameters

  • idpUrl: string - The base URL of the identity provider (IdP).
  • clientId: string - The client identifier issued during registration.
  • redirectUri: string - The URI to which the response will be sent after authorization.
  • path?: string - Optional. The path to the authorization endpoint at the IdP. Defaults to /login.
  • scope?: string - Optional. The scope of the access request. Defaults to openid.

exchangeCode

Exchanges the authorization code for an access token by making a POST request to the identity provider's token endpoint.

const authData: Auth = await exchangeCode(params: ExchangeCode): Promise<Auth>

Parameters

  • code: string - The authorization code received from the authorization server.
  • codeVerifier: string - The code verifier used in the PKCE flow.
  • idpUrl: string - The base URL of the identity provider (IdP).
  • clientId: string - The client identifier issued during registration.
  • redirectUri: string - The URI to which the response was sent after authorization.

Returns

  • Promise<Auth>: An object containing authentication data like access token.

Throws

  • Will throw an error if the token exchange fails or the returned data does not conform to the expected schema.

handleCallback

Handles the OAuth 2.0 callback by extracting the authorization code and state from the URL, retrieving the code verifier from session storage, and exchanging the code for tokens.

const authData: Auth = await handleCallback(params: handleCallback): Promise<Auth>

Parameters

  • idpUrl: string - The base URL of the identity provider (IdP).
  • clientId: string - The client identifier issued during registration.
  • redirectUri: string - The URI to which the response was sent after authorization.

Returns

  • Promise<Auth>: An object containing authentication data like access token.

Throws

  • Will throw an error if the state or code is missing from the URL, the code verifier is missing from session storage, or the token exchange fails.

Types

Challenge

Represents the PKCE challenge data required for the OAuth 2.0 authorization code flow with PKCE.

type Challenge = {
  state: string;
  codeVerifier: string;
  codeChallenge: string;
};
  • state: A random string used to prevent CSRF attacks.
  • codeVerifier: A high-entropy cryptographic random string used to generate the code challenge.
  • codeChallenge: The code challenge derived from the code verifier.

RedirectToLogin

Parameters required to construct the authorization request URL.

type RedirectToLogin = {
  idpUrl: string;
  clientId: string;
  redirectUri: string;
  path?: string; // Defaults to '/login'
  scope?: string; // Defaults to 'openid'
};
  • idpUrl: The base URL of the identity provider.
  • clientId: The client identifier issued during registration.
  • redirectUri: The URI to which the response will be sent after authorization.
  • path: Optional. The path to the authorization endpoint. Defaults to /login.
  • scope: Optional. The scope of the access request. Defaults to openid.

ExchangeCode

Parameters required to exchange an authorization code for an access token.

type ExchangeCode = {
  code: string;
  codeVerifier: string;
  idpUrl: string;
  clientId: string;
  redirectUri: string;
};
  • code: The authorization code received from the authorization server.
  • codeVerifier: The code verifier used in the PKCE flow.
  • idpUrl: The base URL of the identity provider.
  • clientId: The client identifier issued during registration.
  • redirectUri: The URI to which the response was sent after authorization.

handleCallback

Parameters required to handle the OAuth 2.0 callback.

type handleCallback = {
  idpUrl: string;
  clientId: string;
  redirectUri: string;
};
  • idpUrl: The base URL of the identity provider.
  • clientId: The client identifier issued during registration.
  • redirectUri: The URI to which the response was sent after authorization.

Auth

Represents the authentication data received after exchanging the authorization code.

type Auth = {
  accessToken: string;
  idToken?: string;
  refreshToken?: string;
  expiresIn?: number;
  tokenType?: string;
  // Additional fields as per your authSchema
};
  • accessToken: The access token issued by the authorization server.
  • idToken: Optional. The ID token issued by the authorization server.
  • refreshToken: Optional. The refresh token issued by the authorization server.
  • expiresIn: Optional. The lifetime in seconds of the access token.
  • tokenType: Optional. The type of the token issued.

Error Handling

  • Missing State or Code: If the state or code is missing from the callback URL, handleCallback will throw an error.
  • Missing Code Verifier: If the code verifier is missing from session storage, an error is thrown.
  • Token Exchange Failure: If the token exchange fails or the returned data does not conform to the expected schema, an error is thrown with detailed information.

Dependencies

  • Zod: Used for schema validation. Ensure you have it installed as it's listed under peerDependencies.

    npm install zod
  • TypeScript: Type definitions and interfaces.

  • Fetch API: Used for making HTTP requests. You may need a polyfill for environments where Fetch is not available.

Contributing

Contributions are welcome! Please check the repository for issues or create a new one to discuss what you would like to change.

License

This project is licensed under the MIT License.