@work-bee/session

@work-bee/session

Middleware for managing user sessions within the ServiceWorker.

Install

npm install @work-bee/session

Usage

import { compileConfig, strategyCacheFirst } from "@work-bee/core";
import sessionMiddleware, {
  getTokenAuthorization,
  getExpiryJWT,
  setTokenAuthorization,
} from "@work-bee/session";

const session = sessionMiddleware({
  authnMethods: ["POST"],
  authnPathPattern: //auth/login$/,
  authnGetToken: getTokenAuthorization,
  authnGetExpiry: getExpiryJWT,
  authzPathPattern: //api//,
  authzSetToken: setTokenAuthorization,
});

const config = compileConfig({
  strategy: strategyCacheFirst,
  middlewares: [session],
});

Options

OptionTypeDefaultDescription
authnMethodsstring[]HTTP methods for authentication requests
authnPathPatternRegExpPattern matching authentication endpoints
authnGetToken(response) => stringExtract auth token from response
authnGetExpiry(response, token) => numberExtract token expiry timestamp
authzPathPatternRegExpPattern matching endpoints that need authorization
authzSetToken(request, token) => RequestAttach auth token to outgoing request
inactivityPromptEventTypestringEvent type posted before session expiry
postMessage(message) => Promise<void>Function to send messages to clients
unauthnPathPatternRegExpPattern matching logout/unauthenticate endpoints
expiryEventTypestringEvent type posted when session expires

Returns

{ before, afterNetwork, after, activityEvent }

Helper Exports

import {
  getTokenAuthorization,
  getExpiryJWT,
  getExpiryPaseto,
  setTokenAuthorization,
} from "@work-bee/session";
  • getTokenAuthorization(response) — Extracts Bearer token from Authorization header
  • getExpiryJWT(response, token) — Extracts expiry from a JWT token
  • getExpiryPaseto(response, token) — Extracts expiry from a PASETO token
  • setTokenAuthorization(request, token) — Sets the Authorization Bearer header on a request