@bernierllc/nevar-auth 0.3.2 → 0.5.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/README.md CHANGED
@@ -6,7 +6,7 @@ Verifies nevar.io credentials (JWTs and typed `api_`/`mcp_` keys) and performs a
6
6
  npm install @bernierllc/nevar-auth
7
7
  ```
8
8
 
9
- **Contract:** `ifc:platform/authentication` (`#ActorContext` rev 1), 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`.
9
+ **Contract:** `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`.
10
10
 
11
11
  ## Rules this package enforces
12
12
 
@@ -16,6 +16,7 @@ npm install @bernierllc/nevar-auth
16
16
  - **Introspection uses the endpoint discovery names.** The verifier posts to discovery's `introspection_endpoint`, and falls back to `<issuer>/oauth/introspect` only 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 outside `mode: 'test'`, because it carries the client secret.
17
17
  - **Typed keys are opaque, and only work on configured audiences.** `api_` and `mcp_` keys are checked only through RFC 7662 introspection. The surface of an audience comes from `resourceAudiences`, a set of exact audience URLs per surface, never from the host name: an `api_` key works only on an audience in `resourceAudiences.api`, an `mcp_` key only on one in `resourceAudiences.mcp`, and any other audience refuses both with `wrong_surface`. Omitting `resourceAudiences` is 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.
18
18
  - **JWTs are introspected too, after local verification.** A revoked grant is therefore denied on the very next call. `scope` and `nevar_grant_id` in the returned `ActorContext` come from the introspection response, not from the JWT; a response with no `scope` is refused. The response must also say `role: "authenticated"`: any other role (such as `service_role`), or none, is refused with `invalid_token`.
19
+ - **Execution-grant claims (since 0.4.0).** `nevar_project_id` and `nevar_callback_op` come back on the `ActorContext`, both `null` on every credential that is not an execution grant. A token that carries either claim (JSON `null` counts as carrying it) must carry a `nevar_callback_op` that is a string matching the OperationCatalog id pattern, and a `nevar_project_id` that is a non-empty string or JSON `null`; anything else is refused with `invalid_token` (JWTs, `api_` and `mcp_` keys alike). That includes an operation with no project claim, a project claim with a missing or `null` operation, 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 only `scope`, `nevar_grant_id` and `role`); for an `api_`/`mcp_` key they come from the introspection response.
19
20
  - **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.
20
21
  - **Delegation only talks to the issuer and returns only a verified token.** `delegateActor` requires a `token_endpoint` in discovery on the issuer's own origin, over https (plain http only in `mode: 'test'`). It authenticates with HTTP Basic using `introspectionClient`, and the actor (service) token's `aud` must be the issuer. The returned token is verified for the requested audience, including introspection, before `delegateActor` returns it; if that check cannot complete, the call fails.
21
22
  - **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.
@@ -44,7 +45,8 @@ try {
44
45
  correlationId: req.id,
45
46
  });
46
47
  // actor.sub, actor.nevar_actor_type, actor.nevar_owner_sub, actor.nevar_org_id,
47
- // actor.scope, actor.nevar_grant_id, actor.act, actor.role ("authenticated"), actor.aud
48
+ // actor.scope, actor.nevar_grant_id, actor.act, actor.role ("authenticated"), actor.aud,
49
+ // actor.nevar_project_id, actor.nevar_callback_op (execution-grant claims, string | null; since 0.4.0)
48
50
  } catch (error) {
49
51
  if (error instanceof NevarAuthError && error.retryable) return res.status(503).end();
50
52
  return res.status(401).end();
@@ -58,6 +60,29 @@ const { token } = await auth.delegateActor({
58
60
  });
59
61
  ```
60
62
 
63
+ ## Staff console guard: `requireStaff(scope)`
64
+
65
+ Guards a staff-console route. It is a separate path from `verifyCredential`: staff tokens introspect without an organization or a role, so `verifyCredential` still refuses them and nothing about its checks changed.
66
+
67
+ ```ts
68
+ const guard = auth.requireStaff('admin:danger'); // build once; throws `misconfigured` unless scope is one RFC 6749 scope-token (printable ASCII, no space, quote or backslash) and a `logger` is configured
69
+
70
+ const decision = await guard(request.headers.authorization, { correlationId: requestId });
71
+ if (!decision.allowed) {
72
+ const { status, headers, body } = decision.response; // always the same 404
73
+ return send(status, headers, body);
74
+ }
75
+ const { sub, grantId, authTime, scope } = decision.staff;
76
+ ```
77
+
78
+ It allows a request only when introspection says the token is active **and** `iss` is this issuer, `acr` is `STAFF_ACR`, `aud` is one string matching the staff audience set for the environment, the required claims are present, `exp` is in the future and the token's `scope` list (single-space separated, RFC 6749 syntax; anything else, including Unicode whitespace, is `invalid_claims`) contains the one you asked for. A credential that is not RFC 6750 bearer syntax (NUL, control characters, non-ASCII, quotes) is `malformed_token` and never reaches the issuer. `acr` and `aud` are checked separately (the issuer decides a token is a staff token from `acr`, not `aud`).
79
+
80
+ - **One refusal.** Every reason returns the identical 404: same status, headers and bytes (`buildStaffRefusal()`, `STAFF_REFUSAL_BODY`). A caller cannot tell a revoked console from a missing scope from an outage.
81
+ - **Fails closed.** An introspection outage, a misconfigured client or any unexpected error refuses; it is never treated as inactive and never as allowed.
82
+ - **Logging.** The reason goes to your `logger` with the grant id, the scope and a stable code, never the token or the response: `malformed_token`, `inactive`, `wrong_issuer`, `expired`, `wrong_acr`, `wrong_audience`, `missing_scope`, `invalid_claims`, `introspection_unavailable`, `introspection_misconfigured`, `internal_error`. `requireStaff` refuses to build without a `logger`: with none, refusals and outages would vanish behind a bare 404. The last three are errors and go to the optional `logger.error` (falling back to `warn`) so a monitor can see them.
83
+ - **Environment.** The production issuer maps to the production audience set; any other issuer (staging, a local test issuer) maps to the staging set.
84
+ - **Pinned, not fetched.** `STAFF_ACR`, `STAFF_AUDIENCE_PATTERNS`, `STAFF_TOKEN_TTL_SECONDS` (300), `STAFF_STEP_UP_WINDOW_SECONDS` (300), `STAFF_CONSOLE_REV` (2) and `ACTOR_CONTEXT_REV` (4) are constants in source, equal to the vendored hub fixture under `src/__tests__/fixtures/`. There is no runtime config, env or fetch. A change is a new fixture revision and a minor release.
85
+
61
86
  ## Error codes
62
87
 
63
88
  Each of these is a `NevarAuthError` with a `code`, a `retryable` flag and a `grantId` (or `null`).
@@ -105,7 +130,7 @@ await issuer.close();
105
130
  - `startTestIssuer({ introspectionPath, advertiseIntrospection })` moves the introspection route (default `/oauth/introspect`) or leaves `introspection_endpoint` out of discovery.
106
131
 
107
132
  **Sample credentials:**
108
- - `issuer.tokens`: `valid`, `expired`, `wrongAudience`, `wrongIssuer`, `revoked`, `agent` and `service` (whose `aud` is the issuer).
133
+ - `issuer.tokens`: `valid`, `expired`, `wrongAudience`, `wrongIssuer`, `revoked`, `agent`, `service` (whose `aud` is the issuer) and `executionGrant` (since 0.4.0: a service token carrying `TEST_EXECUTION_GRANT`, project `proj_test_1` and operation `projects.tasks.run_due`).
109
134
  - `TEST_RESOURCE_AUDIENCES`: the `resourceAudiences` set matching `TEST_AUDIENCES`.
110
135
  - `TEST_KEYS`: one `api_` key and one `mcp_` key.
111
136
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { type StaffDecision, type StaffGuardOptions } from './staff.js';
1
2
  export { NevarAuthError, type NevarAuthErrorCode } from './errors.js';
3
+ export { ACTOR_CONTEXT_REV, buildStaffRefusal, STAFF_ACR, STAFF_AUDIENCE_PATTERNS, STAFF_CONSOLE_REV, STAFF_REFUSAL_BODY, STAFF_STEP_UP_WINDOW_SECONDS, STAFF_TOKEN_TTL_SECONDS, type StaffContext, type StaffDecision, type StaffEnvironment, type StaffGuardOptions, type StaffRefusal, type StaffRefusalReason, } from './staff.js';
2
4
  /** The two real issuers. Pass one as `issuer`. */
3
5
  export declare const NEVAR_ISSUERS: {
4
6
  readonly production: "https://auth.nevar.io";
@@ -28,10 +30,16 @@ export interface ActorContext {
28
30
  role: 'authenticated';
29
31
  /** The audience this credential was verified for. */
30
32
  aud: string;
33
+ /** ActorContext rev 3: the project an execution-grant token is bound to; `null` on every other token and on a grant with no project. */
34
+ nevar_project_id: string | null;
35
+ /** ActorContext rev 3: the OperationCatalog id an execution-grant token is bound to; `null` on every other token. The callee enforces the binding. */
36
+ nevar_callback_op: string | null;
31
37
  }
32
38
  /** Anything with `warn(message, context)`, e.g. a `@bernierllc/logger` instance. */
33
39
  export interface NevarAuthLogger {
34
40
  warn(message: string, context?: Record<string, unknown>): void;
41
+ /** Optional. `requireStaff` uses it when the issuer could not answer, so a monitor sees an outage apart from refusals. */
42
+ error?(message: string, context?: Record<string, unknown>): void;
35
43
  }
36
44
  /**
37
45
  * The exact resource audiences typed keys may be used on (Q15). An `api_` key is accepted only when the expected
@@ -91,6 +99,13 @@ export interface NevarAuth {
91
99
  verifyCredential(credential: string, options: VerifyOptions): Promise<ActorContext>;
92
100
  /** RFC 8693 token exchange: a token for `audience` that carries the user as `sub` and this service in `act`. */
93
101
  delegateActor(options: DelegateOptions): Promise<DelegatedToken>;
102
+ /**
103
+ * Guard for one staff-console scope. `auth.requireStaff('admin:danger')` returns a function; call it with the bearer
104
+ * credential. Allows only an active token with `acr` `STAFF_ACR`, a staff `aud` for this issuer's environment (production
105
+ * issuer: production set; any other issuer: staging set) and the scope. Never throws on a bad credential: every refusal
106
+ * is `{ allowed: false, response }` with the same `buildStaffRefusal()` bytes. Throws `misconfigured` on a bad `scope`.
107
+ */
108
+ requireStaff(scope: string): (credential: unknown, options?: StaffGuardOptions) => Promise<StaffDecision>;
94
109
  }
95
110
  export declare function createNevarAuth(config: NevarAuthConfig): NevarAuth;
96
111
  /**
package/dist/index.js CHANGED
@@ -7,7 +7,13 @@ Redistribution or use in other products or commercial offerings is not permitted
7
7
  */
8
8
  import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors as joseErrors, jwtVerify, } from 'jose';
9
9
  import { NevarAuthError } from './errors.js';
10
+ import { assertStaffScope, buildStaffRefusal, evaluateStaffClaims, } from './staff.js';
10
11
  export { NevarAuthError } from './errors.js';
12
+ export { ACTOR_CONTEXT_REV, buildStaffRefusal, STAFF_ACR, STAFF_AUDIENCE_PATTERNS, STAFF_CONSOLE_REV, STAFF_REFUSAL_BODY, STAFF_STEP_UP_WINDOW_SECONDS, STAFF_TOKEN_TTL_SECONDS, } from './staff.js';
13
+ /** A staff token is short; anything longer is refused before it is sent to the issuer. */
14
+ // RFC 6750 b64token: a JWT or typed key is base64url plus dots; anything else (NUL, Unicode, quotes) never reaches the issuer.
15
+ const BEARER_TOKEN_RE = /^[A-Za-z0-9\-._~+/]+=*$/;
16
+ const MAX_STAFF_TOKEN_LENGTH = 8192;
11
17
  /** The two real issuers. Pass one as `issuer`. */
12
18
  export const NEVAR_ISSUERS = {
13
19
  production: 'https://auth.nevar.io',
@@ -124,7 +130,8 @@ export function createNevarAuth(config) {
124
130
  throw new NevarAuthError('dependency_unavailable', 'JWKS unreachable', { cause });
125
131
  }
126
132
  };
127
- async function introspect(token, grantId) {
133
+ /** The issuer's introspection answer as-is, active or not. Throws only when the issuer could not answer. */
134
+ async function introspectRaw(token, grantId) {
128
135
  // Q10: discovery's introspection_endpoint; the conventional path only when discovery names none.
129
136
  const { introspection_endpoint } = await discover();
130
137
  const endpoint = requireIssuerEndpoint(introspection_endpoint ?? `${issuer}/oauth/introspect`, 'introspection_endpoint');
@@ -135,6 +142,10 @@ export function createNevarAuth(config) {
135
142
  if (status !== 200) {
136
143
  throw new NevarAuthError('dependency_unavailable', `Introspection returned ${status}`, { grantId });
137
144
  }
145
+ return body;
146
+ }
147
+ async function introspect(token, grantId) {
148
+ const body = await introspectRaw(token, grantId);
138
149
  if (body.active !== true) {
139
150
  throw new NevarAuthError('revoked', 'Credential is not active', {
140
151
  grantId: typeof body.nevar_grant_id === 'string' ? body.nevar_grant_id : grantId,
@@ -228,7 +239,7 @@ export function createNevarAuth(config) {
228
239
  async function verify(credential, audience) {
229
240
  if (typeof credential !== 'string')
230
241
  throw new NevarAuthError('invalid_token', 'Credential is not a string');
231
- const token = credential.replace(/^Bearer\s+/i, '').trim();
242
+ const token = credential.replace(/^Bearer /i, '');
232
243
  const claims = /^(api|mcp)_/.test(token) ? await verifyKey(token, audience) : await verifyJwt(token, audience);
233
244
  return toActorContext(claims, audience);
234
245
  }
@@ -263,6 +274,69 @@ export function createNevarAuth(config) {
263
274
  throw authError;
264
275
  }
265
276
  },
277
+ requireStaff(scope) {
278
+ assertStaffScope(scope);
279
+ // Refusals and issuer outages are only visible through the logger; without one a monitor sees a silent 404.
280
+ if (!logger)
281
+ throw new NevarAuthError('misconfigured', 'requireStaff needs a logger: refusal reasons and issuer outages are only recorded there');
282
+ const environment = issuer === NEVAR_ISSUERS.production ? 'production' : 'staging';
283
+ return async (credential, { correlationId } = {}) => {
284
+ let grantId = null;
285
+ let reason;
286
+ const detail = {};
287
+ try {
288
+ const token = typeof credential === 'string' ? credential.replace(/^Bearer /i, '') : '';
289
+ if (!token || token.length > MAX_STAFF_TOKEN_LENGTH || !BEARER_TOKEN_RE.test(token)) {
290
+ reason = 'malformed_token';
291
+ }
292
+ else {
293
+ try {
294
+ const unverified = decodeJwt(token).nevar_grant_id; // log reference only, never trusted
295
+ if (typeof unverified === 'string')
296
+ grantId = unverified.slice(0, 64);
297
+ }
298
+ catch (notJwt) {
299
+ // Not a JWT: the issuer decides what this is. The grant ref just stays null in the log line.
300
+ if (!(notJwt instanceof joseErrors.JWTInvalid))
301
+ throw notJwt;
302
+ }
303
+ const body = await introspectRaw(token, grantId);
304
+ if (typeof body.nevar_grant_id === 'string')
305
+ grantId = body.nevar_grant_id.slice(0, 64);
306
+ if (typeof body.reason === 'string')
307
+ detail.issuerReason = body.reason.slice(0, 64);
308
+ const verdict = evaluateStaffClaims(body, { issuer, environment, scope, nowSeconds: Math.floor(Date.now() / 1000) });
309
+ if (verdict.ok)
310
+ return { allowed: true, staff: verdict.staff };
311
+ reason = verdict.reason;
312
+ }
313
+ }
314
+ catch (error) {
315
+ // Fail closed: an issuer outage or any bug is a refusal, never "inactive, so fine" and never an allow.
316
+ if (error instanceof NevarAuthError) {
317
+ reason = error.code === 'misconfigured' ? 'introspection_misconfigured' : 'introspection_unavailable';
318
+ detail.errorCode = error.code;
319
+ }
320
+ else {
321
+ reason = 'internal_error';
322
+ }
323
+ detail.error = error instanceof Error ? error.message : String(error);
324
+ }
325
+ const context = { reason, grantId, scope, correlationId, ...detail };
326
+ const monitored = reason === 'introspection_unavailable' || reason === 'introspection_misconfigured' || reason === 'internal_error';
327
+ try {
328
+ if (monitored && logger.error)
329
+ logger.error('nevar-auth: staff check could not complete', context);
330
+ else
331
+ logger.warn('nevar-auth: staff request refused', context);
332
+ }
333
+ catch (logFailure) {
334
+ // A broken logger must not turn the refusal into a thrown error (a different response); say so on stderr.
335
+ console.error('[@bernierllc/nevar-auth] logger failed while recording a staff refusal', context, logFailure);
336
+ }
337
+ return { allowed: false, response: buildStaffRefusal() };
338
+ };
339
+ },
266
340
  async delegateActor({ serviceToken, subjectToken, audience, correlationId }) {
267
341
  try {
268
342
  requireAudience(audience);
@@ -373,6 +447,8 @@ function jwtError(cause, grantId) {
373
447
  code = 'wrong_audience';
374
448
  return new NevarAuthError(code, cause instanceof Error ? cause.message : 'Token verification failed', { cause, grantId });
375
449
  }
450
+ /** OperationCatalog id pattern, from actor-context.schema.json (`nevar_callback_op`) at ActorContext rev 3. */
451
+ const OPERATION_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)?(\.[a-z][a-z0-9_]*){2}$/;
376
452
  function toActorContext(claims, audience) {
377
453
  const grantId = typeof claims.nevar_grant_id === 'string' && claims.nevar_grant_id ? claims.nevar_grant_id : null;
378
454
  const invalid = (claim) => new NevarAuthError('invalid_token', `Claim ${claim} is missing or invalid`, { grantId });
@@ -398,6 +474,19 @@ function toActorContext(claims, audience) {
398
474
  if (act !== undefined && !isActClaim(act)) {
399
475
  throw new NevarAuthError('invalid_delegation', 'Claim act is malformed', { grantId });
400
476
  }
477
+ // Execution-grant claims (ifc:platform/authentication#ActorContext@r3, sha dfb29f99150b). Neither claim present
478
+ // (JSON null counts as present) means no grant: both null. Otherwise the operation must be an OperationCatalog id
479
+ // and the project claim must be present, a non-empty string or JSON null. We only copy; the callee binds the operation.
480
+ const hasGrantClaims = 'nevar_project_id' in claims || 'nevar_callback_op' in claims;
481
+ const project = claims.nevar_project_id;
482
+ const operation = claims.nevar_callback_op;
483
+ if (hasGrantClaims) {
484
+ if (typeof operation !== 'string' || !OPERATION_ID.test(operation))
485
+ throw invalid('nevar_callback_op');
486
+ if (!('nevar_project_id' in claims) || (project !== null && (typeof project !== 'string' || !project))) {
487
+ throw invalid('nevar_project_id');
488
+ }
489
+ }
401
490
  return {
402
491
  sub: claims.sub,
403
492
  nevar_actor_type: actorType,
@@ -408,6 +497,8 @@ function toActorContext(claims, audience) {
408
497
  act: act ?? null,
409
498
  role: 'authenticated',
410
499
  aud: audience,
500
+ nevar_project_id: hasGrantClaims ? project : null,
501
+ nevar_callback_op: hasGrantClaims ? operation : null,
411
502
  };
412
503
  }
413
504
  function isActClaim(value) {
@@ -0,0 +1,65 @@
1
+ /** Hub contract revision the staff constants come from: ifc:platform/authentication#StaffConsole rev 2. */
2
+ export declare const STAFF_CONSOLE_REV = 2;
3
+ /** Hub contract revision of the ActorContext this package verifies against: ifc:platform/authentication#ActorContext rev 4. */
4
+ export declare const ACTOR_CONTEXT_REV = 4;
5
+ /** `acr` of a token minted for a console session by a staff member. */
6
+ export declare const STAFF_ACR = "urn:nevar:acr:staff";
7
+ /** A staff token lives this long (issuer constant). */
8
+ export declare const STAFF_TOKEN_TTL_SECONDS = 300;
9
+ /** A step-up covers this long; a danger scope is only ever on a token minted inside one (issuer constant). */
10
+ export declare const STAFF_STEP_UP_WINDOW_SECONDS = 300;
11
+ export type StaffEnvironment = 'production' | 'staging';
12
+ /** The staff audience sets, verbatim from hub StaffConsole rev 2. Local development reuses `staging`. Each read returns a fresh RegExp. */
13
+ export declare const STAFF_AUDIENCE_PATTERNS: Readonly<Record<StaffEnvironment, RegExp>>;
14
+ /** Why `requireStaff` refused. Goes to the logger only; it is never part of the response. */
15
+ export type StaffRefusalReason = 'malformed_token' | 'inactive' | 'wrong_issuer' | 'expired' | 'wrong_acr' | 'wrong_audience' | 'missing_scope' | 'invalid_claims' | 'introspection_unavailable' | 'introspection_misconfigured' | 'internal_error';
16
+ /** The one response every refusal returns: same status, headers and bytes whatever the reason. */
17
+ export interface StaffRefusal {
18
+ status: 404;
19
+ headers: Record<string, string>;
20
+ body: string;
21
+ }
22
+ export declare const STAFF_REFUSAL_BODY = "{\"error\":\"not_found\"}";
23
+ /** A fresh copy of the uniform refusal. Compare with `Buffer.from(body)` and the header map. */
24
+ export declare function buildStaffRefusal(): StaffRefusal;
25
+ /** The verified staff identity, built from the issuer's introspection only. Carries no organization and no role. */
26
+ export interface StaffContext {
27
+ sub: string;
28
+ /** Space-separated scopes, as issued. */
29
+ scope: string;
30
+ aud: string;
31
+ acr: typeof STAFF_ACR;
32
+ /** Seconds since the epoch: when the staff member last authenticated. */
33
+ authTime: number;
34
+ /** The console session id (`nevar_grant_id`). */
35
+ grantId: string;
36
+ jti: string;
37
+ iat: number;
38
+ exp: number;
39
+ }
40
+ export type StaffDecision = {
41
+ allowed: true;
42
+ staff: StaffContext;
43
+ } | {
44
+ allowed: false;
45
+ response: StaffRefusal;
46
+ };
47
+ export interface StaffGuardOptions {
48
+ /** Carried into the refusal log. */
49
+ correlationId?: string;
50
+ }
51
+ /** A scope is one RFC 6749 scope-token. Anything else is a caller bug, refused at construction. */
52
+ export declare function assertStaffScope(scope: unknown): asserts scope is string;
53
+ /** Does an introspected staff token satisfy the guard? Pure: no I/O, no clock beyond `nowSeconds`. */
54
+ export declare function evaluateStaffClaims(claims: Record<string, unknown>, expected: {
55
+ issuer: string;
56
+ environment: StaffEnvironment;
57
+ scope: string;
58
+ nowSeconds: number;
59
+ }): {
60
+ ok: true;
61
+ staff: StaffContext;
62
+ } | {
63
+ ok: false;
64
+ reason: StaffRefusalReason;
65
+ };
package/dist/staff.js ADDED
@@ -0,0 +1,89 @@
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 { NevarAuthError } from './errors.js';
9
+ // Staff identity (plan work:staff-identity, step 10). The constants below are PINNED here on purpose: no runtime
10
+ // config, no env, no fetch from the issuer. `src/__tests__/fixtures/staff-console.rev2.json` vendors the hub values and
11
+ // a test asserts every constant equals it. Changing one is a new fixture revision and a minor release, never an edit.
12
+ /** Hub contract revision the staff constants come from: ifc:platform/authentication#StaffConsole rev 2. */
13
+ export const STAFF_CONSOLE_REV = 2;
14
+ /** Hub contract revision of the ActorContext this package verifies against: ifc:platform/authentication#ActorContext rev 4. */
15
+ export const ACTOR_CONTEXT_REV = 4;
16
+ /** `acr` of a token minted for a console session by a staff member. */
17
+ export const STAFF_ACR = 'urn:nevar:acr:staff';
18
+ /** A staff token lives this long (issuer constant). */
19
+ export const STAFF_TOKEN_TTL_SECONDS = 300;
20
+ /** A step-up covers this long; a danger scope is only ever on a token minted inside one (issuer constant). */
21
+ export const STAFF_STEP_UP_WINDOW_SECONDS = 300;
22
+ const AUDIENCE_SOURCES = {
23
+ production: '^https://admin\\.nevar\\.io/v1/[a-z][a-z0-9-]*$',
24
+ staging: '^https://admin\\.notnevar\\.us/v1/[a-z][a-z0-9-]*$',
25
+ };
26
+ // The guard matches against these private instances. Nothing exported hands out a reference to them, so a consumer
27
+ // calling `.compile()` on an exported pattern cannot loosen the guard.
28
+ const GUARD_AUDIENCE = {
29
+ production: new RegExp(AUDIENCE_SOURCES.production),
30
+ staging: new RegExp(AUDIENCE_SOURCES.staging),
31
+ };
32
+ /** The staff audience sets, verbatim from hub StaffConsole rev 2. Local development reuses `staging`. Each read returns a fresh RegExp. */
33
+ export const STAFF_AUDIENCE_PATTERNS = Object.freeze({
34
+ get production() { return new RegExp(AUDIENCE_SOURCES.production); },
35
+ get staging() { return new RegExp(AUDIENCE_SOURCES.staging); },
36
+ });
37
+ export const STAFF_REFUSAL_BODY = '{"error":"not_found"}';
38
+ /** A fresh copy of the uniform refusal. Compare with `Buffer.from(body)` and the header map. */
39
+ export function buildStaffRefusal() {
40
+ return {
41
+ status: 404,
42
+ headers: {
43
+ 'cache-control': 'no-store',
44
+ 'content-length': String(Buffer.byteLength(STAFF_REFUSAL_BODY)),
45
+ 'content-type': 'application/json; charset=utf-8',
46
+ },
47
+ body: STAFF_REFUSAL_BODY,
48
+ };
49
+ }
50
+ // RFC 6749 section 3.3: scope-token = 1*( %x21 / %x23-5B / %x5D-7E ), tokens separated by single spaces. ASCII only, so
51
+ // Unicode whitespace (U+00A0, U+2003, ...) can never split or join a scope.
52
+ const SCOPE_TOKEN = '[\\x21\\x23-\\x5B\\x5D-\\x7E]+';
53
+ const SCOPE_TOKEN_RE = new RegExp(`^${SCOPE_TOKEN}$`);
54
+ const SCOPE_LIST_RE = new RegExp(`^${SCOPE_TOKEN}( ${SCOPE_TOKEN})*$`);
55
+ /** A scope is one RFC 6749 scope-token. Anything else is a caller bug, refused at construction. */
56
+ export function assertStaffScope(scope) {
57
+ if (typeof scope !== 'string' || !SCOPE_TOKEN_RE.test(scope)) {
58
+ throw new NevarAuthError('misconfigured', 'requireStaff needs one scope: printable ASCII, no spaces, quotes or backslashes');
59
+ }
60
+ }
61
+ /** Does an introspected staff token satisfy the guard? Pure: no I/O, no clock beyond `nowSeconds`. */
62
+ export function evaluateStaffClaims(claims, expected) {
63
+ if (claims.active !== true)
64
+ return { ok: false, reason: 'inactive' };
65
+ if (claims.iss !== expected.issuer)
66
+ return { ok: false, reason: 'wrong_issuer' };
67
+ if (claims.acr !== STAFF_ACR)
68
+ return { ok: false, reason: 'wrong_acr' };
69
+ // aud is exactly one string; an array (even of one) is not a staff token, so it cannot slip a second audience through.
70
+ if (typeof claims.aud !== 'string' || !GUARD_AUDIENCE[expected.environment].test(claims.aud)) {
71
+ return { ok: false, reason: 'wrong_audience' };
72
+ }
73
+ const { sub, scope, jti, nevar_grant_id: grantId, iat, exp, auth_time: authTime } = claims;
74
+ if (typeof sub !== 'string' || !sub ||
75
+ typeof scope !== 'string' || !SCOPE_LIST_RE.test(scope) ||
76
+ typeof jti !== 'string' || !jti ||
77
+ typeof grantId !== 'string' || !grantId ||
78
+ !isFiniteNumber(iat) || !isFiniteNumber(exp) || !isFiniteNumber(authTime)) {
79
+ return { ok: false, reason: 'invalid_claims' };
80
+ }
81
+ if (exp <= expected.nowSeconds)
82
+ return { ok: false, reason: 'expired' };
83
+ if (!scope.split(' ').includes(expected.scope))
84
+ return { ok: false, reason: 'missing_scope' };
85
+ return { ok: true, staff: { sub, scope, aud: claims.aud, acr: STAFF_ACR, authTime, grantId, jti, iat, exp } };
86
+ }
87
+ function isFiniteNumber(value) {
88
+ return typeof value === 'number' && Number.isFinite(value);
89
+ }
@@ -60,6 +60,12 @@ export declare const TEST_GRANTS: {
60
60
  readonly revoked: "grant_test_revoked";
61
61
  readonly apiKey: "grant_test_api_key";
62
62
  readonly mcpKey: "grant_test_mcp_key";
63
+ readonly executionGrant: "grant_test_execution_grant";
64
+ };
65
+ /** The execution-grant claims (ActorContext rev 3) on `issuer.tokens.executionGrant`; the operation matches the OperationCatalog id pattern. */
66
+ export declare const TEST_EXECUTION_GRANT: {
67
+ readonly nevar_project_id: "proj_test_1";
68
+ readonly nevar_callback_op: "projects.tasks.run_due";
63
69
  };
64
70
  /** Claims of the default user token. `sign()` merges overrides onto these. */
65
71
  export declare const TEST_USER_CLAIMS: {
@@ -103,6 +109,8 @@ export interface TestIssuer {
103
109
  agent: string;
104
110
  /** A service token with `aud` = this issuer (Q6): the `serviceToken` for `delegateActor`. */
105
111
  service: string;
112
+ /** An execution-grant callback token (ActorContext rev 3): a service actor carrying `TEST_EXECUTION_GRANT`, acting through `act`. */
113
+ executionGrant: string;
106
114
  };
107
115
  keys: typeof TEST_KEYS;
108
116
  introspectionClient: typeof TEST_INTROSPECTION_CLIENT;
@@ -62,7 +62,10 @@ export const TEST_GRANTS = {
62
62
  revoked: 'grant_test_revoked',
63
63
  apiKey: 'grant_test_api_key',
64
64
  mcpKey: 'grant_test_mcp_key',
65
+ executionGrant: 'grant_test_execution_grant',
65
66
  };
67
+ /** The execution-grant claims (ActorContext rev 3) on `issuer.tokens.executionGrant`; the operation matches the OperationCatalog id pattern. */
68
+ export const TEST_EXECUTION_GRANT = { nevar_project_id: 'proj_test_1', nevar_callback_op: 'projects.tasks.run_due' };
66
69
  /** Claims of the default user token. `sign()` merges overrides onto these. */
67
70
  export const TEST_USER_CLAIMS = {
68
71
  sub: TEST_SUBJECTS.user,
@@ -242,6 +245,14 @@ export async function startTestIssuer(options = {}) {
242
245
  nevar_grant_id: TEST_GRANTS.agent,
243
246
  }),
244
247
  service: await sign(service),
248
+ executionGrant: await sign({
249
+ sub: TEST_SUBJECTS.service,
250
+ nevar_actor_type: 'service',
251
+ nevar_owner_sub: TEST_SUBJECTS.user,
252
+ nevar_grant_id: TEST_GRANTS.executionGrant,
253
+ act: { sub: TEST_SUBJECTS.service },
254
+ ...TEST_EXECUTION_GRANT,
255
+ }),
245
256
  };
246
257
  return {
247
258
  url,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bernierllc/nevar-auth",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
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
5
  "type": "module",
6
6
  "main": "./dist/index.js",