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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@authaction/node-sdk

v0.2.0

Published

AuthAction backend SDK for Node.js — verify tokens you receive, obtain the ones you need. Express, Fastify, NestJS, Apollo GraphQL, and MCP servers

Readme

@authaction/node-sdk

Backend SDK for Node.js. Two halves:

  • Verify the tokens your service receives, via JWKS — key fetching, caching and rotation are handled for you.
  • Obtain the tokens your service needs to call onward, including acting on a person's behalf.

Works with Express, Fastify, NestJS, Apollo GraphQL, and any Node service — including MCP servers.

Installation

npm install @authaction/node-sdk

Import paths

| Path | Framework | |---|---| | @authaction/node-sdk | Core verifier and token client (any Node.js app) | | @authaction/node-sdk/express | Express middleware | | @authaction/node-sdk/fastify | Fastify plugin / hook | | @authaction/node-sdk/nestjs | NestJS module + guard | | @authaction/node-sdk/apollo | Apollo GraphQL context |


Core

import { createVerifier } from '@authaction/node-sdk';

const verifier = createVerifier({
  domain:   process.env.AUTHACTION_DOMAIN!,   // e.g. myapp.eu.authaction.com
  audience: process.env.AUTHACTION_AUDIENCE!, // e.g. https://api.myapp.com
});

// Verify a raw token — throws JWTExpired / JWTClaimValidationFailed on failure
const payload = await verifier.verifyToken(token);

// Verify from Authorization header — returns null on missing/invalid, never throws
const payload = await verifier.verifyRequest(req);

Acting on a user's behalf

A service that calls an API for someone — an MCP server, a job runner, an AI agent — has usually had one option: a static service credential that says nothing about who asked. The resulting audit trail records the service, and the person disappears.

exchangeToken trades the person's token for a short-lived one that names both (RFC 8693). The issued token keeps them as sub and records your service in act, so the API — and the audit log — can see who authorised the call and what carried it out.

import { createClient } from '@authaction/node-sdk';

const client = createClient({
  domain:       process.env.AUTHACTION_DOMAIN!,
  clientId:     process.env.AUTHACTION_CLIENT_ID!,
  clientSecret: process.env.AUTHACTION_CLIENT_SECRET!,
});

// The user's token arrives with the request you are handling.
const { access_token } = await client.exchangeTokenForUser(
  userToken,
  ['https://api.myapp.com'],
);

// Call onward. The API sees sub = the user, act = this service.
await fetch('https://api.myapp.com/payouts', {
  headers: { Authorization: `Bearer ${access_token}` },
});

The issued token is short-lived and never outlives the token it came from, so revoking someone's session also kills anything derived from it.

The subject token does not have to be issued by AuthAction. Register your own identity provider — Okta, Entra ID, Google Workspace, Auth0 — under Identity Providers in the dashboard, and tokens your team already holds can be exchanged directly, with no change to how they sign in.

Caching the actor token

exchangeTokenForUser makes two calls: one for your service's own identity, one for the exchange. A service doing this per request should hold the first and call exchangeToken directly.

const actor = await client.getM2MToken(['https://api.myapp.com']); // cache until expiry

const { access_token } = await client.exchangeToken({
  subjectToken: userToken,
  actorToken:   actor.access_token,
  audience:     ['https://api.myapp.com'],
  scope:        'payouts:read', // optional — may only narrow what the user already has
});

Omitting actorToken performs impersonation instead: the issued token carries no act claim and is indistinguishable from the user acting alone. It is never done implicitly — leaving it out is how you ask for it.

Without a stored secret

A clientSecret sitting in an environment variable is long-lived, and it says nothing about which workload is using it — which undoes most of what a short-lived delegated token buys you.

If your service runs somewhere that issues its own identity — Kubernetes, GitHub Actions, EKS, GKE, or anything speaking SPIFFE — present that instead. Register the workload once in the dashboard against your agent application, then drop the secret entirely:

import { createClient, workloadTokenFromFile } from '@authaction/node-sdk';

const client = createClient({
  domain: process.env.AUTHACTION_DOMAIN!,
  // Kubernetes projected service-account token, read fresh per request
  clientAssertion: workloadTokenFromFile(),
});

clientId and clientSecret are both unnecessary here — the credential identifies the workload, and AuthAction resolves it to your agent.

Pass a function, not a string. The platform rewrites these credentials as they rotate — the kubelet rewrites the service-account token roughly hourly — so a string read once at startup stops verifying part-way through the day. workloadTokenFromFile() re-reads on every request; any () => Promise<string> works the same way.

// GitHub Actions
const client = createClient({
  domain: process.env.AUTHACTION_DOMAIN!,
  clientAssertion: async () => {
    const res = await fetch(
      `${process.env.ACTIONS_ID_TOKEN_REQUEST_URL}&audience=authaction`,
      { headers: { Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` } },
    );
    return (await res.json()).value;
  },
});

Only applications registered as agents may exchange tokens, and a workload identity can only be bound to one — an ordinary service client cannot gain the ability to act for users this way.

Calling as the service itself

const { access_token } = await client.getM2MToken(['https://api.myapp.com']);

Errors

Failed token requests throw AuthActionTokenError, carrying the HTTP status and the OAuth2 code where the server supplied one.

import { AuthActionTokenError } from '@authaction/node-sdk';

try {
  await client.exchangeToken({ subjectToken: userToken });
} catch (e) {
  if (e instanceof AuthActionTokenError && e.code === 'invalid_grant') {
    // The user's token expired — send them back through login.
  }
}

Express

import express from 'express';
import { createVerifier } from '@authaction/node-sdk';
import { jwtMiddleware, requireAuth } from '@authaction/node-sdk/express';

const app = express();
const verifier = createVerifier({ domain, audience });

// Protect all routes under /api
app.use('/api', jwtMiddleware(verifier));

// Protect a single route
app.get('/protected', requireAuth(verifier), (req, res) => {
  res.json({ sub: req.user?.sub });
});

// Optional auth (passes through without token, sets req.user if present)
app.use(jwtMiddleware(verifier, { required: false }));

req.user is populated with the decoded JWT payload on success.


Fastify

import Fastify from 'fastify';
import { createVerifier } from '@authaction/node-sdk';
import { jwtPlugin, jwtHook } from '@authaction/node-sdk/fastify';

const app = Fastify();
const verifier = createVerifier({ domain, audience });

// Option A — global plugin (protects all routes)
await app.register(jwtPlugin(verifier));

// Option B — per-route hook
app.get('/protected', { onRequest: jwtHook(verifier) }, (req, reply) => {
  reply.send({ sub: (req as any).user?.sub });
});

// Option C — optional auth
app.addHook('onRequest', jwtHook(verifier, { required: false }));

NestJS

// app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthActionModule, AuthActionGuard } from '@authaction/node-sdk/nestjs';

@Module({
  imports: [
    AuthActionModule.forRoot({
      domain:   process.env.AUTHACTION_DOMAIN!,
      audience: process.env.AUTHACTION_AUDIENCE!,
    }),
  ],
  providers: [
    { provide: APP_GUARD, useClass: AuthActionGuard }, // protect all routes globally
  ],
})
export class AppModule {}
// messages.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Public, CurrentUser } from '@authaction/node-sdk/nestjs';
import type { TokenPayload } from '@authaction/node-sdk';

@Controller('messages')
export class MessagesController {
  @Get('public')
  @Public()                                         // opt out of auth
  publicMessage() {
    return { message: 'Public' };
  }

  @Get('protected')
  protectedMessage(@CurrentUser() user: TokenPayload) {
    return { message: 'Protected', sub: user.sub };
  }
}

Apollo GraphQL

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { createVerifier } from '@authaction/node-sdk';
import { apolloContext, requireUser } from '@authaction/node-sdk/apollo';

const verifier = createVerifier({ domain, audience });

const server = new ApolloServer({ typeDefs, resolvers });

await startStandaloneServer(server, {
  context: apolloContext(verifier), // injects { user: TokenPayload | null }
});
// In a resolver
const resolvers = {
  Query: {
    me(_parent, _args, context) {
      const user = requireUser(context); // throws UNAUTHENTICATED if user is null
      return { sub: user.sub };
    },
  },
};

Token payload

interface TokenPayload {
  sub: string;            // user or M2M client identifier
  iss: string;            // issuer
  aud: string | string[]; // audience
  exp: number;            // expiry (Unix seconds)
  iat: number;            // issued-at (Unix seconds)
  scope?: string;         // space-separated scopes
  [key: string]: unknown; // any additional claims
}

Environment variables

| Variable | Used by | Example | |---|---|---| | AUTHACTION_DOMAIN | both | myapp.eu.authaction.com | | AUTHACTION_AUDIENCE | verifier | https://api.myapp.com | | AUTHACTION_CLIENT_ID | token client | your application's client id | | AUTHACTION_CLIENT_SECRET | token client | your application's client secret (omit when using a workload credential) |

AUTHACTION_DOMAIN=your-tenant.eu.authaction.com
AUTHACTION_AUDIENCE=https://api.your-app.com

How JWKS caching works

  • Public keys are fetched from https://<domain>/.well-known/jwks.json on first use
  • Cached in-process with a 1-hour TTL (configurable via jwksCacheMaxAge)
  • Automatically re-fetched when an unknown kid is encountered (key rotation)

License

MIT