axiam-sdk 1.1.2 → 1.2.2
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 +73 -3
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/browser/index.d.cts +1 -1
- package/dist/browser/index.d.ts +1 -1
- package/dist/{client-BGFn1VQh.d.cts → client-Bp7riC4k.d.cts} +147 -3
- package/dist/{client-DrQZZ1js.d.ts → client-CaurIxje.d.ts} +147 -3
- package/dist/{cookieJar-BTmpjXZe.d.ts → cookieJar-DC4GLKrJ.d.ts} +2 -2
- package/dist/{cookieJar-BqYOnNN-.d.cts → cookieJar-oKazfbN1.d.cts} +2 -2
- package/dist/{errors-DZ3k8a8i.d.cts → errors-CWlh-wcm.d.cts} +7 -1
- package/dist/{errors-DZ3k8a8i.d.ts → errors-CWlh-wcm.d.ts} +7 -1
- package/dist/{errors-dlGXAsbh.d.ts → errors-DDo3oxcH.d.ts} +1 -1
- package/dist/{errors-RvGlTyUj.d.cts → errors-DHauOsqx.d.cts} +1 -1
- package/dist/grpc/index.d.cts +4 -4
- package/dist/grpc/index.d.ts +4 -4
- package/dist/grpc/index.js +26 -5
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +26 -5
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +26 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +26 -5
- package/dist/index.mjs.map +1 -1
- package/dist/middleware/index.d.cts +5 -5
- package/dist/middleware/index.d.ts +5 -5
- package/dist/middleware/index.js +164 -12
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +164 -12
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +15 -4
- package/dist/node/index.d.ts +15 -4
- package/dist/node/index.js +186 -14
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +185 -15
- package/dist/node/index.mjs.map +1 -1
- package/dist/{oidcState-C3VLn3eD.d.ts → oidcState-CZhj0MBP.d.ts} +123 -5
- package/dist/{oidcState-BaJ-SM_R.d.cts → oidcState-EnEJmoF5.d.cts} +123 -5
- package/dist/rest/index.d.cts +6 -6
- package/dist/rest/index.d.ts +6 -6
- package/dist/rest/index.js +26 -5
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +26 -5
- package/dist/rest/index.mjs.map +1 -1
- package/dist/{session-B03NsqVs.d.ts → session-Beo11VT_.d.ts} +9 -0
- package/dist/{session-plDr4lFu.d.cts → session-CeIUXgpE.d.cts} +9 -0
- package/package.json +18 -18
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;;;AClDO,IAAe,UAAA,GAAf,cAAkC,KAAA,C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,UAAA;AAAA,QACA,SAAA,CAAU,MAAA;AAAA,QACV,kBAAkB,IAAA,EAAM;AAAA,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,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// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string = '') {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nestjs/metadata.ts","../../src/nestjs/decorators.ts","../../src/core/errors.ts","../../src/middleware/authzCore.ts","../../src/nestjs/guard.ts"],"names":["SetMetadata","UnauthorizedException","ForbiddenException","BadRequestException","ServiceUnavailableException"],"mappings":";;;;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;;;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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EA,MAAA,MAAM,UAAU,MAAM,cAAA;AAAA,QACpB,OAAA;AAAA,QACA,iBAAA,CAAkB,MAAA;AAAA,QAClB,UAAA;AAAA,QACA,SAAA,CAAU,MAAA;AAAA,QACV,kBAAkB,IAAA,EAAM;AAAA,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,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// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
|
|
@@ -1 +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,E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,qBAAA,CAAsB,OAAA,EAAS,iBAAA,CAAkB,QAAQ,CAAA;AAAA,MACxE,SAAS,GAAA,EAAK;AACZ,QAAA,MAAM,OAAA,GAAU,GAAA,YAAe,uBAAA,GAA0B,GAAA,CAAI,OAAA,GAAU,kBAAA;AACvE,QAAA,MAAM,IAAI,mBAAA,CAAoB,EAAE,KAAA,EAAO,iBAAA,EAAmB,SAAS,CAAA;AAAA,MACrE;AAEA,MAAA,MAAM,UAAU,MAAM,cAAA;AAAA,QACpB,OAAA;AAAA,QACA,iBAAA,CAAkB,MAAA;AAAA,QAClB,UAAA;AAAA,QACA,SAAA,CAAU,MAAA;AAAA,QACV,kBAAkB,IAAA,EAAM;AAAA,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 /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string = '') {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nestjs/metadata.ts","../../src/nestjs/decorators.ts","../../src/core/errors.ts","../../src/middleware/authzCore.ts","../../src/nestjs/guard.ts"],"names":[],"mappings":";;;;;AAKO,IAAM,2BAAA,0BAAqC,mBAAmB;AAG9D,IAAM,6BAAA,0BAAuC,qBAAqB;AAGlE,IAAM,2BAAA,0BAAqC,mBAAmB;;;AC8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(guard.ts). Symbols, not strings, so a consuming app's\n// own metadata never collides with these by coincidence.\n\n/** Set by {@link RequireAuth}; read by {@link AxiamGuard}. */\nexport const AXIAM_REQUIRE_AUTH_METADATA = Symbol('axiam:requireAuth');\n\n/** Set by {@link RequireAccess}; read by {@link AxiamGuard}. Value shape: {@link RequireAccessMetadata}. */\nexport const AXIAM_REQUIRE_ACCESS_METADATA = Symbol('axiam:requireAccess');\n\n/** Set by {@link RequireRole}; read by {@link AxiamGuard}. Value shape: `string[]`. */\nexport const AXIAM_REQUIRE_ROLE_METADATA = Symbol('axiam:requireRole');\n","// NestJS metadata decorators (CONTRACT.md §11, Tier 2). Pure metadata\n// attachment via `@nestjs/common`'s `SetMetadata` — no enforcement logic\n// lives here (that's `guard.ts`'s `AxiamGuard`, which reads the metadata\n// back out via `Reflector`). Uses NestJS's own decorator machinery, so this\n// SDK's tsconfig does NOT enable `experimentalDecorators` — only the\n// consuming Nest application needs it (which it already does, by being a\n// Nest app).\n\nimport { SetMetadata } from '@nestjs/common';\nimport type { RequireAccessOptions } from '../middleware/authzCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\n\n/** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */\nexport interface NestParamResource {\n /** The route parameter name (e.g. `request.params[name]`) carrying the resource id. */\n readonly param: string;\n}\n\n/** The `resource` argument accepted by `@RequireAccess` (CONTRACT.md §11.2.3): a static literal, {@link NestParamResource} (route parameter), or a `(request) => string` resolver. */\nexport type NestResourceSpec = string | NestParamResource | ((request: unknown) => string);\n\n/** The metadata value `@RequireAccess` attaches, read back by {@link AxiamGuard} via `Reflector`. */\nexport interface RequireAccessMetadata {\n /** The action being performed (e.g. `\"read\"`, `\"write\"`, `\"delete\"`), passed through to `checkAccess` verbatim. */\n action: string;\n /** How to resolve the checked resource's id from the request (§11.2.3). */\n resource: NestResourceSpec;\n /** Optional scope/logger settings, passed through to `checkAccess`/the debug-only denial log. */\n opts?: RequireAccessOptions;\n}\n\n/**\n * `@RequireAuth()` (CONTRACT.md §11.1) — marks a handler/controller as\n * requiring an authenticated AXIAM identity. `AxiamGuard` responds 401 if\n * `request.axiamUser` (injected by `axiamMiddleware`/`axiamPlugin` mounted\n * on the underlying HTTP adapter) is absent.\n */\nexport function RequireAuth(): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_AUTH_METADATA, true);\n}\n\n/**\n * `@RequireAccess(action, resource, opts?)` (CONTRACT.md §11) — a per-route\n * authorization requirement enforced by `AxiamGuard`. `resource` is resolved\n * per §11.2.3's precedence: a literal string, `{ param: 'id' }` (a route\n * parameter), or a `(request) => string` resolver.\n *\n * @example\n * ```ts\n * \\@RequireAccess('read', { param: 'id' })\n * \\@Get(':id')\n * getDocument(\\@Param('id') id: string) { ... }\n * ```\n */\nexport function RequireAccess(\n action: string,\n resource: NestResourceSpec,\n opts?: RequireAccessOptions,\n): ClassDecorator & MethodDecorator {\n const metadata: RequireAccessMetadata = { action, resource, opts };\n return SetMetadata(AXIAM_REQUIRE_ACCESS_METADATA, metadata);\n}\n\n/**\n * `@RequireRole(...roles)` (CONTRACT.md §11.1, MAY) — a local (no server\n * round-trip) check that the authenticated identity's roles contain at\n * least one of `roles`. Cheaper but coarser than `@RequireAccess`; NOT a\n * substitute for a resource-level check.\n */\nexport function RequireRole(...roles: string[]): ClassDecorator & MethodDecorator {\n return SetMetadata(AXIAM_REQUIRE_ROLE_METADATA, roles);\n}\n","// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// AxiamGuard — the enforcement side of the §11 NestJS decorators (Tier 2).\n//\n// Reads the metadata `decorators.ts` attaches via `Reflector`, then reuses\n// the EXACT same `middleware/authzCore.ts` primitives\n// (`assertAuthzClient`/`evaluateAccess`/`hasAnyRole`/`ResourceResolutionError`)\n// that back the Express/Fastify guards, so the three framework integrations\n// can never drift on the §11 error-mapping/subject-propagation/no-caching\n// rules. Never performs its own token extraction (§11.2.1): it only reads\n// `request.axiamUser`, which must already be set by `axiamMiddleware`/\n// `axiamPlugin` mounted on the underlying HTTP adapter (Nest runs on top of\n// Express or Fastify) — 401 if absent.\n\nimport {\n BadRequestException,\n ForbiddenException,\n ServiceUnavailableException,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common';\nimport type { Reflector } from '@nestjs/core';\nimport {\n assertAuthzClient,\n evaluateAccess,\n hasAnyRole,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n} from '../middleware/authzCore.js';\nimport type { AxiamIdentity } from '../middleware/verifyCore.js';\nimport {\n AXIAM_REQUIRE_ACCESS_METADATA,\n AXIAM_REQUIRE_AUTH_METADATA,\n AXIAM_REQUIRE_ROLE_METADATA,\n} from './metadata.js';\nimport type { NestResourceSpec, RequireAccessMetadata } from './decorators.js';\n\n/** DI token for the `AuthzVerifiableSession` `AxiamGuard` is constructed with — provide it with `{ provide: AXIAM_SESSION, useValue: session }`. */\nexport const AXIAM_SESSION = Symbol('AXIAM_SESSION');\n\ninterface RequestWithAxiamUser {\n axiamUser?: AxiamIdentity;\n params?: Record<string, string | undefined>;\n}\n\n/**\n * Resolve the resource id from `request` per `spec` (mirrors\n * `middleware/authzCore.ts`'s `resolveResourceId`, adapted to the\n * `{ param }`-object resource shape `@RequireAccess` uses). A missing or\n * empty resolution is a **programming error** raised as\n * {@link ResourceResolutionError} — never a silent allow (§11.2.3).\n */\nfunction resolveNestResourceId(request: RequestWithAxiamUser, spec: NestResourceSpec): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(request);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = request.params?.[spec.param];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.param}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/**\n * `AxiamGuard` (CONTRACT.md §11, Tier 2) — a Nest `CanActivate` guard\n * enforcing the `@RequireAuth`/`@RequireAccess`/`@RequireRole` decorators. A\n * handler/controller with none of the three decorators is left unrestricted\n * by this guard (`true`).\n *\n * Deliberately a **plain class with no Nest decorators of its own** (no\n * `@Injectable()`/`@Inject()`) — this SDK's tsconfig does not enable\n * `experimentalDecorators` (only the consuming Nest app's does), so\n * `AxiamGuard` is wired into a Nest app via an explicit factory provider\n * rather than Nest's implicit constructor-injection-via-metadata:\n *\n * ```ts\n * import { APP_GUARD, Reflector } from '\\@nestjs/core';\n * import { AxiamGuard, AXIAM_SESSION } from 'axiam-sdk/nestjs';\n *\n * providers: [\n * { provide: AXIAM_SESSION, useValue: authzSession },\n * {\n * provide: APP_GUARD,\n * useFactory: (reflector: Reflector, session: AuthzVerifiableSession) => new AxiamGuard(reflector, session),\n * inject: [Reflector, AXIAM_SESSION],\n * },\n * ],\n * ```\n *\n * Requires an `AuthzVerifiableSession` — only dereferenced (via\n * `assertAuthzClient`, throwing if `authzClient` is absent) when a\n * `@RequireAccess` decorator is actually present on the matched\n * handler/controller, mirroring the Express/Fastify guards' construction-time\n * check.\n */\nexport class AxiamGuard implements CanActivate {\n constructor(\n private readonly reflector: Reflector,\n private readonly session?: AuthzVerifiableSession,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const requireAuth = this.reflector.getAllAndOverride<boolean>(AXIAM_REQUIRE_AUTH_METADATA, targets);\n const requireRoles = this.reflector.getAllAndOverride<string[]>(AXIAM_REQUIRE_ROLE_METADATA, targets);\n const requireAccessMeta = this.reflector.getAllAndOverride<RequireAccessMetadata>(\n AXIAM_REQUIRE_ACCESS_METADATA,\n targets,\n );\n\n if (!requireAuth && !requireRoles && !requireAccessMeta) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest<RequestWithAxiamUser>();\n const axiamUser = request.axiamUser;\n if (!axiamUser) {\n throw new UnauthorizedException({\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin first',\n });\n }\n\n if (requireRoles && !hasAnyRole(axiamUser.roles, requireRoles)) {\n throw new ForbiddenException({ error: 'authorization_denied', message: 'missing required role' });\n }\n\n if (requireAccessMeta) {\n const checker = assertAuthzClient(this.session ?? ({} as AuthzVerifiableSession));\n\n let resourceId: string;\n try {\n resourceId = resolveNestResourceId(request, requireAccessMeta.resource);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n throw new BadRequestException({ error: 'invalid_request', message });\n }\n\n const outcome = await evaluateAccess(\n checker,\n requireAccessMeta.action,\n resourceId,\n axiamUser.userId,\n requireAccessMeta.opts?.scope,\n );\n if (outcome.kind === 'denied') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'access denied', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ForbiddenException({ error: 'authorization_denied', message: outcome.message });\n }\n if (outcome.kind === 'unavailable') {\n requireAccessMeta.opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', {\n action: requireAccessMeta.action,\n resourceId,\n });\n throw new ServiceUnavailableException({ error: 'authz_unavailable', message: outcome.message });\n }\n }\n\n return true;\n }\n}\n"]}
|
package/dist/node/index.d.cts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
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-
|
|
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-oKazfbN1.cjs';
|
|
2
2
|
export { D as DEFAULT_POLL_INTERVAL_MS, M as MAX_ENTRIES, a as MIN_POLL_INTERVAL_MS, R as RevocationFeed, b as RevocationFeedOptions } from '../revocationFeed-KQhvMMl8.cjs';
|
|
3
3
|
export { a as AccessTokenExpectations, A as AxiamClaims, b as CLOCK_SKEW_LEEWAY_SEC, C as CnfClaim, d as ID_TOKEN_ALG, I as IdTokenClaims, e as IdTokenExpectations, f as IdTokenVerifier, J as JWKS_PATH, g as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, P as PresentedProofs, V as Verifier, h as assertTenantClaim, i as certificateThumbprintS256, j as createJwksVerifier, c as createVerifier, v as verifyCertificateBinding, k as verifyTokenBinding } from '../jwks-CTVpOWzI.cjs';
|
|
4
|
-
|
|
4
|
+
import { P as ProviderNonce } from '../oidcState-EnEJmoF5.cjs';
|
|
5
|
+
export { A as ACCESS_TOKEN_TYPE, a as AuthorizationRequest, B as BACKCHANNEL_LOGOUT_EVENT, C as CIBA_GRANT_TYPE, b as CIBA_SLOW_DOWN_INCREMENT_SECS, c as CibaAwaitParams, d as CibaClock, e as CibaDelivery, f as CibaInitiateParams, g as CibaInitiateResponse, h as CibaPingHeaders, i as CibaPollParams, j as CibaRequestSigner, k as CibaSignerDescription, l as CibaSigningAlg, m as CibaSigningKey, n as CibaUserHint, D as DEFAULT_CIBA_INTERVAL_SECS, o as DEFAULT_POLL_INTERVAL_SECS, p as DEVICE_CODE_GRANT_TYPE, q as DISCOVERY_PATH, r as DeviceAuthorization, s as DeviceAuthorizeParams, t as DeviceLoginParams, u as DevicePollParams, E as ExchangedToken, F as FederationProvider, v as FederationProviderList, H as HANDOFF_CODE_TTL_SECS, w as HANDOFF_QUERY_PARAM, I as IntrospectParams, x as IntrospectionResult, J as JWT_TOKEN_TYPE, L as LoginClientCredentialsParams, y as LoginWithProviderIdTokenOptions, z as LogoutUrlParams, M as MAX_LOGOUT_TOKEN_AGE_SECS, G as MIN_DISCOVERY_TTL_MS, K as MemoryOidcStateStore, N as MtlsEndpointAliases, O as OIDC_STATE_TTL_MS, Q as OidcBeginParams, R as OidcClient, S as OidcClientOptions, T as OidcConfiguration, U as OidcExchangeParams, V as OidcParParams, W as OidcRefreshParams, X as OidcStateEntry, Y as OidcStateStore, Z as OidcTokenSet, _ as PROTOCOL_OAUTH2, $ as PROTOCOL_OIDC_CONNECT, a0 as PROTOCOL_SAML, a1 as PROVIDER_ID_TOKEN_GRANT_TYPE, a2 as PollSchedule, a3 as PushedAuthorizationRequest, a4 as RequestedPermission, a5 as RequestingPartyToken, a6 as ResourceSet, a7 as RevokeParams, a8 as RptPermission, a9 as SIGNED_REQUEST_LIFETIME_SECS, aa as SLOW_DOWN_INCREMENT_SECS, ab as SSO_CALLBACK_PATH, ac as SSO_HANDOFF_PATH, ad as SSO_OAUTH2_CALLBACK_PATH, ae as SSO_OAUTH2_START_PATH, af as SSO_PROVIDERS_PATH, ag as SSO_START_PATH, ah as SsoCompleteHandoffParams, ai as SsoCompleteOauth2Params, aj as SsoCompleteParams, ak as SsoCompleteResult, al as SsoProvidersParams, am as SsoStartOauth2Params, an as SsoStartParams, ao as SsoStartResult, ap as TOKEN_EXCHANGE_GRANT_TYPE, aq as TokenExchangeParams, ar as UMA_CLAIM_TOKEN_FORMAT, as as UMA_PROTECTION_SCOPE, at as UMA_TICKET_GRANT_TYPE, au as UmaChallenge, av as UmaExchangeTicketParams, aw as VerifiedLogoutToken, ax as createOidcClient, ay as isAccessDenied, az as isExpiredToken, aA as normalizeOrigin, aB as umaChallengeHeader, aC as umaParseChallenge } from '../oidcState-EnEJmoF5.cjs';
|
|
5
6
|
import { S as Sensitive } from '../sensitive-BC_s7Rrd.cjs';
|
|
6
7
|
import { AuthError } from '../index.cjs';
|
|
7
8
|
import { AxiamClient } from '../index.cjs';
|
|
8
9
|
import 'axios';
|
|
9
10
|
import 'tough-cookie';
|
|
10
|
-
import '../session-
|
|
11
|
+
import '../session-CeIUXgpE.cjs';
|
|
11
12
|
import '../telemetry-Du0-zS5f.cjs';
|
|
12
13
|
import '../types-zXSpiQM-.cjs';
|
|
13
14
|
import 'node:crypto';
|
|
@@ -153,6 +154,16 @@ declare function generateCodeVerifier(): Sensitive<string>;
|
|
|
153
154
|
* authorization URL — so it is returned as a plain string.
|
|
154
155
|
*/
|
|
155
156
|
declare function computeCodeChallenge(codeVerifier: string): string;
|
|
157
|
+
/**
|
|
158
|
+
* A fresh nonce pair for native sign-in with a provider ID token
|
|
159
|
+
* (CONTRACT.md §37.4) — **pure local computation, no network I/O**.
|
|
160
|
+
*
|
|
161
|
+
* `raw` is 32 CSPRNG bytes, base64url without padding, wrapped in
|
|
162
|
+
* {@link Sensitive}; `hashed` is the lower-case hexadecimal SHA-256 of the
|
|
163
|
+
* bytes of `raw` as sent. Give `hashed` to the provider's SDK as *its* nonce
|
|
164
|
+
* and `raw` to `loginWithProviderIdToken`. Nothing is stored.
|
|
165
|
+
*/
|
|
166
|
+
declare function nativeNonce(): ProviderNonce;
|
|
156
167
|
|
|
157
168
|
/** Default freshness window, in seconds, for the `t=` timestamp (CONTRACT.md §13.2). */
|
|
158
169
|
declare const DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
|
|
@@ -540,5 +551,5 @@ declare class SsfReceiver {
|
|
|
540
551
|
poll(streamId: string, options?: SsfPollOptions): Promise<SsfPollResult>;
|
|
541
552
|
}
|
|
542
553
|
|
|
543
|
-
export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, DPOP_IAT_LEEWAY_SEC, InMemoryJtiStore, JWKS_REFETCH_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryReplayStore, SSF_EVENT_TYPES, Sensitive, SetRefusedError, SsfReceiver, WebhookVerifyError, accessTokenHash, canonicalHtu, computeCodeChallenge, generateCodeVerifier, jwkThumbprintS256, pushErrorCode, randomUrlSafeToken, setErrFromReason, verifyDpopProof, verifyWebhook };
|
|
554
|
+
export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, DPOP_IAT_LEEWAY_SEC, InMemoryJtiStore, JWKS_REFETCH_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryReplayStore, ProviderNonce, SSF_EVENT_TYPES, Sensitive, SetRefusedError, SsfReceiver, WebhookVerifyError, accessTokenHash, canonicalHtu, computeCodeChallenge, generateCodeVerifier, jwkThumbprintS256, nativeNonce, pushErrorCode, randomUrlSafeToken, setErrFromReason, verifyDpopProof, verifyWebhook };
|
|
544
555
|
export type { AccessTokenProvider, DpopVerifyOptions, JtiStore, RefusedSet, ReplayStore, SecurityEvent, SetErr, SetFailureReason, SsfPollOptions, SsfPollResult, SsfReceiverConfig, VerifiedWebhookEvent, VerifyWebhookOptions, WebhookVerifyFailureReason };
|
package/dist/node/index.d.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
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-
|
|
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-DC4GLKrJ.js';
|
|
2
2
|
export { D as DEFAULT_POLL_INTERVAL_MS, M as MAX_ENTRIES, a as MIN_POLL_INTERVAL_MS, R as RevocationFeed, b as RevocationFeedOptions } from '../revocationFeed-KQhvMMl8.js';
|
|
3
3
|
export { a as AccessTokenExpectations, A as AxiamClaims, b as CLOCK_SKEW_LEEWAY_SEC, C as CnfClaim, d as ID_TOKEN_ALG, I as IdTokenClaims, e as IdTokenExpectations, f as IdTokenVerifier, J as JWKS_PATH, g as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, P as PresentedProofs, V as Verifier, h as assertTenantClaim, i as certificateThumbprintS256, j as createJwksVerifier, c as createVerifier, v as verifyCertificateBinding, k as verifyTokenBinding } from '../jwks-CTVpOWzI.js';
|
|
4
|
-
|
|
4
|
+
import { P as ProviderNonce } from '../oidcState-CZhj0MBP.js';
|
|
5
|
+
export { A as ACCESS_TOKEN_TYPE, a as AuthorizationRequest, B as BACKCHANNEL_LOGOUT_EVENT, C as CIBA_GRANT_TYPE, b as CIBA_SLOW_DOWN_INCREMENT_SECS, c as CibaAwaitParams, d as CibaClock, e as CibaDelivery, f as CibaInitiateParams, g as CibaInitiateResponse, h as CibaPingHeaders, i as CibaPollParams, j as CibaRequestSigner, k as CibaSignerDescription, l as CibaSigningAlg, m as CibaSigningKey, n as CibaUserHint, D as DEFAULT_CIBA_INTERVAL_SECS, o as DEFAULT_POLL_INTERVAL_SECS, p as DEVICE_CODE_GRANT_TYPE, q as DISCOVERY_PATH, r as DeviceAuthorization, s as DeviceAuthorizeParams, t as DeviceLoginParams, u as DevicePollParams, E as ExchangedToken, F as FederationProvider, v as FederationProviderList, H as HANDOFF_CODE_TTL_SECS, w as HANDOFF_QUERY_PARAM, I as IntrospectParams, x as IntrospectionResult, J as JWT_TOKEN_TYPE, L as LoginClientCredentialsParams, y as LoginWithProviderIdTokenOptions, z as LogoutUrlParams, M as MAX_LOGOUT_TOKEN_AGE_SECS, G as MIN_DISCOVERY_TTL_MS, K as MemoryOidcStateStore, N as MtlsEndpointAliases, O as OIDC_STATE_TTL_MS, Q as OidcBeginParams, R as OidcClient, S as OidcClientOptions, T as OidcConfiguration, U as OidcExchangeParams, V as OidcParParams, W as OidcRefreshParams, X as OidcStateEntry, Y as OidcStateStore, Z as OidcTokenSet, _ as PROTOCOL_OAUTH2, $ as PROTOCOL_OIDC_CONNECT, a0 as PROTOCOL_SAML, a1 as PROVIDER_ID_TOKEN_GRANT_TYPE, a2 as PollSchedule, a3 as PushedAuthorizationRequest, a4 as RequestedPermission, a5 as RequestingPartyToken, a6 as ResourceSet, a7 as RevokeParams, a8 as RptPermission, a9 as SIGNED_REQUEST_LIFETIME_SECS, aa as SLOW_DOWN_INCREMENT_SECS, ab as SSO_CALLBACK_PATH, ac as SSO_HANDOFF_PATH, ad as SSO_OAUTH2_CALLBACK_PATH, ae as SSO_OAUTH2_START_PATH, af as SSO_PROVIDERS_PATH, ag as SSO_START_PATH, ah as SsoCompleteHandoffParams, ai as SsoCompleteOauth2Params, aj as SsoCompleteParams, ak as SsoCompleteResult, al as SsoProvidersParams, am as SsoStartOauth2Params, an as SsoStartParams, ao as SsoStartResult, ap as TOKEN_EXCHANGE_GRANT_TYPE, aq as TokenExchangeParams, ar as UMA_CLAIM_TOKEN_FORMAT, as as UMA_PROTECTION_SCOPE, at as UMA_TICKET_GRANT_TYPE, au as UmaChallenge, av as UmaExchangeTicketParams, aw as VerifiedLogoutToken, ax as createOidcClient, ay as isAccessDenied, az as isExpiredToken, aA as normalizeOrigin, aB as umaChallengeHeader, aC as umaParseChallenge } from '../oidcState-CZhj0MBP.js';
|
|
5
6
|
import { S as Sensitive } from '../sensitive-BC_s7Rrd.js';
|
|
6
7
|
import { AuthError } from '../index.js';
|
|
7
8
|
import { AxiamClient } from '../index.js';
|
|
8
9
|
import 'axios';
|
|
9
10
|
import 'tough-cookie';
|
|
10
|
-
import '../session-
|
|
11
|
+
import '../session-Beo11VT_.js';
|
|
11
12
|
import '../telemetry-Du0-zS5f.js';
|
|
12
13
|
import '../types-BOX-6Srv.js';
|
|
13
14
|
import 'node:crypto';
|
|
@@ -153,6 +154,16 @@ declare function generateCodeVerifier(): Sensitive<string>;
|
|
|
153
154
|
* authorization URL — so it is returned as a plain string.
|
|
154
155
|
*/
|
|
155
156
|
declare function computeCodeChallenge(codeVerifier: string): string;
|
|
157
|
+
/**
|
|
158
|
+
* A fresh nonce pair for native sign-in with a provider ID token
|
|
159
|
+
* (CONTRACT.md §37.4) — **pure local computation, no network I/O**.
|
|
160
|
+
*
|
|
161
|
+
* `raw` is 32 CSPRNG bytes, base64url without padding, wrapped in
|
|
162
|
+
* {@link Sensitive}; `hashed` is the lower-case hexadecimal SHA-256 of the
|
|
163
|
+
* bytes of `raw` as sent. Give `hashed` to the provider's SDK as *its* nonce
|
|
164
|
+
* and `raw` to `loginWithProviderIdToken`. Nothing is stored.
|
|
165
|
+
*/
|
|
166
|
+
declare function nativeNonce(): ProviderNonce;
|
|
156
167
|
|
|
157
168
|
/** Default freshness window, in seconds, for the `t=` timestamp (CONTRACT.md §13.2). */
|
|
158
169
|
declare const DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
|
|
@@ -540,5 +551,5 @@ declare class SsfReceiver {
|
|
|
540
551
|
poll(streamId: string, options?: SsfPollOptions): Promise<SsfPollResult>;
|
|
541
552
|
}
|
|
542
553
|
|
|
543
|
-
export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, DPOP_IAT_LEEWAY_SEC, InMemoryJtiStore, JWKS_REFETCH_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryReplayStore, SSF_EVENT_TYPES, Sensitive, SetRefusedError, SsfReceiver, WebhookVerifyError, accessTokenHash, canonicalHtu, computeCodeChallenge, generateCodeVerifier, jwkThumbprintS256, pushErrorCode, randomUrlSafeToken, setErrFromReason, verifyDpopProof, verifyWebhook };
|
|
554
|
+
export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, DPOP_IAT_LEEWAY_SEC, InMemoryJtiStore, JWKS_REFETCH_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryReplayStore, ProviderNonce, SSF_EVENT_TYPES, Sensitive, SetRefusedError, SsfReceiver, WebhookVerifyError, accessTokenHash, canonicalHtu, computeCodeChallenge, generateCodeVerifier, jwkThumbprintS256, nativeNonce, pushErrorCode, randomUrlSafeToken, setErrFromReason, verifyDpopProof, verifyWebhook };
|
|
544
555
|
export type { AccessTokenProvider, DpopVerifyOptions, JtiStore, RefusedSet, ReplayStore, SecurityEvent, SetErr, SetFailureReason, SsfPollOptions, SsfPollResult, SsfReceiverConfig, VerifiedWebhookEvent, VerifyWebhookOptions, WebhookVerifyFailureReason };
|