@bernierllc/nevar-auth
v0.4.0
Published
Verifier for Nevar central auth (auth.nevar.io): JWT via OIDC discovery + JWKS, api_/mcp_ keys via RFC 7662 introspection, RFC 8693 delegation, plus a real-HTTP test issuer.
Readme
@bernierllc/nevar-auth
Verifies nevar.io credentials (JWTs and typed api_/mcp_ keys) and performs actor delegation. Every nevar.io service uses it to turn an incoming credential into an ActorContext.
npm install @bernierllc/nevar-authContract: ifc:platform/authentication (#ActorContext@r3, sha dfb29f99150b, since 0.4.0), with the package-conformance decisions Q6, Q10, Q11, Q12, Q15 and Q16 implemented. Production issuer https://auth.nevar.io, staging issuer https://auth.notnevar.us.
Rules this package enforces
- The JWKS comes from OIDC discovery. Only asymmetric
algs are accepted, and every token must carry akidDiscovery and the JWKS are reused for about an hour, then refetched, so issuer key rotation needs no restart. - Every token has exactly one audience, and the caller names the audience it expects. A token whose
audlists several audiences is refused. - JWTs must be RFC 9068 access tokens. The header
typmust beat+jwt. An ID token (typ: JWT) or a token with notypis refused withinvalid_token, even when it names a resource audience. - Introspection uses the endpoint discovery names. The verifier posts to discovery's
introspection_endpoint, and falls back to<issuer>/oauth/introspectonly when discovery omits it. An endpoint that is present but not an absolute URL fails discovery; it never falls back. Like the token endpoint, it must be on the issuer's own origin, over https outsidemode: 'test', because it carries the client secret. - Typed keys are opaque, and only work on configured audiences.
api_andmcp_keys are checked only through RFC 7662 introspection. The surface of an audience comes fromresourceAudiences, a set of exact audience URLs per surface, never from the host name: anapi_key works only on an audience inresourceAudiences.api, anmcp_key only on one inresourceAudiences.mcp, and any other audience refuses both withwrong_surface. OmittingresourceAudiencesis deprecated since 0.3.0 (removed in 1.0.0): the verifier falls back to the 0.2 first-DNS-label rule and prints a one-time warning. - JWTs are introspected too, after local verification. A revoked grant is therefore denied on the very next call.
scopeandnevar_grant_idin the returnedActorContextcome from the introspection response, not from the JWT; a response with noscopeis refused. The response must also sayrole: "authenticated": any other role (such asservice_role), or none, is refused withinvalid_token. - Execution-grant claims (since 0.4.0).
nevar_project_idandnevar_callback_opcome back on theActorContext, bothnullon every credential that is not an execution grant. A token that carries either claim (JSONnullcounts as carrying it) must carry anevar_callback_opthat is a string matching the OperationCatalog id pattern, and anevar_project_idthat is a non-empty string or JSONnull; anything else is refused withinvalid_token(JWTs,api_andmcp_keys alike). That includes an operation with no project claim, a project claim with a missing ornulloperation, a wrong type, and an operation that fails the pattern. The package only copies the two claims: the callee enforces the operation binding. For a JWT they come from the verified JWT, never from the introspection response (which supplies onlyscope,nevar_grant_idandrole); for anapi_/mcp_key they come from the introspection response. - Identity comes only from the verified credential.
verifyCredentialtakes no actor header. A service acting for a user obtains a delegated token through RFC 8693 token exchange (delegateActor), and that token carries anactclaim. - Delegation only talks to the issuer and returns only a verified token.
delegateActorrequires atoken_endpointin discovery on the issuer's own origin, over https (plain http only inmode: 'test'). It authenticates with HTTP Basic usingintrospectionClient, and the actor (service) token'saudmust be the issuer. The returned token is verified for the requested audience, including introspection, beforedelegateActorreturns it; if that check cannot complete, the call fails. - When the issuer cannot be reached, the call fails. You get
dependency_unavailablewithretryable: true. The verifier never falls back to cached or local keys. - Logs carry the grant ref, never the token. The grant ref is capped at 64 characters, since it may be read from a token that failed verification.
Usage
import { createNevarAuth, NEVAR_ISSUERS, NevarAuthError } from '@bernierllc/nevar-auth';
const auth = createNevarAuth({
issuer: NEVAR_ISSUERS.production,
introspectionClient: { clientId: process.env.NEVAR_AUTH_CLIENT_ID!, clientSecret: process.env.NEVAR_AUTH_CLIENT_SECRET! },
// Exact audience URLs per surface; an audience may be in only one set. Required from 1.0.0;
// omitting it is deprecated since 0.3.0 (see Migrating from 0.2).
resourceAudiences: {
api: ['https://api.nevar.io/v1/plan'],
mcp: ['https://mcp.nevar.io/v1/plan'],
},
logger, // optional, { warn(message, context) }; denials are logged with code + grantId
});
try {
const actor = await auth.verifyCredential(req.headers.authorization ?? '', {
audience: 'https://api.nevar.io/v1/plan',
correlationId: req.id,
});
// actor.sub, actor.nevar_actor_type, actor.nevar_owner_sub, actor.nevar_org_id,
// actor.scope, actor.nevar_grant_id, actor.act, actor.role ("authenticated"), actor.aud,
// actor.nevar_project_id, actor.nevar_callback_op (execution-grant claims, string | null; since 0.4.0)
} catch (error) {
if (error instanceof NevarAuthError && error.retryable) return res.status(503).end();
return res.status(401).end();
}
// Acting for the user against another service:
const { token } = await auth.delegateActor({
serviceToken: myServiceToken,
subjectToken: userToken,
audience: 'https://mcp.nevar.io/v1/plan',
});Error codes
Each of these is a NevarAuthError with a code, a retryable flag and a grantId (or null).
| Code | Meaning |
|------|---------|
| invalid_token | The credential is not a string or is malformed, has a bad signature, an unknown kid or a symmetric alg, or is missing a required claim (exp, iss, aud and sub are always required) or has an invalid one. |
| untrusted_key | Production mode refused the test-only key test-only-not-production. |
| wrong_issuer | iss is not the configured issuer. |
| wrong_audience | aud is not exactly the expected audience, or it names several. |
| wrong_surface | The key's prefix does not match the audience's surface. |
| expired | The credential is past its exp. |
| revoked | Introspection reports the credential inactive. This covers both revoked and unknown credentials. |
| invalid_delegation | The token exchange was refused, the token's act claim is malformed, or the exchanged token does not verify for the requested audience. |
| dependency_unavailable | Discovery, the JWKS, introspection or the token endpoint failed: unreachable, a 5xx or 429, a non-JSON body, or an unusable discovery document. This is the only retryable code. |
| misconfigured | Our setup is wrong. One of: the caller named no audience; mode is not exactly 'production' or 'test', which createNevarAuth throws at construction; mode: 'test' points at a real nevar.io issuer; the issuer URL ends in /; the discovery issuer does not match; introspection or the token endpoint refused our client credentials; resourceAudiences is not two arrays of non-empty strings, or lists one audience under both api and mcp (thrown at construction); discovery names no token_endpoint, or the token or introspection endpoint is on another origin than the issuer, or is non-https outside test mode. |
Migrating from 0.2
- Pass
resourceAudiencestocreateNevarAuth, listing every audience your service accepts typed keys on. In 0.3 a config without it still works on the 0.2 first-DNS-label rule and prints a one-time deprecation warning; from 1.0.0 construction throwsmisconfiguredwithout it. audienceSurfaceis deprecated since 0.3.0 and removed in 1.0.0. It still returns the 0.2 first-label surface and warns once; the surface now comes fromresourceAudiences.- With
resourceAudiencesset (and always from 1.0.0), JWTs must carrytyp: at+jwt, and introspection must returnscopeandnevar_grant_id: the verifier takes both from introspection, not the JWT. Under the deprecated 0.2 config an untyped JWT, or an introspection response without those fields, still works (the JWT's claims are used) and prints a one-time warning. - Issuers must mint access tokens with
typ: at+jwt, give service tokensaud= the issuer, and advertise a same-origintoken_endpointfor delegation and a same-originintrospection_endpoint(or none).
Testing: @bernierllc/nevar-auth/testing
import { createNevarAuth } from '@bernierllc/nevar-auth';
import { startTestIssuer, TEST_AUDIENCES, TEST_RESOURCE_AUDIENCES } from '@bernierllc/nevar-auth/testing';
const issuer = await startTestIssuer(); // a real HTTP server on 127.0.0.1
const auth = createNevarAuth({
issuer: issuer.url,
introspectionClient: issuer.introspectionClient,
resourceAudiences: TEST_RESOURCE_AUDIENCES,
mode: 'test',
});
await auth.verifyCredential(issuer.tokens.valid, { audience: TEST_AUDIENCES.api });
await issuer.close();What the test issuer serves:
- Discovery, the JWKS, introspection and token exchange. Introspection and token exchange both require Basic client credentials, and token exchange requires the actor token's
audto be the issuer. startTestIssuer({ introspectionPath, advertiseIntrospection })moves the introspection route (default/oauth/introspect) or leavesintrospection_endpointout of discovery.
Sample credentials:
issuer.tokens:valid,expired,wrongAudience,wrongIssuer,revoked,agent,service(whoseaudis the issuer) andexecutionGrant(since 0.4.0: a service token carryingTEST_EXECUTION_GRANT, projectproj_test_1and operationprojects.tasks.run_due).TEST_RESOURCE_AUDIENCES: theresourceAudiencesset matchingTEST_AUDIENCES.TEST_KEYS: oneapi_key and onemcp_key.
Controls:
issuer.sign(claims, { expiresIn, issuer, kid, typ })mints a custom token.typdefaults toat+jwt;nullomits it.issuer.overrideIntrospection(grantId, fields)changes what introspection reports for a grant; a field set toundefinedis removed.issuer.revoke(grantId)revokes a grant.issuer.setUnavailable(endpoint)makes an endpoint return 503, to simulate an outage.
Fixtures: the test keypair (kid test-only-not-production) and its JWKS are exported as TEST_PRIVATE_JWK and TEST_JWKS. A verifier in production mode (the default) rejects that kid before it makes any network call, so test tokens cannot authenticate in production.
Why a new package
I searched the repo for an existing verifier before writing this one. None fits:
@bernierllc/crypto-utilshandles HS* JWTs only.@bernierllc/permission-checkerdoes RBAC, which is out of scope.@bernierllc/auth-serviceis not a verifier.
No other JWKS or introspection helper exists in the repo. JWT verification itself is delegated to jose.
Integration status
| Integration | Status | Why |
|-------------|--------|-----|
| Logger | not-applicable | Accepts any { warn } logger so it stays dependency-light; consumers pass @bernierllc/logger. |
| NeverHub | not-applicable | Core-tier package with no runtime lifecycle to register. |
License
MIT. See LICENSE.
