@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
Maintainers
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-sdkImport 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.comHow JWKS caching works
- Public keys are fetched from
https://<domain>/.well-known/jwks.jsonon first use - Cached in-process with a 1-hour TTL (configurable via
jwksCacheMaxAge) - Automatically re-fetched when an unknown
kidis encountered (key rotation)
License
MIT
