@antzsoft/token-verifier
v1.1.0
Published
ANTZ user-token verification for Node.js services (framework-agnostic, with optional NestJS module)
Readme
ANTZ Token Verifier
Installable extraction of ANTZ's existing token-verification logic. The core is framework-agnostic: it works in any Node.js server (NestJS, Express, Fastify, Koa, Hono on Node, plain node:http). It needs the Node.js runtime (crypto, http); edge runtimes such as Cloudflare Workers or Vercel Edge are not supported. Configure it once and call verify(token) instead of copying the verifier between services.
Working name: @antzsoft/token-verifier. Version 1.0.0, distributed through npmjs (public access) and private Git. Node 22.12+; The core has no framework dependency; the optional NestJS module supports Nest 10, 11 and 12. The package is ESM with declarations and can be loaded by modern Node's require().
Phase 1 contract
Preserve the existing verifier's behavior for legacy HS256, non-SSO RS256 and SSO RS256 tokens. Fetch public keys from the existing CI4 /nonSso/getJwks endpoint, which correctly serves the active mode's keys. There is no requirement for CI4 to serve both modes simultaneously and no CI4 change is required.
No service authentication in phase 1. Application ID/secret authentication for key requests belongs to phase 2. Login, issuance, refresh, session/revocation checks, account lookup, permissions and zoo authorization remain responsibilities of the consuming application.
Build and install locally
npm ci
npm run check
npm pack
# In the consuming project:
npm install /absolute/path/antz-token-verifier/antzsoft-token-verifier-1.0.0.tgzLocal registry (Verdaccio)
For local testing with other ANTZ services, the package can be published to a local Verdaccio registry at http://localhost:4873. .npmrc maps the @antzsoft scope to Verdaccio. Comment that line out to make the scope resolve from npmjs.
npm i -g verdaccio && verdaccio # first time: npm adduser --registry http://localhost:4873
npm run publish:dry-run # show the steps without changing anything
npm run publish:local # bump patch, run checks, publish to Verdaccio
npm run publish:local -- --version minor # or major / an exact x.y.z
npm run local-registry:republish # re-publish the current version to Verdaccio
npm run publish:npm # bump patch, run checks, publish to npmjs (public)
npm run publish:npm -- --otp 123456 # npmjs requires 2FA: pass the authenticator code
# In the consuming project:
npm install @antzsoft/token-verifier --registry http://localhost:4873node publish.mjs with no --registry follows .npmrc, as in the other ANTZ SDKs. With the @antzsoft:registry=http://localhost:4873 line active it publishes to Verdaccio; with that line commented out it publishes to npmjs. The scripts then pass the chosen scope registry explicitly, so a user-level ~/.npmrc cannot redirect the publish. npmjs publishes need a CHANGELOG entry for the new version and an npm login allowed to publish under @antzsoft.
Install from GitHub
Install a reviewed full commit SHA from the private repository, then commit the consumer lockfile:
npm install 'git+https://github.com/ANTZ-Systems/antzsoft-token-verifier.git#<full-commit-sha>'The Git prepare lifecycle compiles JavaScript and declarations before npm packs the dependency. Installation requires GitHub read access, build dependencies and enabled lifecycle scripts. Keep credentials outside URLs and lockfiles; check the actual resolved transport because npm can normalize GitHub URLs to SSH. Use Node 22.12 or later, including in build/deployment environments. Registry installation (npm install @antzsoft/token-verifier) is the alternative. CommonJS consumers on supported Node can use require(); TypeScript declarations support the core and NestJS entry points.
Verify a clean Git install and locked reinstall, then load both entry points and compile the consumer. Successful download alone does not prove the build artifacts were included. Its token-verification behavior is unchanged.
Configure once, call the method
The settings retain the names/defaults of the existing Species API verifier. Pass your existing trusted configuration; the package does not read environment variables implicitly. Values below are placeholders.
import { TokenVerifier, TokenVerificationError } from '@antzsoft/token-verifier';
const verifier = new TokenVerifier({
ANTZ_TOKEN_VERIFICATION_MODE: 'hybrid',
JWT_SECRET: process.env.JWT_SECRET,
ANTZ_LEGACY_HS256_ALLOW_UNTIL: process.env.ANTZ_LEGACY_HS256_ALLOW_UNTIL,
ANTZ_API_BASE_URL: 'https://your-ci4.example',
ANTZ_NON_SSO_JWT_ISSUER: 'https://your-antz-issuer.example',
ANTZ_NON_SSO_JWT_AUDIENCE: 'antz-api',
ANTZ_SSO_JWT_ISSUER: 'https://your-wso2-issuer.example',
ANTZ_SSO_JWT_AUDIENCE_POLICY: 'required',
ANTZ_SSO_JWT_AUDIENCE: 'your-existing-audience',
NODE_ENV: process.env.NODE_ENV,
});
try {
const { family, payload } = await verifier.verify(rawJwt);
// Continue the application's existing session/account/permission checks.
} catch (error) {
if (error instanceof TokenVerificationError) {
// Existing contract: reason + unavailable. Never log JWTs or secrets.
console.error(error.reason);
}
throw error;
}Pass the raw JWT without the Bearer prefix; extractBearerToken(req.headers.authorization) returns it from an Authorization: Bearer <jwt> header, or undefined when the header is missing or malformed. Retain one instance per process to reuse the key cache. Constructor initialization replaces the old service's onModuleInit(); callers do not need to invoke a lifecycle method.
| Setting | Existing behavior preserved |
|---|---|
| ANTZ_TOKEN_VERIFICATION_MODE | legacy-hs256 (default), rs256-jwks, or hybrid |
| JWT_SECRET | Required in legacy/hybrid; exact string retained |
| ANTZ_LEGACY_HS256_ALLOW_UNTIL | Optional cutoff; blank means no configured cutoff |
| ANTZ_API_BASE_URL | Required for RSA modes; /nonSso/getJwks appended |
| ANTZ_NON_SSO_JWT_ISSUER | Required for RSA modes |
| ANTZ_NON_SSO_JWT_AUDIENCE | Defaults to antz-api |
| ANTZ_SSO_JWT_ISSUER | Required for RSA modes; must differ from non-SSO issuer |
| ANTZ_SSO_JWT_AUDIENCE_POLICY | required or ignore, matching existing deployment |
| ANTZ_SSO_JWT_AUDIENCE | Required when policy is required; comma-separated audiences supported |
| NODE_ENV | production enforces HTTPS; otherwise existing HTTP/HTTPS support retained |
Other frameworks (Express, Fastify, Koa, Hono, node:http)
Import only the root entry point. It does not load NestJS, reflect-metadata or rxjs, so those packages need not be installed. Create one TokenVerifier per process and call it from your framework's middleware/hook. Authorization decisions stay in your application.
import { TokenVerifier, TokenVerificationError, extractBearerToken } from '@antzsoft/token-verifier';
const verifier = new TokenVerifier({ /* settings above */ });
// Express / Connect-style middleware
app.use(async (req, res, next) => {
const token = extractBearerToken(req.headers.authorization);
if (!token) return res.status(401).end();
try {
req.auth = await verifier.verify(token);
next();
} catch (error) {
if (!(error instanceof TokenVerificationError)) return next(error);
res.status(error.unavailable ? 503 : 401).json({ reason: error.reason });
}
});
// Fastify
fastify.addHook('preHandler', async (request, reply) => {
const token = extractBearerToken(request.headers.authorization);
if (!token) return reply.code(401).send();
request.auth = await verifier.verify(token); // map TokenVerificationError in your error handler
});
// Koa
app.use(async (ctx, next) => {
const token = extractBearerToken(ctx.get('authorization') || undefined);
if (!token) ctx.throw(401);
ctx.state.auth = await verifier.verify(token);
await next();
});
// Hono
app.use('*', async (c, next) => {
const token = extractBearerToken(c.req.header('authorization'));
if (!token) return c.text('Unauthorized', 401);
c.set('auth', await verifier.verify(token));
await next();
});error.unavailable === true (reason jwks_unavailable) means the key endpoint could not be reached; treat it as a temporary server-side failure rather than a bad token.
NestJS integration
import { Module } from '@nestjs/common';
import { TokenVerifierModule } from '@antzsoft/token-verifier/nestjs';
@Module({
imports: [TokenVerifierModule.register({
ANTZ_TOKEN_VERIFICATION_MODE: 'legacy-hs256',
JWT_SECRET: process.env.JWT_SECRET,
})],
})
export class AppModule {}Inject TokenVerifier into your existing guard/service and call verify(token). The module exports a singleton provider and installs no global guard. Your existing Nest 10, 11 or 12 application supplies @nestjs/common, reflect-metadata and rxjs. These peers are optional and only required for the /nestjs entry point.
Runnable examples: examples/express and examples/nestjs (NestJS 12 guard). examples/e2e runs both apps end to end against a fake CI4 JWKS endpoint, covering every mode and failure reason.
Behavior and migration
The source baseline is Species API TokenVerificationService at commit 402eac6ca385245dc68588adb257984f5f98dca7. This is an extraction of that verifier, not a claim that every application's authentication flow is identical.
- The same
jsonwebtokenandjwks-rsaversions verify tokens; no algorithm fallback or token-directed key URLs. - One JWKS client for both trusted RSA issuers, using CI4's active-mode endpoint.
- Existing per-key cache: 1 hour, up to 10 keys; 5 key requests/minute; 5-second timeout. Unknown keys follow existing refresh behavior, without the new 30-second cooldown from 0.1.0.
- Existing exp/nbf checks have no added clock tolerance; future iat allowance remains 60 seconds. Identity, legacy cutoff and audience rules match the source.
- Cached keys may continue verifying previously issued tokens across a mode change, as in the source. An active-mode switch does not introduce immediate token revocation. A fresh instance rejects an unavailable key.
Correction from unreleased 0.1.0: replace modern/legacy options with the settings above; read payload instead of claims; catch reason instead of code. Removed package-specific clock tolerance, custom required claims, per-issuer URLs, new legacy issuer restriction, and new fetch/cache policy. Version 0.2.0 records this API correction; no consumer was changed automatically.
See architecture/parity, errors, security, release process, and verification.
