axiam-sdk 1.3.0 → 1.4.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.
Files changed (58) hide show
  1. package/README.md +130 -14
  2. package/dist/amqp/index.d.cts +384 -17
  3. package/dist/amqp/index.d.ts +384 -17
  4. package/dist/amqp/index.js +639 -66
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +631 -67
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
  9. package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
  10. package/dist/browser/index.d.cts +1 -1
  11. package/dist/browser/index.d.ts +1 -1
  12. package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
  13. package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
  14. package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
  15. package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
  16. package/dist/grpc/index.d.cts +5 -5
  17. package/dist/grpc/index.d.ts +5 -5
  18. package/dist/grpc/index.js +249 -18
  19. package/dist/grpc/index.js.map +1 -1
  20. package/dist/grpc/index.mjs +249 -18
  21. package/dist/grpc/index.mjs.map +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +29 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +29 -3
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
  29. package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
  30. package/dist/middleware/index.d.cts +220 -43
  31. package/dist/middleware/index.d.ts +220 -43
  32. package/dist/middleware/index.js +587 -149
  33. package/dist/middleware/index.js.map +1 -1
  34. package/dist/middleware/index.mjs +579 -150
  35. package/dist/middleware/index.mjs.map +1 -1
  36. package/dist/nestjs/index.d.cts +18 -4
  37. package/dist/nestjs/index.d.ts +18 -4
  38. package/dist/nestjs/index.js +20 -1
  39. package/dist/nestjs/index.js.map +1 -1
  40. package/dist/nestjs/index.mjs +19 -2
  41. package/dist/nestjs/index.mjs.map +1 -1
  42. package/dist/node/index.d.cts +5 -5
  43. package/dist/node/index.d.ts +5 -5
  44. package/dist/node/index.js +351 -66
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/index.mjs +348 -67
  47. package/dist/node/index.mjs.map +1 -1
  48. package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
  49. package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
  50. package/dist/rest/index.d.cts +3 -3
  51. package/dist/rest/index.d.ts +3 -3
  52. package/dist/rest/index.js +29 -3
  53. package/dist/rest/index.js.map +1 -1
  54. package/dist/rest/index.mjs +29 -3
  55. package/dist/rest/index.mjs.map +1 -1
  56. package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
  57. package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
  58. package/package.json +10 -10
@@ -1,9 +1,9 @@
1
- import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-CqXzLNmT.cjs';
1
+ import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-Des2NcKA.cjs';
2
2
  import { CanActivate, ExecutionContext } from '@nestjs/common';
3
3
  import { Reflector } from '@nestjs/core';
4
4
  import '../sensitive-BC_s7Rrd.cjs';
5
5
  import '../types-zXSpiQM-.cjs';
6
- import '../jwks-CTVpOWzI.cjs';
6
+ import '../jwks-CQtWokVd.cjs';
7
7
  import '../revocationFeed-KQhvMMl8.cjs';
8
8
 
9
9
  /** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
@@ -45,11 +45,23 @@ declare function RequireAuth(): ClassDecorator & MethodDecorator;
45
45
  declare function RequireAccess(action: string, resource: NestResourceSpec, opts?: RequireAccessOptions): ClassDecorator & MethodDecorator;
46
46
  /**
47
47
  * `@RequireRole(...roles)` (CONTRACT.md §11.1, MAY) — a local (no server
48
- * round-trip) check that the authenticated identity's roles contain at
48
+ * round-trip) check that the verified token's `roles` claim contains at
49
49
  * least one of `roles`. Cheaper but coarser than `@RequireAccess`; NOT a
50
50
  * substitute for a resource-level check.
51
+ *
52
+ * Contract 1.68 (§11.2 rule 11): only the `roles` claim is read, and a token
53
+ * without one is refused 403 — the application must request the `roles`
54
+ * scope for this decorator to admit anyone. It never reads `scope`; use
55
+ * {@link RequireScope} for that.
51
56
  */
52
57
  declare function RequireRole(...roles: string[]): ClassDecorator & MethodDecorator;
58
+ /**
59
+ * `@RequireScope(...scopes)` (CONTRACT.md §11.1, contract 1.68) — a local
60
+ * (no server round-trip) check that the verified token's `scope` claim
61
+ * contains at least one of `scopes` (whole entries, exact and
62
+ * case-sensitive). 403 on failure and when the token has no `scope` claim.
63
+ */
64
+ declare function RequireScope(...scopes: string[]): ClassDecorator & MethodDecorator;
53
65
 
54
66
  /** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */
55
67
  declare const AXIAM_SESSION: unique symbol;
@@ -98,6 +110,8 @@ declare const AXIAM_REQUIRE_AUTH_METADATA: unique symbol;
98
110
  declare const AXIAM_REQUIRE_ACCESS_METADATA: unique symbol;
99
111
  /** Set by {@link RequireRole}; read by {@link AxiamGuard}. Value shape: `string[]`. */
100
112
  declare const AXIAM_REQUIRE_ROLE_METADATA: unique symbol;
113
+ /** Set by {@link RequireScope}; read by {@link AxiamGuard}. Value shape: `string[]`. */
114
+ declare const AXIAM_REQUIRE_SCOPE_METADATA: unique symbol;
101
115
 
102
- export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_SESSION, AuthzVerifiableSession, AxiamGuard, RequireAccess, RequireAccessOptions, RequireAuth, RequireRole };
116
+ export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_REQUIRE_SCOPE_METADATA, AXIAM_SESSION, AuthzVerifiableSession, AxiamGuard, RequireAccess, RequireAccessOptions, RequireAuth, RequireRole, RequireScope };
103
117
  export type { NestParamResource, NestResourceSpec, RequireAccessMetadata };
@@ -1,9 +1,9 @@
1
- import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-D-hquWSI.js';
1
+ import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-Ced9zDIV.js';
2
2
  import { CanActivate, ExecutionContext } from '@nestjs/common';
3
3
  import { Reflector } from '@nestjs/core';
4
4
  import '../sensitive-BC_s7Rrd.js';
5
5
  import '../types-BOX-6Srv.js';
6
- import '../jwks-CTVpOWzI.js';
6
+ import '../jwks-CQtWokVd.js';
7
7
  import '../revocationFeed-KQhvMMl8.js';
8
8
 
9
9
  /** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
@@ -45,11 +45,23 @@ declare function RequireAuth(): ClassDecorator & MethodDecorator;
45
45
  declare function RequireAccess(action: string, resource: NestResourceSpec, opts?: RequireAccessOptions): ClassDecorator & MethodDecorator;
46
46
  /**
47
47
  * `@RequireRole(...roles)` (CONTRACT.md §11.1, MAY) — a local (no server
48
- * round-trip) check that the authenticated identity's roles contain at
48
+ * round-trip) check that the verified token's `roles` claim contains at
49
49
  * least one of `roles`. Cheaper but coarser than `@RequireAccess`; NOT a
50
50
  * substitute for a resource-level check.
51
+ *
52
+ * Contract 1.68 (§11.2 rule 11): only the `roles` claim is read, and a token
53
+ * without one is refused 403 — the application must request the `roles`
54
+ * scope for this decorator to admit anyone. It never reads `scope`; use
55
+ * {@link RequireScope} for that.
51
56
  */
52
57
  declare function RequireRole(...roles: string[]): ClassDecorator & MethodDecorator;
58
+ /**
59
+ * `@RequireScope(...scopes)` (CONTRACT.md §11.1, contract 1.68) — a local
60
+ * (no server round-trip) check that the verified token's `scope` claim
61
+ * contains at least one of `scopes` (whole entries, exact and
62
+ * case-sensitive). 403 on failure and when the token has no `scope` claim.
63
+ */
64
+ declare function RequireScope(...scopes: string[]): ClassDecorator & MethodDecorator;
53
65
 
54
66
  /** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */
55
67
  declare const AXIAM_SESSION: unique symbol;
@@ -98,6 +110,8 @@ declare const AXIAM_REQUIRE_AUTH_METADATA: unique symbol;
98
110
  declare const AXIAM_REQUIRE_ACCESS_METADATA: unique symbol;
99
111
  /** Set by {@link RequireRole}; read by {@link AxiamGuard}. Value shape: `string[]`. */
100
112
  declare const AXIAM_REQUIRE_ROLE_METADATA: unique symbol;
113
+ /** Set by {@link RequireScope}; read by {@link AxiamGuard}. Value shape: `string[]`. */
114
+ declare const AXIAM_REQUIRE_SCOPE_METADATA: unique symbol;
101
115
 
102
- export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_SESSION, AuthzVerifiableSession, AxiamGuard, RequireAccess, RequireAccessOptions, RequireAuth, RequireRole };
116
+ export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_REQUIRE_SCOPE_METADATA, AXIAM_SESSION, AuthzVerifiableSession, AxiamGuard, RequireAccess, RequireAccessOptions, RequireAuth, RequireRole, RequireScope };
103
117
  export type { NestParamResource, NestResourceSpec, RequireAccessMetadata };
@@ -8,6 +8,7 @@ var common = require('@nestjs/common');
8
8
  var AXIAM_REQUIRE_AUTH_METADATA = /* @__PURE__ */ Symbol("axiam:requireAuth");
9
9
  var AXIAM_REQUIRE_ACCESS_METADATA = /* @__PURE__ */ Symbol("axiam:requireAccess");
10
10
  var AXIAM_REQUIRE_ROLE_METADATA = /* @__PURE__ */ Symbol("axiam:requireRole");
11
+ var AXIAM_REQUIRE_SCOPE_METADATA = /* @__PURE__ */ Symbol("axiam:requireScope");
11
12
 
12
13
  // src/nestjs/decorators.ts
13
14
  function RequireAuth() {
@@ -20,6 +21,9 @@ function RequireAccess(action, resource, opts) {
20
21
  function RequireRole(...roles) {
21
22
  return common.SetMetadata(AXIAM_REQUIRE_ROLE_METADATA, roles);
22
23
  }
24
+ function RequireScope(...scopes) {
25
+ return common.SetMetadata(AXIAM_REQUIRE_SCOPE_METADATA, scopes);
26
+ }
23
27
 
24
28
  // src/core/errors.ts
25
29
  var AxiamError = class extends Error {
@@ -100,8 +104,17 @@ async function deny(message, action, resourceId, challenger, reasonCode) {
100
104
  return { kind: "denied", message, reasonCode };
101
105
  }
102
106
  function hasAnyRole(identityRoles, roles) {
107
+ if (!Array.isArray(identityRoles)) {
108
+ return false;
109
+ }
103
110
  return roles.some((role) => identityRoles.includes(role));
104
111
  }
112
+ function hasAnyScope(identityScopes, scopes) {
113
+ if (!Array.isArray(identityScopes)) {
114
+ return false;
115
+ }
116
+ return scopes.some((scope) => identityScopes.includes(scope));
117
+ }
105
118
 
106
119
  // src/nestjs/guard.ts
107
120
  var AXIAM_SESSION = /* @__PURE__ */ Symbol("AXIAM_SESSION");
@@ -131,11 +144,12 @@ var AxiamGuard = class {
131
144
  const targets = [context.getHandler(), context.getClass()];
132
145
  const requireAuth = this.reflector.getAllAndOverride(AXIAM_REQUIRE_AUTH_METADATA, targets);
133
146
  const requireRoles = this.reflector.getAllAndOverride(AXIAM_REQUIRE_ROLE_METADATA, targets);
147
+ const requireScopes = this.reflector.getAllAndOverride(AXIAM_REQUIRE_SCOPE_METADATA, targets);
134
148
  const requireAccessMeta = this.reflector.getAllAndOverride(
135
149
  AXIAM_REQUIRE_ACCESS_METADATA,
136
150
  targets
137
151
  );
138
- if (!requireAuth && !requireRoles && !requireAccessMeta) {
152
+ if (!requireAuth && !requireRoles && !requireScopes && !requireAccessMeta) {
139
153
  return true;
140
154
  }
141
155
  const request = context.switchToHttp().getRequest();
@@ -149,6 +163,9 @@ var AxiamGuard = class {
149
163
  if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {
150
164
  throw new common.ForbiddenException({ error: "authorization_denied", message: "missing required role" });
151
165
  }
166
+ if (requireScopes && !hasAnyScope(axiamUser.scopes, requireScopes)) {
167
+ throw new common.ForbiddenException({ error: "authorization_denied", message: "missing required scope" });
168
+ }
152
169
  if (requireAccessMeta) {
153
170
  const checker = assertAuthzClient(this.session ?? {});
154
171
  let resourceId;
@@ -187,10 +204,12 @@ var AxiamGuard = class {
187
204
  exports.AXIAM_REQUIRE_ACCESS_METADATA = AXIAM_REQUIRE_ACCESS_METADATA;
188
205
  exports.AXIAM_REQUIRE_AUTH_METADATA = AXIAM_REQUIRE_AUTH_METADATA;
189
206
  exports.AXIAM_REQUIRE_ROLE_METADATA = AXIAM_REQUIRE_ROLE_METADATA;
207
+ exports.AXIAM_REQUIRE_SCOPE_METADATA = AXIAM_REQUIRE_SCOPE_METADATA;
190
208
  exports.AXIAM_SESSION = AXIAM_SESSION;
191
209
  exports.AxiamGuard = AxiamGuard;
192
210
  exports.RequireAccess = RequireAccess;
193
211
  exports.RequireAuth = RequireAuth;
194
212
  exports.RequireRole = RequireRole;
213
+ exports.RequireScope = RequireScope;
195
214
  //# sourceMappingURL=index.js.map
196
215
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/nestjs/metadata.ts","../../src/nestjs/decorators.ts","../../src/core/errors.ts","../../src/middleware/authzCore.ts","../../src/nestjs/guard.ts"],"names":["SetMetadata","UnauthorizedException","ForbiddenException","BadRequest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AS,OAAA,CAAQ,SAAS,CAAA;AAAA,MAChG;AAAA,IACF;AAEA,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"index.js","sourcesContent":["// Reflect-metadata keys shared by the §11 decorators (decorators.ts) and the\n// enforcement guard (guard.ts). Symbols, not strings, so a consuming app's\n// own metadata never collides with these by coincidence.\n\n/** Set by {@link RequireAuth}; read by {@link AxiamGuard}. */\nexport const AXIAM_REQUIRE_AUTH_METADATA = Symbol('axiam:requireAuth');\n\n/** Set by {@link RequireAccess}; read by {@link AxiamGuard}. Value shape: {@link RequireAccessMetadata}. */\nexport const AXIAM_REQUIRE_ACCESS_METADATA = Symbol('axiam:requireAccess');\n\n/** Set by {@link RequireRole}; read by {@link AxiamGuard}. Value shape: `string[]`. */\nexport const AXIAM_REQUIRE_ROLE_METADATA = Symbol('axiam:requireRole');\n","// NestJS metadata decorators (CONTRACT.md §11, Tier 2). Pure metadata\n// attachment via `@nestjs/common`'s `SetMetadata` — no enforcement logic\n// lives here (that's `guard.ts`'s `AxiamGuard`, which reads the metadata\n// back out via `Reflector`). Uses NestJS's own decorator machinery, so this\n// SDK's tsconfig does NOT enable `experimentalDecorators` — only the\n// consuming Nest application needs it (which it already does, by being a\n// Nest app).\n\nimport { SetMetadata } from '@nestjs/common';\nimport type { RequireAccessOptions } from '../middleware/authzCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\n\n/** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */\nexport interface NestParamResource {\n /** The route parameter name (e.g. `request.params[name]`) carrying the resource id. */\n readonly param: string;\n}\n\n/** The `resource` argument accepted by `@RequireAccess` (CONTRACT.md §11.2.3): a static literal, {@link NestParamResource} (route parameter), or a `(request) => string` resolver. */\nexport type NestResourceSpec = string | NestParamResource | ((request: unknown) => string);\n\n/** The metadata value `@RequireAccess` attaches, read back by {@link AxiamGuard} via `Reflector`. */\nexport interface RequireAccessMetadata {\n /** The action being performed (e.g. `\"read\"`, `\"write\"`, `\"delete\"`), passed through to `checkAccess` verbatim. */\n action: string;\n /** How to resolve the checked resource's id from the request (§11.2.3). */\n resource: NestResourceSpec;\n /** Optional scope/logger settings, passed through to `checkAccess`/the debug-only denial log. */\n opts?: RequireAccessOptions;\n}\n\n/**\n * `@RequireAuth()` (CONTRACT.md §11.1) — marks a handler/controller as\n * requiring an authenticated AXIAM identity. `AxiamGuard` responds 401 if\n * `request.axiamUser` (injected by `axiamMiddleware`/`axiamPlugin` mounted\n * on the underlying HTTP adapter) is absent.\n */\nexport function RequireAuth(): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_AUTH_METADATA, true);\n}\n\n/**\n * `@RequireAccess(action, resource, opts?)` (CONTRACT.md §11) — a per-route\n * authorization requirement enforced by `AxiamGuard`. `resource` is resolved\n * per §11.2.3's precedence: a literal string, `{ param: 'id' }` (a route\n * parameter), or a `(request) => string` resolver.\n *\n * @example\n * ```ts\n * \\@RequireAccess('read', { param: 'id' })\n * \\@Get(':id')\n * getDocument(\\@Param('id') id: string) { ... }\n * ```\n */\nexport function RequireAccess(\n action: string,\n resource: NestResourceSpec,\n opts?: RequireAccessOptions,\n): ClassDecorator & MethodDecorator {\n const metadata: RequireAccessMetadata = { action, resource, opts };\n return SetMetadata(AXIAM_REQUIRE_ACCESS_METADATA, metadata);\n}\n\n/**\n * `@RequireRole(...roles)` (CONTRACT.md §11.1, MAY) — a local (no server\n * round-trip) check that the authenticated identity's roles contain at\n * least one of `roles`. Cheaper but coarser than `@RequireAccess`; NOT a\n * substitute for a resource-level check.\n */\nexport function RequireRole(...roles: string[]): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_ROLE_METADATA, roles);\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/nestjs/metadata.ts","../../src/nestjs/decorators.ts","../../src/core/errors.ts","../../src/middleware/authzCore.ts","../../src/nestjs/guard.ts"],"names":["SetMetadata","UnauthorizedException","ForbiddenException","BadRequestException","ServiceUnavailableException"],"mappings":";;;;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,4BAAA,0BAAsC,oBAAoB;;;AC4BhE,SAAS,WAAA,GAAgD;AAC9D,EAAA,OAAOA,kBAAA,CAAY,6BAA6B,IAAI,CAAA;AACtD;AAeO,SAAS,aAAA,CACd,MAAA,EACA,QAAA,EACA,IAAA,EACkC;AAClC,EAAA,MAAM,QAAA,GAAkC,EAAE,MAAA,EAAQ,QAAA,EAAU,IAAA,EAAK;AACjE,EAAA,OAAOA,kBAAA,CAAY,+BAA+B,QAAQ,CAAA;AAC5D;AAaO,SAAS,eAAe,KAAA,EAAmD;AAChF,EAAA,OAAOA,kBAAA,CAAY,6BAA6B,KAAK,CAAA;AACvD;AAQO,SAAS,gBAAgB,MAAA,EAAoD;AAClF,EAAA,OAAOA,kBAAA,CAAY,8BAA8B,MAAM,CAAA;AACzD;;;AClEO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAoGO,IAAM,UAAA,GAAN,MAAM,WAAA,SAAmB,UAAA,CAAW;AAAA;A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ement guard (guard.ts). Symbols, not strings, so a consuming app's\n// own metadata never collides with these by coincidence.\n\n/** Set by {@link RequireAuth}; read by {@link AxiamGuard}. */\nexport const AXIAM_REQUIRE_AUTH_METADATA = Symbol('axiam:requireAuth');\n\n/** Set by {@link RequireAccess}; read by {@link AxiamGuard}. Value shape: {@link RequireAccessMetadata}. */\nexport const AXIAM_REQUIRE_ACCESS_METADATA = Symbol('axiam:requireAccess');\n\n/** Set by {@link RequireRole}; read by {@link AxiamGuard}. Value shape: `string[]`. */\nexport const AXIAM_REQUIRE_ROLE_METADATA = Symbol('axiam:requireRole');\n\n/** Set by {@link RequireScope}; read by {@link AxiamGuard}. Value shape: `string[]`. */\nexport const AXIAM_REQUIRE_SCOPE_METADATA = Symbol('axiam:requireScope');\n","// NestJS metadata decorators (CONTRACT.md §11, Tier 2). Pure metadata\n// attachment via `@nestjs/common`'s `SetMetadata` — no enforcement logic\n// lives here (that's `guard.ts`'s `AxiamGuard`, which reads the metadata\n// back out via `Reflector`). Uses NestJS's own decorator machinery, so this\n// SDK's tsconfig does NOT enable `experimentalDecorators` — only the\n// consuming Nest application needs it (which it already does, by being a\n// Nest app).\n\nimport { SetMetadata } from '@nestjs/common';\nimport type { RequireAccessOptions } from '../middleware/authzCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n AXIAM_REQUIRE_SCOPE_METADATA,\n} from './metadata.js';\n\n/** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */\nexport interface NestParamResource {\n /** The route parameter name (e.g. `request.params[name]`) carrying the resource id. */\n readonly param: string;\n}\n\n/** The `resource` argument accepted by `@RequireAccess` (CONTRACT.md §11.2.3): a static literal, {@link NestParamResource} (route parameter), or a `(request) => string` resolver. */\nexport type NestResourceSpec = string | NestParamResource | ((request: unknown) => string);\n\n/** The metadata value `@RequireAccess` attaches, read back by {@link AxiamGuard} via `Reflector`. */\nexport interface RequireAccessMetadata {\n /** The action being performed (e.g. `\"read\"`, `\"write\"`, `\"delete\"`), passed through to `checkAccess` verbatim. */\n action: string;\n /** How to resolve the checked resource's id from the request (§11.2.3). */\n resource: NestResourceSpec;\n /** Optional scope/logger settings, passed through to `checkAccess`/the debug-only denial log. */\n opts?: RequireAccessOptions;\n}\n\n/**\n * `@RequireAuth()` (CONTRACT.md §11.1) — marks a handler/controller as\n * requiring an authenticated AXIAM identity. `AxiamGuard` responds 401 if\n * `request.axiamUser` (injected by `axiamMiddleware`/`axiamPlugin` mounted\n * on the underlying HTTP adapter) is absent.\n */\nexport function RequireAuth(): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_AUTH_METADATA, true);\n}\n\n/**\n * `@RequireAccess(action, resource, opts?)` (CONTRACT.md §11) — a per-route\n * authorization requirement enforced by `AxiamGuard`. `resource` is resolved\n * per §11.2.3's precedence: a literal string, `{ param: 'id' }` (a route\n * parameter), or a `(request) => string` resolver.\n *\n * @example\n * ```ts\n * \\@RequireAccess('read', { param: 'id' })\n * \\@Get(':id')\n * getDocument(\\@Param('id') id: string) { ... }\n * ```\n */\nexport function RequireAccess(\n action: string,\n resource: NestResourceSpec,\n opts?: RequireAccessOptions,\n): ClassDecorator & MethodDecorator {\n const metadata: RequireAccessMetadata = { action, resource, opts };\n return SetMetadata(AXIAM_REQUIRE_ACCESS_METADATA, metadata);\n}\n\n/**\n * `@RequireRole(...roles)` (CONTRACT.md §11.1, MAY) — a local (no server\n * round-trip) check that the verified token's `roles` claim contains at\n * least one of `roles`. Cheaper but coarser than `@RequireAccess`; NOT a\n * substitute for a resource-level check.\n *\n * Contract 1.68 (§11.2 rule 11): only the `roles` claim is read, and a token\n * without one is refused 403 — the application must request the `roles`\n * scope for this decorator to admit anyone. It never reads `scope`; use\n * {@link RequireScope} for that.\n */\nexport function RequireRole(...roles: string[]): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_ROLE_METADATA, roles);\n}\n\n/**\n * `@RequireScope(...scopes)` (CONTRACT.md §11.1, contract 1.68) — a local\n * (no server round-trip) check that the verified token's `scope` claim\n * contains at least one of `scopes` (whole entries, exact and\n * case-sensitive). 403 on failure and when the token has no `scope` claim.\n */\nexport function RequireScope(...scopes: string[]): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_SCOPE_METADATA, scopes);\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { AxiamIdentity, VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/**\n * Local (no server round-trip) role check (§11.2.9, §11.2 rule 11): true iff\n * `roles` and the identity's roles share at least one entry, by exact,\n * case-sensitive equality.\n *\n * `identityRoles` is {@link AxiamIdentity.roles} — the verified token's `roles`\n * claim and nothing else (contract 1.68; N15). `undefined` (the token carries\n * no `roles` claim) and `[]` (it says the user holds none) both fail: the check\n * fails closed and never falls back to `scope`.\n */\nexport function hasAnyRole(identityRoles: readonly string[] | undefined, roles: readonly string[]): boolean {\n if (!Array.isArray(identityRoles)) {\n return false;\n }\n return roles.some((role) => identityRoles.includes(role));\n}\n\n/**\n * Local (no server round-trip) scope check (§11.1 `require_scope`, §11.2 rule\n * 11 (d); contract 1.68): true iff the identity's granted OAuth2 scopes —\n * {@link AxiamIdentity.scopes}, the token's `scope` claim split on single\n * spaces — contain at least one of `scopes`, each compared as a whole entry by\n * exact, case-sensitive equality. `undefined` (no `scope` claim) fails.\n */\nexport function hasAnyScope(identityScopes: readonly string[] | undefined, scopes: readonly string[]): boolean {\n if (!Array.isArray(identityScopes)) {\n return false;\n }\n return scopes.some((scope) => identityScopes.includes(scope));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n hasAnyScope,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n AXIAM_REQUIRE_SCOPE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireScopes = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_SCOPE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireScopes && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireScopes && !hasAnyScope(axiamUser.scopes, requireScopes)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required scope' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
@@ -6,6 +6,7 @@ import { SetMetadata, UnauthorizedException, ForbiddenException, BadRequestExcep
6
6
  var AXIAM_REQUIRE_AUTH_METADATA = /* @__PURE__ */ Symbol("axiam:requireAuth");
7
7
  var AXIAM_REQUIRE_ACCESS_METADATA = /* @__PURE__ */ Symbol("axiam:requireAccess");
8
8
  var AXIAM_REQUIRE_ROLE_METADATA = /* @__PURE__ */ Symbol("axiam:requireRole");
9
+ var AXIAM_REQUIRE_SCOPE_METADATA = /* @__PURE__ */ Symbol("axiam:requireScope");
9
10
 
10
11
  // src/nestjs/decorators.ts
11
12
  function RequireAuth() {
@@ -18,6 +19,9 @@ function RequireAccess(action, resource, opts) {
18
19
  function RequireRole(...roles) {
19
20
  return SetMetadata(AXIAM_REQUIRE_ROLE_METADATA, roles);
20
21
  }
22
+ function RequireScope(...scopes) {
23
+ return SetMetadata(AXIAM_REQUIRE_SCOPE_METADATA, scopes);
24
+ }
21
25
 
22
26
  // src/core/errors.ts
23
27
  var AxiamError = class extends Error {
@@ -98,8 +102,17 @@ async function deny(message, action, resourceId, challenger, reasonCode) {
98
102
  return { kind: "denied", message, reasonCode };
99
103
  }
100
104
  function hasAnyRole(identityRoles, roles) {
105
+ if (!Array.isArray(identityRoles)) {
106
+ return false;
107
+ }
101
108
  return roles.some((role) => identityRoles.includes(role));
102
109
  }
110
+ function hasAnyScope(identityScopes, scopes) {
111
+ if (!Array.isArray(identityScopes)) {
112
+ return false;
113
+ }
114
+ return scopes.some((scope) => identityScopes.includes(scope));
115
+ }
103
116
 
104
117
  // src/nestjs/guard.ts
105
118
  var AXIAM_SESSION = /* @__PURE__ */ Symbol("AXIAM_SESSION");
@@ -129,11 +142,12 @@ var AxiamGuard = class {
129
142
  const targets = [context.getHandler(), context.getClass()];
130
143
  const requireAuth = this.reflector.getAllAndOverride(AXIAM_REQUIRE_AUTH_METADATA, targets);
131
144
  const requireRoles = this.reflector.getAllAndOverride(AXIAM_REQUIRE_ROLE_METADATA, targets);
145
+ const requireScopes = this.reflector.getAllAndOverride(AXIAM_REQUIRE_SCOPE_METADATA, targets);
132
146
  const requireAccessMeta = this.reflector.getAllAndOverride(
133
147
  AXIAM_REQUIRE_ACCESS_METADATA,
134
148
  targets
135
149
  );
136
- if (!requireAuth && !requireRoles && !requireAccessMeta) {
150
+ if (!requireAuth && !requireRoles && !requireScopes && !requireAccessMeta) {
137
151
  return true;
138
152
  }
139
153
  const request = context.switchToHttp().getRequest();
@@ -147,6 +161,9 @@ var AxiamGuard = class {
147
161
  if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {
148
162
  throw new ForbiddenException({ error: "authorization_denied", message: "missing required role" });
149
163
  }
164
+ if (requireScopes && !hasAnyScope(axiamUser.scopes, requireScopes)) {
165
+ throw new ForbiddenException({ error: "authorization_denied", message: "missing required scope" });
166
+ }
150
167
  if (requireAccessMeta) {
151
168
  const checker = assertAuthzClient(this.session ?? {});
152
169
  let resourceId;
@@ -182,6 +199,6 @@ var AxiamGuard = class {
182
199
  }
183
200
  };
184
201
 
185
- export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_SESSION, AxiamGuard, RequireAccess, RequireAuth, RequireRole };
202
+ export { AXIAM_REQUIRE_ACCESS_METADATA, AXIAM_REQUIRE_AUTH_METADATA, AXIAM_REQUIRE_ROLE_METADATA, AXIAM_REQUIRE_SCOPE_METADATA, AXIAM_SESSION, AxiamGuard, RequireAccess, RequireAuth, RequireRole, RequireScope };
186
203
  //# sourceMappingURL=index.mjs.map
187
204
  //# sourceMappingURL=index.mjs.map