@benefi/auth
v1.0.6
Published
@benefi/auth ============
Keywords
Readme
@benefi/auth
Typed JWT verifier with AWS Secrets Manager rotation support.
This package provides a small helper around jsonwebtoken and AWS Secrets Manager to verify JWTs that are signed with a secret stored in Secrets Manager, with built‑in support for secret rotation (tries AWSCURRENT first, then AWSPREVIOUS) and structured error codes.
Installation
npm install @benefi/auth
# or
yarn add @benefi/authWhen to use this package
- You store your JWT secret in AWS Secrets Manager.
- You rotate the secret using version stages (
AWSCURRENT/AWSPREVIOUS). - You want a simple verifier function that returns typed success/error results instead of throwing.
Quick start
import { createTokenVerifier } from "@benefi/auth";
// Option 1: pass a Secrets Manager secret ID string
const verifyToken = createTokenVerifier("my-jwt-secret-id");
// Option 2: pass a config object
// const verifyToken = createTokenVerifier({
// secretId: "my-jwt-secret-id",
// region: "us-east-1", // optional, defaults to us-east-1
// });
const result = await verifyToken(tokenFromRequest);
if (!result.success) {
// Use result.error.code to decide response status / message
// e.g. TOKEN_REQUIRED, TOKEN_EXPIRED, INVALID_TOKEN, SECRET_FETCH_FAILURE
console.error(result.error);
// return res.status(401).json({ error: result.error });
} else {
// Decoded JWT payload with a stable shape
const { customerId, iat, exp } = result.data;
// Attach to request context, etc.
// req.customerId = customerId;
}API
createTokenVerifier(secretOrConfig: SecretInput): (token: string) => Promise<VerifyResult>
Creates an async verifier function that you can call with a JWT string.
secretOrConfig(SecretInput)string: treated as an AWS Secrets ManagerSecretId, region defaults tous-east-1.{ secretId: string; region?: string }: explicitly configure the secret id and AWS region.
- Return value: an async function
verify(token: string): Promise<VerifyResult>.
The returned verify function:
- Validates that
tokenis a non‑empty string. - Fetches the secret from AWS Secrets Manager:
- First with version stage
AWSCURRENT. - If verification fails for any reason other than
TokenExpiredError, retries withAWSPREVIOUS.
- First with version stage
- Verifies the token using
jsonwebtoken. - Maps the decoded payload into a stable
DecodedJwtshape:customerId: stringiat: numberexp: number
- Returns a typed
VerifyResultinstead of throwing.
Types
These types are re‑exported from the main entry point:
SecretInputtype JwtSecretConfig = { secretId: string; region?: string; }; type SecretInput = string | JwtSecretConfig;DecodedJwttype DecodedJwt = { customerId: string; iat: number; exp: number; };ErrorCodetype ErrorCode = | "TOKEN_REQUIRED" | "TOKEN_EXPIRED" | "INVALID_TOKEN" | "SECRET_FETCH_FAILURE";VerifySuccesstype VerifySuccess = { success: true; data: DecodedJwt; token: string; };VerifyErrortype VerifyError = { success: false; error: { code: ErrorCode; message: string; }; };VerifyResulttype VerifyResult = VerifySuccess | VerifyError;
You can also import ERROR_CODES for convenience:
import { ERROR_CODES } from "@benefi/auth";
if (!result.success && result.error.code === ERROR_CODES.TOKEN_EXPIRED) {
// handle expired token branch
}AWS configuration
This package uses @aws-sdk/client-secrets-manager under the hood. Make sure your environment is configured so the AWS SDK can authenticate:
- Environment variables (e.g.
AWS_REGION,AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN), or - Instance/role credentials (e.g. EC2 instance profile, ECS task role, Lambda execution role).
If no region is provided in JwtSecretConfig, the package defaults to "us-east-1" (DEFAULT_AWS_REGION).
Error handling
The verifier never throws for expected validation failures; instead it returns a VerifyError:
TOKEN_REQUIRED– token is missing, empty, or not a string.TOKEN_EXPIRED–jsonwebtokenreportedTokenExpiredErrorwhile verifying with the current secret.INVALID_TOKEN– verification failed with both current and previous secrets (bad token, bad signature, wrong algorithm, etc.).SECRET_FETCH_FAILURE– issues talking to Secrets Manager (e.g. permissions, missing secret, invalid response). The error message will contain the underlying AWS error when available.
Use these codes to decide what HTTP status code and response body to send from your API.
License
MIT
