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

@nodii/grpc-auth

v0.22.0

Published

gRPC service-to-service auth for Nodii microservices: server + client interceptors, JWKS fetch from S3, JWT verifier, token manager.

Readme

@nodii/grpc-auth

Service-to-service gRPC auth for the Nodii microservice stack.

Provides:

  • createServerAuthInterceptor — verifies an incoming Bearer token from the authorization metadata header and attaches an S2SAuthContext to the call.
  • createClientAuthInterceptor — acquires a token via an S2STokenManager and attaches it to outgoing calls.
  • S2STokenManager — caches tokens from a SigV4-signed API Gateway endpoint and reuses each one for its lifetime (hub decision D845). Refreshes early without blocking callers. Every mint is bounded by mintTimeoutMs (default 1500 ms): a mint that takes longer fails as a transient S2STokenMintError, so a hung issuer cannot hang a caller, and a cached token keeps being served. Build one per process: a manager built per call never hits its cache.
  • verifyS2SToken — JWT verifier with JWKS resolution.
  • createSigV4S3JWKSet — JWKS resolver that pulls a private .well-known/jwks.json from S3 using SigV4 (not anonymous HTTPS).
  • withAuthUnary + requireScope — handler-level wrapper for unary RPC scope enforcement.

Inbound webhooks

verifyWebhook, from @nodii/grpc-auth/webhook, is the one verifier for inbound provider webhooks (S12-24). Each provider keeps its own signature scheme, so the scheme is configuration. Pass the raw bytes, before any parse:

import { verifyWebhook, type WebhookScheme } from "@nodii/grpc-auth/webhook";

const stripe: WebhookScheme = {
  kind: "hmac",
  algorithm: "sha256",
  signature: { header: "stripe-signature", encoding: "hex", separator: ",", prefix: "v1=" },
  timestamp: { header: "stripe-signature", separator: ",", prefix: "t=", format: "unix-seconds", toleranceSeconds: 300 },
  signed: { parts: [{ field: "timestamp" }, { literal: "." }, { field: "body" }] },
};

const verdict = verifyWebhook(stripe, [{ secret, id: "current" }], {
  rawBody,
  headers: c.req.raw.headers,
});
if (verdict.status === "refused") return c.json({ error: "unauthorized" }, 401); // log verdict.reason
  • Verdicts: verified, skipped (a credential scheme matched; nothing was verified over the body, S12-16) or refused with a reason. The reason is for the security log, never the response. A refused request changes no state.
  • The helper decides no policy: the timestamp window is required on a scheme with a timestamp, and a key's overlap is the notAfter you give it. The helper logs nothing and holds no provider table.
  • precheckWebhook runs every check that needs no key, so a service can refuse a malformed request before it pays to decrypt one.
  • A provider that signs something other than the raw body: compute the string yourself and pass it in values, named by { value: "..." } in the scheme (Twilio's URL and sorted parameters, SNS's canonical fields). For a public-key provider whose key comes from a certificate, resolve the certificate first and pass the base64 DER SPKI as the key.

The shared vectors are in scripts/parity/webhook-cases.json; they include a scheme for each signature shape in S12 §5.

The edge's signed step-up instant

The edge forwards the token's step_up_at (the session's last second factor, epoch seconds) as x-nodii-step-up-at, with x-nodii-step-up-at-signature: the gateway HMAC over purpose step-up-at, the value, the principal's x-nodii-jti and the x-request-id. It sends neither header when the token has no step_up_at. verifyGatewayStepUpAt({ stepUpAt, signature, jti, requestId, secrets }) returns verified with the instant, absent, or invalid with a reason (PARTIAL, UNBOUND, MALFORMED, BAD_BASE64URL, MISMATCH, OUT_OF_ROTATION_GRACE). Verify the principal bundle first and pass its jti. Then decide freshness with @nodii/auth-sdk's evaluateStepUp, which also needs a second factor in amr; treat absent and invalid as no step-up. On Hono, @nodii/auth-sdk/gateway's requireStepUp({ maxAgeSeconds }) does all of this. Python (verify_gateway_step_up_at) and Go (VerifyGatewayStepUpAt) run the same shared vectors, scripts/parity/step-up-at-cases.json.

Install

bun add @nodii/grpc-auth
# peer deps
bun add @grpc/grpc-js jose

Server: verify incoming tokens

import * as grpc from "@grpc/grpc-js";
import {
  createServerAuthInterceptor,
  createSigV4S3JWKSet,
  setJwksResolver,
} from "@nodii/grpc-auth";

// Configure JWKS source once, at boot.
setJwksResolver(
  createSigV4S3JWKSet({
    region: "ap-south-1",
    bucket: "nucleus-cloud-s2s-auth",
    key: ".well-known/jwks.json",
    cacheMaxAgeMs: 60_000,
    cooldownDurationMs: 5_000,
  }),
);

const server = new grpc.Server({
  interceptors: [
    createServerAuthInterceptor({
      expectedIssuer: "nucleus-s2s-auth",
      expectedAudience: "nucleus-internal",
    }),
  ],
});

The interceptor extracts Bearer <token>, calls verifyS2SToken, and attaches the auth context to the call as (call as any).auth. Handlers read it via the same path:

function handler(call: ServerUnaryCall<Req, Res>, cb: sendUnaryData<Res>) {
  const auth = (call as any).auth as S2SAuthContext | undefined;
  // auth.serviceName, auth.scopes, ...
}

Note. (call as any).auth is the production-proven pattern from provisioning. A typed getCallContext(call) helper is planned for v0.3.0 (lifted from inventory). It will live alongside the legacy reader, not replace it.

Server: per-handler scope enforcement

import { withAuthUnary } from "@nodii/grpc-auth";

const REQUIRED_SCOPES_BY_METHOD: Record<string, string> = {
  createCustomer: "provisioning:customers:write",
  getCurrentIpAssignmentsForIp: "provisioning:ip_assignments:read",
};

const wrap = withAuthUnary({
  expectedIssuer: "nucleus-s2s-auth",
  expectedAudience: "nucleus-internal",
  requiredScopesByMethod: REQUIRED_SCOPES_BY_METHOD,
  // Optional: skip auth in local dev. Defaults to false.
  skipAuth: () => process.env.LOCAL === "true",
});

server.addService(MyServiceDefinition, {
  createCustomer: wrap("createCustomer", impl.createCustomer),
  // ...
});

Client: acquire and attach a token

import {
  S2STokenManager,
  createClientAuthInterceptor,
} from "@nodii/grpc-auth";

const tokenManager = new S2STokenManager({
  apiBaseUrl: process.env.S2S_AUTH_API_BASE!,
  region: process.env.AWS_REGION ?? "ap-south-1",
  refreshSkewSeconds: 30,
  // Bound on ONE mint (issue 816). Default 1500; values above 9000 are clamped to 9000.
  mintTimeoutMs: 1500,
});

const client = new MyGrpcServiceClient(target, credentials, {
  interceptors: [
    createClientAuthInterceptor({
      tokenManager,
      audience: "nucleus-internal",
      scopes: ["flows:write"],
      instanceId: process.env.INSTANCE_ID,
    }),
  ],
});

Transport: TLS between services

NODII_DEPLOY_ENV is the switch. It is required and has no default.

| NODII_DEPLOY_ENV | Listener | Client | |---|---|---| | uat, prod | TLS | Verifies the peer against our CA. Plaintext is refused | | dev, test | Plaintext | Plaintext |

In uat and prod, set up the transport at start-up, before the process dials or listens. It reads Secrets Manager, so the task role needs read access.

import {
  grpcChannelCredentials,
  grpcServerCredentials,
  initGrpcTransport,
} from "@nodii/grpc-auth";

await initGrpcTransport({ serviceName: "auth-service" });

server.bindAsync(address, grpcServerCredentials(), onBound);
const client = new PeerClient(target, grpcChannelCredentials());
  • The CA comes from nodii/<env>/tls/ca (GRPC_TLS_CA). The listener's certificate and key come from nodii/<env>/tls/<serviceName> (GRPC_TLS_CERT, GRPC_TLS_KEY).
  • A process that only dials leaves out serviceName and needs only the CA.
  • An unreadable secret, an empty value, invalid PEM or a key that does not match its certificate stops the process at start-up. GrpcTransportConfigError.code names the refusal.
  • In uat and prod, grpcChannelCredentials() and grpcServerCredentials() throw grpc_tls_not_configured until the transport is set up. buildS2SClient, the approval clients and the role-catalog client use these credentials by default.
  • Secrets are reread every reloadIntervalMs (default five minutes), and a rotated listener certificate takes effect with no restart. A failed reload is logged, keeps the current certificate and calls onReloadError.
  • To roll the CA, publish a bundle holding the old and new CA, restart, issue from the new CA, then remove the old one. Only channels built after a reload are sure to hold a new CA.
  • Hot reload needs Bun 1.4.4 or later. On Bun 1.3 a listener built this way presents no certificate.

The Go port (InitGrpcTransport) and the Python port (init_grpc_transport) follow the same switch and use the same codes.

Versioning notes

v0.1.0 is a 1:1 lift of provisioning's S2S auth code (production-proven, also running in traffic-logs). Two narrow changes vs the source:

  1. The JWKS source is configured via setJwksResolver(...) instead of a module-level constant. Provisioning's hardcoded region: "ap-south-1", bucket: "nucleus-cloud-s2s-auth", key: ".well-known/jwks.json" move into the consumer's bootstrap.
  2. withAuthUnary accepts requiredScopesByMethod and skipAuth as parameters instead of importing them from a service-specific env.

These are dependency-injection refactors, not behavior changes. Verifier semantics (algorithms, clock skew, claim shape, scope parsing), token cache logic, and JWKS refresh+cooldown are unchanged.

Planned follow-ups:

  • v0.2.0 — pluggable test JWKS source (TEST_S2S_JWKS_PATH pattern from traffic-logs).
  • v0.3.0 — typed CallContext / getCallContext / mutateCallContext API alongside the legacy (call as any).auth reads (pattern from inventory).
  • v0.4.0 — pluggable logger (replaces console.log calls; quiet by default).