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

@signalco/auth-server

v0.4.0

Published

## Getting started

Downloads

276

Readme

@signalco/auth-server

Getting started

Initialize and expose functions that you will later use to protect your application.

// file: auth.ts

import { initAuth } from '@signalco/auth-server';

function jwtSecretFactory() {
    const signSecret = process.env.MYAPP_JWT_SIGN_SECRET;
    return Buffer.from(signSecret, 'base64');
}

export const { withAuth, createJwt, setCookie, clearCookie } = initAuth({
    jwt: {
        namespace: 'app',
        issues: 'api',
        audience: 'web',
        jwtSecretFactory: jwtSecretFactory,
    },
    cookie: {
        name: 'auth_session',
        expiry: 60 * 60 * 1000
    },
    getUser: storageGetUser
});

JWT sign secret should be a 256 bit (32 byte) secret key. You can generate one with openssl rand -base64 32. Keep it secret and safe. It should never be exposed to the client or stored in the repository. In example above, it is read from an environment variable where it is saved as Base64 string and decoded when needed. It is advised to cache the decoded secret in a closure to avoid decoding it every time a token is created or verified.

Tip: If you somehow expose the sign secret, you can rotate it by changing the environment variable and restarting the server. This will invalidate all existing tokens and force users to log in again.

Protecting route endpoint with withAuth

When you want to protect a route, you can use withAuth function to wrap your route handler. It will verify the JWT token from the request and pass the user object to your handler if the token is valid. If token is invalid or missing, it will return a 401 Unauthorized response without calling the handler you provided.

import { withAuth } from './auth';

export async function GET() {
    return await withAuth(async (user) => {
        return new Response(JSON.stringify(user), { status: 200 });
    });
};

Protecting server action with auth

When you want to protect a server action, you can use auth function to wrap your action handler. It will verify the JWT token from the request and return user data if the token is valid. If token is invalid or missing, the function will throw an error. You can catch this error and return a 401 Unauthorized response to the client.

import { withAuth } from './auth';

export async function myAction() {
    'use server';

    const { user } = await auth();

    // ... action logic
};

Login

When you authenticate a user, you should create a JWT token and set it as a cookie in the response. You can use createJwt and setCookie functions for that.

import { createJwt, setCookie } from './auth';

// ... login logic (validate user credentials, etc.)

setCookie(createJwt(user.id));

If you want more control over cookie, you can create and set it manually.

import { createJwt } from './auth';

(await cookies()).set(
    'auth_session', // Make sure this matches configured `cookie.name`
    await createJwt(user.id), 
    {
        secure: true,
        httpOnly: true,
        sameSite: 'strict',
        expires: new Date(Date.now() + 60 * 60 * 1000),
    });

Logout

When you want to log out a user, you should clear the JWT cookie. You can use clearCookie function for that.

import { clearCookie } from './auth';

await clearCookie();

Extensions

RBAC

You can implement Role-Based Access Control (RBAC) by wrapping initAuth function with initRbac function. It will override auth and withAuth functions to include role checking.

import { initRbac } from '@signalco/auth-server';

export const { withAuth, createJwt, setCookie, clearCookie } = initRbac(initAuth(...));

You can then use withAuth and auth functions as before, but you can also pass a roles to withAuth function to check if the user has the required role.

export async function GET() {
    return await withAuth(['admin'], async (user) => {
        return new Response(JSON.stringify(user), { status: 200 });
    });
};
import { withAuth } from './auth';

export async function myAction() {
    'use server';

    const { user } = await auth(['admin']);

    // ... action logic
};