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

@identigo/node

v0.3.0

Published

Identigo SDK for Node.js backends: access-token + DPoP verification, middleware, management client, webhook verification.

Readme

@identigo/node

Server-side SDK for Identigo, a FAPI 2.0-grade identity provider.

  • Protect your API. Verifies Identigo access tokens (RFC 9068 JWTs) and their DPoP proofs (RFC 9449), with ready-made middleware for Hono and Express and a framework-neutral core for everything else: Fastify, Koa, NestJS, Next.js, SvelteKit, Nuxt, React Router, Bun, Deno, plain node:http.
  • Role, scope and step-up guards (RFC 9470).
  • Management API client for your backend: invite users, manage members, roles and webhooks.
  • Webhook verification (Standard Webhooks).

Signing users in from a browser app? That's @identigo/browser. This package is for the API that app calls.

Contents

Install

npm install @identigo/node
  • Node.js 22.12 or later. The package is ESM. CommonJS projects (including a default NestJS app) can require() it too: Node 22.12+ loads ES modules from require().
  • TypeScript: set "moduleResolution" to "nodenext", "node16" or "bundler". The package only declares its entry points through exports, which the old "node"/"node10" resolution ignores.
  • Runtimes: the token verifier uses only WebCrypto and jose; the webhook helpers use node:crypto. Bun, Deno and Cloudflare Workers (with nodejs_compat) provide that module. Edge runtimes without it — such as Next.js middleware.ts on the Edge runtime — can't load the package.

Using an AI coding agent?

The package ships an Agent Skill at node_modules/@identigo/node/skills/identigo-node/ with the configuration rules, a reference per framework, the Management API, webhooks and a 401 troubleshooting table. Point your agent at its SKILL.md, or copy the folder into your agent's skills directory (for Claude Code, .claude/skills/).

Configuration

Every example below reads three values. Put them in environment variables:

| Variable | Example | What it is | | ------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENTIGO_ISSUER | https://auth.example.com/oidc | Your Identigo issuer. Note the /oidc path. | | IDENTIGO_AUDIENCE | urn:identigo:app:app_1a2b3c4d5e6f7g8h | The API audience of your Identigo app: urn:identigo:app:<clientId>, or the custom API audience if you set one on the app. Tokens for other apps are rejected. | | API_PUBLIC_ORIGIN | https://api.example.com | The origin clients use to call this API, exactly as they type it (scheme, host, port; no path). |

Why API_PUBLIC_ORIGIN? Each DPoP proof is signed for one URL. Behind a load balancer or proxy the Host header your app sees is either different from that URL or controlled by the caller, so the SDK never trusts it: it takes the origin from your configuration and only the path and query from the request. If a proxy strips a path prefix before forwarding (clients call /api/projects, your app sees /projects), also pass pathPrefix: "/api".

In local development http://localhost:3000 is a valid public origin.

Protect an API

Every adapter does the same thing: reject the request with 401 and a standard WWW-Authenticate challenge unless it carries a valid DPoP-bound access token and a fresh proof for this exact method and URL, then hand you the verified token:

interface VerifiedAccessToken {
  sub?: string; // Identigo user id (for machine tokens, the client id)
  clientId?: string; // the app that obtained the token
  roles: string[]; // the user's roles in your app
  attrs: Record<string, string>; // the member's attributes in your app
  scope: string[];
  acr?: string; // assurance level reached, e.g. "urn:identigo:aal2:phr"
  amr: string[]; // sign-in methods used: "pwd", "otp", "hwk", ...
  claims: JWTPayload; // every claim in the token
  dpopBound: boolean;
}

Create the verifier (or the middleware) once, at startup, not per request: it caches the issuer's signing keys and remembers used DPoP proofs.

Express

Works with Express 4 and 5, Connect, and anything else with Node's (req, res, next) signature.

import express from "express";
import { identigoExpress, expressRequireRole, expressRequireStepUp } from "@identigo/node";

const app = express();

app.use(
  "/api",
  identigoExpress({
    issuer: process.env.IDENTIGO_ISSUER!,
    audience: process.env.IDENTIGO_AUDIENCE!,
    publicOrigin: process.env.API_PUBLIC_ORIGIN!,
  }),
);

app.get("/api/me", (req, res) => {
  res.json({ id: req.identigo!.sub, roles: req.identigo!.roles });
});
app.delete("/api/projects/:id", expressRequireRole("admin"), (req, res) => {
  res.sendStatus(204);
});
app.post("/api/payouts", expressRequireStepUp({ level: "passkey" }), (req, res) => {
  res.json({ ok: true });
});

app.listen(3000);

Tell TypeScript about req.identigo once, anywhere in your project:

// types/express.d.ts
import type { VerifiedAccessToken } from "@identigo/node";

declare module "express-serve-static-core" {
  interface Request {
    identigo?: VerifiedAccessToken;
  }
}

Hono

Works on every runtime Hono supports: Node (@hono/node-server), Bun, Deno and Cloudflare Workers.

import { Hono } from "hono";
import { identigoHono, requireRole, requireStepUp, type IdentigoVariables } from "@identigo/node";

const app = new Hono<{ Variables: IdentigoVariables }>();

app.use(
  "/api/*",
  identigoHono({
    issuer: process.env.IDENTIGO_ISSUER!,
    audience: process.env.IDENTIGO_AUDIENCE!,
    publicOrigin: process.env.API_PUBLIC_ORIGIN!,
  }),
);

app.get("/api/me", (c) => {
  const user = c.get("identigo");
  return c.json({ id: user.sub, roles: user.roles });
});
app.delete("/api/projects/:id", requireRole("admin"), (c) => c.body(null, 204));
app.post("/api/payouts", requireStepUp({ level: "passkey" }), (c) => c.json({ ok: true }));

export default app;

On Cloudflare Workers, process.env needs the nodejs_compat flag; otherwise build the middleware from c.env on the first request and reuse it.

Fastify

import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
import {
  authenticate,
  checkRoles,
  createVerifier,
  type AuthFailure,
  type VerifiedAccessToken,
} from "@identigo/node";

declare module "fastify" {
  interface FastifyRequest {
    identigo: VerifiedAccessToken | null;
  }
}

const verifier = createVerifier({
  issuer: process.env.IDENTIGO_ISSUER!,
  audience: process.env.IDENTIGO_AUDIENCE!,
});
const publicOrigin = process.env.API_PUBLIC_ORIGIN!;

/** Fastify's headers as the `get(name)` lookup the SDK expects. */
const headersOf = (request: FastifyRequest) => ({
  get: (name: string) => request.headers[name.toLowerCase()]?.toString() ?? null,
});

function reject(reply: FastifyReply, failure: AuthFailure) {
  return reply.code(failure.status).headers(failure.headers).send(failure.body);
}

const app = Fastify();
app.decorateRequest("identigo", null);

// Protect everything registered inside this plugin.
await app.register(
  async (api) => {
    api.addHook("onRequest", async (request, reply) => {
      const result = await authenticate(
        verifier,
        { method: request.method, url: request.url, headers: headersOf(request) },
        { publicOrigin },
      );
      if (!result.ok) return reject(reply, result);
      request.identigo = result.token;
    });

    api.get("/me", async (request) => ({ id: request.identigo!.sub, roles: request.identigo!.roles }));

    api.delete("/projects/:id", async (request: FastifyRequest, reply) => {
      const denied = checkRoles(request.identigo!, ["admin"]);
      if (denied) return reject(reply, denied);
      return reply.code(204).send();
    });
  },
  { prefix: "/api" },
);

await app.listen({ port: 3000 });

Koa

import Koa, { type Middleware } from "koa";
import Router from "@koa/router";
import { authenticate, checkRoles, createVerifier, type VerifiedAccessToken } from "@identigo/node";

const verifier = createVerifier({
  issuer: process.env.IDENTIGO_ISSUER!,
  audience: process.env.IDENTIGO_AUDIENCE!,
});
const publicOrigin = process.env.API_PUBLIC_ORIGIN!;

const identigo: Middleware<{ identigo: VerifiedAccessToken }> = async (ctx, next) => {
  const result = await authenticate(
    verifier,
    { method: ctx.method, url: ctx.originalUrl, headers: { get: (name) => ctx.get(name) || null } },
    { publicOrigin },
  );
  if (!result.ok) {
    ctx.status = result.status;
    ctx.set(result.headers);
    ctx.body = result.body;
    return;
  }
  ctx.state.identigo = result.token;
  await next();
};

const requireRole =
  (...roles: string[]): Middleware<{ identigo: VerifiedAccessToken }> =>
  async (ctx, next) => {
    const denied = checkRoles(ctx.state.identigo, roles);
    if (!denied) return next();
    ctx.status = denied.status;
    ctx.set(denied.headers);
    ctx.body = denied.body;
  };

const router = new Router<{ identigo: VerifiedAccessToken }>({ prefix: "/api" });
router.use(identigo);
router.get("/me", (ctx) => {
  ctx.body = { id: ctx.state.identigo.sub, roles: ctx.state.identigo.roles };
});
router.delete("/projects/:id", requireRole("admin"), (ctx) => {
  ctx.status = 204;
});

new Koa().use(router.routes()).listen(3000);

NestJS

A guard that verifies the token, plus decorators for roles, step-up and the current user. This uses the default Express platform.

// identigo.guard.ts
import {
  createParamDecorator,
  HttpException,
  Injectable,
  type CanActivate,
  type ExecutionContext,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import type { Request, Response } from "express";
import {
  authenticate,
  checkStepUp,
  checkRoles,
  createVerifier,
  type StepUpOptions,
  type AuthFailure,
  type VerifiedAccessToken,
} from "@identigo/node";

/** `@Roles(["admin", "editor"])`: the user needs at least one of them. */
export const Roles = Reflector.createDecorator<string[]>();
/** `@RequireStepUp({ level: "passkey" })` or `({ maxAge: 300 })`: a stronger or more recent sign-in. */
export const RequireStepUp = Reflector.createDecorator<StepUpOptions>();
/** `@CurrentUser() user: VerifiedAccessToken` */
export const CurrentUser = createParamDecorator(
  (_data: unknown, context: ExecutionContext) =>
    context.switchToHttp().getRequest<Request & { identigo: VerifiedAccessToken }>().identigo,
);

const verifier = createVerifier({
  issuer: process.env.IDENTIGO_ISSUER!,
  audience: process.env.IDENTIGO_AUDIENCE!,
});

@Injectable()
export class IdentigoGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const http = context.switchToHttp();
    const req = http.getRequest<Request & { identigo?: VerifiedAccessToken }>();
    const reject = (failure: AuthFailure): never => {
      http.getResponse<Response>().set(failure.headers);
      throw new HttpException(failure.body, failure.status);
    };

    const result = await authenticate(
      verifier,
      { method: req.method, url: req.originalUrl, headers: { get: (name) => req.get(name) ?? null } },
      { publicOrigin: process.env.API_PUBLIC_ORIGIN! },
    );
    if (!result.ok) return reject(result);
    req.identigo = result.token;

    const targets = [context.getHandler(), context.getClass()];
    const roles = this.reflector.getAllAndOverride(Roles, targets);
    const stepUp = this.reflector.getAllAndOverride(RequireStepUp, targets);
    const denied =
      (roles && checkRoles(result.token, roles)) || (stepUp && checkStepUp(result.token, stepUp));
    if (denied) return reject(denied);
    return true;
  }
}
// projects.controller.ts
import { Controller, Delete, Get, Param, Post, UseGuards } from "@nestjs/common";
import type { VerifiedAccessToken } from "@identigo/node";
import { CurrentUser, IdentigoGuard, RequireStepUp, Roles } from "./identigo.guard";

@Controller("api")
@UseGuards(IdentigoGuard)
export class ProjectsController {
  @Get("me")
  me(@CurrentUser() user: VerifiedAccessToken) {
    return { id: user.sub, roles: user.roles };
  }

  @Delete("projects/:id")
  @Roles(["admin"])
  remove(@Param("id") id: string) {
    return { deleted: id };
  }

  @Post("payouts")
  @RequireStepUp({ level: "passkey" })
  payout() {
    return { ok: true };
  }
}

To protect every route, register it globally instead: app.useGlobalGuards(new IdentigoGuard(app.get(Reflector))). On the Fastify platform, read req.url and req.headers instead of Express's req.originalUrl and req.get(), and set the headers with reply.headers(...).

Next.js (App Router)

Route handlers receive a standard Request, which the SDK accepts directly. Keep the verifier in a server-only module:

// lib/identigo.ts
import "server-only";
import {
  authenticate,
  checkRoles,
  createVerifier,
  type AuthFailure,
  type VerifiedAccessToken,
} from "@identigo/node";

const verifier = createVerifier({
  issuer: process.env.IDENTIGO_ISSUER!,
  audience: process.env.IDENTIGO_AUDIENCE!,
});

const toResponse = (failure: AuthFailure) =>
  Response.json(failure.body, { status: failure.status, headers: failure.headers });

/** Verifies the caller (and that they have one of `roles`, if given). */
export async function authorize(
  request: Request,
  ...roles: string[]
): Promise<{ user: VerifiedAccessToken; error?: never } | { user?: never; error: Response }> {
  const result = await authenticate(verifier, request, { publicOrigin: process.env.API_PUBLIC_ORIGIN! });
  if (!result.ok) return { error: toResponse(result) };
  const denied = checkRoles(result.token, roles);
  if (denied) return { error: toResponse(denied) };
  return { user: result.token };
}
// app/api/projects/[id]/route.ts
import { authorize } from "@/lib/identigo";

export async function GET(request: Request) {
  const { user, error } = await authorize(request);
  if (error) return error;
  return Response.json({ id: user.sub, roles: user.roles });
}

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { error } = await authorize(request, "admin");
  if (error) return error;
  const { id } = await params;
  return Response.json({ deleted: id });
}

Route handlers run on the Node.js runtime by default; don't set export const runtime = "edge" on them. Verify tokens in the route handlers rather than in middleware.ts.

On Vercel, set API_PUBLIC_ORIGIN to the domain your clients call. Preview deployments have their own domains, so give each environment its own value.

Fetch-based frameworks (SvelteKit, Nuxt, React Router, Bun, Deno)

Anything that gives you a Fetch API Request works the same way as Next.js. Reuse the authorize helper above (without the server-only import) and call it with the framework's request object:

// SvelteKit — src/hooks.server.ts (protects every /api route)
import type { Handle } from "@sveltejs/kit/hooks"; // SvelteKit 2: from "@sveltejs/kit"

export const handle: Handle = async ({ event, resolve }) => {
  if (event.url.pathname.startsWith("/api/")) {
    const { user, error } = await authorize(event.request);
    if (error) return error;
    event.locals.identigo = user; // declare `identigo: VerifiedAccessToken` in App.Locals
  }
  return resolve(event);
};
// Nuxt 3/4 (h3 v1) — server/middleware/identigo.ts
import { defineEventHandler, toWebRequest } from "h3";

export default defineEventHandler(async (event) => {
  if (!event.path.startsWith("/api/")) return;
  const { user, error } = await authorize(toWebRequest(event)); // h3 v2: event.req
  if (error) return error;
  event.context.identigo = user;
});
// React Router 7 / Remix — a loader or action
export async function loader({ request }: { request: Request }) {
  const { user, error } = await authorize(request, "admin");
  if (error) throw error;
  return { id: user.sub };
}
// Bun.serve or Deno.serve
export default {
  async fetch(request: Request) {
    const { user, error } = await authorize(request);
    if (error) return error;
    return Response.json({ id: user.sub });
  },
};

Plain node:http

identigoExpress only needs Node's request and response objects:

import { createServer } from "node:http";
import { identigoExpress, type VerifiedAccessToken } from "@identigo/node";

const identigo = identigoExpress({
  issuer: process.env.IDENTIGO_ISSUER!,
  audience: process.env.IDENTIGO_AUDIENCE!,
  publicOrigin: process.env.API_PUBLIC_ORIGIN!,
});

createServer((req, res) => {
  identigo(req, res, (err) => {
    if (err) {
      res.statusCode = 500;
      return res.end();
    }
    const user = (req as typeof req & { identigo: VerifiedAccessToken }).identigo;
    res.setHeader("content-type", "application/json");
    res.end(JSON.stringify({ id: user.sub }));
  });
}).listen(3000);

Any other framework

authenticate(verifier, request, { publicOrigin, pathPrefix? }) is the whole integration. It needs the method, the request URL (absolute or just path and query), and something with a get(name) method for headers. It never throws for a bad token: it resolves to either { ok: true, token } or { ok: false, status, headers, body }, which you send back as-is.

const result = await authenticate(
  verifier,
  { method, url: pathAndQuery, headers: { get: (name) => readHeader(name) ?? null } },
  { publicOrigin },
);
if (!result.ok) return send(result.status, result.headers, result.body);

It does throw for unexpected failures, such as a replay store that's down; let those reach your framework's error handler.

Roles, scopes and step-up

| Check | Hono | Express | Anything else (returns a failure or undefined) | | ------------------------------------- | ------------------------ | ------------------------------- | ------------------------------------------------ | | Has any of the roles | requireRole(...) | expressRequireRole(...) | checkRoles(token, roles) | | Has all the scopes | requireScope(...) | expressRequireScope(...) | checkScopes(token, scopes) | | Signed in strongly enough or recently | requireStepUp(options) | expressRequireStepUp(options) | checkStepUp(token, options) |

  • Roles are the user's roles in your app, managed in the Identigo console or with the Management API. Use them for user-facing permissions.

  • Scopes suit machine-to-machine callers.

  • Step-up asks for more proof before a sensitive action:

    | Option | Means | | ------------------ | ------------------------------------------------------------------- | | level: "mfa" | Signed in with two factors, such as a password and a one-time code. | | level: "passkey" | Signed in with a passkey or security key, which can't be phished. | | maxAge: 300 | Signed in (or confirmed it's them) within the last 300 seconds. |

    Combine them if you like: requireStepUp({ level: "passkey", maxAge: 300 }). When the user falls short, the API answers 401 with a standard challenge (RFC 9470), and @identigo/browser sends them to Identigo to confirm and back to the same page — the browser app writes no code for it. See step-up in @identigo/browser. (requireAcr(min) still works; requireStepUp is the same check with plainer options.)

Roles shown in the browser are for display; always enforce them here, on the server.

Calling your API from a browser (CORS)

If a single-page app on another origin calls your API, allow the two headers every request carries, and expose the challenge header so the app can read step-up requests:

// Express — the cors package
app.use(
  cors({
    origin: "https://app.example.com",
    allowedHeaders: ["Authorization", "DPoP", "Content-Type"],
    exposedHeaders: ["WWW-Authenticate", "DPoP-Nonce"],
  }),
);

// Hono — hono/cors
app.use(
  "/api/*",
  cors({
    origin: "https://app.example.com",
    allowHeaders: ["Authorization", "DPoP", "Content-Type"],
    exposeHeaders: ["WWW-Authenticate", "DPoP-Nonce"],
  }),
);

Register CORS before the Identigo middleware, so preflight OPTIONS requests are answered without a token. No cookies are involved, so you don't need credentials.

Running more than one instance

Every DPoP proof can be used once. The default replay store lives in process memory, so with several instances (or serverless functions) a stolen proof could be replayed against a different instance within its 60-second lifetime. Share the store:

import { createClient } from "redis";
import { identigoExpress, type ReplayStore } from "@identigo/node";

const redis = await createClient({ url: process.env.REDIS_URL }).connect();

const replayStore: ReplayStore = {
  // SET NX succeeds only for the first request that uses this proof.
  async checkAndStore(key, ttlSeconds) {
    return (await redis.set(key, "1", { NX: true, EX: ttlSeconds })) === "OK";
  },
};

app.use("/api", identigoExpress({ issuer, audience, publicOrigin, replayStore }));

Any store with an atomic "insert if absent, with expiry" works: a MongoDB collection with a unique key and a TTL index, Postgres INSERT … ON CONFLICT DO NOTHING, DynamoDB conditional writes.

Management API

Lets your backend administer your own app: invite users, manage members and their roles, define roles, and register webhooks. It authenticates as a machine (m2m) app with a private key — there are no client secrets.

One-time setup:

  1. Generate an ES256 key pair, keep the private JWK in your secret store:

    import { exportJWK, generateKeyPair } from "jose";
    
    const { publicKey, privateKey } = await generateKeyPair("ES256", { extractable: true });
    const kid = `backend-${new Date().toISOString().slice(0, 7)}`;
    console.log("public (register in Identigo):", JSON.stringify({ ...(await exportJWK(publicKey)), kid }));
    console.log("private (secret store only):", JSON.stringify({ ...(await exportJWK(privateKey)), kid }));
  2. In the Identigo console, create an app of type Machine (m2m) that manages your app, paste the public JWK, and grant only the scopes it needs: manage:members:read, manage:members:write, manage:roles:read, manage:roles:write, manage:users:invite, manage:webhooks.

Use it — create one client per process and share it; it caches its access token:

import { ManagementClient, ManagementApiError } from "@identigo/node";

export const identigoAdmin = new ManagementClient({
  origin: "https://auth.example.com", // the Identigo host, without /oidc
  clientId: process.env.IDENTIGO_M2M_CLIENT_ID!,
  privateKey: JSON.parse(process.env.IDENTIGO_M2M_PRIVATE_JWK!),
  scopes: ["manage:members:read", "manage:members:write", "manage:users:invite"],
});

// Invite someone. The response is the same whether or not they already have an Identigo account;
// they become a member when they accept the emailed link.
await identigoAdmin.invite({ email: "[email protected]", roles: ["editor"] });

// Every member, across pages.
for await (const member of identigoAdmin.members()) {
  console.log(member.userId, member.user?.email, member.roles, member.status);
}

// Change an existing member. This replaces roles, attributes and status.
try {
  await identigoAdmin.upsertMember(userId, { roles: ["viewer"], status: "suspended" });
} catch (err) {
  if (err instanceof ManagementApiError && err.status === 404) {
    // not a member of this app
  } else throw err;
}

In Next.js, put the client in a server-only module. In NestJS, provide it once:

@Module({
  providers: [
    {
      provide: ManagementClient,
      useFactory: () =>
        new ManagementClient({
          origin: process.env.IDENTIGO_ORIGIN!,
          clientId: process.env.IDENTIGO_M2M_CLIENT_ID!,
          privateKey: JSON.parse(process.env.IDENTIGO_M2M_PRIVATE_JWK!),
          scopes: ["manage:members:read"],
        }),
    },
  ],
  exports: [ManagementClient],
})
export class IdentigoModule {}

Suspending or removing a member stops their token refreshes for your app straight away; access tokens they already hold stay valid until they expire (5 minutes by default).

Webhooks

Identigo can notify your backend when something changes: user.updated, user.deleted, membership.created, membership.updated, membership.deleted, session.revoked. Create a webhook in the console (or with identigoAdmin.createWebhook(...)) and store the whsec_… secret it shows you once.

verifyWebhook(secret, headers, rawBody) checks the signature and timestamp and returns the parsed event, or throws WebhookVerificationError. It needs the body exactly as received: parsing JSON and serialising it again changes the bytes and breaks the signature.

type IdentigoEvent = { type: string; timestamp: string; data: Record<string, unknown> };

Express — take the raw body for this route only, before any global express.json():

import { verifyWebhook, WebhookVerificationError } from "@identigo/node";

app.post("/webhooks/identigo", express.raw({ type: "application/json" }), (req, res) => {
  let event: IdentigoEvent;
  try {
    event = verifyWebhook(
      process.env.IDENTIGO_WEBHOOK_SECRET!,
      { get: (name) => req.get(name) ?? null },
      req.body.toString("utf8"),
    );
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.sendStatus(400);
    throw err;
  }
  queue.add(event); // answer quickly, process in the background
  res.sendStatus(204);
});

Hono:

app.post("/webhooks/identigo", async (c) => {
  try {
    const event = verifyWebhook<IdentigoEvent>(
      process.env.IDENTIGO_WEBHOOK_SECRET!,
      c.req.raw.headers,
      await c.req.text(),
    );
    queue.add(event);
    return c.body(null, 204);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return c.body(null, 400);
    throw err;
  }
});

Next.js (app/api/webhooks/identigo/route.ts), and any other Fetch-based framework:

import { verifyWebhook, WebhookVerificationError } from "@identigo/node";

export async function POST(request: Request) {
  try {
    const event = verifyWebhook<IdentigoEvent>(
      process.env.IDENTIGO_WEBHOOK_SECRET!,
      request.headers,
      await request.text(),
    );
    await queue.add(event);
    return new Response(null, { status: 204 });
  } catch (err) {
    if (err instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw err;
  }
}

Fastify — keep the body as a string inside the webhook plugin:

await app.register(async (hooks) => {
  hooks.addContentTypeParser("application/json", { parseAs: "string" }, (_req, body, done) =>
    done(null, body),
  );
  hooks.post("/webhooks/identigo", async (request, reply) => {
    const event = verifyWebhook<IdentigoEvent>(
      process.env.IDENTIGO_WEBHOOK_SECRET!,
      headersOf(request),
      request.body as string,
    );
    queue.add(event);
    return reply.code(204).send();
  });
});

NestJS — create the app with NestFactory.create(AppModule, { rawBody: true }), then:

@Post("webhooks/identigo")
@HttpCode(204)
receive(@Req() req: RawBodyRequest<Request>) {
  const event = verifyWebhook<IdentigoEvent>(
    process.env.IDENTIGO_WEBHOOK_SECRET!,
    { get: (name) => req.get(name) ?? null },
    req.rawBody!.toString("utf8"),
  );
  this.queue.add(event);
}

Deliveries are retried for up to 24 hours, so handle each event idempotently. Treat an event as a prompt to re-read the current state with the Management API before doing anything destructive.

Troubleshooting

The error_description in a 401 body says what failed.

| Message | Usual cause | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | DPoP htu mismatch | publicOrigin doesn't match the URL the client called, or a proxy strips a path prefix (set pathPrefix). | | Access token invalid: unexpected "aud" … | audience isn't your app's API audience, or the token belongs to a different Identigo app. | | Access token invalid: unexpected "iss" … | issuer must include /oidc and match exactly, including https. | | DPoP-bound token presented as Bearer | The client sent Authorization: Bearer. Use @identigo/browser's identigo.fetch(), which sends Authorization: DPoP and a proof. | | DPoP proof missing | A proxy or CORS configuration dropped the DPoP header. | | DPoP proof replayed | The client retried a request with the same proof. Each request needs a fresh one, which identigo.fetch() does for you. | | DPoP proof invalid: "iat" claim timestamp … | The client's or server's clock is more than 30 seconds out. |

Security notes

  • Why DPoP. Identigo access tokens are sender-constrained (cnf.jkt): every request carries a fresh proof signed by the client's private key, bound to the HTTP method, URL and token. A leaked token alone is useless. The verifier rejects DPoP-bound tokens presented as Bearer, and by default rejects unbound tokens altogether (requireDpop: true).
  • publicOrigin is mandatory. The proof is bound to the URL the client called (htu). Behind a proxy, Host / X-Forwarded-* are attacker-controllable or simply differ from the public URL, so the middleware never derives the origin from the request; only the path and query are taken from it.
  • Replay detection. DPoP proofs are single-use. The default MemoryReplayStore is per process — pass a shared replayStore when you run more than one instance.
  • Pinned algorithms and token type. Access tokens must be typ: at+jwt signed with ES256, EdDSA or PS256; ID tokens, alg: none and HMAC tokens are rejected. Keys come from the issuer's JWKS with caching and rotation handling.
  • Management credentials. Machine clients authenticate with private_key_jwt — no shared secrets. The private key is imported non-extractable, and each ManagementClient binds its tokens to its own freshly generated, non-extractable DPoP key. Tokens are held in memory only.
  • Step-up. requireStepUp answers 401 with WWW-Authenticate: DPoP error="insufficient_user_authentication", acr_values="…", max_age="…" (RFC 9470); the browser SDK performs the step-up automatically.

API reference

Verification

| Export | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | createVerifier(options) | Returns verify(request) → Promise<VerifiedAccessToken>. Options: issuer, audience, keys?, requireDpop? (true), clockToleranceSeconds? (30), dpopMaxAgeSeconds? (60), replayStore?. | | VerifiedAccessToken | { sub?, clientId?, scope[], roles[], attrs, acr?, amr[], authTime?, claims, dpopBound } | | TokenVerificationError | code (invalid_token, invalid_dpop_proof, …) and wwwAuthenticate for the 401 challenge. | | ReplayStore, MemoryReplayStore | checkAndStore(key, ttlSeconds) → Promise<boolean>. |

Middleware

Options for every adapter: publicOrigin, pathPrefix?, and either verifier or the createVerifier options.

| Export | Description | | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | identigoHono(options) | Verifies the request; 401 on failure; sets c.get("identigo"). | | requireRole(...roles) / requireScope(...scopes) | Hono guards: 403 unless any role / all scopes. | | requireStepUp({ level?, maxAge? }) / requireAcr(min) | Hono step-up guards: RFC 9470 401 unless the sign-in is strong enough and recent enough. | | getHonoAuth(c) | The verified token for a Hono context. | | identigoExpress(options) | Express/Connect/node:http middleware; sets req.identigo. | | expressRequireRole / expressRequireScope / expressRequireStepUp / expressRequireAcr | Express guards with the same semantics. | | authenticate(verifier, request, urlOptions) | Framework-agnostic: { ok: true, token } or { ok: false, status, headers, body }. | | checkRoles, checkScopes, checkStepUp, checkAcr | Framework-agnostic guards returning an AuthFailure or undefined. | | acrSatisfies(acr, min), ACR_LEVELS | urn:identigo:aal1 < aal2 < aal2:phr < aal3; short forms ("aal2:phr") and "mfa" / "passkey" accepted. | | publicUrl(requestUrl, urlOptions) | The URL used for the DPoP htu check. |

ManagementClient

Constructor: { origin, clientId, privateKey, kid?, scopes, issuer?, refreshSkewSeconds?, fetch?, timeoutMs? }.

| Method | Route | Scope | | --------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------ | | getAppId() | (token app_id claim) | — | | getApp() | GET /apps/:appId | any | | listRoles() / createRole(input) | GET / POST /apps/:appId/roles | manage:roles:read / manage:roles:write | | updateRole(key, input) / deleteRole(key) | PATCH / DELETE /apps/:appId/roles/:key | manage:roles:write | | listMembers({ cursor?, limit? }) / members() | GET /apps/:appId/members (page / async iterator) | manage:members:read | | upsertMember(userId, { roles?, attributes?, status? }) | PUT /apps/:appId/members/:userId (existing members) | manage:members:write | | removeMember(userId) | DELETE /apps/:appId/members/:userId | manage:members:write | | invite({ email, name?, roles?, attributes? }) | POST /apps/:appId/invitations | manage:users:invite | | listWebhooks() / createWebhook(input) / deleteWebhook(id) | /apps/:appId/webhooks | manage:webhooks | | request(method, path, body?) | any path under /api/v1/manage | — | | getAccessToken() / clearToken() | token cache | — |

Non-2xx responses throw ManagementApiError (status, code, message, body).

Webhooks

verifyWebhook(secret, headers, rawBody, now?) → parsed payload, or throws WebhookVerificationError (bad signature, missing headers, timestamp outside WEBHOOK_TOLERANCE_SECONDS). signWebhook(secret, id, timestamp, body) produces the signature header.

Development

Inside the monorepo the package is consumed as TypeScript source (exports → src/index.ts), so the server and tests need no build step. npm run build emits ESM + .d.ts to dist/. npm pack / npm publish run prepack, which builds and points exports at dist/ for the tarball (postpack restores the source entry). Releases are published from CI only, with npm trusted publishing — see docs/runbooks/release-sdks.md.

Licence

MIT