@bernierllc/nevar-auth 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,114 @@
1
1
  # @bernierllc/nevar-auth
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ 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`.
4
+
5
+ ```bash
6
+ npm install @bernierllc/nevar-auth
7
+ ```
8
+
9
+ **Contract:** rev 0. Production issuer `https://auth.nevar.io`, staging issuer `https://auth.staging.nevar.io`.
10
+
11
+ ## Rules this package enforces
12
+
13
+ - **The JWKS comes from OIDC discovery.** Only asymmetric `alg`s are accepted, and every token must carry a `kid`.
14
+ - **Every token has exactly one audience**, and the caller names the audience it expects. A token whose `aud` lists several audiences is refused.
15
+ - **Typed keys are opaque.** `api_` and `mcp_` keys are checked only through RFC 7662 introspection at `<issuer>/oauth/introspect`. A key's prefix must match the surface of the audience: an `api_` key works only on an `api.` audience, an `mcp_` key only on an `mcp.` audience, and any other audience refuses both.
16
+ - **JWTs are introspected too, after local verification.** A revoked grant is therefore denied on the very next call.
17
+ - **Identity comes only from the verified credential.** `verifyCredential` takes no actor header. A service acting for a user obtains a delegated token through RFC 8693 token exchange (`delegateActor`), and that token carries an `act` claim.
18
+ - **When the issuer cannot be reached, the call fails.** You get `dependency_unavailable` with `retryable: true`. The verifier never falls back to cached or local keys.
19
+ - **Logs carry the grant ref, never the token.**
20
+
21
+ ## Usage
22
+
23
+ ```ts
24
+ import { createNevarAuth, NEVAR_ISSUERS, NevarAuthError } from '@bernierllc/nevar-auth';
25
+
26
+ const auth = createNevarAuth({
27
+ issuer: NEVAR_ISSUERS.production,
28
+ introspectionClient: { clientId: process.env.NEVAR_AUTH_CLIENT_ID!, clientSecret: process.env.NEVAR_AUTH_CLIENT_SECRET! },
29
+ logger, // optional, { warn(message, context) }; denials are logged with code + grantId
30
+ });
31
+
32
+ try {
33
+ const actor = await auth.verifyCredential(req.headers.authorization ?? '', {
34
+ audience: 'https://api.nevar.io/v1/plan',
35
+ correlationId: req.id,
36
+ });
37
+ // actor.sub, actor.nevar_actor_type, actor.nevar_owner_sub, actor.nevar_org_id,
38
+ // actor.scope, actor.nevar_grant_id, actor.act, actor.role ("authenticated"), actor.aud
39
+ } catch (error) {
40
+ if (error instanceof NevarAuthError && error.retryable) return res.status(503).end();
41
+ return res.status(401).end();
42
+ }
43
+
44
+ // Acting for the user against another service:
45
+ const { token } = await auth.delegateActor({
46
+ serviceToken: myServiceToken,
47
+ subjectToken: userToken,
48
+ audience: 'https://mcp.nevar.io/v1/plan',
49
+ });
50
+ ```
51
+
52
+ ## Error codes
53
+
54
+ Each of these is a `NevarAuthError` with a `code`, a `retryable` flag and a `grantId` (or `null`).
55
+
56
+ | Code | Meaning |
57
+ |------|---------|
58
+ | `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. |
59
+ | `untrusted_key` | Production mode refused the test-only key `test-only-not-production`. |
60
+ | `wrong_issuer` | `iss` is not the configured issuer. |
61
+ | `wrong_audience` | `aud` is not exactly the expected audience, or it names several. |
62
+ | `wrong_surface` | The key's prefix does not match the audience's surface. |
63
+ | `expired` | The credential is past its `exp`. |
64
+ | `revoked` | Introspection reports the credential inactive. This covers both revoked and unknown credentials. |
65
+ | `invalid_delegation` | The token exchange was refused, or the token's `act` claim is malformed. |
66
+ | `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. |
67
+ | `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 refused our client credentials. |
68
+
69
+ ## Testing: `@bernierllc/nevar-auth/testing`
70
+
71
+ ```ts
72
+ import { createNevarAuth } from '@bernierllc/nevar-auth';
73
+ import { startTestIssuer, TEST_AUDIENCES } from '@bernierllc/nevar-auth/testing';
74
+
75
+ const issuer = await startTestIssuer(); // a real HTTP server on 127.0.0.1
76
+ const auth = createNevarAuth({ issuer: issuer.url, introspectionClient: issuer.introspectionClient, mode: 'test' });
77
+
78
+ await auth.verifyCredential(issuer.tokens.valid, { audience: TEST_AUDIENCES.api });
79
+ await issuer.close();
80
+ ```
81
+
82
+ **What the test issuer serves:**
83
+ - Discovery, the JWKS, introspection (protected by Basic auth) and token exchange.
84
+
85
+ **Sample credentials:**
86
+ - `issuer.tokens`: `valid`, `expired`, `wrongAudience`, `wrongIssuer`, `revoked`, `agent` and `service`.
87
+ - `TEST_KEYS`: one `api_` key and one `mcp_` key.
88
+
89
+ **Controls:**
90
+ - `issuer.sign(claims, { expiresIn, issuer, kid })` mints a custom token.
91
+ - `issuer.revoke(grantId)` revokes a grant.
92
+ - `issuer.setUnavailable(endpoint)` makes an endpoint return 503, to simulate an outage.
93
+
94
+ **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.
95
+
96
+ ## Why a new package
97
+
98
+ I searched the repo for an existing verifier before writing this one. None fits:
99
+ - `@bernierllc/crypto-utils` handles HS* JWTs only.
100
+ - `@bernierllc/permission-checker` does RBAC, which is out of scope.
101
+ - `@bernierllc/auth-service` is not a verifier.
102
+
103
+ No other JWKS or introspection helper exists in the repo. JWT verification itself is delegated to [`jose`](https://github.com/panva/jose).
4
104
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@bernierllc/nevar-auth`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
105
+ ## Integration status
106
+
107
+ | Integration | Status | Why |
108
+ |-------------|--------|-----|
109
+ | Logger | not-applicable | Accepts any `{ warn }` logger so it stays dependency-light; consumers pass `@bernierllc/logger`. |
110
+ | NeverHub | not-applicable | Core-tier package with no runtime lifecycle to register. |
111
+
112
+ ## License
113
+
114
+ MIT. See [LICENSE](./LICENSE).
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Why a credential was refused, or why it could not be checked.
3
+ *
4
+ * Every deny code is distinct so a service can log and count them separately.
5
+ * Only `dependency_unavailable` is retryable.
6
+ */
7
+ export type NevarAuthErrorCode =
8
+ /** Malformed, bad signature, unknown `kid`, symmetric `alg`, or a required claim missing or invalid. */
9
+ 'invalid_token'
10
+ /** Production mode refused the test-only signing key. */
11
+ | 'untrusted_key'
12
+ /** `iss` is not the configured issuer. */
13
+ | 'wrong_issuer'
14
+ /** `aud` is not exactly the expected audience (or names several). */
15
+ | 'wrong_audience'
16
+ /** An `api_` key on an MCP audience, an `mcp_` key on an API audience, or a key on any other surface. */
17
+ | 'wrong_surface'
18
+ /** Past `exp`. */
19
+ | 'expired'
20
+ /** The issuer reports the credential inactive: revoked, or unknown to it. */
21
+ | 'revoked'
22
+ /** Token exchange refused, or a delegated token's `act` claim is malformed. */
23
+ | 'invalid_delegation'
24
+ /** Discovery, JWKS, introspection or token endpoint unreachable or failing. Retry; never fall back to local keys. */
25
+ | 'dependency_unavailable'
26
+ /** The issuer answered but rejected our setup: discovery `issuer` mismatch or introspection client refused. */
27
+ | 'misconfigured';
28
+ /** Every failure from this package. Carries the grant ref when known, never the token. */
29
+ export declare class NevarAuthError extends Error {
30
+ readonly code: NevarAuthErrorCode;
31
+ readonly retryable: boolean;
32
+ /** `nevar_grant_id` of the refused credential, when it could be read. Safe to log. */
33
+ readonly grantId: string | null;
34
+ constructor(code: NevarAuthErrorCode, message: string, options?: {
35
+ cause?: unknown;
36
+ grantId?: string | null;
37
+ });
38
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,21 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /** Every failure from this package. Carries the grant ref when known, never the token. */
9
+ export class NevarAuthError extends Error {
10
+ code;
11
+ retryable;
12
+ /** `nevar_grant_id` of the refused credential, when it could be read. Safe to log. */
13
+ grantId;
14
+ constructor(code, message, options = {}) {
15
+ super(message, { cause: options.cause });
16
+ this.name = 'NevarAuthError';
17
+ this.code = code;
18
+ this.retryable = code === 'dependency_unavailable';
19
+ this.grantId = options.grantId ?? null;
20
+ }
21
+ }
@@ -0,0 +1,80 @@
1
+ export { NevarAuthError, type NevarAuthErrorCode } from './errors.js';
2
+ /** The two real issuers. Pass one as `issuer`. */
3
+ export declare const NEVAR_ISSUERS: {
4
+ readonly production: "https://auth.nevar.io";
5
+ readonly staging: "https://auth.staging.nevar.io";
6
+ };
7
+ /** `kid` of the fixture signing key in `@bernierllc/nevar-auth/testing`. Refused in production mode. */
8
+ export declare const TEST_KID = "test-only-not-production";
9
+ declare const ACTOR_TYPES: readonly ["user", "agent", "service"];
10
+ export type ActorType = (typeof ACTOR_TYPES)[number];
11
+ /** RFC 8693 actor claim. Nested `act` is a delegation chain, outermost actor first. */
12
+ export interface ActClaim {
13
+ sub: string;
14
+ act?: ActClaim;
15
+ [claim: string]: unknown;
16
+ }
17
+ /** The verified identity on a request. Built only from a verified credential, never from request headers. */
18
+ export interface ActorContext {
19
+ sub: string;
20
+ nevar_actor_type: ActorType;
21
+ /** Accountable owner. Always set for `agent` and `service`; `null` for a user with none. */
22
+ nevar_owner_sub: string | null;
23
+ nevar_org_id: string;
24
+ /** Space-separated scopes, as issued. */
25
+ scope: string;
26
+ nevar_grant_id: string;
27
+ /** Present only on delegated tokens. */
28
+ act: ActClaim | null;
29
+ role: 'authenticated';
30
+ /** The audience this credential was verified for. */
31
+ aud: string;
32
+ }
33
+ /** Anything with `warn(message, context)`, e.g. a `@bernierllc/logger` instance. */
34
+ export interface NevarAuthLogger {
35
+ warn(message: string, context?: Record<string, unknown>): void;
36
+ }
37
+ export interface NevarAuthConfig {
38
+ /** `NEVAR_ISSUERS.production`, `NEVAR_ISSUERS.staging`, or a test issuer's `url`. */
39
+ issuer: string;
40
+ /** This service's client credentials for RFC 7662 introspection, sent as HTTP Basic. */
41
+ introspectionClient: {
42
+ clientId: string;
43
+ clientSecret: string;
44
+ };
45
+ /** Default `production`, which refuses `kid` `test-only-not-production`. */
46
+ mode?: 'production' | 'test';
47
+ /** Receives one line per refused credential: code, grant ref, audience, correlation id. Never the token. */
48
+ logger?: NevarAuthLogger;
49
+ /** Per-request timeout for issuer calls. Default 5000 ms. */
50
+ timeoutMs?: number;
51
+ }
52
+ export interface VerifyOptions {
53
+ /** The single resource this service is, e.g. `https://api.nevar.io/v1/plan`. */
54
+ audience: string;
55
+ /** Carried into denial logs. */
56
+ correlationId?: string;
57
+ }
58
+ export interface DelegateOptions {
59
+ /** This service's own token (`nevar_actor_type: service`), sent as the RFC 8693 `actor_token`. */
60
+ serviceToken: string;
61
+ /** The user's token as it reached this service, sent as `subject_token`. */
62
+ subjectToken: string;
63
+ /** The one resource the delegated token is for. */
64
+ audience: string;
65
+ correlationId?: string;
66
+ }
67
+ export interface DelegatedToken {
68
+ token: string;
69
+ /** Seconds, from the issuer's `expires_in`; `null` if it sent none. */
70
+ expiresIn: number | null;
71
+ }
72
+ export interface NevarAuth {
73
+ /** Verify a bearer credential (JWT or `api_`/`mcp_` key) for one audience. Throws `NevarAuthError`. */
74
+ verifyCredential(credential: string, options: VerifyOptions): Promise<ActorContext>;
75
+ /** RFC 8693 token exchange: a token for `audience` that carries the user as `sub` and this service in `act`. */
76
+ delegateActor(options: DelegateOptions): Promise<DelegatedToken>;
77
+ }
78
+ export declare function createNevarAuth(config: NevarAuthConfig): NevarAuth;
79
+ /** `api` for `https://api.…`, `mcp` for `https://mcp.…`, otherwise `null` (no typed key is accepted there). */
80
+ export declare function audienceSurface(audience: string): 'api' | 'mcp' | null;
package/dist/index.js ADDED
@@ -0,0 +1,302 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors as joseErrors, jwtVerify, } from 'jose';
9
+ import { NevarAuthError } from './errors.js';
10
+ export { NevarAuthError } from './errors.js';
11
+ /** The two real issuers. Pass one as `issuer`. */
12
+ export const NEVAR_ISSUERS = {
13
+ production: 'https://auth.nevar.io',
14
+ staging: 'https://auth.staging.nevar.io',
15
+ };
16
+ /** `kid` of the fixture signing key in `@bernierllc/nevar-auth/testing`. Refused in production mode. */
17
+ export const TEST_KID = 'test-only-not-production';
18
+ /** Asymmetric algorithms only: a shared-secret `alg` is refused before any key lookup. */
19
+ const ASYMMETRIC_ALGORITHMS = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA'];
20
+ const ACTOR_TYPES = ['user', 'agent', 'service'];
21
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
+ const TOKEN_TYPE_ACCESS = 'urn:ietf:params:oauth:token-type:access_token';
23
+ export function createNevarAuth(config) {
24
+ const { issuer, introspectionClient, logger } = config;
25
+ const mode = config.mode ?? 'production';
26
+ // Fail closed at boot: an unknown mode string must never be treated as "not production".
27
+ if (mode !== 'production' && mode !== 'test') {
28
+ throw new NevarAuthError('misconfigured', `mode must be 'production' or 'test', got ${String(mode)}`);
29
+ }
30
+ if (issuer.endsWith('/')) {
31
+ throw new NevarAuthError('misconfigured', `issuer must have no trailing slash, got ${issuer}`);
32
+ }
33
+ if (mode === 'test' && Object.values(NEVAR_ISSUERS).includes(issuer)) {
34
+ throw new NevarAuthError('misconfigured', `mode 'test' is refused for the real issuer ${issuer}`);
35
+ }
36
+ const timeoutMs = config.timeoutMs ?? 5000;
37
+ // RFC 6749 §2.3.1: form-encode id and secret before base64.
38
+ const basicAuth = 'Basic ' +
39
+ Buffer.from(`${encodeURIComponent(introspectionClient.clientId)}:${encodeURIComponent(introspectionClient.clientSecret)}`).toString('base64');
40
+ let metadata;
41
+ let jwks;
42
+ async function post(url, form, headers = {}) {
43
+ return http(url, {
44
+ method: 'POST',
45
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', ...headers },
46
+ body: new URLSearchParams(form),
47
+ });
48
+ }
49
+ async function http(url, init = {}) {
50
+ let res;
51
+ try {
52
+ res = await fetch(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
53
+ }
54
+ catch (cause) {
55
+ throw new NevarAuthError('dependency_unavailable', `Issuer unreachable: ${url}`, { cause });
56
+ }
57
+ if (res.status === 429 || res.status >= 500) {
58
+ throw new NevarAuthError('dependency_unavailable', `Issuer returned ${res.status}: ${url}`);
59
+ }
60
+ let body;
61
+ try {
62
+ body = await res.json();
63
+ }
64
+ catch (cause) {
65
+ throw new NevarAuthError('dependency_unavailable', `Issuer returned non-JSON: ${url}`, { cause });
66
+ }
67
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
68
+ throw new NevarAuthError('dependency_unavailable', `Issuer returned a non-object JSON body: ${url}`);
69
+ }
70
+ return { status: res.status, body: body };
71
+ }
72
+ function discover() {
73
+ metadata ??= (async () => {
74
+ const { status, body } = await http(`${issuer}/.well-known/openid-configuration`);
75
+ if (status !== 200 || typeof body.jwks_uri !== 'string') {
76
+ throw new NevarAuthError('dependency_unavailable', `OIDC discovery failed (${status})`);
77
+ }
78
+ try {
79
+ new URL(body.jwks_uri);
80
+ }
81
+ catch (cause) {
82
+ throw new NevarAuthError('dependency_unavailable', `Discovery jwks_uri is not an absolute URL`, { cause });
83
+ }
84
+ if (body.issuer !== issuer) {
85
+ throw new NevarAuthError('misconfigured', `Discovery names issuer ${String(body.issuer)}, configured ${issuer}`);
86
+ }
87
+ return body;
88
+ })().catch((error) => {
89
+ metadata = undefined; // never cache a failure; the next call retries discovery
90
+ throw error;
91
+ });
92
+ return metadata;
93
+ }
94
+ const getKey = async (header, token) => {
95
+ const { jwks_uri } = await discover();
96
+ jwks ??= createRemoteJWKSet(new URL(jwks_uri), { timeoutDuration: timeoutMs });
97
+ try {
98
+ return await jwks(header, token);
99
+ }
100
+ catch (cause) {
101
+ if (cause instanceof joseErrors.JWKSNoMatchingKey || cause instanceof joseErrors.JWKSMultipleMatchingKeys) {
102
+ throw cause;
103
+ }
104
+ throw new NevarAuthError('dependency_unavailable', 'JWKS unreachable', { cause });
105
+ }
106
+ };
107
+ async function introspect(token, grantId) {
108
+ const { status, body } = await post(`${issuer}/oauth/introspect`, { token }, { authorization: basicAuth });
109
+ if (status === 401 || status === 403) {
110
+ throw new NevarAuthError('misconfigured', `Introspection refused this service's client credentials (${status})`, { grantId });
111
+ }
112
+ if (status !== 200) {
113
+ throw new NevarAuthError('dependency_unavailable', `Introspection returned ${status}`, { grantId });
114
+ }
115
+ if (body.active !== true) {
116
+ throw new NevarAuthError('revoked', 'Credential is not active', {
117
+ grantId: typeof body.nevar_grant_id === 'string' ? body.nevar_grant_id : grantId,
118
+ });
119
+ }
120
+ return body;
121
+ }
122
+ async function verifyJwt(token, audience) {
123
+ let grantId = null;
124
+ let kid;
125
+ let alg;
126
+ try {
127
+ ({ kid, alg } = decodeProtectedHeader(token));
128
+ const grant = decodeJwt(token).nevar_grant_id; // unverified; used only as a log reference
129
+ grantId = typeof grant === 'string' ? grant : null;
130
+ }
131
+ catch (cause) {
132
+ throw new NevarAuthError('invalid_token', 'Credential is neither a JWT nor an api_/mcp_ key', { cause });
133
+ }
134
+ if (!kid)
135
+ throw new NevarAuthError('invalid_token', 'Token header has no kid', { grantId });
136
+ if (!alg || !ASYMMETRIC_ALGORITHMS.includes(alg)) {
137
+ throw new NevarAuthError('invalid_token', `Algorithm ${String(alg)} is not an allowed asymmetric algorithm`, { grantId });
138
+ }
139
+ if (mode !== 'test' && kid === TEST_KID) {
140
+ throw new NevarAuthError('untrusted_key', 'Test-only signing key refused in production mode', { grantId });
141
+ }
142
+ let payload;
143
+ try {
144
+ ({ payload } = await jwtVerify(token, getKey, {
145
+ issuer,
146
+ audience,
147
+ algorithms: ASYMMETRIC_ALGORITHMS,
148
+ requiredClaims: ['exp', 'iss', 'aud', 'sub'],
149
+ }));
150
+ }
151
+ catch (cause) {
152
+ throw jwtError(cause, grantId);
153
+ }
154
+ if (Array.isArray(payload.aud) && payload.aud.length !== 1) {
155
+ throw new NevarAuthError('wrong_audience', 'Token names more than one audience', { grantId });
156
+ }
157
+ // Signature and claims hold; the issuer decides whether the grant is still live. Nothing caches a positive answer.
158
+ await introspect(token, grantId);
159
+ return payload;
160
+ }
161
+ async function verifyKey(key, audience) {
162
+ const prefix = key.slice(0, 3);
163
+ if (audienceSurface(audience) !== prefix) {
164
+ throw new NevarAuthError('wrong_surface', `A ${prefix}_ key is not accepted on ${audience}`);
165
+ }
166
+ const claims = await introspect(key, null);
167
+ const grantId = typeof claims.nevar_grant_id === 'string' ? claims.nevar_grant_id : null;
168
+ if (claims.iss !== issuer)
169
+ throw new NevarAuthError('wrong_issuer', 'Key was issued by another issuer', { grantId });
170
+ const aud = Array.isArray(claims.aud) && claims.aud.length === 1 ? claims.aud[0] : claims.aud;
171
+ if (aud !== audience)
172
+ throw new NevarAuthError('wrong_audience', `Key is not for ${audience}`, { grantId });
173
+ if (claims.exp !== undefined && (typeof claims.exp !== 'number' || !Number.isFinite(claims.exp))) {
174
+ throw new NevarAuthError('invalid_token', 'Claim exp is invalid', { grantId });
175
+ }
176
+ if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
177
+ throw new NevarAuthError('expired', 'Key has expired', { grantId });
178
+ }
179
+ return claims;
180
+ }
181
+ return {
182
+ async verifyCredential(credential, { audience, correlationId }) {
183
+ try {
184
+ requireAudience(audience);
185
+ if (typeof credential !== 'string')
186
+ throw new NevarAuthError('invalid_token', 'Credential is not a string');
187
+ const token = credential.replace(/^Bearer\s+/i, '').trim();
188
+ const claims = /^(api|mcp)_/.test(token) ? await verifyKey(token, audience) : await verifyJwt(token, audience);
189
+ return toActorContext(claims, audience);
190
+ }
191
+ catch (error) {
192
+ const authError = error instanceof NevarAuthError ? error : new NevarAuthError('invalid_token', 'Verification failed', { cause: error });
193
+ logger?.warn('nevar-auth: credential denied', {
194
+ code: authError.code,
195
+ grantId: authError.grantId,
196
+ audience,
197
+ correlationId,
198
+ });
199
+ throw authError;
200
+ }
201
+ },
202
+ async delegateActor({ serviceToken, subjectToken, audience, correlationId }) {
203
+ try {
204
+ requireAudience(audience);
205
+ const { token_endpoint } = await discover();
206
+ if (!token_endpoint)
207
+ throw new NevarAuthError('misconfigured', 'Discovery has no token_endpoint');
208
+ const { status, body } = await post(token_endpoint, {
209
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
210
+ subject_token: subjectToken,
211
+ subject_token_type: TOKEN_TYPE_ACCESS,
212
+ actor_token: serviceToken,
213
+ actor_token_type: TOKEN_TYPE_ACCESS,
214
+ audience,
215
+ });
216
+ if (status !== 200 || typeof body.access_token !== 'string') {
217
+ throw new NevarAuthError('invalid_delegation', `Token exchange refused: ${String(body.error ?? status)}${typeof body.error_description === 'string' ? ` (${body.error_description})` : ''}`);
218
+ }
219
+ return { token: body.access_token, expiresIn: typeof body.expires_in === 'number' ? body.expires_in : null };
220
+ }
221
+ catch (error) {
222
+ if (error instanceof NevarAuthError) {
223
+ logger?.warn('nevar-auth: delegation failed', { code: error.code, audience, correlationId });
224
+ }
225
+ throw error;
226
+ }
227
+ },
228
+ };
229
+ }
230
+ /** jose skips the `aud` check when `audience` is undefined, so a missing audience must never reach it. */
231
+ function requireAudience(audience) {
232
+ if (typeof audience !== 'string' || audience === '') {
233
+ throw new NevarAuthError('misconfigured', 'The caller must name the audience it expects');
234
+ }
235
+ }
236
+ /** `api` for `https://api.…`, `mcp` for `https://mcp.…`, otherwise `null` (no typed key is accepted there). */
237
+ export function audienceSurface(audience) {
238
+ let host;
239
+ try {
240
+ host = new URL(audience).hostname;
241
+ }
242
+ catch {
243
+ return null; // not a URL, so not an api/mcp resource
244
+ }
245
+ const label = host.split('.')[0];
246
+ return label === 'api' || label === 'mcp' ? label : null;
247
+ }
248
+ function jwtError(cause, grantId) {
249
+ if (cause instanceof NevarAuthError)
250
+ return cause;
251
+ let code = 'invalid_token';
252
+ if (cause instanceof joseErrors.JWTExpired)
253
+ code = 'expired';
254
+ else if (cause instanceof joseErrors.JWTClaimValidationFailed && cause.claim === 'iss')
255
+ code = 'wrong_issuer';
256
+ else if (cause instanceof joseErrors.JWTClaimValidationFailed && cause.claim === 'aud')
257
+ code = 'wrong_audience';
258
+ return new NevarAuthError(code, cause instanceof Error ? cause.message : 'Token verification failed', { cause, grantId });
259
+ }
260
+ function toActorContext(claims, audience) {
261
+ const grantId = typeof claims.nevar_grant_id === 'string' && claims.nevar_grant_id ? claims.nevar_grant_id : null;
262
+ const invalid = (claim) => new NevarAuthError('invalid_token', `Claim ${claim} is missing or invalid`, { grantId });
263
+ const actorType = claims.nevar_actor_type;
264
+ if (typeof claims.sub !== 'string' || !UUID.test(claims.sub))
265
+ throw invalid('sub');
266
+ if (!ACTOR_TYPES.includes(actorType))
267
+ throw invalid('nevar_actor_type');
268
+ const owner = claims.nevar_owner_sub ?? undefined; // serializers emit null for "no owner"; treat it as absent
269
+ if (owner !== undefined && (typeof owner !== 'string' || !UUID.test(owner)))
270
+ throw invalid('nevar_owner_sub');
271
+ if (actorType !== 'user' && owner === undefined)
272
+ throw invalid('nevar_owner_sub');
273
+ if (typeof claims.nevar_org_id !== 'string' || !claims.nevar_org_id)
274
+ throw invalid('nevar_org_id');
275
+ if (typeof claims.scope !== 'string')
276
+ throw invalid('scope');
277
+ if (!grantId)
278
+ throw invalid('nevar_grant_id');
279
+ if (claims.role !== 'authenticated')
280
+ throw invalid('role');
281
+ const act = claims.act ?? undefined; // null means "not delegated", same as absent
282
+ if (act !== undefined && !isActClaim(act)) {
283
+ throw new NevarAuthError('invalid_delegation', 'Claim act is malformed', { grantId });
284
+ }
285
+ return {
286
+ sub: claims.sub,
287
+ nevar_actor_type: actorType,
288
+ nevar_owner_sub: owner ?? null,
289
+ nevar_org_id: claims.nevar_org_id,
290
+ scope: claims.scope,
291
+ nevar_grant_id: grantId,
292
+ act: act ?? null,
293
+ role: 'authenticated',
294
+ aud: audience,
295
+ };
296
+ }
297
+ function isActClaim(value) {
298
+ if (typeof value !== 'object' || value === null)
299
+ return false;
300
+ const { sub, act } = value;
301
+ return typeof sub === 'string' && UUID.test(sub) && (act === undefined || isActClaim(act));
302
+ }
@@ -0,0 +1,106 @@
1
+ export { TEST_KID } from '../index.js';
2
+ /** Test-only ES256 private key. Never trusted in production mode. */
3
+ export declare const TEST_PRIVATE_JWK: {
4
+ readonly kty: "EC";
5
+ readonly crv: "P-256";
6
+ readonly x: "hoZ_zvbuOcVC9pqHSsMKjy3bkKsK7kSIyX5T-nAyByM";
7
+ readonly y: "Lht8xVjTepstmdHUrlt0kfBcCAgiyWX9Ieuy4-3QAlM";
8
+ readonly d: "K5iFaUp37Elhqiu2f4qy-qob2X1FrulwcPwN9AkYCQk";
9
+ readonly kid: "test-only-not-production";
10
+ readonly alg: "ES256";
11
+ };
12
+ /** The public JWKS the test issuer serves. */
13
+ export declare const TEST_JWKS: {
14
+ readonly keys: readonly [{
15
+ readonly kty: "EC";
16
+ readonly crv: "P-256";
17
+ readonly x: "hoZ_zvbuOcVC9pqHSsMKjy3bkKsK7kSIyX5T-nAyByM";
18
+ readonly y: "Lht8xVjTepstmdHUrlt0kfBcCAgiyWX9Ieuy4-3QAlM";
19
+ readonly kid: "test-only-not-production";
20
+ readonly alg: "ES256";
21
+ readonly use: "sig";
22
+ }];
23
+ };
24
+ export declare const TEST_AUDIENCES: {
25
+ readonly api: "https://api.nevar.io/v1/plan";
26
+ readonly mcp: "https://mcp.nevar.io/v1/plan";
27
+ /** Same surface as `api`, different resource: a token for `api` is refused here. */
28
+ readonly otherApi: "https://api.nevar.io/v1/mail";
29
+ };
30
+ export declare const TEST_SUBJECTS: {
31
+ readonly user: "00000000-0000-4000-8000-000000000001";
32
+ readonly agent: "00000000-0000-4000-8000-000000000002";
33
+ readonly service: "00000000-0000-4000-8000-000000000003";
34
+ /** A user in the second organization. */
35
+ readonly otherUser: "00000000-0000-4000-8000-000000000004";
36
+ };
37
+ export declare const TEST_ORGS: {
38
+ readonly primary: "org_test_primary";
39
+ readonly other: "org_test_other";
40
+ };
41
+ /** Client credentials the test issuer accepts at `/oauth/introspect`. */
42
+ export declare const TEST_INTROSPECTION_CLIENT: {
43
+ readonly clientId: "test-only-client";
44
+ readonly clientSecret: "test-only-secret:with+special%chars";
45
+ };
46
+ /** Opaque typed keys the test issuer knows. Never JWTs. */
47
+ export declare const TEST_KEYS: {
48
+ readonly api: "api_test_only_0000000000000000000000000001";
49
+ readonly mcp: "mcp_test_only_0000000000000000000000000002";
50
+ };
51
+ export declare const TEST_GRANTS: {
52
+ readonly user: "grant_test_user";
53
+ readonly agent: "grant_test_agent";
54
+ readonly service: "grant_test_service";
55
+ readonly revoked: "grant_test_revoked";
56
+ readonly apiKey: "grant_test_api_key";
57
+ readonly mcpKey: "grant_test_mcp_key";
58
+ };
59
+ /** Claims of the default user token. `sign()` merges overrides onto these. */
60
+ export declare const TEST_USER_CLAIMS: {
61
+ readonly sub: "00000000-0000-4000-8000-000000000001";
62
+ readonly nevar_actor_type: "user";
63
+ readonly nevar_org_id: "org_test_primary";
64
+ readonly scope: "plan:read plan:write";
65
+ readonly nevar_grant_id: "grant_test_user";
66
+ readonly role: "authenticated";
67
+ readonly aud: "https://api.nevar.io/v1/plan";
68
+ };
69
+ export type TestEndpoint = 'discovery' | 'jwks' | 'introspection' | 'token';
70
+ export interface SignOptions {
71
+ /** jose time span or seconds from now. Default `'10m'`. A negative number makes an expired token; `null` omits `exp`. */
72
+ expiresIn?: string | number | null;
73
+ /** Default: this issuer's URL. */
74
+ issuer?: string;
75
+ /** Header `kid`. Default `test-only-not-production`; `null` omits it. */
76
+ kid?: string | null;
77
+ }
78
+ export interface TestIssuer {
79
+ /** Issuer identifier and base URL, e.g. `http://127.0.0.1:54321`. */
80
+ url: string;
81
+ /** Signed sample tokens, minted for this issuer's URL when it starts. */
82
+ tokens: {
83
+ valid: string;
84
+ expired: string;
85
+ wrongAudience: string;
86
+ wrongIssuer: string;
87
+ /** Validly signed, but its grant is revoked at the issuer. */
88
+ revoked: string;
89
+ agent: string;
90
+ /** A service token: the `serviceToken` for `delegateActor`. */
91
+ service: string;
92
+ };
93
+ keys: typeof TEST_KEYS;
94
+ introspectionClient: typeof TEST_INTROSPECTION_CLIENT;
95
+ /** Sign any claims with the test key. Overrides merge onto `TEST_USER_CLAIMS`; `undefined` removes a claim. */
96
+ sign(claims?: Record<string, unknown>, options?: SignOptions): Promise<string>;
97
+ /** Revoke a grant: introspection reports every token and key with this `nevar_grant_id` inactive from now on. */
98
+ revoke(grantId: string): void;
99
+ /** Make an endpoint answer 503 (or recover with `false`), to test `dependency_unavailable`. */
100
+ setUnavailable(endpoint: TestEndpoint, unavailable?: boolean): void;
101
+ close(): Promise<void>;
102
+ }
103
+ /** Start a test issuer on 127.0.0.1. Serves discovery, JWKS, RFC 7662 introspection and RFC 8693 token exchange. */
104
+ export declare function startTestIssuer(options?: {
105
+ port?: number;
106
+ }): Promise<TestIssuer>;
@@ -0,0 +1,259 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /**
9
+ * Test fixtures and a real-HTTP test issuer for `@bernierllc/nevar-auth`.
10
+ *
11
+ * Everything here is signed with the test-only key (`kid` `test-only-not-production`), which a verifier in
12
+ * production mode refuses. Use `createNevarAuth({ mode: 'test', issuer: testIssuer.url, ... })` in tests.
13
+ */
14
+ import { createServer } from 'node:http';
15
+ import { importJWK, jwtVerify, SignJWT } from 'jose';
16
+ import { TEST_KID } from '../index.js';
17
+ export { TEST_KID } from '../index.js';
18
+ /** Test-only ES256 private key. Never trusted in production mode. */
19
+ export const TEST_PRIVATE_JWK = {
20
+ kty: 'EC',
21
+ crv: 'P-256',
22
+ x: 'hoZ_zvbuOcVC9pqHSsMKjy3bkKsK7kSIyX5T-nAyByM',
23
+ y: 'Lht8xVjTepstmdHUrlt0kfBcCAgiyWX9Ieuy4-3QAlM',
24
+ d: 'K5iFaUp37Elhqiu2f4qy-qob2X1FrulwcPwN9AkYCQk',
25
+ kid: TEST_KID,
26
+ alg: 'ES256',
27
+ };
28
+ /** The public JWKS the test issuer serves. */
29
+ export const TEST_JWKS = {
30
+ keys: [{ kty: 'EC', crv: 'P-256', x: TEST_PRIVATE_JWK.x, y: TEST_PRIVATE_JWK.y, kid: TEST_KID, alg: 'ES256', use: 'sig' }],
31
+ };
32
+ export const TEST_AUDIENCES = {
33
+ api: 'https://api.nevar.io/v1/plan',
34
+ mcp: 'https://mcp.nevar.io/v1/plan',
35
+ /** Same surface as `api`, different resource: a token for `api` is refused here. */
36
+ otherApi: 'https://api.nevar.io/v1/mail',
37
+ };
38
+ export const TEST_SUBJECTS = {
39
+ user: '00000000-0000-4000-8000-000000000001',
40
+ agent: '00000000-0000-4000-8000-000000000002',
41
+ service: '00000000-0000-4000-8000-000000000003',
42
+ /** A user in the second organization. */
43
+ otherUser: '00000000-0000-4000-8000-000000000004',
44
+ };
45
+ export const TEST_ORGS = { primary: 'org_test_primary', other: 'org_test_other' };
46
+ /** Client credentials the test issuer accepts at `/oauth/introspect`. */
47
+ export const TEST_INTROSPECTION_CLIENT = { clientId: 'test-only-client', clientSecret: 'test-only-secret:with+special%chars' };
48
+ /** Opaque typed keys the test issuer knows. Never JWTs. */
49
+ export const TEST_KEYS = {
50
+ api: 'api_test_only_0000000000000000000000000001',
51
+ mcp: 'mcp_test_only_0000000000000000000000000002',
52
+ };
53
+ export const TEST_GRANTS = {
54
+ user: 'grant_test_user',
55
+ agent: 'grant_test_agent',
56
+ service: 'grant_test_service',
57
+ revoked: 'grant_test_revoked',
58
+ apiKey: 'grant_test_api_key',
59
+ mcpKey: 'grant_test_mcp_key',
60
+ };
61
+ /** Claims of the default user token. `sign()` merges overrides onto these. */
62
+ export const TEST_USER_CLAIMS = {
63
+ sub: TEST_SUBJECTS.user,
64
+ nevar_actor_type: 'user',
65
+ nevar_org_id: TEST_ORGS.primary,
66
+ scope: 'plan:read plan:write',
67
+ nevar_grant_id: TEST_GRANTS.user,
68
+ role: 'authenticated',
69
+ aud: TEST_AUDIENCES.api,
70
+ };
71
+ const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
72
+ const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
73
+ const WRONG_ISSUER = 'https://auth.wrong-issuer.invalid';
74
+ /** Start a test issuer on 127.0.0.1. Serves discovery, JWKS, RFC 7662 introspection and RFC 8693 token exchange. */
75
+ export async function startTestIssuer(options = {}) {
76
+ const privateKey = await importJWK(TEST_PRIVATE_JWK, 'ES256');
77
+ const publicKey = await importJWK(TEST_JWKS.keys[0], 'ES256');
78
+ const revoked = new Set([TEST_GRANTS.revoked]);
79
+ const unavailable = new Set();
80
+ let url = '';
81
+ async function sign(claims = {}, opts = {}) {
82
+ const merged = { ...TEST_USER_CLAIMS, ...claims };
83
+ for (const key of Object.keys(merged))
84
+ if (merged[key] === undefined)
85
+ delete merged[key];
86
+ const kid = opts.kid === undefined ? TEST_KID : opts.kid;
87
+ const now = Math.floor(Date.now() / 1000);
88
+ const expiresIn = opts.expiresIn === undefined ? '10m' : opts.expiresIn;
89
+ const jwt = new SignJWT(merged)
90
+ .setProtectedHeader(kid === null ? { alg: 'ES256' } : { alg: 'ES256', kid })
91
+ .setIssuer(opts.issuer ?? url)
92
+ .setIssuedAt(typeof expiresIn === 'number' && expiresIn < 0 ? now + expiresIn - 60 : now);
93
+ if (expiresIn !== null)
94
+ jwt.setExpirationTime(typeof expiresIn === 'number' ? now + expiresIn : expiresIn);
95
+ return jwt.sign(privateKey);
96
+ }
97
+ const keyClaims = () => ({
98
+ [TEST_KEYS.api]: {
99
+ ...TEST_USER_CLAIMS,
100
+ sub: TEST_SUBJECTS.agent,
101
+ nevar_actor_type: 'agent',
102
+ nevar_owner_sub: TEST_SUBJECTS.user,
103
+ nevar_grant_id: TEST_GRANTS.apiKey,
104
+ aud: TEST_AUDIENCES.api,
105
+ iss: url,
106
+ },
107
+ [TEST_KEYS.mcp]: {
108
+ ...TEST_USER_CLAIMS,
109
+ sub: TEST_SUBJECTS.agent,
110
+ nevar_actor_type: 'agent',
111
+ nevar_owner_sub: TEST_SUBJECTS.user,
112
+ nevar_grant_id: TEST_GRANTS.mcpKey,
113
+ aud: TEST_AUDIENCES.mcp,
114
+ iss: url,
115
+ },
116
+ });
117
+ /** Our own signature + issuer + expiry, and the grant not revoked. Audience is the caller's job. */
118
+ async function live(token) {
119
+ try {
120
+ const { payload } = await jwtVerify(token, publicKey, { issuer: url });
121
+ return revoked.has(String(payload.nevar_grant_id)) ? null : payload;
122
+ }
123
+ catch {
124
+ return null; // not ours, expired or tampered: inactive per RFC 7662
125
+ }
126
+ }
127
+ async function introspect(form) {
128
+ const token = form.get('token') ?? '';
129
+ const key = keyClaims()[token];
130
+ if (key)
131
+ return revoked.has(String(key.nevar_grant_id)) ? { active: false } : { active: true, ...key };
132
+ const payload = await live(token);
133
+ return payload ? { active: true, ...payload } : { active: false };
134
+ }
135
+ async function exchange(form) {
136
+ if (form.get('grant_type') !== TOKEN_EXCHANGE)
137
+ return [400, { error: 'unsupported_grant_type' }];
138
+ const audiences = form.getAll('audience');
139
+ if (audiences.length !== 1 || !audiences[0]) {
140
+ return [400, { error: 'invalid_target', error_description: 'exactly one audience' }];
141
+ }
142
+ const subject = await live(form.get('subject_token') ?? '');
143
+ const actor = await live(form.get('actor_token') ?? '');
144
+ if (!subject)
145
+ return [400, { error: 'invalid_grant', error_description: 'subject_token is not active' }];
146
+ if (!actor || actor.nevar_actor_type !== 'service') {
147
+ return [400, { error: 'invalid_grant', error_description: 'actor_token must be an active service token' }];
148
+ }
149
+ const { iat: _iat, exp: _exp, iss: _iss, aud: _aud, jti: _jti, act: priorAct, ...claims } = subject;
150
+ const act = priorAct ? { sub: actor.sub, act: priorAct } : { sub: actor.sub };
151
+ const accessToken = await sign({ ...claims, aud: audiences[0], act }, { expiresIn: 300 });
152
+ return [200, { access_token: accessToken, issued_token_type: ACCESS_TOKEN_TYPE, token_type: 'Bearer', expires_in: 300 }];
153
+ }
154
+ async function handle(req, res) {
155
+ const send = (status, body) => {
156
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify(body));
157
+ };
158
+ const path = new URL(req.url ?? '/', url).pathname;
159
+ const routes = {
160
+ 'GET /.well-known/openid-configuration': 'discovery',
161
+ 'GET /.well-known/jwks.json': 'jwks',
162
+ 'POST /oauth/introspect': 'introspection',
163
+ 'POST /oauth/token': 'token',
164
+ };
165
+ const endpoint = routes[`${req.method} ${path}`];
166
+ if (!endpoint)
167
+ return send(404, { error: 'not_found' });
168
+ if (unavailable.has(endpoint))
169
+ return send(503, { error: 'temporarily_unavailable' });
170
+ let raw = '';
171
+ req.setEncoding('utf8');
172
+ for await (const chunk of req)
173
+ raw += chunk;
174
+ const form = new URLSearchParams(raw);
175
+ switch (endpoint) {
176
+ case 'discovery':
177
+ return send(200, {
178
+ issuer: url,
179
+ jwks_uri: `${url}/.well-known/jwks.json`,
180
+ token_endpoint: `${url}/oauth/token`,
181
+ introspection_endpoint: `${url}/oauth/introspect`,
182
+ grant_types_supported: [TOKEN_EXCHANGE],
183
+ id_token_signing_alg_values_supported: ['ES256'],
184
+ });
185
+ case 'jwks':
186
+ return send(200, TEST_JWKS);
187
+ case 'introspection': {
188
+ if (!basicAuthMatches(req.headers.authorization))
189
+ return send(401, { error: 'invalid_client' });
190
+ return send(200, await introspect(form));
191
+ }
192
+ case 'token': {
193
+ const [status, body] = await exchange(form);
194
+ return send(status, body);
195
+ }
196
+ }
197
+ }
198
+ const server = createServer((req, res) => {
199
+ handle(req, res).catch((error) => {
200
+ console.error('nevar-auth test issuer: request failed', error);
201
+ res.writeHead(500).end();
202
+ });
203
+ });
204
+ await new Promise((resolve, reject) => {
205
+ server.once('error', reject);
206
+ server.listen(options.port ?? 0, '127.0.0.1', resolve);
207
+ });
208
+ url = `http://127.0.0.1:${server.address().port}`;
209
+ const service = {
210
+ sub: TEST_SUBJECTS.service,
211
+ nevar_actor_type: 'service',
212
+ nevar_owner_sub: TEST_SUBJECTS.user,
213
+ nevar_grant_id: TEST_GRANTS.service,
214
+ };
215
+ const tokens = {
216
+ valid: await sign(),
217
+ expired: await sign({}, { expiresIn: -3600 }),
218
+ wrongAudience: await sign({ aud: TEST_AUDIENCES.otherApi }),
219
+ wrongIssuer: await sign({}, { issuer: WRONG_ISSUER }),
220
+ revoked: await sign({ nevar_grant_id: TEST_GRANTS.revoked }),
221
+ agent: await sign({
222
+ sub: TEST_SUBJECTS.agent,
223
+ nevar_actor_type: 'agent',
224
+ nevar_owner_sub: TEST_SUBJECTS.user,
225
+ nevar_grant_id: TEST_GRANTS.agent,
226
+ }),
227
+ service: await sign(service),
228
+ };
229
+ return {
230
+ url,
231
+ tokens,
232
+ keys: TEST_KEYS,
233
+ introspectionClient: TEST_INTROSPECTION_CLIENT,
234
+ sign,
235
+ revoke: (grantId) => void revoked.add(grantId),
236
+ setUnavailable: (endpoint, value = true) => void (value ? unavailable.add(endpoint) : unavailable.delete(endpoint)),
237
+ close: () => new Promise((resolve, reject) => {
238
+ server.closeAllConnections();
239
+ server.close((error) => (error ? reject(error) : resolve()));
240
+ }),
241
+ };
242
+ }
243
+ /** RFC 6749 §2.3.1: Basic credentials are form-encoded before base64, so decode both halves before comparing. */
244
+ function basicAuthMatches(header) {
245
+ if (!header?.startsWith('Basic '))
246
+ return false;
247
+ const decoded = Buffer.from(header.slice(6), 'base64').toString();
248
+ const colon = decoded.indexOf(':');
249
+ if (colon < 0)
250
+ return false;
251
+ try {
252
+ const id = decodeURIComponent(decoded.slice(0, colon));
253
+ const secret = decodeURIComponent(decoded.slice(colon + 1));
254
+ return id === TEST_INTROSPECTION_CLIENT.clientId && secret === TEST_INTROSPECTION_CLIENT.clientSecret;
255
+ }
256
+ catch {
257
+ return false; // malformed percent-encoding is a bad credential, answered with 401
258
+ }
259
+ }
package/package.json CHANGED
@@ -1,10 +1,73 @@
1
1
  {
2
2
  "name": "@bernierllc/nevar-auth",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for @bernierllc/nevar-auth",
3
+ "version": "0.2.0",
4
+ "description": "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.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./testing": {
14
+ "types": "./dist/testing/index.d.ts",
15
+ "default": "./dist/testing/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20.0.0"
25
+ },
5
26
  "keywords": [
27
+ "nevar",
28
+ "auth",
29
+ "jwt",
30
+ "jwks",
6
31
  "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
32
+ "introspection",
33
+ "token-exchange",
34
+ "bernierllc"
35
+ ],
36
+ "author": "Bernier LLC",
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/bernierllc/tools",
41
+ "directory": "packages/core/nevar-auth"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "dependencies": {
48
+ "jose": "6.2.13"
49
+ },
50
+ "devDependencies": {
51
+ "@jest/globals": "^29.7.0",
52
+ "@types/jest": "^29.5.14",
53
+ "@types/node": "^20.0.0",
54
+ "@typescript-eslint/eslint-plugin": "^8.38.0",
55
+ "@typescript-eslint/parser": "^8.38.0",
56
+ "eslint": "^8.0.0",
57
+ "jest": "^29.5.0",
58
+ "rimraf": "^5.0.0",
59
+ "ts-jest": "^29.4.0",
60
+ "typescript": "^5.5.0"
61
+ },
62
+ "scripts": {
63
+ "build": "tsc -p tsconfig.json",
64
+ "dev": "tsc -p tsconfig.json --watch",
65
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
66
+ "test:run": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
67
+ "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch",
68
+ "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
69
+ "lint": "eslint src --ext .ts",
70
+ "lint:fix": "eslint src --ext .ts --fix",
71
+ "clean": "rimraf dist"
72
+ }
73
+ }