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

@shukoi/auth

v1.0.4

Published

Enterprise multi-strategy authentication (JWKS, API Key, Session Cookie, OIDC) and declarative RBAC/ABAC authorization for Shukoi.

Readme

@shukoi/auth

Enterprise Multi-Strategy Authentication & Declarative RBAC/ABAC Authorization for Shukoi

npm version License: MIT

@shukoi/auth delivers modular, production-ready identity management and granular access control for Shukoi REST APIs and Model Context Protocol (MCP) agents without vendor lock-in.


Key Features & Invariants

  • 🔐 Multi-Strategy Resolution: Seamlessly orchestrates JWT/JWKS, Hashed API Keys, HMAC-Signed Session Cookies, and RFC 7662 OIDC Token Introspection in a single composable resolver.
  • 🛡️ Declarative RBAC & ABAC: Action-level security guards enforcing roles, capability permissions, and dynamic tenant/ownership policies, eliminating Broken Object Level Authorization (BOLA/IDOR) risks.
  • ⚡ $O(1)$ Pre-Hashed Static API Keys: Static API keys are pre-hashed with SHA-256 at factory initialization, providing true $O(1)$ constant-time lookup immune to loop-position timing attacks.
  • 🚀 Single-Flight JWKS & Keystore Caching: Coalesces concurrent in-flight JWKS fetches into one outbound request and caches the instantiated createLocalJWKSet keystore, eliminating per-verification rebuilds.
  • 🛡️ Zero Memory Leaks in OIDC Introspection: Caches active token introspection decisions via an internal BoundedLruCache (cap: 5,000 entries) with TTL expiration, eliminating heap exhaustion under traffic floods.
  • 🌐 Pure Web-Standard Engine: Zero node:* imports; 100% compatible with Cloudflare Workers V8 Isolates, AWS Lambda, Bun, and Node.js.
  • 🧪 Testing Harness: Includes MockSessionStore, MockApiKeyStore, and credential fixtures in @shukoi/auth/testing.

Installation

pnpm add @shukoi/auth @shukoi/core jose

Strategy Configurations

1. Cached JWKS Strategy (OIDC / Auth0 / Clerk / Supabase)

Verifies standard Bearer JWT tokens against a remote JSON Web Key Set:

import { createJwksStrategy } from '@shukoi/auth';

const jwksStrategy = createJwksStrategy({
  jwksUri: 'https://auth.example.com/.well-known/jwks.json',
  allowedAlgorithms: ['RS256', 'ES256'],
  issuer: 'https://auth.example.com/',
  audience: 'https://api.example.com',
  cacheTtlMs: 300_000, // 5 minutes local keystore cache
  fetchTimeoutMs: 5000, // 5 seconds fetch timeout
});

2. Hashed API Key Strategy (Static & Dynamic Stores)

Supports both $O(1)$ pre-hashed static keys (for machine-to-machine integrations) and dynamic database-backed stores:

import { createHashedApiKeyStrategy } from '@shukoi/auth';

// Option A: Static API Keys (pre-hashed at initialization)
const staticApiKeyStrategy = createHashedApiKeyStrategy({
  apiKeyHeaderName: 'x-api-key',
  staticKeys: {
    sk_live_abc123456789: {
      user: { id: 'service_worker_1', role: 'service' },
      scopes: ['invoices:read', 'invoices:write'],
    },
  },
});

// Option B: Database / Dynamic API Key Store
const dynamicApiKeyStrategy = createHashedApiKeyStrategy({
  apiKeyHeaderName: 'x-api-key',
  store: {
    async findByKeyHash(keyHash) {
      // Look up key by SHA-256 hex hash in database
      const row = await db.apiKeys.findUnique({ where: { hash: keyHash } });
      if (!row) return null;
      return { user: { id: row.userId }, scopes: row.scopes };
    },
  },
});

3. HMAC-Signed Session Cookie Strategy

Validates stateful session identifiers from Cookie headers with HMAC-SHA256 signature verification:

import { createSessionCookieStrategy } from '@shukoi/auth';

const sessionStrategy = createSessionCookieStrategy({
  secret: process.env.SESSION_SECRET!, // min 32 chars
  cookieName: 'sid',
  rollingTtlMs: 86_400_000, // 24 hours
  store: {
    async get(sessionId) {
      const data = await redis.get(`session:${sessionId}`);
      return data ? JSON.parse(data) : null;
    },
    async set(sessionId, data, ttlMs) {
      await redis.set(`session:${sessionId}`, JSON.stringify(data), 'PX', ttlMs);
    },
    async destroy(sessionId) {
      await redis.del(`session:${sessionId}`);
    },
  },
});

4. RFC 7662 OIDC Token Introspection Strategy

Validates opaque Bearer access tokens against centralized identity providers with bounded caching:

import { createOidcIntrospectionStrategy } from '@shukoi/auth';

const oidcStrategy = createOidcIntrospectionStrategy({
  introspectionUrl: 'https://idp.example.com/oauth/v2/introspect',
  clientId: process.env.OAUTH_CLIENT_ID!,
  clientSecret: process.env.OAUTH_CLIENT_SECRET!,
  cacheTtlMs: 60_000, // Cache introspection decision for 1 minute
  fetchTimeoutMs: 5000, // Timeout with AbortSignal
});

Composite Auth Resolver

Chain multiple authentication strategies in priority order:

import { createCompositeAuthResolver } from '@shukoi/auth';

export const resolveAuth = createCompositeAuthResolver([
  sessionStrategy, // 1. Try session cookie first
  jwksStrategy, // 2. Fall back to Bearer JWT
  staticApiKeyStrategy, // 3. Fall back to static API key
]);

// Usage in HTTP handler:
const auth = await resolveAuth(request.headers);
console.log('Authenticated User:', auth.user);
console.log('Granted Scopes:', auth.scopes);

Declarative Action Authorization (RBAC & ABAC)

Enforce fine-grained permissions at the action definition level:

import { defineAction } from '@shukoi/core';
import { Type } from '@sinclair/typebox';

export const updateInvoiceAction = defineAction({
  name: 'updateInvoice',
  description: 'Updates invoice details with role and tenant boundary check',
  authRequired: true,
  auth: {
    roles: ['admin', 'billing_manager'],
    permissions: ['invoices:write'],
    policy: (auth, input) => {
      // Prevents BOLA/IDOR: caller can only update invoices belonging to their tenant
      const user = auth.user as { tenantId?: string } | null;
      return user?.tenantId === input.tenantId;
    },
  },
  input: Type.Object({
    tenantId: Type.String(),
    invoiceId: Type.String(),
    amountCents: Type.Integer({ minimum: 100 }),
  }),
  output: Type.Object({
    success: Type.Boolean(),
  }),
  async handler(input, ctx) {
    ctx.logger.info('Updating invoice', { id: input.invoiceId });
    return { success: true };
  },
});

Testing Without External Identity Providers

Use mock stores from @shukoi/auth/testing in unit tests:

import { MockApiKeyStore, MockSessionStore } from '@shukoi/auth/testing';
import { createHashedApiKeyStrategy, hashApiKey } from '@shukoi/auth';

const store = new MockApiKeyStore();
const hashed = await hashApiKey('my-secret-key');
await store.addKey(hashed, { id: 'test-user' }, ['read:all']);

const strategy = createHashedApiKeyStrategy({ store });
const res = await strategy.authenticate({ 'x-api-key': 'my-secret-key' });
expect(res?.user).toEqual({ id: 'test-user' });