axiam-sdk 1.0.0-alpha2 → 1.0.0-alpha21
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 +219 -8
- package/dist/amqp/index.d.cts +1 -1
- package/dist/amqp/index.d.ts +1 -1
- package/dist/amqp/index.js +4 -0
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +4 -0
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-xwmCivHH.d.ts → authzCore-DtSN59if.d.ts} +19 -2
- package/dist/{authzCore-CV-Td-V1.d.cts → authzCore-DuRI1aJf.d.cts} +19 -2
- package/dist/client-B_FqmZ0i.d.cts +72 -0
- package/dist/client-Dn1fs5MH.d.ts +72 -0
- package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
- package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
- package/dist/grpc/index.d.cts +113 -6
- package/dist/grpc/index.d.ts +113 -6
- package/dist/grpc/index.js +435 -18
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +434 -19
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +209 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +204 -14
- package/dist/index.mjs.map +1 -1
- package/dist/jwks-BgojMGC5.d.cts +152 -0
- package/dist/jwks-BgojMGC5.d.ts +152 -0
- package/dist/middleware/index.d.cts +208 -8
- package/dist/middleware/index.d.ts +208 -8
- package/dist/middleware/index.js +1107 -1
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +1100 -3
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +2 -2
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +3 -0
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +3 -0
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +50 -94
- package/dist/node/index.d.ts +50 -94
- package/dist/node/index.js +1039 -15
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +1023 -16
- package/dist/node/index.mjs.map +1 -1
- package/dist/oidcState-BGxqWUun.d.cts +598 -0
- package/dist/oidcState-CkFuCjpM.d.ts +598 -0
- package/dist/rest/index.d.cts +107 -5
- package/dist/rest/index.d.ts +107 -5
- package/dist/rest/index.js +209 -13
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +204 -14
- package/dist/rest/index.mjs.map +1 -1
- package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
- package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
- package/dist/session-BWUWhhyB.d.cts +154 -0
- package/dist/session-BWUWhhyB.d.ts +154 -0
- package/package.json +2 -2
- package/dist/client-BPg9kfKV.d.ts +0 -150
- package/dist/client-CAeQw1a-.d.cts +0 -150
- package/dist/jwks-CX-nhD6A.d.cts +0 -29
- package/dist/jwks-CX-nhD6A.d.ts +0 -29
- package/dist/sensitive-CWBH_tHr.d.cts +0 -12
- package/dist/sensitive-CWBH_tHr.d.ts +0 -12
package/dist/nestjs/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-DtSN59if.js';
|
|
2
2
|
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
3
|
import { Reflector } from '@nestjs/core';
|
|
4
4
|
import '../types-BVkMoqLU.js';
|
|
5
|
-
import '../jwks-
|
|
5
|
+
import '../jwks-BgojMGC5.js';
|
|
6
6
|
|
|
7
7
|
/** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
|
|
8
8
|
interface NestParamResource {
|
package/dist/nestjs/index.js
CHANGED
|
@@ -29,7 +29,9 @@ var AxiamError = class extends Error {
|
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
31
|
var AuthzError = class _AuthzError extends AxiamError {
|
|
32
|
+
/** The denied action, when the server reported it. */
|
|
32
33
|
action;
|
|
34
|
+
/** The resource the denied action targeted, when the server reported it. */
|
|
33
35
|
resourceId;
|
|
34
36
|
constructor(message, action, resourceId) {
|
|
35
37
|
super(message);
|
|
@@ -40,6 +42,7 @@ var AuthzError = class _AuthzError extends AxiamError {
|
|
|
40
42
|
}
|
|
41
43
|
};
|
|
42
44
|
var NetworkError = class _NetworkError extends AxiamError {
|
|
45
|
+
/** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */
|
|
43
46
|
cause;
|
|
44
47
|
constructor(message, cause) {
|
|
45
48
|
super(message);
|
package/dist/nestjs/index.js.map
CHANGED
|
@@ -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","BadRequestException","ServiceUnavailableException"],"mappings":";;;;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;;;AC8B9D,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;AAQO,SAAS,eAAe,KAAA,EAAmD;AAChF,EAAA,OAAOA,kBAAA,CAAY,6BAA6B,KAAK,CAAA;AACvD;;;AClEO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KA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D,CAAA;AACD,QAAA,MAAM,IAAID,0BAAmB,EAAE,KAAA,EAAO,wBAAwB,OAAA,EAAS,OAAA,CAAQ,SAAS,CAAA;AAAA,MAC1F;AACA,MAAA,IAAI,OAAA,CAAQ,SAAS,aAAA,EAAe;AAClC,QAAA,iBAAA,CAAkB,IAAA,EAAM,MAAA,EAAQ,KAAA,CAAM,iBAAA,EAAmB,yBAAA,EAA2B;AAAA,UAClF,QAAQ,iBAAA,CAAkB,MAAA;AAAA,UAC1B;AAAA,SACD,CAAA;AACD,QAAA,MAAM,IAAIE,mCAA4B,EAAE,KAAA,EAAO,qBAAqB,OAAA,EAAS,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// Exactly three concrete error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. No error message or field may\n// embed a raw token string (D-16). The prototype chain is fixed up manually\n// in each constructor so `instanceof` works reliably across the transpiled\n// CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat when\n// extending built-ins like Error).\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\nexport class AuthError extends AxiamError {\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport class AuthzError extends AxiamError {\n readonly action?: string;\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\nexport class NetworkError extends AxiamError {\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 } 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 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 authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n readonly kind: 'param';\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\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\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 error: string;\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 | { kind: 'allowed' }\n | { kind: 'denied'; message: string }\n | { kind: 'unavailable'; message: string };\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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;;;AC8B9D,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;AAQO,SAAS,eAAe,KAAA,EAAmD;AAChF,EAAA,OAAOA,kBAAA,CAAY,6BAA6B,KAAK,CAAA;AACvD;;;AClDO,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;AAuFO,IAAM,UAAA,GAAN,MAAM,WAAA,SAAmB,UAAA,CAAW;AAAA;AAAA,EAEhC,MAAA;AAAA;AAAA,EAEA,UAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAiB,UAAA,EAAqB;AACjE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,WAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,C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 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 /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\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 /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\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 } 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\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 | {\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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"]}
|
package/dist/nestjs/index.mjs
CHANGED
|
@@ -27,7 +27,9 @@ var AxiamError = class extends Error {
|
|
|
27
27
|
}
|
|
28
28
|
};
|
|
29
29
|
var AuthzError = class _AuthzError extends AxiamError {
|
|
30
|
+
/** The denied action, when the server reported it. */
|
|
30
31
|
action;
|
|
32
|
+
/** The resource the denied action targeted, when the server reported it. */
|
|
31
33
|
resourceId;
|
|
32
34
|
constructor(message, action, resourceId) {
|
|
33
35
|
super(message);
|
|
@@ -38,6 +40,7 @@ var AuthzError = class _AuthzError extends AxiamError {
|
|
|
38
40
|
}
|
|
39
41
|
};
|
|
40
42
|
var NetworkError = class _NetworkError extends AxiamError {
|
|
43
|
+
/** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */
|
|
41
44
|
cause;
|
|
42
45
|
constructor(message, cause) {
|
|
43
46
|
super(message);
|
|
@@ -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":[],"mappings":";;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;;;AC8B9D,SAAS,WAAA,GAAgD;AAC9D,EAAA,OAAO,WAAA,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,OAAO,WAAA,CAAY,+BAA+B,QAAQ,CAAA;AAC5D;AAQO,SAAS,eAAe,KAAA,EAAmD;AAChF,EAAA,OAAO,WAAA,CAAY,6BAA6B,KAAK,CAAA;AACvD;;;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;AAUO,IAAM,UAAA,GAAN,MAAM,WAAA,SAAmB,UAAA,CAAW;AAAA,EAChC,MAAA;AAAA,EACA,UAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAiB,UAAA,EAAqB;AACjE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAA,G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;AAAA,IACF;AAEA,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"index.mjs","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// Exactly three concrete error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. No error message or field may\n// embed a raw token string (D-16). The prototype chain is fixed up manually\n// in each constructor so `instanceof` works reliably across the transpiled\n// CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat when\n// extending built-ins like Error).\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\nexport class AuthError extends AxiamError {\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport class AuthzError extends AxiamError {\n readonly action?: string;\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\nexport class NetworkError extends AxiamError {\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 } 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 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 authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n readonly kind: 'param';\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\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\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 error: string;\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 | { kind: 'allowed' }\n | { kind: 'denied'; message: string }\n | { kind: 'unavailable'; message: string };\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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":[],"mappings":";;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;;;AC8B9D,SAAS,WAAA,GAAgD;AAC9D,EAAA,OAAO,WAAA,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,OAAO,WAAA,CAAY,+BAA+B,QAAQ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A,OAC1B;AACA,MAAA,IAAI,OAAA,CAAQ,SAAS,QAAA,EAAU;AAC7B,QAAA,iBAAA,CAAkB,IAAA,EAAM,MAAA,EAAQ,KAAA,CAAM,iBAAA,EAAmB,eAAA,EAAiB;AAAA,UACxE,QAAQ,iBAAA,CAAkB,MAAA;AAAA,UAC1B;AAAA,SACD,CAAA;AACD,QAAA,MAAM,IAAI,mBAAmB,EAAE,KAAA,EAAO,wBAAwB,OAAA,EAAS,OAAA,CAAQ,SAAS,CAAA;AAAA,MAC1F;AACA,MAAA,IAAI,OAAA,CAAQ,SAAS,aAAA,EAAe;AAClC,QAAA,iBAAA,CAAkB,IAAA,EAAM,MAAA,EAAQ,KAAA,CAAM,iBAAA,EAAmB,yBAAA,EAA2B;AAAA,UAClF,QAAQ,iBAAA,CAAkB,MAAA;AAAA,UAC1B;AAAA,SACD,CAAA;AACD,QAAA,MAAM,IAAI,4BAA4B,EAAE,KAAA,EAAO,qBAAqB,OAAA,EAAS,OAAA,CAAQ,SAAS,CAAA;AAAA,MAChG;AAAA,IACF;AAEA,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"index.mjs","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 /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\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 /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\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 } 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\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 | {\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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"]}
|
package/dist/node/index.d.cts
CHANGED
|
@@ -1,104 +1,60 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
import
|
|
1
|
+
export { A as ACCESS_COOKIE, C as CSRF_COOKIE, N as NodeSession, R as REFRESH_COOKIE, T as TokenManager, c as createJar, a as createNodeClient, b as createNodeSession, e as extractCookieValue, w as wrapAxios } from '../cookieJar-BTDnjjbL.cjs';
|
|
2
|
+
export { A as AxiamClaims, I as ID_TOKEN_ALG, a as IdTokenClaims, b as IdTokenExpectations, c as IdTokenVerifier, J as JWKS_PATH, d as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, V as Verifier, e as createJwksVerifier, f as createVerifier } from '../jwks-BgojMGC5.cjs';
|
|
3
|
+
export { A as AuthorizationRequest, D as DISCOVERY_PATH, I as IntrospectParams, a as IntrospectionResult, L as LoginClientCredentialsParams, M as MIN_DISCOVERY_TTL_MS, b as MemoryOidcStateStore, O as OIDC_STATE_TTL_MS, c as OidcBeginParams, d as OidcClient, e as OidcClientOptions, f as OidcConfiguration, g as OidcExchangeParams, h as OidcRefreshParams, i as OidcStateEntry, j as OidcStateStore, k as OidcTokenSet, R as RevokeParams, S as SSO_CALLBACK_PATH, l as SSO_START_PATH, m as SsoCompleteParams, n as SsoCompleteResult, o as SsoStartParams, p as SsoStartResult, q as createOidcClient, r as normalizeOrigin } from '../oidcState-BGxqWUun.cjs';
|
|
4
|
+
import { S as Sensitive } from '../sensitive-BC_s7Rrd.cjs';
|
|
5
|
+
import 'tough-cookie';
|
|
6
|
+
import '../session-BWUWhhyB.cjs';
|
|
7
|
+
import 'axios';
|
|
8
|
+
import '../client-B_FqmZ0i.cjs';
|
|
7
9
|
import '../types-BVkMoqLU.cjs';
|
|
8
10
|
|
|
9
|
-
declare class TokenManager {
|
|
10
|
-
#private;
|
|
11
|
-
constructor(jar: CookieJar, baseUrl: string, tenantId?: string);
|
|
12
|
-
/**
|
|
13
|
-
* Synchronous, best-effort read of the last-known access token. Returns
|
|
14
|
-
* `null` if no token has been cached yet (no request/refresh has
|
|
15
|
-
* completed since construction, or `syncFromJar()` was never called).
|
|
16
|
-
*/
|
|
17
|
-
cachedAccessToken(): Sensitive<string> | null;
|
|
18
|
-
/**
|
|
19
|
-
* Async read of the current `axiam_refresh` cookie value from the jar,
|
|
20
|
-
* wrapped in Sensitive<T>. Queried against the refresh endpoint's URL
|
|
21
|
-
* since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible
|
|
22
|
-
* at the bare base URL).
|
|
23
|
-
*/
|
|
24
|
-
refreshTokenValue(): Promise<Sensitive<string> | null>;
|
|
25
|
-
/**
|
|
26
|
-
* Refresh the in-memory cached access token from the jar. Call this after
|
|
27
|
-
* every REST request/refresh so the synchronous gRPC-interceptor fast-path
|
|
28
|
-
* (`cachedAccessToken()`) stays current (Pitfall 3).
|
|
29
|
-
*/
|
|
30
|
-
syncFromJar(): Promise<void>;
|
|
31
|
-
/** The resolved tenant identifier (slug or UUID form), if known. */
|
|
32
|
-
tenantId(): string | undefined;
|
|
33
|
-
/** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */
|
|
34
|
-
setTenantId(tenantId: string): void;
|
|
35
|
-
/** Clear all cached token state (used by logout()). */
|
|
36
|
-
clear(): void;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
declare class NodeSession extends SharedSession {
|
|
40
|
-
#private;
|
|
41
|
-
readonly tokenManager: TokenManager;
|
|
42
|
-
readonly jwksVerifier: Verifier;
|
|
43
|
-
constructor(options: AxiamClientOptions, base: SharedSession, tokenManager: TokenManager, jwksVerifier: Verifier, jar: CookieJar);
|
|
44
|
-
/**
|
|
45
|
-
* Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this
|
|
46
|
-
* session's per-instance `refreshGuard` (inherited from SharedSession) by
|
|
47
|
-
* both REST's reactive interceptor (rest/interceptors.ts) and gRPC's
|
|
48
|
-
* callWithRefresh — since `refreshGuard` is scoped to THIS session
|
|
49
|
-
* instance (CR-02, D-13), both transports share exactly one in-flight
|
|
50
|
-
* refresh for this session regardless of which one triggers it, while
|
|
51
|
-
* remaining fully independent from any other session's guard.
|
|
52
|
-
*/
|
|
53
|
-
doRefresh: () => Promise<void>;
|
|
54
|
-
/**
|
|
55
|
-
* Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a
|
|
56
|
-
* successful login()/verifyMfa(). Refreshes the cached access token (so
|
|
57
|
-
* the gRPC interceptor's synchronous fast-path is current immediately
|
|
58
|
-
* after login) and reads the `axiam_csrf` cookie out of the jar into
|
|
59
|
-
* `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.
|
|
60
|
-
*/
|
|
61
|
-
onAuthenticated: () => Promise<void>;
|
|
62
|
-
}
|
|
63
|
-
/** Build the Node persona's session: REST SharedSession + cookie jar + TokenManager + JWKS verifier. */
|
|
64
|
-
declare function createNodeSession(options: AxiamClientOptions): NodeSession;
|
|
65
11
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
*
|
|
72
|
-
* correctly under Node.
|
|
12
|
+
* The only PKCE code-challenge method this SDK emits (RFC 7636 §4.2,
|
|
13
|
+
* CONTRACT.md §12.1 rule 3). `plain` is intentionally absent.
|
|
14
|
+
*/
|
|
15
|
+
declare const CODE_CHALLENGE_METHOD_S256 = "S256";
|
|
16
|
+
/**
|
|
17
|
+
* Entropy, in bytes, of a generated `state` / `nonce` / `code_verifier`.
|
|
73
18
|
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* built from the same `NodeSession`.
|
|
19
|
+
* §12.1 rule 1 requires at least 16 bytes (128 bits) and RECOMMENDS 32;
|
|
20
|
+
* rule 2 RECOMMENDS 32 bytes for the verifier, which base64url-encodes to
|
|
21
|
+
* exactly 43 characters — the minimum RFC 7636 §4.1 length, drawn only from
|
|
22
|
+
* the unreserved set `[A-Za-z0-9-._~]`.
|
|
79
23
|
*/
|
|
80
|
-
declare
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
24
|
+
declare const CSPRNG_BYTES = 32;
|
|
25
|
+
/**
|
|
26
|
+
* Generate a URL-safe random token: `bytes` CSPRNG bytes, base64url-encoded
|
|
27
|
+
* **without** padding (RFC 4648 §5 — Node's `'base64url'` encoding never
|
|
28
|
+
* emits `=`).
|
|
29
|
+
*
|
|
30
|
+
* Used for both `state` and `nonce`, which §12.3 rule 2 classes as
|
|
31
|
+
* **non-secret**: they are returned as plain strings, are echoed through the
|
|
32
|
+
* browser's address bar by construction, and are safe to log.
|
|
33
|
+
*/
|
|
34
|
+
declare function randomUrlSafeToken(bytes?: number): string;
|
|
90
35
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
36
|
+
* Generate a fresh PKCE `code_verifier` (RFC 7636 §4.1): 32 CSPRNG bytes
|
|
37
|
+
* base64url-encoded without padding, i.e. 43 characters from the unreserved
|
|
38
|
+
* set.
|
|
39
|
+
*
|
|
40
|
+
* Returned already wrapped in {@link Sensitive} — §12.5 makes the verifier
|
|
41
|
+
* secret **for its whole lifetime**, including while it sits in the
|
|
42
|
+
* `AuthorizationRequest` handed back to the caller and in any
|
|
43
|
+
* `OidcStateStore` entry.
|
|
95
44
|
*/
|
|
96
|
-
declare function
|
|
45
|
+
declare function generateCodeVerifier(): Sensitive<string>;
|
|
97
46
|
/**
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
47
|
+
* Derive the PKCE `code_challenge` from a verifier:
|
|
48
|
+
* `BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))`, unpadded
|
|
49
|
+
* (RFC 7636 §4.2, CONTRACT.md §12.1 rule 3).
|
|
50
|
+
*
|
|
51
|
+
* The verifier is hashed as ASCII exactly as the RFC specifies. Verified
|
|
52
|
+
* against the RFC 7636 Appendix B test vector in
|
|
53
|
+
* `test/node/oidcPkce.test.ts`, which every SDK must carry (§12.1 rule 3).
|
|
54
|
+
*
|
|
55
|
+
* The challenge is a one-way digest and is **not** secret — it travels in the
|
|
56
|
+
* authorization URL — so it is returned as a plain string.
|
|
101
57
|
*/
|
|
102
|
-
declare function
|
|
58
|
+
declare function computeCodeChallenge(codeVerifier: string): string;
|
|
103
59
|
|
|
104
|
-
export {
|
|
60
|
+
export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, computeCodeChallenge, generateCodeVerifier, randomUrlSafeToken };
|