@canopy-io/nestjs 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @canopy-io/nestjs
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2c9163d: A machine client can act for a signed-in person. `exchangeToken` trades the person's access token for a `delegated` one (RFC 8693 token exchange); the verifier accepts the `delegated` type per call with `alsoAllow: ["delegated"]`, holds it to `serviceAudience` and requires its `act.sub`, and `delegation(claims)` reads the person and the client off it. `LocalAuthorizer.evaluate` takes `acting_client_id` and allows only when the identity and the client both hold the permission (`acting_client_not_granted` otherwise). In NestJS, `@AllowDelegatedTokens()` admits the token on a route, and `CanopyGuard` then checks both. The generated types carry `acting_client_id` and `acting_client_allowed` on evaluate. The skill says which credential an agent holds, names three mistakes (a full-access key, an account key it does not need, the person's own token) and shows an agent acting for a person.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [2c9163d]
12
+ - @canopy-io/node@0.22.0
13
+
3
14
  ## 0.8.1
4
15
 
5
16
  ### Patch Changes
package/README.md CHANGED
@@ -21,6 +21,7 @@ Requires NestJS 10 or 11 and Node 18 or later. `@canopy-io/node` comes with it.
21
21
  - **Three scopes.** `node` is the default and the strict question; `app_wide` asks only whether the identity holds the permission anywhere in the Environment; `org` asks the node question at the organization the caller's token is acting in.
22
22
  - **`CanopyTokenGuard`** verifies a Canopy-issued bearer token locally against the published signing keys and attaches the claims, for applications with no auth layer in front. Additive — skip it if you already run Passport or your own JWT middleware.
23
23
  - **`@AllowServiceTokens()`** admits a machine client's `client_credentials` token on the routes built for machines, authorized from the client's own grants; every other route keeps refusing it.
24
+ - **`@AllowDelegatedTokens()`** admits a machine client acting for a person after a token exchange, authorized only where the person and the client both hold the permission.
24
25
  - **`@InjectCanopy()`** hands you the full `@canopy-io/node` client for everything the guard does not cover.
25
26
  - **Fails closed, with the status telling you which failure it was.** `403` for a denial, `503` for an undecidable one, `500` for a broken integration.
26
27
  - **A bounded check.** Its own evaluation timeout and retry count, separate from the client-wide ones, with the wait between attempts capped.
@@ -224,6 +225,21 @@ from the verified claims, never from anything the caller sends. The token's
224
225
  request.canopyToken?.sub` serves both kinds. A machine client pinned to an
225
226
  organization carries its `org_id`, so `scope: "org"` works the same way.
226
227
 
228
+ A machine client acting for a person presents a `delegated` token (see
229
+ `exchangeToken` in `@canopy-io/node`), which answers `401` except on a route or
230
+ controller carrying `@AllowDelegatedTokens()`. It is held to
231
+ `verify.serviceAudience` too. There `CanopyGuard` evaluates the person
232
+ (`resolveIdentity` still reads `sub`) and the client in `act.sub`, and allows
233
+ only when both hold the permission:
234
+
235
+ ```ts
236
+ @UseGuards(CanopyTokenGuard, CanopyGuard)
237
+ @AllowDelegatedTokens()
238
+ @RequirePermission("deals.read", { scope: "org" })
239
+ @Get()
240
+ list() {}
241
+ ```
242
+
227
243
  A rejected token is a 401 whatever the detail, with the specific code left on
228
244
  `error.cause` for your logs rather than handed to the caller — who has no use
229
245
  for the difference and should not be told which check failed. The exception is
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var CANOPY_AUTHORIZER = "CANOPY_AUTHORIZER";
21
21
  var CANOPY_TOKEN_VERIFIER = "CANOPY_TOKEN_VERIFIER";
22
22
  var CANOPY_PERMISSION = "CANOPY_PERMISSION";
23
23
  var CANOPY_ALLOW_SERVICE_TOKENS = "CANOPY_ALLOW_SERVICE_TOKENS";
24
+ var CANOPY_ALLOW_DELEGATED_TOKENS = "CANOPY_ALLOW_DELEGATED_TOKENS";
24
25
 
25
26
  // src/canopy.guard.ts
26
27
  function isClosable(value) {
@@ -80,9 +81,11 @@ exports.CanopyGuard = class CanopyGuard {
80
81
  * policy" — and neither outcome lets the request proceed.
81
82
  */
82
83
  async evaluate(requirement, identityId, request, cancellation) {
84
+ const actingClientId = this.actingClientOf(request);
83
85
  const query = {
84
86
  ...this.buildQuery(requirement, identityId, request),
85
- ...this.isServiceToken(request) ? { principal_type: "service" } : {}
87
+ ...this.isServiceToken(request) ? { principal_type: "service" } : {},
88
+ ...actingClientId === void 0 ? {} : { acting_client_id: actingClientId }
86
89
  };
87
90
  try {
88
91
  return await this.authorizer.evaluate(
@@ -168,6 +171,21 @@ exports.CanopyGuard = class CanopyGuard {
168
171
  const claims = request?.[attachedAs];
169
172
  return claims?.type === "service";
170
173
  }
174
+ /**
175
+ * The machine client acting for the identity, when the verified token is
176
+ * `delegated`: its `act.sub`, so the check asks both. An empty string for a
177
+ * delegated token naming no client, which the authorizer refuses; the
178
+ * verifier refuses such a token first, so this is the second lock.
179
+ */
180
+ actingClientOf(request) {
181
+ const attachedAs = this.options.attachTokenAs ?? "canopyToken";
182
+ const claims = request?.[attachedAs];
183
+ if (claims?.type !== "delegated") {
184
+ return void 0;
185
+ }
186
+ const sub = claims.act?.sub;
187
+ return typeof sub === "string" ? sub : "";
188
+ }
171
189
  /** A staff token (`org_scope: "all"`), read off the verified claims only. */
172
190
  isStaffToken(request) {
173
191
  const attachedAs = this.options.attachTokenAs ?? "canopyToken";
@@ -243,15 +261,19 @@ exports.CanopyTokenGuard = class CanopyTokenGuard {
243
261
  "Missing bearer token in the Authorization header."
244
262
  );
245
263
  }
246
- const admitsServiceTokens = this.reflector.getAllAndOverride(
247
- CANOPY_ALLOW_SERVICE_TOKENS,
248
- [context.getHandler(), context.getClass()]
249
- ) === true;
264
+ const admits = (key) => this.reflector.getAllAndOverride(key, [
265
+ context.getHandler(),
266
+ context.getClass()
267
+ ]) === true;
268
+ const alsoAllow = [
269
+ ...admits(CANOPY_ALLOW_SERVICE_TOKENS) ? ["service"] : [],
270
+ ...admits(CANOPY_ALLOW_DELEGATED_TOKENS) ? ["delegated"] : []
271
+ ];
250
272
  let claims;
251
273
  try {
252
274
  claims = await this.verifier.verify(
253
275
  token,
254
- admitsServiceTokens ? { alsoAllow: ["service"] } : {}
276
+ alsoAllow.length > 0 ? { alsoAllow } : {}
255
277
  );
256
278
  } catch (error) {
257
279
  if (!node.isCanopyTokenError(error)) {
@@ -384,6 +406,7 @@ exports.CanopyModule = class CanopyModule {
384
406
  exports.CanopyModule = __decorateClass([
385
407
  common.Module({})
386
408
  ], exports.CanopyModule);
409
+ var AllowDelegatedTokens = () => common.SetMetadata(CANOPY_ALLOW_DELEGATED_TOKENS, true);
387
410
  var AllowServiceTokens = () => common.SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);
388
411
  var InjectCanopy = () => common.Inject(CANOPY_CLIENT);
389
412
  var RequirePermission = (permission, options = {}) => common.SetMetadata(CANOPY_PERMISSION, {
@@ -391,6 +414,7 @@ var RequirePermission = (permission, options = {}) => common.SetMetadata(CANOPY_
391
414
  scope: options.scope ?? "node"
392
415
  });
393
416
 
417
+ exports.AllowDelegatedTokens = AllowDelegatedTokens;
394
418
  exports.AllowServiceTokens = AllowServiceTokens;
395
419
  exports.CANOPY_ALLOW_SERVICE_TOKENS = CANOPY_ALLOW_SERVICE_TOKENS;
396
420
  exports.CANOPY_AUTHORIZER = CANOPY_AUTHORIZER;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tokens.ts","../src/canopy.guard.ts","../src/canopy-token.guard.ts","../src/canopy.module.ts","../src/allow-service-tokens.decorator.ts","../src/inject-canopy.decorator.ts","../src/require-permission.decorator.ts"],"names":["CanopyGuard","Logger","ForbiddenException","authorizationErrorStatus","ServiceUnavailableException","InternalServerErrorException","Injectable","Reflector","CanopyTokenGuard","UnauthorizedException","isCanopyTokenError","tokenErrorStatus","Inject","LocalAuthorizer","CanopyModule","Canopy","TokenVerifier","Module","SetMetadata"],"mappings":";;;;;;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiB;AAGvB,IAAM,aAAA,GAAgB;AAStB,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,iBAAA,GAAoB;AAO1B,IAAM,2BAAA,GAA8B;;;ACiB3C,SAAS,W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AAQ,OAAA,GAAU,EAAE,SAAS,OAAA,CAAQ,OAAA,KAAY,EAAC;AAAA,MACtD,SAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,aAAA;AAAA,QACA,cAAA;AAAA,QACA,qBAAA;AAAA,QACA,iBAAA;AAAA,QACAd,mBAAA;AAAA,QACAQ;AAAA;AACF,KACF;AAAA,EACF;AACF;AA1FaM,oBAAA,GAAN,eAAA,CAAA;AAAA,EADNG,aAAA,CAAO,EAAE;AAAA,CAAA,EACGH,oBAAA,CAAA;ACrDN,IAAM,kBAAA,GAAqB,MAChCI,kBAAA,CAAY,2BAAA,EAA6B,IAAI;ACVxC,IAAM,YAAA,GAAe,MAA0BN,aAAAA,CAAO,aAAa;ACqCnE,IAAM,oBAAoB,CAC/B,UAAA,EACA,UAAoC,EAAC,KAErCM,mBAA2C,iBAAA,EAAmB;AAAA,EAC5D,UAAA;AAAA,EACA,KAAA,EAAO,QAAQ,KAAA,IAAS;AAC1B,CAAC","file":"index.cjs","sourcesContent":["/**\n * Injection tokens.\n *\n * These are strings rather than classes because esbuild does not emit\n * `design:paramtypes`, so nothing here can be injected by constructor type\n * alone — every dependency is named with an explicit `@Inject`.\n */\n\n/** The resolved `CanopyModuleOptions`. */\nexport const CANOPY_OPTIONS = \"CANOPY_OPTIONS\";\n\n/** The configured `Canopy` client. */\nexport const CANOPY_CLIENT = \"CANOPY_CLIENT\";\n\n/**\n * The configured `LocalAuthorizer`.\n *\n * Shared deliberately: it holds one copy of the hierarchy for the whole\n * process, so a second instance would double both the memory and the traffic\n * it exists to avoid.\n */\nexport const CANOPY_AUTHORIZER = \"CANOPY_AUTHORIZER\";\n\n/** The configured `TokenVerifier`, shared so its key cache is shared too. */\nexport const CANOPY_TOKEN_VERIFIER = \"CANOPY_TOKEN_VERIFIER\";\n\n/** Metadata key holding what `@RequirePermission` recorded on a handler. */\nexport const CANOPY_PERMISSION = \"CANOPY_PERMISSION\";\n\n/**\n * Metadata key `@AllowServiceTokens()` writes: a route or controller that\n * admits a machine client's `service` token beside the types the verifier\n * already accepts.\n */\nexport const CANOPY_ALLOW_SERVICE_TOKENS = \"CANOPY_ALLOW_SERVICE_TOKENS\";\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n InternalServerErrorException,\n Logger,\n ServiceUnavailableException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n authorizationErrorStatus,\n type LocalAuthorizer,\n type LocalDecision,\n type RequestBody,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport type { PermissionRequirement } from \"./require-permission.decorator.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_OPTIONS,\n CANOPY_PERMISSION,\n} from \"./tokens.js\";\n\n/** Read off the generated operation, so it follows the API rather than restating it. */\ntype EvaluateQuery = RequestBody<\"ApiPermissionsController_evaluate\">;\n\n/**\n * The verdict and, on a denial, the reason the grant roots and the tree can\n * give; not the API's full explain payload. A decision reached in-process\n * cannot report `granting_roles` or an effective node — that reasoning lives\n * on the server — and typing the narrow thing keeps that honest.\n */\ntype Verdict = LocalDecision;\n\ninterface Cancellation {\n signal: AbortSignal;\n dispose: () => void;\n}\n\n/** The Node stream underneath an Express or Fastify response. */\ninterface ClosableResponse {\n once: (event: string, listener: () => void) => unknown;\n removeListener: (event: string, listener: () => void) => unknown;\n writableEnded?: boolean;\n raw?: ClosableResponse;\n}\n\nfunction isClosable(value: unknown): value is ClosableResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ClosableResponse).once === \"function\" &&\n typeof (value as ClosableResponse).removeListener === \"function\"\n );\n}\n\n/**\n * Find the Node response stream behind whatever the adapter hands back.\n *\n * `.raw` is checked first and on its own merits, because the object Nest\n * returns is not always the stream. Express returns the `ServerResponse`\n * itself, which listens; Fastify returns a `Reply`, which is a plain object\n * with the real response on `.raw`. Testing the outer object first and\n * returning early on failure would skip `.raw` in exactly the case it exists\n * for.\n */\nfunction resolveStream(response: unknown): ClosableResponse | undefined {\n const raw = (response as { raw?: unknown } | null | undefined)?.raw;\n\n if (isClosable(raw)) {\n return raw;\n }\n\n if (isClosable(response)) {\n return response;\n }\n\n return undefined;\n}\n\n/**\n * Enforces `@RequirePermission` by asking Canopy, once, per guarded request.\n *\n * The guard fails closed at every step. An unresolvable identity, a `node`\n * check with no node, a denial, or an unreachable API all end the request —\n * there is no path through this class that allows a request whose decision is\n * unknown. That is the property worth protecting when reading this code: an\n * `allow` must be something Canopy actually said.\n *\n * A route with no requirement is allowed through untouched, so the guard can be\n * applied globally and opted into per route. Registered that way it runs before\n * controller- and route-scoped guards, so whatever authenticates the request has\n * to be registered globally ahead of it — otherwise `resolveIdentity` runs\n * before there is anything to resolve and every guarded route denies.\n */\n@Injectable()\nexport class CanopyGuard implements CanActivate {\n private readonly logger = new Logger(CanopyGuard.name);\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_AUTHORIZER) private readonly authorizer: LocalAuthorizer,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<\n PermissionRequirement | undefined\n >(CANOPY_PERMISSION, [context.getHandler(), context.getClass()]);\n\n if (!requirement) {\n return true;\n }\n\n const http = context.switchToHttp();\n const request: unknown = http.getRequest();\n const identityId = resolveSafely(this.options.resolveIdentity, request);\n\n if (!identityId) {\n throw new ForbiddenException(\n \"No identity on the request. Canopy cannot evaluate a permission without one.\",\n );\n }\n\n const decision = await this.evaluate(\n requirement,\n identityId,\n request,\n watchDisconnect(http),\n );\n\n if (!decision.allowed) {\n throw new ForbiddenException(\n `Caller does not hold ${requirement.permission}.`,\n );\n }\n\n return true;\n }\n\n /**\n * Asks Canopy the question the decorator recorded.\n *\n * Every failure is converted into a thrown exception rather than a `false`\n * decision, so a caller cannot mistake \"we could not tell\" for \"denied by\n * policy\" — and neither outcome lets the request proceed.\n */\n private async evaluate(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n cancellation: Cancellation | undefined,\n ): Promise<Verdict> {\n const query = {\n ...this.buildQuery(requirement, identityId, request),\n ...(this.isServiceToken(request)\n ? { principal_type: \"service\" as const }\n : {}),\n };\n\n try {\n // Answered in-process. The authorizer holds the identity's grant roots\n // and a shared copy of the hierarchy, so the common case reaches no\n // network at all; only a cold or expired entry does, and its deadline\n // and retries are bounded by the same options as before.\n return await this.authorizer.evaluate(\n query,\n cancellation ? { signal: cancellation.signal } : {},\n );\n } catch (error) {\n // The caller hung up mid-check. There is no one left to answer, and this\n // is not Canopy failing — so it must not be logged or reported as though\n // it were. Rethrowing the abort ends the request without inventing a\n // decision.\n if (cancellation?.signal.aborted) {\n throw error;\n }\n\n // Deliberately not re-thrown as-is: a failure here must not reach the\n // client as though Canopy had answered.\n this.logger.error(\n `Could not evaluate ${requirement.permission} for ${identityId}`,\n error instanceof Error ? error.stack : String(error),\n );\n\n throw this.toHttpException(error);\n } finally {\n cancellation?.dispose();\n }\n }\n\n /**\n * Turn a failed check into the status that describes it.\n *\n * Every branch denies — nothing here can let a request through — but they say\n * different things, and the difference is what makes an incident diagnosable.\n * Reporting a rejected API key as \"temporarily unavailable\" invites a retry\n * that will never succeed and hides a misconfiguration behind an outage. The\n * mapping is `authorizationErrorStatus` in `@canopy-io/node`, so an\n * integration outside NestJS answers the same way.\n */\n private toHttpException(error: unknown): Error {\n const { status, message } = authorizationErrorStatus(error);\n\n if (status === 403) {\n return new ForbiddenException(message);\n }\n\n if (status === 503) {\n return new ServiceUnavailableException(message);\n }\n\n return new InternalServerErrorException(message);\n }\n\n private buildQuery(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n ): EvaluateQuery {\n if (requirement.scope === \"app_wide\") {\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"app_wide\",\n };\n }\n\n // An organization is a hierarchy node, and a membership is a role\n // assignment at it — so the org question IS the node question, asked at\n // the node the caller's token says it is acting in.\n if (requirement.scope === \"org\") {\n const orgId = this.resolveOrg(request);\n\n if (!orgId) {\n // Staff reach every organization but act in one only after entering\n // it, which the organization records and may refuse. The route's own\n // organization is never a stand-in for that entry.\n throw new ForbiddenException(\n this.isStaffToken(request)\n ? `No organization on the request. ${requirement.permission} is checked inside the caller's active organization; this staff session has not entered one, and enters with switch-organization.`\n : `No organization on the request. ${requirement.permission} is checked inside the caller's active organization, and this caller is not acting in one.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: orgId,\n };\n }\n\n const nodeId = this.options.resolveNode\n ? resolveSafely(this.options.resolveNode, request)\n : undefined;\n\n if (!nodeId) {\n throw new ForbiddenException(\n `No node on the request. ${requirement.permission} is checked at a node; configure resolveNode, or declare the route as app_wide if that is genuinely the question.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: nodeId,\n };\n }\n\n /**\n * Whose grants answer the check: a machine client's when the verified token\n * `CanopyTokenGuard` attached is a `service` token, an identity's\n * otherwise. Read off the verified claims only, so a caller cannot choose\n * whose grants are consulted.\n */\n private isServiceToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { type?: unknown } | undefined)?.type === \"service\";\n }\n\n /** A staff token (`org_scope: \"all\"`), read off the verified claims only. */\n private isStaffToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { org_scope?: unknown } | undefined)?.org_scope === \"all\";\n }\n\n /**\n * The organization the request acts in: `resolveOrg` when configured,\n * otherwise the `org_id` claim off the verified token `CanopyTokenGuard`\n * attached. Both sources trace back to a verified token — the org id\n * decides whose grants answer the check, so it must never be readable off\n * anything the caller controls directly.\n */\n private resolveOrg(request: unknown): string | null | undefined {\n if (this.options.resolveOrg) {\n return resolveSafely(this.options.resolveOrg, request);\n }\n\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n const orgId = (claims as { org_id?: unknown } | undefined)?.org_id;\n\n return typeof orgId === \"string\" && orgId !== \"\" ? orgId : undefined;\n }\n}\n\n/**\n * Run a resolver, treating a throw as \"could not resolve\".\n *\n * Resolvers reach into the request — `request.user.sub` is the shape the docs\n * suggest and the one most applications write. On an unauthenticated request\n * `request.user` is undefined and that expression throws, which without this\n * would surface as a 500. An identity that cannot be established is exactly the\n * request that must be denied, so it becomes the same 403 as returning nothing.\n */\nfunction resolveSafely(\n resolve: (request: never) => string | null | undefined,\n request: unknown,\n): string | null | undefined {\n try {\n return (resolve as (request: unknown) => string | null | undefined)(\n request,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Abort the permission check if the caller hangs up while it is in flight.\n *\n * Watches the *response*, not the request. A request stream emits `close` on\n * every normal request once its body has been read, so listening there would\n * abort perfectly healthy checks; a response emits `close` before\n * `writableEnded` only when nothing was ever sent — which is exactly the\n * disconnect case. The `writableEnded` re-check at fire time keeps that true\n * even if the ordering differs by adapter.\n *\n * Returns undefined for a transport with no such response — a GraphQL or\n * microservice context — where the check simply runs to its deadline.\n */\nfunction watchDisconnect(http: {\n getResponse?: () => unknown;\n}): Cancellation | undefined {\n const raw = resolveStream(http.getResponse?.());\n\n if (!raw) {\n return undefined;\n }\n\n const controller = new AbortController();\n\n const onClose = () => {\n if (raw.writableEnded === true) {\n return;\n }\n\n controller.abort(\n new DOMException(\"The client closed the request\", \"AbortError\"),\n );\n };\n\n raw.once(\"close\", onClose);\n\n return {\n signal: controller.signal,\n dispose: () => raw.removeListener(\"close\", onClose),\n };\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n ServiceUnavailableException,\n UnauthorizedException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n type CanopyTokenClaims,\n isCanopyTokenError,\n tokenErrorStatus,\n TokenVerifier,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport {\n CANOPY_ALLOW_SERVICE_TOKENS,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * A request `CanopyTokenGuard` has run on: the verified claims under\n * `canopyToken` (or the module's `attachTokenAs`). `TCustom` names the\n * Environment's custom claims, each optional, so a handler reads them typed:\n *\n * ```ts\n * @Get(\"export\")\n * export(@Req() request: CanopyTokenRequest<{ plan?: \"free\" | \"pro\" }>) {\n * if (request.canopyToken?.plan !== \"pro\") {\n * throw new ForbiddenException();\n * }\n * }\n * ```\n */\nexport interface CanopyTokenRequest<TCustom extends object = object> {\n canopyToken?: CanopyTokenClaims & TCustom;\n}\n\n/**\n * Verifies the bearer token and attaches its claims to the request.\n *\n * This is the authentication half, and it is opt-in on purpose. `CanopyGuard`\n * answers \"may this identity do this?\"; something has to have established\n * *which* identity first, and `resolveIdentity` says as much — \"usually a\n * claim off the verified access token your auth layer already attached\".\n *\n * Use this guard when Canopy issues your tokens and you have no auth layer\n * yet. Skip it entirely if you already run Passport or your own JWT\n * middleware — it is additive, and nothing else in the package depends on it.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @RequirePermission(\"documents.read\")\n * findAll() {}\n * ```\n *\n * Order matters: this must run first, because `CanopyGuard` reads what it\n * attaches. Nest runs guards left to right, so listing them in that order is\n * the whole of the wiring.\n *\n * Claims land on `request.canopyToken` by default, which is why\n * `resolveIdentity` is usually `(req) => req.canopyToken?.sub`. The property\n * is configurable so it cannot collide with a `request.user` an existing\n * middleware already owns.\n *\n * A machine client's `service` token is refused unless the route or its\n * controller carries `@AllowServiceTokens()`: a route built for people must\n * not admit a machine by accident.\n */\n@Injectable()\nexport class CanopyTokenGuard implements CanActivate {\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_TOKEN_VERIFIER) private readonly verifier: TokenVerifier,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<{\n headers?: Record<string, string | string[] | undefined>;\n [key: string]: unknown;\n }>();\n\n const token = readBearerToken(request.headers?.[\"authorization\"]);\n\n if (token === null) {\n throw new UnauthorizedException(\n \"Missing bearer token in the Authorization header.\",\n );\n }\n\n const admitsServiceTokens =\n this.reflector.getAllAndOverride<boolean | undefined>(\n CANOPY_ALLOW_SERVICE_TOKENS,\n [context.getHandler(), context.getClass()],\n ) === true;\n\n let claims: CanopyTokenClaims;\n\n try {\n claims = await this.verifier.verify(\n token,\n admitsServiceTokens ? { alsoAllow: [\"service\"] } : {},\n );\n } catch (error) {\n // Not being able to verify is not the same as failing to verify. When\n // the key set cannot be read the caller's token may be perfectly good —\n // we simply cannot say — so this is ours to own, exactly as the\n // permission guard answers 503 rather than denying on an undecidable\n // check.\n //\n // Reporting it as 401 would be worse than merely inaccurate: a client\n // reads 401 as \"your token is stale\", discards a valid one and asks for\n // another, which aims a refresh storm at the issuer that is already\n // down. And an outage that only ever emits 4xx is invisible to anything\n // watching 5xx.\n if (!isCanopyTokenError(error)) {\n throw error;\n }\n\n const { status, message } = tokenErrorStatus(error);\n\n if (status === 503) {\n throw new ServiceUnavailableException(message, { cause: error });\n }\n\n // Every other cause is the token itself, and a 401 whatever the detail:\n // the caller cannot fix a bad signature by being granted something. The\n // specific code stays on the error for logs rather than going to the\n // caller, who has no use for the difference and should not be told which\n // check failed.\n throw new UnauthorizedException(message, { cause: error });\n }\n\n request[this.options.attachTokenAs ?? \"canopyToken\"] = claims;\n\n return true;\n }\n}\n\n/**\n * The token out of an `Authorization: Bearer …` header.\n *\n * Returns null rather than throwing so the caller owns the message. The scheme\n * is matched case-insensitively because RFC 7235 says it is case-insensitive,\n * and clients do send `bearer`.\n */\nfunction readBearerToken(header: string | string[] | undefined): string | null {\n const value = Array.isArray(header) ? header[0] : header;\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n // Split by hand rather than with `/^bearer\\s+(.+)$/i`: the header is the\n // caller's to write, and that pattern backtracks on a long run of spaces.\n const trimmed = value.trim();\n const scheme = trimmed.slice(0, 6);\n const separator = trimmed.charAt(6);\n\n if (scheme.toLowerCase() !== \"bearer\" || !/\\s/.test(separator)) {\n return null;\n }\n\n const token = trimmed.slice(7).trim();\n\n return token.length > 0 ? token : null;\n}\n","import { type DynamicModule, Module, type Provider } from \"@nestjs/common\";\n\nimport { Canopy, LocalAuthorizer, TokenVerifier } from \"@canopy-io/node\";\n\nimport { CanopyGuard } from \"./canopy.guard.js\";\nimport { CanopyTokenGuard } from \"./canopy-token.guard.js\";\nimport type {\n CanopyModuleAsyncOptions,\n CanopyModuleOptions,\n} from \"./options.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * Wires one configured `Canopy` client and the guard that uses it into a Nest\n * application.\n *\n * ```ts\n * CanopyModule.forRoot<AuthedRequest>({\n * apiKey: process.env.CANOPY_API_KEY,\n * resolveIdentity: (request) => request.user?.sub,\n * resolveNode: (request) => request.params?.orgId,\n * })\n * ```\n *\n * The client is a singleton because it holds no per-request state — it is a\n * `fetch` wrapper with credentials — so there is nothing to gain from building\n * one per request and a connection pool to lose.\n */\n\n/**\n * Per-attempt deadline for a cache miss on the request path.\n *\n * Five seconds rather than the client's 30: this call sits on the request path,\n * so its deadline is time an inbound request spends waiting. An authorization\n * service that has not answered in five seconds is not going to save the\n * request.\n */\nconst DEFAULT_EVALUATE_TIMEOUT_MS = 5_000;\n\n/**\n * Retries for a cache miss on the request path.\n *\n * One, not the client's two. A deadline bounds an attempt; this bounds how many\n * of them an inbound request can wait through. One retry still absorbs a\n * transient blip, and caps the worst case at roughly two deadlines rather than\n * three.\n */\nconst DEFAULT_EVALUATE_MAX_RETRIES = 1;\n\n/**\n * The authorizer both registration paths build.\n *\n * The guard's `evaluateTimeoutMs` / `evaluateMaxRetries` still apply, but to\n * far fewer calls: they bound a cache miss rather than every request.\n */\nfunction buildAuthorizer<TRequest>(\n client: Canopy,\n options: CanopyModuleOptions<TRequest>,\n): LocalAuthorizer {\n return new LocalAuthorizer(client.client, {\n ...(options.authorizationTtlMs === undefined\n ? {}\n : { ttlMs: options.authorizationTtlMs }),\n timeoutMs: options.evaluateTimeoutMs ?? DEFAULT_EVALUATE_TIMEOUT_MS,\n maxRetries: options.evaluateMaxRetries ?? DEFAULT_EVALUATE_MAX_RETRIES,\n ...(options.onDecision === undefined\n ? {}\n : { onDecision: options.onDecision }),\n ...(options.onDenied === undefined ? {} : { onDenied: options.onDenied }),\n });\n}\n\n@Module({})\nexport class CanopyModule {\n static forRoot<TRequest = unknown>(\n options: CanopyModuleOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n { provide: CANOPY_OPTIONS, useValue: options },\n {\n provide: CANOPY_CLIENT,\n useFactory: () => new Canopy(options),\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: () => new TokenVerifier(options.verify),\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy) => buildAuthorizer(client, options),\n inject: [CANOPY_CLIENT],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n\n /**\n * The same wiring when the API key comes from something injectable, such as\n * `ConfigService`, rather than being available at module-definition time.\n */\n static forRootAsync<TRequest = unknown>(\n options: CanopyModuleAsyncOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CANOPY_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: CANOPY_CLIENT,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new Canopy(resolved),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new TokenVerifier(resolved.verify),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy, resolved: CanopyModuleOptions<TRequest>) =>\n buildAuthorizer(client, resolved),\n inject: [CANOPY_CLIENT, CANOPY_OPTIONS],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n // Spread rather than assigned: under exactOptionalPropertyTypes an\n // explicit `imports: undefined` is not the same as no `imports` at all.\n ...(options.imports ? { imports: options.imports } : {}),\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n}\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_SERVICE_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client's token on this route or controller.\n *\n * A machine client obtains a token for itself with the `client_credentials`\n * grant; its `type` is `service` and its `sub` is the client's `client_id`.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route built\n * for people never admits a machine by accident. Here it is accepted beside\n * the types the verifier already allows, and `CanopyGuard` authorizes it from\n * the client's own grants.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowServiceTokens()\n * @RequirePermission(\"orders.import\", { scope: \"org\" })\n * @Post(\"import\")\n * import() {}\n * ```\n *\n * Read `request.canopyToken.type` in the handler when people and machines\n * should be treated differently.\n */\nexport const AllowServiceTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);\n","import { Inject } from \"@nestjs/common\";\n\nimport { CANOPY_CLIENT } from \"./tokens.js\";\n\n/**\n * Injects the configured client.\n *\n * ```ts\n * constructor(@InjectCanopy() private readonly canopy: Canopy) {}\n * ```\n *\n * Named rather than resolved by type because this package is bundled with\n * esbuild, which emits no `design:paramtypes` — so type-only injection would\n * fail at runtime with a confusing \"cannot resolve dependency\" rather than at\n * build time.\n */\nexport const InjectCanopy = (): ParameterDecorator => Inject(CANOPY_CLIENT);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_PERMISSION } from \"./tokens.js\";\n\n/**\n * Which question the guard asks Canopy.\n *\n * `node` walks the node's lineage, so a role granted on an ancestor is\n * inherited at the node being touched. `app_wide` asks only whether the\n * identity holds the permission anywhere in the Environment. `org` is the\n * node question asked at the organization the caller's token is acting in —\n * the `org_id` claim — so the route needs no `resolveNode` and no node in\n * its path.\n */\nexport type PermissionScope = \"node\" | \"app_wide\" | \"org\";\n\n/** What `@RequirePermission` records for the guard to read back. */\nexport interface PermissionRequirement {\n readonly permission: string;\n readonly scope: PermissionScope;\n}\n\nexport interface RequirePermissionOptions {\n /**\n * Defaults to `node`.\n *\n * `app_wide` is opt-in on purpose. It answers a coarser question and returns\n * no effective node, which makes it right for deciding whether to render a\n * menu item and wrong for guarding a resource that belongs to one — a\n * distinction that is easy to get backwards if the looser check is the\n * default.\n *\n * `org` evaluates at the organization on the caller's verified token\n * (`org_id`), read from the claims `CanopyTokenGuard` attaches or from\n * `resolveOrg` if configured. A caller acting in no organization is denied\n * — an org-scoped route has no meaning outside one.\n */\n readonly scope?: PermissionScope;\n}\n\n/**\n * Require a Canopy permission before a route runs.\n *\n * ```ts\n * @UseGuards(CanopyGuard)\n * @RequirePermission(\"orders.refund\")\n * @Post(\":orderId/refund\")\n * refund() {}\n * ```\n *\n * Applies to a single handler or to a whole controller; a handler's own\n * requirement wins over its controller's.\n */\nexport const RequirePermission = (\n permission: string,\n options: RequirePermissionOptions = {},\n): MethodDecorator & ClassDecorator =>\n SetMetadata<string, PermissionRequirement>(CANOPY_PERMISSION, {\n permission,\n scope: options.scope ?? \"node\",\n });\n"]}
1
+ {"version":3,"sources":["../src/tokens.ts","../src/canopy.guard.ts","../src/canopy-token.guard.ts","../src/canopy.module.ts","../src/allow-delegated-tokens.decorator.ts","../src/allow-service-tokens.decorator.ts","../src/inject-canopy.decorator.ts","../src/require-permission.decorator.ts"],"names":["CanopyGuard","Logger","ForbiddenException","authorizationErrorStatus","ServiceUnavailableException","InternalServerErrorException","Injectable","Reflector","CanopyTokenGuard","UnauthorizedException","isCanopyTokenError","tokenErrorStatus","Inject","LocalAuthorizer","CanopyModule","Canopy","TokenVerifier","Module","SetMetadata"],"mappings":";;;;;;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiB;AAGvB,IAAM,aAAA,GAAgB;AAStB,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,iBAAA,GAAoB;AAO1B,IAAM,2BAAA,GAA8B;AAMpC,IAAM,6BAAA,GAAgC,+BAAA;;;ACW7C,SAAS,WAAW,KAAA,EAA2C;AAC7D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACV,OAAQ,KAAA,CAA2B,IAAA,KAAS,UAAA,IAC5C,OAAQ,KAAA,CAA2B,cAAA,KAAmB,UAAA;AAE1D;AAYA,SAAS,cAAc,QAAA,EAAiD;AACtE,EAAA,MAAM,MAAO,QAAA,EAAmD,GAAA;AAEhE,EAAA,IAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AACnB,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,IAAI,UAAA,CAAW,QAAQ,CAAA,EAAG;AACxB,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,OAAO,MAAA;AACT;AAkBaA,sBAAN,iBAAA,CAAyC;AAAA,EAG9C,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AAA;AAAA,QAClC,MAAA,EAAQ,CAAC,aAAA,EAAe,cAAc;AAAA,OACxC;AAAA,MACAhB,mBAAA;AAAA,MACAQ;AAAA,KACF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQM,oBAAA;AAAA,MACR,MAAA,EAAQ,QAAQ,QAAA,IAAY,KAAA;AAAA;AAAA;AAAA,MAG5B,GAAI,QAAQ,OAAA,GAAU,EAAE,SAAS,OAAA,CAAQ,OAAA,KAAY,EAAC;AAAA,MACtD,SAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,aAAA;AAAA,QACA,cAAA;AAAA,QACA,qBAAA;AAAA,QACA,iBAAA;AAAA,QACAd,mBAAA;AAAA,QACAQ;AAAA;AACF,KACF;AAAA,EACF;AACF;AA1FaM,oBAAA,GAAN,eAAA,CAAA;AAAA,EADNG,aAAA,CAAO,EAAE;AAAA,CAAA,EACGH,oBAAA,CAAA;ACpDN,IAAM,oBAAA,GAAuB,MAClCI,kBAAA,CAAY,6BAAA,EAA+B,IAAI;ACF1C,IAAM,kBAAA,GAAqB,MAChCA,kBAAAA,CAAY,2BAAA,EAA6B,IAAI;ACVxC,IAAM,YAAA,GAAe,MAA0BN,aAAAA,CAAO,aAAa;ACqCnE,IAAM,oBAAoB,CAC/B,UAAA,EACA,UAAoC,EAAC,KAErCM,mBAA2C,iBAAA,EAAmB;AAAA,EAC5D,UAAA;AAAA,EACA,KAAA,EAAO,QAAQ,KAAA,IAAS;AAC1B,CAAC","file":"index.cjs","sourcesContent":["/**\n * Injection tokens.\n *\n * These are strings rather than classes because esbuild does not emit\n * `design:paramtypes`, so nothing here can be injected by constructor type\n * alone — every dependency is named with an explicit `@Inject`.\n */\n\n/** The resolved `CanopyModuleOptions`. */\nexport const CANOPY_OPTIONS = \"CANOPY_OPTIONS\";\n\n/** The configured `Canopy` client. */\nexport const CANOPY_CLIENT = \"CANOPY_CLIENT\";\n\n/**\n * The configured `LocalAuthorizer`.\n *\n * Shared deliberately: it holds one copy of the hierarchy for the whole\n * process, so a second instance would double both the memory and the traffic\n * it exists to avoid.\n */\nexport const CANOPY_AUTHORIZER = \"CANOPY_AUTHORIZER\";\n\n/** The configured `TokenVerifier`, shared so its key cache is shared too. */\nexport const CANOPY_TOKEN_VERIFIER = \"CANOPY_TOKEN_VERIFIER\";\n\n/** Metadata key holding what `@RequirePermission` recorded on a handler. */\nexport const CANOPY_PERMISSION = \"CANOPY_PERMISSION\";\n\n/**\n * Metadata key `@AllowServiceTokens()` writes: a route or controller that\n * admits a machine client's `service` token beside the types the verifier\n * already accepts.\n */\nexport const CANOPY_ALLOW_SERVICE_TOKENS = \"CANOPY_ALLOW_SERVICE_TOKENS\";\n\n/**\n * Metadata key `@AllowDelegatedTokens()` writes: a route or controller that\n * admits a `delegated` token, a machine client acting for a person.\n */\nexport const CANOPY_ALLOW_DELEGATED_TOKENS = \"CANOPY_ALLOW_DELEGATED_TOKENS\";\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n InternalServerErrorException,\n Logger,\n ServiceUnavailableException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n authorizationErrorStatus,\n type LocalAuthorizer,\n type LocalDecision,\n type RequestBody,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport type { PermissionRequirement } from \"./require-permission.decorator.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_OPTIONS,\n CANOPY_PERMISSION,\n} from \"./tokens.js\";\n\n/** Read off the generated operation, so it follows the API rather than restating it. */\ntype EvaluateQuery = RequestBody<\"ApiPermissionsController_evaluate\">;\n\n/**\n * The verdict and, on a denial, the reason the grant roots and the tree can\n * give; not the API's full explain payload. A decision reached in-process\n * cannot report `granting_roles` or an effective node — that reasoning lives\n * on the server — and typing the narrow thing keeps that honest.\n */\ntype Verdict = LocalDecision;\n\ninterface Cancellation {\n signal: AbortSignal;\n dispose: () => void;\n}\n\n/** The Node stream underneath an Express or Fastify response. */\ninterface ClosableResponse {\n once: (event: string, listener: () => void) => unknown;\n removeListener: (event: string, listener: () => void) => unknown;\n writableEnded?: boolean;\n raw?: ClosableResponse;\n}\n\nfunction isClosable(value: unknown): value is ClosableResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ClosableResponse).once === \"function\" &&\n typeof (value as ClosableResponse).removeListener === \"function\"\n );\n}\n\n/**\n * Find the Node response stream behind whatever the adapter hands back.\n *\n * `.raw` is checked first and on its own merits, because the object Nest\n * returns is not always the stream. Express returns the `ServerResponse`\n * itself, which listens; Fastify returns a `Reply`, which is a plain object\n * with the real response on `.raw`. Testing the outer object first and\n * returning early on failure would skip `.raw` in exactly the case it exists\n * for.\n */\nfunction resolveStream(response: unknown): ClosableResponse | undefined {\n const raw = (response as { raw?: unknown } | null | undefined)?.raw;\n\n if (isClosable(raw)) {\n return raw;\n }\n\n if (isClosable(response)) {\n return response;\n }\n\n return undefined;\n}\n\n/**\n * Enforces `@RequirePermission` by asking Canopy, once, per guarded request.\n *\n * The guard fails closed at every step. An unresolvable identity, a `node`\n * check with no node, a denial, or an unreachable API all end the request —\n * there is no path through this class that allows a request whose decision is\n * unknown. That is the property worth protecting when reading this code: an\n * `allow` must be something Canopy actually said.\n *\n * A route with no requirement is allowed through untouched, so the guard can be\n * applied globally and opted into per route. Registered that way it runs before\n * controller- and route-scoped guards, so whatever authenticates the request has\n * to be registered globally ahead of it — otherwise `resolveIdentity` runs\n * before there is anything to resolve and every guarded route denies.\n */\n@Injectable()\nexport class CanopyGuard implements CanActivate {\n private readonly logger = new Logger(CanopyGuard.name);\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_AUTHORIZER) private readonly authorizer: LocalAuthorizer,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<\n PermissionRequirement | undefined\n >(CANOPY_PERMISSION, [context.getHandler(), context.getClass()]);\n\n if (!requirement) {\n return true;\n }\n\n const http = context.switchToHttp();\n const request: unknown = http.getRequest();\n const identityId = resolveSafely(this.options.resolveIdentity, request);\n\n if (!identityId) {\n throw new ForbiddenException(\n \"No identity on the request. Canopy cannot evaluate a permission without one.\",\n );\n }\n\n const decision = await this.evaluate(\n requirement,\n identityId,\n request,\n watchDisconnect(http),\n );\n\n if (!decision.allowed) {\n throw new ForbiddenException(\n `Caller does not hold ${requirement.permission}.`,\n );\n }\n\n return true;\n }\n\n /**\n * Asks Canopy the question the decorator recorded.\n *\n * Every failure is converted into a thrown exception rather than a `false`\n * decision, so a caller cannot mistake \"we could not tell\" for \"denied by\n * policy\" — and neither outcome lets the request proceed.\n */\n private async evaluate(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n cancellation: Cancellation | undefined,\n ): Promise<Verdict> {\n const actingClientId = this.actingClientOf(request);\n const query = {\n ...this.buildQuery(requirement, identityId, request),\n ...(this.isServiceToken(request)\n ? { principal_type: \"service\" as const }\n : {}),\n ...(actingClientId === undefined\n ? {}\n : { acting_client_id: actingClientId }),\n };\n\n try {\n // Answered in-process. The authorizer holds the identity's grant roots\n // and a shared copy of the hierarchy, so the common case reaches no\n // network at all; only a cold or expired entry does, and its deadline\n // and retries are bounded by the same options as before.\n return await this.authorizer.evaluate(\n query,\n cancellation ? { signal: cancellation.signal } : {},\n );\n } catch (error) {\n // The caller hung up mid-check. There is no one left to answer, and this\n // is not Canopy failing — so it must not be logged or reported as though\n // it were. Rethrowing the abort ends the request without inventing a\n // decision.\n if (cancellation?.signal.aborted) {\n throw error;\n }\n\n // Deliberately not re-thrown as-is: a failure here must not reach the\n // client as though Canopy had answered.\n this.logger.error(\n `Could not evaluate ${requirement.permission} for ${identityId}`,\n error instanceof Error ? error.stack : String(error),\n );\n\n throw this.toHttpException(error);\n } finally {\n cancellation?.dispose();\n }\n }\n\n /**\n * Turn a failed check into the status that describes it.\n *\n * Every branch denies — nothing here can let a request through — but they say\n * different things, and the difference is what makes an incident diagnosable.\n * Reporting a rejected API key as \"temporarily unavailable\" invites a retry\n * that will never succeed and hides a misconfiguration behind an outage. The\n * mapping is `authorizationErrorStatus` in `@canopy-io/node`, so an\n * integration outside NestJS answers the same way.\n */\n private toHttpException(error: unknown): Error {\n const { status, message } = authorizationErrorStatus(error);\n\n if (status === 403) {\n return new ForbiddenException(message);\n }\n\n if (status === 503) {\n return new ServiceUnavailableException(message);\n }\n\n return new InternalServerErrorException(message);\n }\n\n private buildQuery(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n ): EvaluateQuery {\n if (requirement.scope === \"app_wide\") {\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"app_wide\",\n };\n }\n\n // An organization is a hierarchy node, and a membership is a role\n // assignment at it — so the org question IS the node question, asked at\n // the node the caller's token says it is acting in.\n if (requirement.scope === \"org\") {\n const orgId = this.resolveOrg(request);\n\n if (!orgId) {\n // Staff reach every organization but act in one only after entering\n // it, which the organization records and may refuse. The route's own\n // organization is never a stand-in for that entry.\n throw new ForbiddenException(\n this.isStaffToken(request)\n ? `No organization on the request. ${requirement.permission} is checked inside the caller's active organization; this staff session has not entered one, and enters with switch-organization.`\n : `No organization on the request. ${requirement.permission} is checked inside the caller's active organization, and this caller is not acting in one.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: orgId,\n };\n }\n\n const nodeId = this.options.resolveNode\n ? resolveSafely(this.options.resolveNode, request)\n : undefined;\n\n if (!nodeId) {\n throw new ForbiddenException(\n `No node on the request. ${requirement.permission} is checked at a node; configure resolveNode, or declare the route as app_wide if that is genuinely the question.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: nodeId,\n };\n }\n\n /**\n * Whose grants answer the check: a machine client's when the verified token\n * `CanopyTokenGuard` attached is a `service` token, an identity's\n * otherwise. Read off the verified claims only, so a caller cannot choose\n * whose grants are consulted.\n */\n private isServiceToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { type?: unknown } | undefined)?.type === \"service\";\n }\n\n /**\n * The machine client acting for the identity, when the verified token is\n * `delegated`: its `act.sub`, so the check asks both. An empty string for a\n * delegated token naming no client, which the authorizer refuses; the\n * verifier refuses such a token first, so this is the second lock.\n */\n private actingClientOf(request: unknown): string | undefined {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ] as { type?: unknown; act?: { sub?: unknown } } | undefined;\n\n if (claims?.type !== \"delegated\") {\n return undefined;\n }\n\n const sub = claims.act?.sub;\n\n return typeof sub === \"string\" ? sub : \"\";\n }\n\n /** A staff token (`org_scope: \"all\"`), read off the verified claims only. */\n private isStaffToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { org_scope?: unknown } | undefined)?.org_scope === \"all\";\n }\n\n /**\n * The organization the request acts in: `resolveOrg` when configured,\n * otherwise the `org_id` claim off the verified token `CanopyTokenGuard`\n * attached. Both sources trace back to a verified token — the org id\n * decides whose grants answer the check, so it must never be readable off\n * anything the caller controls directly.\n */\n private resolveOrg(request: unknown): string | null | undefined {\n if (this.options.resolveOrg) {\n return resolveSafely(this.options.resolveOrg, request);\n }\n\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n const orgId = (claims as { org_id?: unknown } | undefined)?.org_id;\n\n return typeof orgId === \"string\" && orgId !== \"\" ? orgId : undefined;\n }\n}\n\n/**\n * Run a resolver, treating a throw as \"could not resolve\".\n *\n * Resolvers reach into the request — `request.user.sub` is the shape the docs\n * suggest and the one most applications write. On an unauthenticated request\n * `request.user` is undefined and that expression throws, which without this\n * would surface as a 500. An identity that cannot be established is exactly the\n * request that must be denied, so it becomes the same 403 as returning nothing.\n */\nfunction resolveSafely(\n resolve: (request: never) => string | null | undefined,\n request: unknown,\n): string | null | undefined {\n try {\n return (resolve as (request: unknown) => string | null | undefined)(\n request,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Abort the permission check if the caller hangs up while it is in flight.\n *\n * Watches the *response*, not the request. A request stream emits `close` on\n * every normal request once its body has been read, so listening there would\n * abort perfectly healthy checks; a response emits `close` before\n * `writableEnded` only when nothing was ever sent — which is exactly the\n * disconnect case. The `writableEnded` re-check at fire time keeps that true\n * even if the ordering differs by adapter.\n *\n * Returns undefined for a transport with no such response — a GraphQL or\n * microservice context — where the check simply runs to its deadline.\n */\nfunction watchDisconnect(http: {\n getResponse?: () => unknown;\n}): Cancellation | undefined {\n const raw = resolveStream(http.getResponse?.());\n\n if (!raw) {\n return undefined;\n }\n\n const controller = new AbortController();\n\n const onClose = () => {\n if (raw.writableEnded === true) {\n return;\n }\n\n controller.abort(\n new DOMException(\"The client closed the request\", \"AbortError\"),\n );\n };\n\n raw.once(\"close\", onClose);\n\n return {\n signal: controller.signal,\n dispose: () => raw.removeListener(\"close\", onClose),\n };\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n ServiceUnavailableException,\n UnauthorizedException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n type CanopyTokenClaims,\n isCanopyTokenError,\n tokenErrorStatus,\n TokenVerifier,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport {\n CANOPY_ALLOW_DELEGATED_TOKENS,\n CANOPY_ALLOW_SERVICE_TOKENS,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * A request `CanopyTokenGuard` has run on: the verified claims under\n * `canopyToken` (or the module's `attachTokenAs`). `TCustom` names the\n * Environment's custom claims, each optional, so a handler reads them typed:\n *\n * ```ts\n * @Get(\"export\")\n * export(@Req() request: CanopyTokenRequest<{ plan?: \"free\" | \"pro\" }>) {\n * if (request.canopyToken?.plan !== \"pro\") {\n * throw new ForbiddenException();\n * }\n * }\n * ```\n */\nexport interface CanopyTokenRequest<TCustom extends object = object> {\n canopyToken?: CanopyTokenClaims & TCustom;\n}\n\n/**\n * Verifies the bearer token and attaches its claims to the request.\n *\n * This is the authentication half, and it is opt-in on purpose. `CanopyGuard`\n * answers \"may this identity do this?\"; something has to have established\n * *which* identity first, and `resolveIdentity` says as much — \"usually a\n * claim off the verified access token your auth layer already attached\".\n *\n * Use this guard when Canopy issues your tokens and you have no auth layer\n * yet. Skip it entirely if you already run Passport or your own JWT\n * middleware — it is additive, and nothing else in the package depends on it.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @RequirePermission(\"documents.read\")\n * findAll() {}\n * ```\n *\n * Order matters: this must run first, because `CanopyGuard` reads what it\n * attaches. Nest runs guards left to right, so listing them in that order is\n * the whole of the wiring.\n *\n * Claims land on `request.canopyToken` by default, which is why\n * `resolveIdentity` is usually `(req) => req.canopyToken?.sub`. The property\n * is configurable so it cannot collide with a `request.user` an existing\n * middleware already owns.\n *\n * A machine client's `service` token is refused unless the route or its\n * controller carries `@AllowServiceTokens()`: a route built for people must\n * not admit a machine by accident. A `delegated` token, a machine client\n * acting for a person, is refused unless it carries `@AllowDelegatedTokens()`.\n */\n@Injectable()\nexport class CanopyTokenGuard implements CanActivate {\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_TOKEN_VERIFIER) private readonly verifier: TokenVerifier,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<{\n headers?: Record<string, string | string[] | undefined>;\n [key: string]: unknown;\n }>();\n\n const token = readBearerToken(request.headers?.[\"authorization\"]);\n\n if (token === null) {\n throw new UnauthorizedException(\n \"Missing bearer token in the Authorization header.\",\n );\n }\n\n const admits = (key: string): boolean =>\n this.reflector.getAllAndOverride<boolean | undefined>(key, [\n context.getHandler(),\n context.getClass(),\n ]) === true;\n const alsoAllow: CanopyTokenClaims[\"type\"][] = [\n ...(admits(CANOPY_ALLOW_SERVICE_TOKENS) ? [\"service\" as const] : []),\n ...(admits(CANOPY_ALLOW_DELEGATED_TOKENS) ? [\"delegated\" as const] : []),\n ];\n\n let claims: CanopyTokenClaims;\n\n try {\n claims = await this.verifier.verify(\n token,\n alsoAllow.length > 0 ? { alsoAllow } : {},\n );\n } catch (error) {\n // Not being able to verify is not the same as failing to verify. When\n // the key set cannot be read the caller's token may be perfectly good —\n // we simply cannot say — so this is ours to own, exactly as the\n // permission guard answers 503 rather than denying on an undecidable\n // check.\n //\n // Reporting it as 401 would be worse than merely inaccurate: a client\n // reads 401 as \"your token is stale\", discards a valid one and asks for\n // another, which aims a refresh storm at the issuer that is already\n // down. And an outage that only ever emits 4xx is invisible to anything\n // watching 5xx.\n if (!isCanopyTokenError(error)) {\n throw error;\n }\n\n const { status, message } = tokenErrorStatus(error);\n\n if (status === 503) {\n throw new ServiceUnavailableException(message, { cause: error });\n }\n\n // Every other cause is the token itself, and a 401 whatever the detail:\n // the caller cannot fix a bad signature by being granted something. The\n // specific code stays on the error for logs rather than going to the\n // caller, who has no use for the difference and should not be told which\n // check failed.\n throw new UnauthorizedException(message, { cause: error });\n }\n\n request[this.options.attachTokenAs ?? \"canopyToken\"] = claims;\n\n return true;\n }\n}\n\n/**\n * The token out of an `Authorization: Bearer …` header.\n *\n * Returns null rather than throwing so the caller owns the message. The scheme\n * is matched case-insensitively because RFC 7235 says it is case-insensitive,\n * and clients do send `bearer`.\n */\nfunction readBearerToken(header: string | string[] | undefined): string | null {\n const value = Array.isArray(header) ? header[0] : header;\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n // Split by hand rather than with `/^bearer\\s+(.+)$/i`: the header is the\n // caller's to write, and that pattern backtracks on a long run of spaces.\n const trimmed = value.trim();\n const scheme = trimmed.slice(0, 6);\n const separator = trimmed.charAt(6);\n\n if (scheme.toLowerCase() !== \"bearer\" || !/\\s/.test(separator)) {\n return null;\n }\n\n const token = trimmed.slice(7).trim();\n\n return token.length > 0 ? token : null;\n}\n","import { type DynamicModule, Module, type Provider } from \"@nestjs/common\";\n\nimport { Canopy, LocalAuthorizer, TokenVerifier } from \"@canopy-io/node\";\n\nimport { CanopyGuard } from \"./canopy.guard.js\";\nimport { CanopyTokenGuard } from \"./canopy-token.guard.js\";\nimport type {\n CanopyModuleAsyncOptions,\n CanopyModuleOptions,\n} from \"./options.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * Wires one configured `Canopy` client and the guard that uses it into a Nest\n * application.\n *\n * ```ts\n * CanopyModule.forRoot<AuthedRequest>({\n * apiKey: process.env.CANOPY_API_KEY,\n * resolveIdentity: (request) => request.user?.sub,\n * resolveNode: (request) => request.params?.orgId,\n * })\n * ```\n *\n * The client is a singleton because it holds no per-request state — it is a\n * `fetch` wrapper with credentials — so there is nothing to gain from building\n * one per request and a connection pool to lose.\n */\n\n/**\n * Per-attempt deadline for a cache miss on the request path.\n *\n * Five seconds rather than the client's 30: this call sits on the request path,\n * so its deadline is time an inbound request spends waiting. An authorization\n * service that has not answered in five seconds is not going to save the\n * request.\n */\nconst DEFAULT_EVALUATE_TIMEOUT_MS = 5_000;\n\n/**\n * Retries for a cache miss on the request path.\n *\n * One, not the client's two. A deadline bounds an attempt; this bounds how many\n * of them an inbound request can wait through. One retry still absorbs a\n * transient blip, and caps the worst case at roughly two deadlines rather than\n * three.\n */\nconst DEFAULT_EVALUATE_MAX_RETRIES = 1;\n\n/**\n * The authorizer both registration paths build.\n *\n * The guard's `evaluateTimeoutMs` / `evaluateMaxRetries` still apply, but to\n * far fewer calls: they bound a cache miss rather than every request.\n */\nfunction buildAuthorizer<TRequest>(\n client: Canopy,\n options: CanopyModuleOptions<TRequest>,\n): LocalAuthorizer {\n return new LocalAuthorizer(client.client, {\n ...(options.authorizationTtlMs === undefined\n ? {}\n : { ttlMs: options.authorizationTtlMs }),\n timeoutMs: options.evaluateTimeoutMs ?? DEFAULT_EVALUATE_TIMEOUT_MS,\n maxRetries: options.evaluateMaxRetries ?? DEFAULT_EVALUATE_MAX_RETRIES,\n ...(options.onDecision === undefined\n ? {}\n : { onDecision: options.onDecision }),\n ...(options.onDenied === undefined ? {} : { onDenied: options.onDenied }),\n });\n}\n\n@Module({})\nexport class CanopyModule {\n static forRoot<TRequest = unknown>(\n options: CanopyModuleOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n { provide: CANOPY_OPTIONS, useValue: options },\n {\n provide: CANOPY_CLIENT,\n useFactory: () => new Canopy(options),\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: () => new TokenVerifier(options.verify),\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy) => buildAuthorizer(client, options),\n inject: [CANOPY_CLIENT],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n\n /**\n * The same wiring when the API key comes from something injectable, such as\n * `ConfigService`, rather than being available at module-definition time.\n */\n static forRootAsync<TRequest = unknown>(\n options: CanopyModuleAsyncOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CANOPY_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: CANOPY_CLIENT,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new Canopy(resolved),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new TokenVerifier(resolved.verify),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy, resolved: CanopyModuleOptions<TRequest>) =>\n buildAuthorizer(client, resolved),\n inject: [CANOPY_CLIENT, CANOPY_OPTIONS],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n // Spread rather than assigned: under exactOptionalPropertyTypes an\n // explicit `imports: undefined` is not the same as no `imports` at all.\n ...(options.imports ? { imports: options.imports } : {}),\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n}\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_DELEGATED_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client acting for a person on this route or controller.\n *\n * A machine client with token exchange on trades a signed-in person's access\n * token for a `delegated` one: `sub` is the person, `act.sub` the client.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route never\n * lets an agent act for someone by accident. Here it is accepted beside the\n * types the verifier already allows, and `CanopyGuard` allows the request\n * only when the person and the client both hold the permission.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowDelegatedTokens()\n * @RequirePermission(\"deals.read\", { scope: \"org\" })\n * @Get()\n * list() {}\n * ```\n *\n * The verifier holds a delegated token to `verify.serviceAudience`, as it\n * does a service token. Read `request.canopyToken.act?.sub` in the handler\n * to record which client acted.\n */\nexport const AllowDelegatedTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_DELEGATED_TOKENS, true);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_SERVICE_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client's token on this route or controller.\n *\n * A machine client obtains a token for itself with the `client_credentials`\n * grant; its `type` is `service` and its `sub` is the client's `client_id`.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route built\n * for people never admits a machine by accident. Here it is accepted beside\n * the types the verifier already allows, and `CanopyGuard` authorizes it from\n * the client's own grants.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowServiceTokens()\n * @RequirePermission(\"orders.import\", { scope: \"org\" })\n * @Post(\"import\")\n * import() {}\n * ```\n *\n * Read `request.canopyToken.type` in the handler when people and machines\n * should be treated differently.\n */\nexport const AllowServiceTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);\n","import { Inject } from \"@nestjs/common\";\n\nimport { CANOPY_CLIENT } from \"./tokens.js\";\n\n/**\n * Injects the configured client.\n *\n * ```ts\n * constructor(@InjectCanopy() private readonly canopy: Canopy) {}\n * ```\n *\n * Named rather than resolved by type because this package is bundled with\n * esbuild, which emits no `design:paramtypes` — so type-only injection would\n * fail at runtime with a confusing \"cannot resolve dependency\" rather than at\n * build time.\n */\nexport const InjectCanopy = (): ParameterDecorator => Inject(CANOPY_CLIENT);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_PERMISSION } from \"./tokens.js\";\n\n/**\n * Which question the guard asks Canopy.\n *\n * `node` walks the node's lineage, so a role granted on an ancestor is\n * inherited at the node being touched. `app_wide` asks only whether the\n * identity holds the permission anywhere in the Environment. `org` is the\n * node question asked at the organization the caller's token is acting in —\n * the `org_id` claim — so the route needs no `resolveNode` and no node in\n * its path.\n */\nexport type PermissionScope = \"node\" | \"app_wide\" | \"org\";\n\n/** What `@RequirePermission` records for the guard to read back. */\nexport interface PermissionRequirement {\n readonly permission: string;\n readonly scope: PermissionScope;\n}\n\nexport interface RequirePermissionOptions {\n /**\n * Defaults to `node`.\n *\n * `app_wide` is opt-in on purpose. It answers a coarser question and returns\n * no effective node, which makes it right for deciding whether to render a\n * menu item and wrong for guarding a resource that belongs to one — a\n * distinction that is easy to get backwards if the looser check is the\n * default.\n *\n * `org` evaluates at the organization on the caller's verified token\n * (`org_id`), read from the claims `CanopyTokenGuard` attaches or from\n * `resolveOrg` if configured. A caller acting in no organization is denied\n * — an org-scoped route has no meaning outside one.\n */\n readonly scope?: PermissionScope;\n}\n\n/**\n * Require a Canopy permission before a route runs.\n *\n * ```ts\n * @UseGuards(CanopyGuard)\n * @RequirePermission(\"orders.refund\")\n * @Post(\":orderId/refund\")\n * refund() {}\n * ```\n *\n * Applies to a single handler or to a whole controller; a handler's own\n * requirement wins over its controller's.\n */\nexport const RequirePermission = (\n permission: string,\n options: RequirePermissionOptions = {},\n): MethodDecorator & ClassDecorator =>\n SetMetadata<string, PermissionRequirement>(CANOPY_PERMISSION, {\n permission,\n scope: options.scope ?? \"node\",\n });\n"]}
package/dist/index.d.cts CHANGED
@@ -133,6 +133,30 @@ declare class CanopyModule {
133
133
  static forRootAsync<TRequest = unknown>(options: CanopyModuleAsyncOptions<TRequest>): DynamicModule;
134
134
  }
135
135
 
136
+ /**
137
+ * Admit a machine client acting for a person on this route or controller.
138
+ *
139
+ * A machine client with token exchange on trades a signed-in person's access
140
+ * token for a `delegated` one: `sub` is the person, `act.sub` the client.
141
+ * `CanopyTokenGuard` refuses such a token everywhere else, so a route never
142
+ * lets an agent act for someone by accident. Here it is accepted beside the
143
+ * types the verifier already allows, and `CanopyGuard` allows the request
144
+ * only when the person and the client both hold the permission.
145
+ *
146
+ * ```ts
147
+ * @UseGuards(CanopyTokenGuard, CanopyGuard)
148
+ * @AllowDelegatedTokens()
149
+ * @RequirePermission("deals.read", { scope: "org" })
150
+ * @Get()
151
+ * list() {}
152
+ * ```
153
+ *
154
+ * The verifier holds a delegated token to `verify.serviceAudience`, as it
155
+ * does a service token. Read `request.canopyToken.act?.sub` in the handler
156
+ * to record which client acted.
157
+ */
158
+ declare const AllowDelegatedTokens: () => MethodDecorator & ClassDecorator;
159
+
136
160
  /**
137
161
  * Admit a machine client's token on this route or controller.
138
162
  *
@@ -205,6 +229,13 @@ declare class CanopyGuard implements CanActivate {
205
229
  * whose grants are consulted.
206
230
  */
207
231
  private isServiceToken;
232
+ /**
233
+ * The machine client acting for the identity, when the verified token is
234
+ * `delegated`: its `act.sub`, so the check asks both. An empty string for a
235
+ * delegated token naming no client, which the authorizer refuses; the
236
+ * verifier refuses such a token first, so this is the second lock.
237
+ */
238
+ private actingClientOf;
208
239
  /** A staff token (`org_scope: "all"`), read off the verified claims only. */
209
240
  private isStaffToken;
210
241
  /**
@@ -263,7 +294,8 @@ interface CanopyTokenRequest<TCustom extends object = object> {
263
294
  *
264
295
  * A machine client's `service` token is refused unless the route or its
265
296
  * controller carries `@AllowServiceTokens()`: a route built for people must
266
- * not admit a machine by accident.
297
+ * not admit a machine by accident. A `delegated` token, a machine client
298
+ * acting for a person, is refused unless it carries `@AllowDelegatedTokens()`.
267
299
  */
268
300
  declare class CanopyTokenGuard implements CanActivate {
269
301
  private readonly reflector;
@@ -365,4 +397,4 @@ declare const CANOPY_PERMISSION = "CANOPY_PERMISSION";
365
397
  */
366
398
  declare const CANOPY_ALLOW_SERVICE_TOKENS = "CANOPY_ALLOW_SERVICE_TOKENS";
367
399
 
368
- export { AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, type CanopyModuleAsyncOptions, type CanopyModuleOptions, CanopyTokenGuard, type CanopyTokenRequest, InjectCanopy, type PermissionRequirement, type PermissionScope, type RequestResolver, RequirePermission, type RequirePermissionOptions };
400
+ export { AllowDelegatedTokens, AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, type CanopyModuleAsyncOptions, type CanopyModuleOptions, CanopyTokenGuard, type CanopyTokenRequest, InjectCanopy, type PermissionRequirement, type PermissionScope, type RequestResolver, RequirePermission, type RequirePermissionOptions };
package/dist/index.d.ts CHANGED
@@ -133,6 +133,30 @@ declare class CanopyModule {
133
133
  static forRootAsync<TRequest = unknown>(options: CanopyModuleAsyncOptions<TRequest>): DynamicModule;
134
134
  }
135
135
 
136
+ /**
137
+ * Admit a machine client acting for a person on this route or controller.
138
+ *
139
+ * A machine client with token exchange on trades a signed-in person's access
140
+ * token for a `delegated` one: `sub` is the person, `act.sub` the client.
141
+ * `CanopyTokenGuard` refuses such a token everywhere else, so a route never
142
+ * lets an agent act for someone by accident. Here it is accepted beside the
143
+ * types the verifier already allows, and `CanopyGuard` allows the request
144
+ * only when the person and the client both hold the permission.
145
+ *
146
+ * ```ts
147
+ * @UseGuards(CanopyTokenGuard, CanopyGuard)
148
+ * @AllowDelegatedTokens()
149
+ * @RequirePermission("deals.read", { scope: "org" })
150
+ * @Get()
151
+ * list() {}
152
+ * ```
153
+ *
154
+ * The verifier holds a delegated token to `verify.serviceAudience`, as it
155
+ * does a service token. Read `request.canopyToken.act?.sub` in the handler
156
+ * to record which client acted.
157
+ */
158
+ declare const AllowDelegatedTokens: () => MethodDecorator & ClassDecorator;
159
+
136
160
  /**
137
161
  * Admit a machine client's token on this route or controller.
138
162
  *
@@ -205,6 +229,13 @@ declare class CanopyGuard implements CanActivate {
205
229
  * whose grants are consulted.
206
230
  */
207
231
  private isServiceToken;
232
+ /**
233
+ * The machine client acting for the identity, when the verified token is
234
+ * `delegated`: its `act.sub`, so the check asks both. An empty string for a
235
+ * delegated token naming no client, which the authorizer refuses; the
236
+ * verifier refuses such a token first, so this is the second lock.
237
+ */
238
+ private actingClientOf;
208
239
  /** A staff token (`org_scope: "all"`), read off the verified claims only. */
209
240
  private isStaffToken;
210
241
  /**
@@ -263,7 +294,8 @@ interface CanopyTokenRequest<TCustom extends object = object> {
263
294
  *
264
295
  * A machine client's `service` token is refused unless the route or its
265
296
  * controller carries `@AllowServiceTokens()`: a route built for people must
266
- * not admit a machine by accident.
297
+ * not admit a machine by accident. A `delegated` token, a machine client
298
+ * acting for a person, is refused unless it carries `@AllowDelegatedTokens()`.
267
299
  */
268
300
  declare class CanopyTokenGuard implements CanActivate {
269
301
  private readonly reflector;
@@ -365,4 +397,4 @@ declare const CANOPY_PERMISSION = "CANOPY_PERMISSION";
365
397
  */
366
398
  declare const CANOPY_ALLOW_SERVICE_TOKENS = "CANOPY_ALLOW_SERVICE_TOKENS";
367
399
 
368
- export { AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, type CanopyModuleAsyncOptions, type CanopyModuleOptions, CanopyTokenGuard, type CanopyTokenRequest, InjectCanopy, type PermissionRequirement, type PermissionScope, type RequestResolver, RequirePermission, type RequirePermissionOptions };
400
+ export { AllowDelegatedTokens, AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, type CanopyModuleAsyncOptions, type CanopyModuleOptions, CanopyTokenGuard, type CanopyTokenRequest, InjectCanopy, type PermissionRequirement, type PermissionScope, type RequestResolver, RequirePermission, type RequirePermissionOptions };
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ var CANOPY_AUTHORIZER = "CANOPY_AUTHORIZER";
19
19
  var CANOPY_TOKEN_VERIFIER = "CANOPY_TOKEN_VERIFIER";
20
20
  var CANOPY_PERMISSION = "CANOPY_PERMISSION";
21
21
  var CANOPY_ALLOW_SERVICE_TOKENS = "CANOPY_ALLOW_SERVICE_TOKENS";
22
+ var CANOPY_ALLOW_DELEGATED_TOKENS = "CANOPY_ALLOW_DELEGATED_TOKENS";
22
23
 
23
24
  // src/canopy.guard.ts
24
25
  function isClosable(value) {
@@ -78,9 +79,11 @@ var CanopyGuard = class {
78
79
  * policy" — and neither outcome lets the request proceed.
79
80
  */
80
81
  async evaluate(requirement, identityId, request, cancellation) {
82
+ const actingClientId = this.actingClientOf(request);
81
83
  const query = {
82
84
  ...this.buildQuery(requirement, identityId, request),
83
- ...this.isServiceToken(request) ? { principal_type: "service" } : {}
85
+ ...this.isServiceToken(request) ? { principal_type: "service" } : {},
86
+ ...actingClientId === void 0 ? {} : { acting_client_id: actingClientId }
84
87
  };
85
88
  try {
86
89
  return await this.authorizer.evaluate(
@@ -166,6 +169,21 @@ var CanopyGuard = class {
166
169
  const claims = request?.[attachedAs];
167
170
  return claims?.type === "service";
168
171
  }
172
+ /**
173
+ * The machine client acting for the identity, when the verified token is
174
+ * `delegated`: its `act.sub`, so the check asks both. An empty string for a
175
+ * delegated token naming no client, which the authorizer refuses; the
176
+ * verifier refuses such a token first, so this is the second lock.
177
+ */
178
+ actingClientOf(request) {
179
+ const attachedAs = this.options.attachTokenAs ?? "canopyToken";
180
+ const claims = request?.[attachedAs];
181
+ if (claims?.type !== "delegated") {
182
+ return void 0;
183
+ }
184
+ const sub = claims.act?.sub;
185
+ return typeof sub === "string" ? sub : "";
186
+ }
169
187
  /** A staff token (`org_scope: "all"`), read off the verified claims only. */
170
188
  isStaffToken(request) {
171
189
  const attachedAs = this.options.attachTokenAs ?? "canopyToken";
@@ -241,15 +259,19 @@ var CanopyTokenGuard = class {
241
259
  "Missing bearer token in the Authorization header."
242
260
  );
243
261
  }
244
- const admitsServiceTokens = this.reflector.getAllAndOverride(
245
- CANOPY_ALLOW_SERVICE_TOKENS,
246
- [context.getHandler(), context.getClass()]
247
- ) === true;
262
+ const admits = (key) => this.reflector.getAllAndOverride(key, [
263
+ context.getHandler(),
264
+ context.getClass()
265
+ ]) === true;
266
+ const alsoAllow = [
267
+ ...admits(CANOPY_ALLOW_SERVICE_TOKENS) ? ["service"] : [],
268
+ ...admits(CANOPY_ALLOW_DELEGATED_TOKENS) ? ["delegated"] : []
269
+ ];
248
270
  let claims;
249
271
  try {
250
272
  claims = await this.verifier.verify(
251
273
  token,
252
- admitsServiceTokens ? { alsoAllow: ["service"] } : {}
274
+ alsoAllow.length > 0 ? { alsoAllow } : {}
253
275
  );
254
276
  } catch (error) {
255
277
  if (!isCanopyTokenError(error)) {
@@ -382,6 +404,7 @@ var CanopyModule = class {
382
404
  CanopyModule = __decorateClass([
383
405
  Module({})
384
406
  ], CanopyModule);
407
+ var AllowDelegatedTokens = () => SetMetadata(CANOPY_ALLOW_DELEGATED_TOKENS, true);
385
408
  var AllowServiceTokens = () => SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);
386
409
  var InjectCanopy = () => Inject(CANOPY_CLIENT);
387
410
  var RequirePermission = (permission, options = {}) => SetMetadata(CANOPY_PERMISSION, {
@@ -389,6 +412,6 @@ var RequirePermission = (permission, options = {}) => SetMetadata(CANOPY_PERMISS
389
412
  scope: options.scope ?? "node"
390
413
  });
391
414
 
392
- export { AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, CanopyTokenGuard, InjectCanopy, RequirePermission };
415
+ export { AllowDelegatedTokens, AllowServiceTokens, CANOPY_ALLOW_SERVICE_TOKENS, CANOPY_AUTHORIZER, CANOPY_CLIENT, CANOPY_OPTIONS, CANOPY_PERMISSION, CANOPY_TOKEN_VERIFIER, CanopyGuard, CanopyModule, CanopyTokenGuard, InjectCanopy, RequirePermission };
393
416
  //# sourceMappingURL=index.js.map
394
417
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tokens.ts","../src/canopy.guard.ts","../src/canopy-token.guard.ts","../src/canopy.module.ts","../src/allow-service-tokens.decorator.ts","../src/inject-canopy.decorator.ts","../src/require-permission.decorator.ts"],"names":["ServiceUnavailableException","Injectable","Inject","Reflector","TokenVerifier","SetMetadata"],"mappings":";;;;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiB;AAGvB,IAAM,aAAA,GAAgB;AAStB,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,iBAAA,GAAoB;AAO1B,IAAM,2BAAA,GAA8B;;;ACiB3C,SAAS,WAAW,KAAA,EAA2C;AAC7D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACV,OAAQ,KAAA,CAA2B,IAAA,KAAS,UAAA,IAC5C,OAAQ,KAAA,CAA2B,cAAA,KAAmB,UAAA;AAE1D;AAYA,SAAS,cAAc,QAAA,EAAiD;AACtE,EAAA,MAAM,MAAO,QAAA,EAAmD,GAAA;AAEhE,EAAA,IAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AACnB,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,IAAI,UAAA,CAAW,QAAQ,CAAA,EAAG;AACxB,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,OAAO,MAAA;AACT;AAkBO,IAAM,cAAN,MAAyC;AAAA,EAG9C,WAAA,CACsC,SAAA,EACQ,UAAA,EAE3B,OAAA,EACjB;AAJoC,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AACQ,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAE3B,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAAA,EAChB;AAAA,EAJmC,SAAA;AAAA,EACQ,UAAA;AAAA,EAE3B,OAAA;AAAA,EANF,MAAA,GAAS,IAAI,MAAA,CAAO,WAAA,CAAY,IAAI,CAAA;AAAA,EASrD,MAAM,YAAY,OAAA,EAA6C;AAC7D,IAAA,MAAM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ACT,YAAY,CAAC,MAAA,EAAgB,QAAA,KAC3B,eAAA,CAAgB,QAAQ,QAAQ,CAAA;AAAA,QAClC,MAAA,EAAQ,CAAC,aAAA,EAAe,cAAc;AAAA,OACxC;AAAA,MACA,WAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,YAAA;AAAA,MACR,MAAA,EAAQ,QAAQ,QAAA,IAAY,KAAA;AAAA;AAAA;AAAA,MAG5B,GAAI,QAAQ,OAAA,GAAU,EAAE,SAAS,OAAA,CAAQ,OAAA,KAAY,EAAC;AAAA,MACtD,SAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,aAAA;AAAA,QACA,cAAA;AAAA,QACA,qBAAA;AAAA,QACA,iBAAA;AAAA,QACA,WAAA;AAAA,QACA;AAAA;AACF,KACF;AAAA,EACF;AACF;AA1Fa,YAAA,GAAN,eAAA,CAAA;AAAA,EADN,MAAA,CAAO,EAAE;AAAA,CAAA,EACG,YAAA,CAAA;ACrDN,IAAM,kBAAA,GAAqB,MAChC,WAAA,CAAY,2BAAA,EAA6B,IAAI;ACVxC,IAAM,YAAA,GAAe,MAA0BF,MAAAA,CAAO,aAAa;ACqCnE,IAAM,oBAAoB,CAC/B,UAAA,EACA,UAAoC,EAAC,KAErCG,YAA2C,iBAAA,EAAmB;AAAA,EAC5D,UAAA;AAAA,EACA,KAAA,EAAO,QAAQ,KAAA,IAAS;AAC1B,CAAC","file":"index.js","sourcesContent":["/**\n * Injection tokens.\n *\n * These are strings rather than classes because esbuild does not emit\n * `design:paramtypes`, so nothing here can be injected by constructor type\n * alone — every dependency is named with an explicit `@Inject`.\n */\n\n/** The resolved `CanopyModuleOptions`. */\nexport const CANOPY_OPTIONS = \"CANOPY_OPTIONS\";\n\n/** The configured `Canopy` client. */\nexport const CANOPY_CLIENT = \"CANOPY_CLIENT\";\n\n/**\n * The configured `LocalAuthorizer`.\n *\n * Shared deliberately: it holds one copy of the hierarchy for the whole\n * process, so a second instance would double both the memory and the traffic\n * it exists to avoid.\n */\nexport const CANOPY_AUTHORIZER = \"CANOPY_AUTHORIZER\";\n\n/** The configured `TokenVerifier`, shared so its key cache is shared too. */\nexport const CANOPY_TOKEN_VERIFIER = \"CANOPY_TOKEN_VERIFIER\";\n\n/** Metadata key holding what `@RequirePermission` recorded on a handler. */\nexport const CANOPY_PERMISSION = \"CANOPY_PERMISSION\";\n\n/**\n * Metadata key `@AllowServiceTokens()` writes: a route or controller that\n * admits a machine client's `service` token beside the types the verifier\n * already accepts.\n */\nexport const CANOPY_ALLOW_SERVICE_TOKENS = \"CANOPY_ALLOW_SERVICE_TOKENS\";\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n InternalServerErrorException,\n Logger,\n ServiceUnavailableException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n authorizationErrorStatus,\n type LocalAuthorizer,\n type LocalDecision,\n type RequestBody,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport type { PermissionRequirement } from \"./require-permission.decorator.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_OPTIONS,\n CANOPY_PERMISSION,\n} from \"./tokens.js\";\n\n/** Read off the generated operation, so it follows the API rather than restating it. */\ntype EvaluateQuery = RequestBody<\"ApiPermissionsController_evaluate\">;\n\n/**\n * The verdict and, on a denial, the reason the grant roots and the tree can\n * give; not the API's full explain payload. A decision reached in-process\n * cannot report `granting_roles` or an effective node — that reasoning lives\n * on the server — and typing the narrow thing keeps that honest.\n */\ntype Verdict = LocalDecision;\n\ninterface Cancellation {\n signal: AbortSignal;\n dispose: () => void;\n}\n\n/** The Node stream underneath an Express or Fastify response. */\ninterface ClosableResponse {\n once: (event: string, listener: () => void) => unknown;\n removeListener: (event: string, listener: () => void) => unknown;\n writableEnded?: boolean;\n raw?: ClosableResponse;\n}\n\nfunction isClosable(value: unknown): value is ClosableResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ClosableResponse).once === \"function\" &&\n typeof (value as ClosableResponse).removeListener === \"function\"\n );\n}\n\n/**\n * Find the Node response stream behind whatever the adapter hands back.\n *\n * `.raw` is checked first and on its own merits, because the object Nest\n * returns is not always the stream. Express returns the `ServerResponse`\n * itself, which listens; Fastify returns a `Reply`, which is a plain object\n * with the real response on `.raw`. Testing the outer object first and\n * returning early on failure would skip `.raw` in exactly the case it exists\n * for.\n */\nfunction resolveStream(response: unknown): ClosableResponse | undefined {\n const raw = (response as { raw?: unknown } | null | undefined)?.raw;\n\n if (isClosable(raw)) {\n return raw;\n }\n\n if (isClosable(response)) {\n return response;\n }\n\n return undefined;\n}\n\n/**\n * Enforces `@RequirePermission` by asking Canopy, once, per guarded request.\n *\n * The guard fails closed at every step. An unresolvable identity, a `node`\n * check with no node, a denial, or an unreachable API all end the request —\n * there is no path through this class that allows a request whose decision is\n * unknown. That is the property worth protecting when reading this code: an\n * `allow` must be something Canopy actually said.\n *\n * A route with no requirement is allowed through untouched, so the guard can be\n * applied globally and opted into per route. Registered that way it runs before\n * controller- and route-scoped guards, so whatever authenticates the request has\n * to be registered globally ahead of it — otherwise `resolveIdentity` runs\n * before there is anything to resolve and every guarded route denies.\n */\n@Injectable()\nexport class CanopyGuard implements CanActivate {\n private readonly logger = new Logger(CanopyGuard.name);\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_AUTHORIZER) private readonly authorizer: LocalAuthorizer,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<\n PermissionRequirement | undefined\n >(CANOPY_PERMISSION, [context.getHandler(), context.getClass()]);\n\n if (!requirement) {\n return true;\n }\n\n const http = context.switchToHttp();\n const request: unknown = http.getRequest();\n const identityId = resolveSafely(this.options.resolveIdentity, request);\n\n if (!identityId) {\n throw new ForbiddenException(\n \"No identity on the request. Canopy cannot evaluate a permission without one.\",\n );\n }\n\n const decision = await this.evaluate(\n requirement,\n identityId,\n request,\n watchDisconnect(http),\n );\n\n if (!decision.allowed) {\n throw new ForbiddenException(\n `Caller does not hold ${requirement.permission}.`,\n );\n }\n\n return true;\n }\n\n /**\n * Asks Canopy the question the decorator recorded.\n *\n * Every failure is converted into a thrown exception rather than a `false`\n * decision, so a caller cannot mistake \"we could not tell\" for \"denied by\n * policy\" — and neither outcome lets the request proceed.\n */\n private async evaluate(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n cancellation: Cancellation | undefined,\n ): Promise<Verdict> {\n const query = {\n ...this.buildQuery(requirement, identityId, request),\n ...(this.isServiceToken(request)\n ? { principal_type: \"service\" as const }\n : {}),\n };\n\n try {\n // Answered in-process. The authorizer holds the identity's grant roots\n // and a shared copy of the hierarchy, so the common case reaches no\n // network at all; only a cold or expired entry does, and its deadline\n // and retries are bounded by the same options as before.\n return await this.authorizer.evaluate(\n query,\n cancellation ? { signal: cancellation.signal } : {},\n );\n } catch (error) {\n // The caller hung up mid-check. There is no one left to answer, and this\n // is not Canopy failing — so it must not be logged or reported as though\n // it were. Rethrowing the abort ends the request without inventing a\n // decision.\n if (cancellation?.signal.aborted) {\n throw error;\n }\n\n // Deliberately not re-thrown as-is: a failure here must not reach the\n // client as though Canopy had answered.\n this.logger.error(\n `Could not evaluate ${requirement.permission} for ${identityId}`,\n error instanceof Error ? error.stack : String(error),\n );\n\n throw this.toHttpException(error);\n } finally {\n cancellation?.dispose();\n }\n }\n\n /**\n * Turn a failed check into the status that describes it.\n *\n * Every branch denies — nothing here can let a request through — but they say\n * different things, and the difference is what makes an incident diagnosable.\n * Reporting a rejected API key as \"temporarily unavailable\" invites a retry\n * that will never succeed and hides a misconfiguration behind an outage. The\n * mapping is `authorizationErrorStatus` in `@canopy-io/node`, so an\n * integration outside NestJS answers the same way.\n */\n private toHttpException(error: unknown): Error {\n const { status, message } = authorizationErrorStatus(error);\n\n if (status === 403) {\n return new ForbiddenException(message);\n }\n\n if (status === 503) {\n return new ServiceUnavailableException(message);\n }\n\n return new InternalServerErrorException(message);\n }\n\n private buildQuery(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n ): EvaluateQuery {\n if (requirement.scope === \"app_wide\") {\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"app_wide\",\n };\n }\n\n // An organization is a hierarchy node, and a membership is a role\n // assignment at it — so the org question IS the node question, asked at\n // the node the caller's token says it is acting in.\n if (requirement.scope === \"org\") {\n const orgId = this.resolveOrg(request);\n\n if (!orgId) {\n // Staff reach every organization but act in one only after entering\n // it, which the organization records and may refuse. The route's own\n // organization is never a stand-in for that entry.\n throw new ForbiddenException(\n this.isStaffToken(request)\n ? `No organization on the request. ${requirement.permission} is checked inside the caller's active organization; this staff session has not entered one, and enters with switch-organization.`\n : `No organization on the request. ${requirement.permission} is checked inside the caller's active organization, and this caller is not acting in one.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: orgId,\n };\n }\n\n const nodeId = this.options.resolveNode\n ? resolveSafely(this.options.resolveNode, request)\n : undefined;\n\n if (!nodeId) {\n throw new ForbiddenException(\n `No node on the request. ${requirement.permission} is checked at a node; configure resolveNode, or declare the route as app_wide if that is genuinely the question.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: nodeId,\n };\n }\n\n /**\n * Whose grants answer the check: a machine client's when the verified token\n * `CanopyTokenGuard` attached is a `service` token, an identity's\n * otherwise. Read off the verified claims only, so a caller cannot choose\n * whose grants are consulted.\n */\n private isServiceToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { type?: unknown } | undefined)?.type === \"service\";\n }\n\n /** A staff token (`org_scope: \"all\"`), read off the verified claims only. */\n private isStaffToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { org_scope?: unknown } | undefined)?.org_scope === \"all\";\n }\n\n /**\n * The organization the request acts in: `resolveOrg` when configured,\n * otherwise the `org_id` claim off the verified token `CanopyTokenGuard`\n * attached. Both sources trace back to a verified token — the org id\n * decides whose grants answer the check, so it must never be readable off\n * anything the caller controls directly.\n */\n private resolveOrg(request: unknown): string | null | undefined {\n if (this.options.resolveOrg) {\n return resolveSafely(this.options.resolveOrg, request);\n }\n\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n const orgId = (claims as { org_id?: unknown } | undefined)?.org_id;\n\n return typeof orgId === \"string\" && orgId !== \"\" ? orgId : undefined;\n }\n}\n\n/**\n * Run a resolver, treating a throw as \"could not resolve\".\n *\n * Resolvers reach into the request — `request.user.sub` is the shape the docs\n * suggest and the one most applications write. On an unauthenticated request\n * `request.user` is undefined and that expression throws, which without this\n * would surface as a 500. An identity that cannot be established is exactly the\n * request that must be denied, so it becomes the same 403 as returning nothing.\n */\nfunction resolveSafely(\n resolve: (request: never) => string | null | undefined,\n request: unknown,\n): string | null | undefined {\n try {\n return (resolve as (request: unknown) => string | null | undefined)(\n request,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Abort the permission check if the caller hangs up while it is in flight.\n *\n * Watches the *response*, not the request. A request stream emits `close` on\n * every normal request once its body has been read, so listening there would\n * abort perfectly healthy checks; a response emits `close` before\n * `writableEnded` only when nothing was ever sent — which is exactly the\n * disconnect case. The `writableEnded` re-check at fire time keeps that true\n * even if the ordering differs by adapter.\n *\n * Returns undefined for a transport with no such response — a GraphQL or\n * microservice context — where the check simply runs to its deadline.\n */\nfunction watchDisconnect(http: {\n getResponse?: () => unknown;\n}): Cancellation | undefined {\n const raw = resolveStream(http.getResponse?.());\n\n if (!raw) {\n return undefined;\n }\n\n const controller = new AbortController();\n\n const onClose = () => {\n if (raw.writableEnded === true) {\n return;\n }\n\n controller.abort(\n new DOMException(\"The client closed the request\", \"AbortError\"),\n );\n };\n\n raw.once(\"close\", onClose);\n\n return {\n signal: controller.signal,\n dispose: () => raw.removeListener(\"close\", onClose),\n };\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n ServiceUnavailableException,\n UnauthorizedException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n type CanopyTokenClaims,\n isCanopyTokenError,\n tokenErrorStatus,\n TokenVerifier,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport {\n CANOPY_ALLOW_SERVICE_TOKENS,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * A request `CanopyTokenGuard` has run on: the verified claims under\n * `canopyToken` (or the module's `attachTokenAs`). `TCustom` names the\n * Environment's custom claims, each optional, so a handler reads them typed:\n *\n * ```ts\n * @Get(\"export\")\n * export(@Req() request: CanopyTokenRequest<{ plan?: \"free\" | \"pro\" }>) {\n * if (request.canopyToken?.plan !== \"pro\") {\n * throw new ForbiddenException();\n * }\n * }\n * ```\n */\nexport interface CanopyTokenRequest<TCustom extends object = object> {\n canopyToken?: CanopyTokenClaims & TCustom;\n}\n\n/**\n * Verifies the bearer token and attaches its claims to the request.\n *\n * This is the authentication half, and it is opt-in on purpose. `CanopyGuard`\n * answers \"may this identity do this?\"; something has to have established\n * *which* identity first, and `resolveIdentity` says as much — \"usually a\n * claim off the verified access token your auth layer already attached\".\n *\n * Use this guard when Canopy issues your tokens and you have no auth layer\n * yet. Skip it entirely if you already run Passport or your own JWT\n * middleware — it is additive, and nothing else in the package depends on it.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @RequirePermission(\"documents.read\")\n * findAll() {}\n * ```\n *\n * Order matters: this must run first, because `CanopyGuard` reads what it\n * attaches. Nest runs guards left to right, so listing them in that order is\n * the whole of the wiring.\n *\n * Claims land on `request.canopyToken` by default, which is why\n * `resolveIdentity` is usually `(req) => req.canopyToken?.sub`. The property\n * is configurable so it cannot collide with a `request.user` an existing\n * middleware already owns.\n *\n * A machine client's `service` token is refused unless the route or its\n * controller carries `@AllowServiceTokens()`: a route built for people must\n * not admit a machine by accident.\n */\n@Injectable()\nexport class CanopyTokenGuard implements CanActivate {\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_TOKEN_VERIFIER) private readonly verifier: TokenVerifier,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<{\n headers?: Record<string, string | string[] | undefined>;\n [key: string]: unknown;\n }>();\n\n const token = readBearerToken(request.headers?.[\"authorization\"]);\n\n if (token === null) {\n throw new UnauthorizedException(\n \"Missing bearer token in the Authorization header.\",\n );\n }\n\n const admitsServiceTokens =\n this.reflector.getAllAndOverride<boolean | undefined>(\n CANOPY_ALLOW_SERVICE_TOKENS,\n [context.getHandler(), context.getClass()],\n ) === true;\n\n let claims: CanopyTokenClaims;\n\n try {\n claims = await this.verifier.verify(\n token,\n admitsServiceTokens ? { alsoAllow: [\"service\"] } : {},\n );\n } catch (error) {\n // Not being able to verify is not the same as failing to verify. When\n // the key set cannot be read the caller's token may be perfectly good —\n // we simply cannot say — so this is ours to own, exactly as the\n // permission guard answers 503 rather than denying on an undecidable\n // check.\n //\n // Reporting it as 401 would be worse than merely inaccurate: a client\n // reads 401 as \"your token is stale\", discards a valid one and asks for\n // another, which aims a refresh storm at the issuer that is already\n // down. And an outage that only ever emits 4xx is invisible to anything\n // watching 5xx.\n if (!isCanopyTokenError(error)) {\n throw error;\n }\n\n const { status, message } = tokenErrorStatus(error);\n\n if (status === 503) {\n throw new ServiceUnavailableException(message, { cause: error });\n }\n\n // Every other cause is the token itself, and a 401 whatever the detail:\n // the caller cannot fix a bad signature by being granted something. The\n // specific code stays on the error for logs rather than going to the\n // caller, who has no use for the difference and should not be told which\n // check failed.\n throw new UnauthorizedException(message, { cause: error });\n }\n\n request[this.options.attachTokenAs ?? \"canopyToken\"] = claims;\n\n return true;\n }\n}\n\n/**\n * The token out of an `Authorization: Bearer …` header.\n *\n * Returns null rather than throwing so the caller owns the message. The scheme\n * is matched case-insensitively because RFC 7235 says it is case-insensitive,\n * and clients do send `bearer`.\n */\nfunction readBearerToken(header: string | string[] | undefined): string | null {\n const value = Array.isArray(header) ? header[0] : header;\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n // Split by hand rather than with `/^bearer\\s+(.+)$/i`: the header is the\n // caller's to write, and that pattern backtracks on a long run of spaces.\n const trimmed = value.trim();\n const scheme = trimmed.slice(0, 6);\n const separator = trimmed.charAt(6);\n\n if (scheme.toLowerCase() !== \"bearer\" || !/\\s/.test(separator)) {\n return null;\n }\n\n const token = trimmed.slice(7).trim();\n\n return token.length > 0 ? token : null;\n}\n","import { type DynamicModule, Module, type Provider } from \"@nestjs/common\";\n\nimport { Canopy, LocalAuthorizer, TokenVerifier } from \"@canopy-io/node\";\n\nimport { CanopyGuard } from \"./canopy.guard.js\";\nimport { CanopyTokenGuard } from \"./canopy-token.guard.js\";\nimport type {\n CanopyModuleAsyncOptions,\n CanopyModuleOptions,\n} from \"./options.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * Wires one configured `Canopy` client and the guard that uses it into a Nest\n * application.\n *\n * ```ts\n * CanopyModule.forRoot<AuthedRequest>({\n * apiKey: process.env.CANOPY_API_KEY,\n * resolveIdentity: (request) => request.user?.sub,\n * resolveNode: (request) => request.params?.orgId,\n * })\n * ```\n *\n * The client is a singleton because it holds no per-request state — it is a\n * `fetch` wrapper with credentials — so there is nothing to gain from building\n * one per request and a connection pool to lose.\n */\n\n/**\n * Per-attempt deadline for a cache miss on the request path.\n *\n * Five seconds rather than the client's 30: this call sits on the request path,\n * so its deadline is time an inbound request spends waiting. An authorization\n * service that has not answered in five seconds is not going to save the\n * request.\n */\nconst DEFAULT_EVALUATE_TIMEOUT_MS = 5_000;\n\n/**\n * Retries for a cache miss on the request path.\n *\n * One, not the client's two. A deadline bounds an attempt; this bounds how many\n * of them an inbound request can wait through. One retry still absorbs a\n * transient blip, and caps the worst case at roughly two deadlines rather than\n * three.\n */\nconst DEFAULT_EVALUATE_MAX_RETRIES = 1;\n\n/**\n * The authorizer both registration paths build.\n *\n * The guard's `evaluateTimeoutMs` / `evaluateMaxRetries` still apply, but to\n * far fewer calls: they bound a cache miss rather than every request.\n */\nfunction buildAuthorizer<TRequest>(\n client: Canopy,\n options: CanopyModuleOptions<TRequest>,\n): LocalAuthorizer {\n return new LocalAuthorizer(client.client, {\n ...(options.authorizationTtlMs === undefined\n ? {}\n : { ttlMs: options.authorizationTtlMs }),\n timeoutMs: options.evaluateTimeoutMs ?? DEFAULT_EVALUATE_TIMEOUT_MS,\n maxRetries: options.evaluateMaxRetries ?? DEFAULT_EVALUATE_MAX_RETRIES,\n ...(options.onDecision === undefined\n ? {}\n : { onDecision: options.onDecision }),\n ...(options.onDenied === undefined ? {} : { onDenied: options.onDenied }),\n });\n}\n\n@Module({})\nexport class CanopyModule {\n static forRoot<TRequest = unknown>(\n options: CanopyModuleOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n { provide: CANOPY_OPTIONS, useValue: options },\n {\n provide: CANOPY_CLIENT,\n useFactory: () => new Canopy(options),\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: () => new TokenVerifier(options.verify),\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy) => buildAuthorizer(client, options),\n inject: [CANOPY_CLIENT],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n\n /**\n * The same wiring when the API key comes from something injectable, such as\n * `ConfigService`, rather than being available at module-definition time.\n */\n static forRootAsync<TRequest = unknown>(\n options: CanopyModuleAsyncOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CANOPY_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: CANOPY_CLIENT,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new Canopy(resolved),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new TokenVerifier(resolved.verify),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy, resolved: CanopyModuleOptions<TRequest>) =>\n buildAuthorizer(client, resolved),\n inject: [CANOPY_CLIENT, CANOPY_OPTIONS],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n // Spread rather than assigned: under exactOptionalPropertyTypes an\n // explicit `imports: undefined` is not the same as no `imports` at all.\n ...(options.imports ? { imports: options.imports } : {}),\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n}\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_SERVICE_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client's token on this route or controller.\n *\n * A machine client obtains a token for itself with the `client_credentials`\n * grant; its `type` is `service` and its `sub` is the client's `client_id`.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route built\n * for people never admits a machine by accident. Here it is accepted beside\n * the types the verifier already allows, and `CanopyGuard` authorizes it from\n * the client's own grants.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowServiceTokens()\n * @RequirePermission(\"orders.import\", { scope: \"org\" })\n * @Post(\"import\")\n * import() {}\n * ```\n *\n * Read `request.canopyToken.type` in the handler when people and machines\n * should be treated differently.\n */\nexport const AllowServiceTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);\n","import { Inject } from \"@nestjs/common\";\n\nimport { CANOPY_CLIENT } from \"./tokens.js\";\n\n/**\n * Injects the configured client.\n *\n * ```ts\n * constructor(@InjectCanopy() private readonly canopy: Canopy) {}\n * ```\n *\n * Named rather than resolved by type because this package is bundled with\n * esbuild, which emits no `design:paramtypes` — so type-only injection would\n * fail at runtime with a confusing \"cannot resolve dependency\" rather than at\n * build time.\n */\nexport const InjectCanopy = (): ParameterDecorator => Inject(CANOPY_CLIENT);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_PERMISSION } from \"./tokens.js\";\n\n/**\n * Which question the guard asks Canopy.\n *\n * `node` walks the node's lineage, so a role granted on an ancestor is\n * inherited at the node being touched. `app_wide` asks only whether the\n * identity holds the permission anywhere in the Environment. `org` is the\n * node question asked at the organization the caller's token is acting in —\n * the `org_id` claim — so the route needs no `resolveNode` and no node in\n * its path.\n */\nexport type PermissionScope = \"node\" | \"app_wide\" | \"org\";\n\n/** What `@RequirePermission` records for the guard to read back. */\nexport interface PermissionRequirement {\n readonly permission: string;\n readonly scope: PermissionScope;\n}\n\nexport interface RequirePermissionOptions {\n /**\n * Defaults to `node`.\n *\n * `app_wide` is opt-in on purpose. It answers a coarser question and returns\n * no effective node, which makes it right for deciding whether to render a\n * menu item and wrong for guarding a resource that belongs to one — a\n * distinction that is easy to get backwards if the looser check is the\n * default.\n *\n * `org` evaluates at the organization on the caller's verified token\n * (`org_id`), read from the claims `CanopyTokenGuard` attaches or from\n * `resolveOrg` if configured. A caller acting in no organization is denied\n * — an org-scoped route has no meaning outside one.\n */\n readonly scope?: PermissionScope;\n}\n\n/**\n * Require a Canopy permission before a route runs.\n *\n * ```ts\n * @UseGuards(CanopyGuard)\n * @RequirePermission(\"orders.refund\")\n * @Post(\":orderId/refund\")\n * refund() {}\n * ```\n *\n * Applies to a single handler or to a whole controller; a handler's own\n * requirement wins over its controller's.\n */\nexport const RequirePermission = (\n permission: string,\n options: RequirePermissionOptions = {},\n): MethodDecorator & ClassDecorator =>\n SetMetadata<string, PermissionRequirement>(CANOPY_PERMISSION, {\n permission,\n scope: options.scope ?? \"node\",\n });\n"]}
1
+ {"version":3,"sources":["../src/tokens.ts","../src/canopy.guard.ts","../src/canopy-token.guard.ts","../src/canopy.module.ts","../src/allow-delegated-tokens.decorator.ts","../src/allow-service-tokens.decorator.ts","../src/inject-canopy.decorator.ts","../src/require-permission.decorator.ts"],"names":["ServiceUnavailableException","Injectable","Inject","Reflector","TokenVerifier","SetMetadata"],"mappings":";;;;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiB;AAGvB,IAAM,aAAA,GAAgB;AAStB,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,iBAAA,GAAoB;AAO1B,IAAM,2BAAA,GAA8B;AAMpC,IAAM,6BAAA,GAAgC,+BAAA;;;ACW7C,SAAS,WAAW,KAAA,EAA2C;AAC7D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACV,OAAQ,KAAA,CAA2B,IAAA,KAAS,UAAA,IAC5C,OAAQ,KAAA,CAA2B,cAAA,KAAmB,UAAA;AAE1D;AAYA,SAAS,cAAc,QAAA,EAAiD;AACtE,EAAA,MAAM,MAAO,QAAA,EAAmD,GAAA;AAEhE,EAAA,IAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AACnB,IAAA,OAAO,GAAA;AAAA,E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ACE,OAAA,EAAS,iBAAA;AAAA,QACT,YAAY,CAAC,MAAA,EAAgB,QAAA,KAC3B,eAAA,CAAgB,QAAQ,QAAQ,CAAA;AAAA,QAClC,MAAA,EAAQ,CAAC,aAAA,EAAe,cAAc;AAAA,OACxC;AAAA,MACA,WAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,YAAA;AAAA,MACR,MAAA,EAAQ,QAAQ,QAAA,IAAY,KAAA;AAAA;AAAA;AAAA,MAG5B,GAAI,QAAQ,OAAA,GAAU,EAAE,SAAS,OAAA,CAAQ,OAAA,KAAY,EAAC;AAAA,MACtD,SAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,aAAA;AAAA,QACA,cAAA;AAAA,QACA,qBAAA;AAAA,QACA,iBAAA;AAAA,QACA,WAAA;AAAA,QACA;AAAA;AACF,KACF;AAAA,EACF;AACF;AA1Fa,YAAA,GAAN,eAAA,CAAA;AAAA,EADN,MAAA,CAAO,EAAE;AAAA,CAAA,EACG,YAAA,CAAA;ACpDN,IAAM,oBAAA,GAAuB,MAClC,WAAA,CAAY,6BAAA,EAA+B,IAAI;ACF1C,IAAM,kBAAA,GAAqB,MAChCC,WAAAA,CAAY,2BAAA,EAA6B,IAAI;ACVxC,IAAM,YAAA,GAAe,MAA0BH,MAAAA,CAAO,aAAa;ACqCnE,IAAM,oBAAoB,CAC/B,UAAA,EACA,UAAoC,EAAC,KAErCG,YAA2C,iBAAA,EAAmB;AAAA,EAC5D,UAAA;AAAA,EACA,KAAA,EAAO,QAAQ,KAAA,IAAS;AAC1B,CAAC","file":"index.js","sourcesContent":["/**\n * Injection tokens.\n *\n * These are strings rather than classes because esbuild does not emit\n * `design:paramtypes`, so nothing here can be injected by constructor type\n * alone — every dependency is named with an explicit `@Inject`.\n */\n\n/** The resolved `CanopyModuleOptions`. */\nexport const CANOPY_OPTIONS = \"CANOPY_OPTIONS\";\n\n/** The configured `Canopy` client. */\nexport const CANOPY_CLIENT = \"CANOPY_CLIENT\";\n\n/**\n * The configured `LocalAuthorizer`.\n *\n * Shared deliberately: it holds one copy of the hierarchy for the whole\n * process, so a second instance would double both the memory and the traffic\n * it exists to avoid.\n */\nexport const CANOPY_AUTHORIZER = \"CANOPY_AUTHORIZER\";\n\n/** The configured `TokenVerifier`, shared so its key cache is shared too. */\nexport const CANOPY_TOKEN_VERIFIER = \"CANOPY_TOKEN_VERIFIER\";\n\n/** Metadata key holding what `@RequirePermission` recorded on a handler. */\nexport const CANOPY_PERMISSION = \"CANOPY_PERMISSION\";\n\n/**\n * Metadata key `@AllowServiceTokens()` writes: a route or controller that\n * admits a machine client's `service` token beside the types the verifier\n * already accepts.\n */\nexport const CANOPY_ALLOW_SERVICE_TOKENS = \"CANOPY_ALLOW_SERVICE_TOKENS\";\n\n/**\n * Metadata key `@AllowDelegatedTokens()` writes: a route or controller that\n * admits a `delegated` token, a machine client acting for a person.\n */\nexport const CANOPY_ALLOW_DELEGATED_TOKENS = \"CANOPY_ALLOW_DELEGATED_TOKENS\";\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n InternalServerErrorException,\n Logger,\n ServiceUnavailableException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n authorizationErrorStatus,\n type LocalAuthorizer,\n type LocalDecision,\n type RequestBody,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport type { PermissionRequirement } from \"./require-permission.decorator.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_OPTIONS,\n CANOPY_PERMISSION,\n} from \"./tokens.js\";\n\n/** Read off the generated operation, so it follows the API rather than restating it. */\ntype EvaluateQuery = RequestBody<\"ApiPermissionsController_evaluate\">;\n\n/**\n * The verdict and, on a denial, the reason the grant roots and the tree can\n * give; not the API's full explain payload. A decision reached in-process\n * cannot report `granting_roles` or an effective node — that reasoning lives\n * on the server — and typing the narrow thing keeps that honest.\n */\ntype Verdict = LocalDecision;\n\ninterface Cancellation {\n signal: AbortSignal;\n dispose: () => void;\n}\n\n/** The Node stream underneath an Express or Fastify response. */\ninterface ClosableResponse {\n once: (event: string, listener: () => void) => unknown;\n removeListener: (event: string, listener: () => void) => unknown;\n writableEnded?: boolean;\n raw?: ClosableResponse;\n}\n\nfunction isClosable(value: unknown): value is ClosableResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ClosableResponse).once === \"function\" &&\n typeof (value as ClosableResponse).removeListener === \"function\"\n );\n}\n\n/**\n * Find the Node response stream behind whatever the adapter hands back.\n *\n * `.raw` is checked first and on its own merits, because the object Nest\n * returns is not always the stream. Express returns the `ServerResponse`\n * itself, which listens; Fastify returns a `Reply`, which is a plain object\n * with the real response on `.raw`. Testing the outer object first and\n * returning early on failure would skip `.raw` in exactly the case it exists\n * for.\n */\nfunction resolveStream(response: unknown): ClosableResponse | undefined {\n const raw = (response as { raw?: unknown } | null | undefined)?.raw;\n\n if (isClosable(raw)) {\n return raw;\n }\n\n if (isClosable(response)) {\n return response;\n }\n\n return undefined;\n}\n\n/**\n * Enforces `@RequirePermission` by asking Canopy, once, per guarded request.\n *\n * The guard fails closed at every step. An unresolvable identity, a `node`\n * check with no node, a denial, or an unreachable API all end the request —\n * there is no path through this class that allows a request whose decision is\n * unknown. That is the property worth protecting when reading this code: an\n * `allow` must be something Canopy actually said.\n *\n * A route with no requirement is allowed through untouched, so the guard can be\n * applied globally and opted into per route. Registered that way it runs before\n * controller- and route-scoped guards, so whatever authenticates the request has\n * to be registered globally ahead of it — otherwise `resolveIdentity` runs\n * before there is anything to resolve and every guarded route denies.\n */\n@Injectable()\nexport class CanopyGuard implements CanActivate {\n private readonly logger = new Logger(CanopyGuard.name);\n\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_AUTHORIZER) private readonly authorizer: LocalAuthorizer,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<\n PermissionRequirement | undefined\n >(CANOPY_PERMISSION, [context.getHandler(), context.getClass()]);\n\n if (!requirement) {\n return true;\n }\n\n const http = context.switchToHttp();\n const request: unknown = http.getRequest();\n const identityId = resolveSafely(this.options.resolveIdentity, request);\n\n if (!identityId) {\n throw new ForbiddenException(\n \"No identity on the request. Canopy cannot evaluate a permission without one.\",\n );\n }\n\n const decision = await this.evaluate(\n requirement,\n identityId,\n request,\n watchDisconnect(http),\n );\n\n if (!decision.allowed) {\n throw new ForbiddenException(\n `Caller does not hold ${requirement.permission}.`,\n );\n }\n\n return true;\n }\n\n /**\n * Asks Canopy the question the decorator recorded.\n *\n * Every failure is converted into a thrown exception rather than a `false`\n * decision, so a caller cannot mistake \"we could not tell\" for \"denied by\n * policy\" — and neither outcome lets the request proceed.\n */\n private async evaluate(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n cancellation: Cancellation | undefined,\n ): Promise<Verdict> {\n const actingClientId = this.actingClientOf(request);\n const query = {\n ...this.buildQuery(requirement, identityId, request),\n ...(this.isServiceToken(request)\n ? { principal_type: \"service\" as const }\n : {}),\n ...(actingClientId === undefined\n ? {}\n : { acting_client_id: actingClientId }),\n };\n\n try {\n // Answered in-process. The authorizer holds the identity's grant roots\n // and a shared copy of the hierarchy, so the common case reaches no\n // network at all; only a cold or expired entry does, and its deadline\n // and retries are bounded by the same options as before.\n return await this.authorizer.evaluate(\n query,\n cancellation ? { signal: cancellation.signal } : {},\n );\n } catch (error) {\n // The caller hung up mid-check. There is no one left to answer, and this\n // is not Canopy failing — so it must not be logged or reported as though\n // it were. Rethrowing the abort ends the request without inventing a\n // decision.\n if (cancellation?.signal.aborted) {\n throw error;\n }\n\n // Deliberately not re-thrown as-is: a failure here must not reach the\n // client as though Canopy had answered.\n this.logger.error(\n `Could not evaluate ${requirement.permission} for ${identityId}`,\n error instanceof Error ? error.stack : String(error),\n );\n\n throw this.toHttpException(error);\n } finally {\n cancellation?.dispose();\n }\n }\n\n /**\n * Turn a failed check into the status that describes it.\n *\n * Every branch denies — nothing here can let a request through — but they say\n * different things, and the difference is what makes an incident diagnosable.\n * Reporting a rejected API key as \"temporarily unavailable\" invites a retry\n * that will never succeed and hides a misconfiguration behind an outage. The\n * mapping is `authorizationErrorStatus` in `@canopy-io/node`, so an\n * integration outside NestJS answers the same way.\n */\n private toHttpException(error: unknown): Error {\n const { status, message } = authorizationErrorStatus(error);\n\n if (status === 403) {\n return new ForbiddenException(message);\n }\n\n if (status === 503) {\n return new ServiceUnavailableException(message);\n }\n\n return new InternalServerErrorException(message);\n }\n\n private buildQuery(\n requirement: PermissionRequirement,\n identityId: string,\n request: unknown,\n ): EvaluateQuery {\n if (requirement.scope === \"app_wide\") {\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"app_wide\",\n };\n }\n\n // An organization is a hierarchy node, and a membership is a role\n // assignment at it — so the org question IS the node question, asked at\n // the node the caller's token says it is acting in.\n if (requirement.scope === \"org\") {\n const orgId = this.resolveOrg(request);\n\n if (!orgId) {\n // Staff reach every organization but act in one only after entering\n // it, which the organization records and may refuse. The route's own\n // organization is never a stand-in for that entry.\n throw new ForbiddenException(\n this.isStaffToken(request)\n ? `No organization on the request. ${requirement.permission} is checked inside the caller's active organization; this staff session has not entered one, and enters with switch-organization.`\n : `No organization on the request. ${requirement.permission} is checked inside the caller's active organization, and this caller is not acting in one.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: orgId,\n };\n }\n\n const nodeId = this.options.resolveNode\n ? resolveSafely(this.options.resolveNode, request)\n : undefined;\n\n if (!nodeId) {\n throw new ForbiddenException(\n `No node on the request. ${requirement.permission} is checked at a node; configure resolveNode, or declare the route as app_wide if that is genuinely the question.`,\n );\n }\n\n return {\n identity_id: identityId,\n permission: requirement.permission,\n scope: \"node\",\n node_id: nodeId,\n };\n }\n\n /**\n * Whose grants answer the check: a machine client's when the verified token\n * `CanopyTokenGuard` attached is a `service` token, an identity's\n * otherwise. Read off the verified claims only, so a caller cannot choose\n * whose grants are consulted.\n */\n private isServiceToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { type?: unknown } | undefined)?.type === \"service\";\n }\n\n /**\n * The machine client acting for the identity, when the verified token is\n * `delegated`: its `act.sub`, so the check asks both. An empty string for a\n * delegated token naming no client, which the authorizer refuses; the\n * verifier refuses such a token first, so this is the second lock.\n */\n private actingClientOf(request: unknown): string | undefined {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ] as { type?: unknown; act?: { sub?: unknown } } | undefined;\n\n if (claims?.type !== \"delegated\") {\n return undefined;\n }\n\n const sub = claims.act?.sub;\n\n return typeof sub === \"string\" ? sub : \"\";\n }\n\n /** A staff token (`org_scope: \"all\"`), read off the verified claims only. */\n private isStaffToken(request: unknown): boolean {\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n return (claims as { org_scope?: unknown } | undefined)?.org_scope === \"all\";\n }\n\n /**\n * The organization the request acts in: `resolveOrg` when configured,\n * otherwise the `org_id` claim off the verified token `CanopyTokenGuard`\n * attached. Both sources trace back to a verified token — the org id\n * decides whose grants answer the check, so it must never be readable off\n * anything the caller controls directly.\n */\n private resolveOrg(request: unknown): string | null | undefined {\n if (this.options.resolveOrg) {\n return resolveSafely(this.options.resolveOrg, request);\n }\n\n const attachedAs = this.options.attachTokenAs ?? \"canopyToken\";\n const claims = (request as Record<string, unknown> | null | undefined)?.[\n attachedAs\n ];\n\n const orgId = (claims as { org_id?: unknown } | undefined)?.org_id;\n\n return typeof orgId === \"string\" && orgId !== \"\" ? orgId : undefined;\n }\n}\n\n/**\n * Run a resolver, treating a throw as \"could not resolve\".\n *\n * Resolvers reach into the request — `request.user.sub` is the shape the docs\n * suggest and the one most applications write. On an unauthenticated request\n * `request.user` is undefined and that expression throws, which without this\n * would surface as a 500. An identity that cannot be established is exactly the\n * request that must be denied, so it becomes the same 403 as returning nothing.\n */\nfunction resolveSafely(\n resolve: (request: never) => string | null | undefined,\n request: unknown,\n): string | null | undefined {\n try {\n return (resolve as (request: unknown) => string | null | undefined)(\n request,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Abort the permission check if the caller hangs up while it is in flight.\n *\n * Watches the *response*, not the request. A request stream emits `close` on\n * every normal request once its body has been read, so listening there would\n * abort perfectly healthy checks; a response emits `close` before\n * `writableEnded` only when nothing was ever sent — which is exactly the\n * disconnect case. The `writableEnded` re-check at fire time keeps that true\n * even if the ordering differs by adapter.\n *\n * Returns undefined for a transport with no such response — a GraphQL or\n * microservice context — where the check simply runs to its deadline.\n */\nfunction watchDisconnect(http: {\n getResponse?: () => unknown;\n}): Cancellation | undefined {\n const raw = resolveStream(http.getResponse?.());\n\n if (!raw) {\n return undefined;\n }\n\n const controller = new AbortController();\n\n const onClose = () => {\n if (raw.writableEnded === true) {\n return;\n }\n\n controller.abort(\n new DOMException(\"The client closed the request\", \"AbortError\"),\n );\n };\n\n raw.once(\"close\", onClose);\n\n return {\n signal: controller.signal,\n dispose: () => raw.removeListener(\"close\", onClose),\n };\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n ServiceUnavailableException,\n UnauthorizedException,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport {\n type CanopyTokenClaims,\n isCanopyTokenError,\n tokenErrorStatus,\n TokenVerifier,\n} from \"@canopy-io/node\";\n\nimport type { CanopyModuleOptions } from \"./options.js\";\nimport {\n CANOPY_ALLOW_DELEGATED_TOKENS,\n CANOPY_ALLOW_SERVICE_TOKENS,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * A request `CanopyTokenGuard` has run on: the verified claims under\n * `canopyToken` (or the module's `attachTokenAs`). `TCustom` names the\n * Environment's custom claims, each optional, so a handler reads them typed:\n *\n * ```ts\n * @Get(\"export\")\n * export(@Req() request: CanopyTokenRequest<{ plan?: \"free\" | \"pro\" }>) {\n * if (request.canopyToken?.plan !== \"pro\") {\n * throw new ForbiddenException();\n * }\n * }\n * ```\n */\nexport interface CanopyTokenRequest<TCustom extends object = object> {\n canopyToken?: CanopyTokenClaims & TCustom;\n}\n\n/**\n * Verifies the bearer token and attaches its claims to the request.\n *\n * This is the authentication half, and it is opt-in on purpose. `CanopyGuard`\n * answers \"may this identity do this?\"; something has to have established\n * *which* identity first, and `resolveIdentity` says as much — \"usually a\n * claim off the verified access token your auth layer already attached\".\n *\n * Use this guard when Canopy issues your tokens and you have no auth layer\n * yet. Skip it entirely if you already run Passport or your own JWT\n * middleware — it is additive, and nothing else in the package depends on it.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @RequirePermission(\"documents.read\")\n * findAll() {}\n * ```\n *\n * Order matters: this must run first, because `CanopyGuard` reads what it\n * attaches. Nest runs guards left to right, so listing them in that order is\n * the whole of the wiring.\n *\n * Claims land on `request.canopyToken` by default, which is why\n * `resolveIdentity` is usually `(req) => req.canopyToken?.sub`. The property\n * is configurable so it cannot collide with a `request.user` an existing\n * middleware already owns.\n *\n * A machine client's `service` token is refused unless the route or its\n * controller carries `@AllowServiceTokens()`: a route built for people must\n * not admit a machine by accident. A `delegated` token, a machine client\n * acting for a person, is refused unless it carries `@AllowDelegatedTokens()`.\n */\n@Injectable()\nexport class CanopyTokenGuard implements CanActivate {\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(CANOPY_TOKEN_VERIFIER) private readonly verifier: TokenVerifier,\n @Inject(CANOPY_OPTIONS)\n private readonly options: CanopyModuleOptions<unknown>,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<{\n headers?: Record<string, string | string[] | undefined>;\n [key: string]: unknown;\n }>();\n\n const token = readBearerToken(request.headers?.[\"authorization\"]);\n\n if (token === null) {\n throw new UnauthorizedException(\n \"Missing bearer token in the Authorization header.\",\n );\n }\n\n const admits = (key: string): boolean =>\n this.reflector.getAllAndOverride<boolean | undefined>(key, [\n context.getHandler(),\n context.getClass(),\n ]) === true;\n const alsoAllow: CanopyTokenClaims[\"type\"][] = [\n ...(admits(CANOPY_ALLOW_SERVICE_TOKENS) ? [\"service\" as const] : []),\n ...(admits(CANOPY_ALLOW_DELEGATED_TOKENS) ? [\"delegated\" as const] : []),\n ];\n\n let claims: CanopyTokenClaims;\n\n try {\n claims = await this.verifier.verify(\n token,\n alsoAllow.length > 0 ? { alsoAllow } : {},\n );\n } catch (error) {\n // Not being able to verify is not the same as failing to verify. When\n // the key set cannot be read the caller's token may be perfectly good —\n // we simply cannot say — so this is ours to own, exactly as the\n // permission guard answers 503 rather than denying on an undecidable\n // check.\n //\n // Reporting it as 401 would be worse than merely inaccurate: a client\n // reads 401 as \"your token is stale\", discards a valid one and asks for\n // another, which aims a refresh storm at the issuer that is already\n // down. And an outage that only ever emits 4xx is invisible to anything\n // watching 5xx.\n if (!isCanopyTokenError(error)) {\n throw error;\n }\n\n const { status, message } = tokenErrorStatus(error);\n\n if (status === 503) {\n throw new ServiceUnavailableException(message, { cause: error });\n }\n\n // Every other cause is the token itself, and a 401 whatever the detail:\n // the caller cannot fix a bad signature by being granted something. The\n // specific code stays on the error for logs rather than going to the\n // caller, who has no use for the difference and should not be told which\n // check failed.\n throw new UnauthorizedException(message, { cause: error });\n }\n\n request[this.options.attachTokenAs ?? \"canopyToken\"] = claims;\n\n return true;\n }\n}\n\n/**\n * The token out of an `Authorization: Bearer …` header.\n *\n * Returns null rather than throwing so the caller owns the message. The scheme\n * is matched case-insensitively because RFC 7235 says it is case-insensitive,\n * and clients do send `bearer`.\n */\nfunction readBearerToken(header: string | string[] | undefined): string | null {\n const value = Array.isArray(header) ? header[0] : header;\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n // Split by hand rather than with `/^bearer\\s+(.+)$/i`: the header is the\n // caller's to write, and that pattern backtracks on a long run of spaces.\n const trimmed = value.trim();\n const scheme = trimmed.slice(0, 6);\n const separator = trimmed.charAt(6);\n\n if (scheme.toLowerCase() !== \"bearer\" || !/\\s/.test(separator)) {\n return null;\n }\n\n const token = trimmed.slice(7).trim();\n\n return token.length > 0 ? token : null;\n}\n","import { type DynamicModule, Module, type Provider } from \"@nestjs/common\";\n\nimport { Canopy, LocalAuthorizer, TokenVerifier } from \"@canopy-io/node\";\n\nimport { CanopyGuard } from \"./canopy.guard.js\";\nimport { CanopyTokenGuard } from \"./canopy-token.guard.js\";\nimport type {\n CanopyModuleAsyncOptions,\n CanopyModuleOptions,\n} from \"./options.js\";\nimport {\n CANOPY_AUTHORIZER,\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n} from \"./tokens.js\";\n\n/**\n * Wires one configured `Canopy` client and the guard that uses it into a Nest\n * application.\n *\n * ```ts\n * CanopyModule.forRoot<AuthedRequest>({\n * apiKey: process.env.CANOPY_API_KEY,\n * resolveIdentity: (request) => request.user?.sub,\n * resolveNode: (request) => request.params?.orgId,\n * })\n * ```\n *\n * The client is a singleton because it holds no per-request state — it is a\n * `fetch` wrapper with credentials — so there is nothing to gain from building\n * one per request and a connection pool to lose.\n */\n\n/**\n * Per-attempt deadline for a cache miss on the request path.\n *\n * Five seconds rather than the client's 30: this call sits on the request path,\n * so its deadline is time an inbound request spends waiting. An authorization\n * service that has not answered in five seconds is not going to save the\n * request.\n */\nconst DEFAULT_EVALUATE_TIMEOUT_MS = 5_000;\n\n/**\n * Retries for a cache miss on the request path.\n *\n * One, not the client's two. A deadline bounds an attempt; this bounds how many\n * of them an inbound request can wait through. One retry still absorbs a\n * transient blip, and caps the worst case at roughly two deadlines rather than\n * three.\n */\nconst DEFAULT_EVALUATE_MAX_RETRIES = 1;\n\n/**\n * The authorizer both registration paths build.\n *\n * The guard's `evaluateTimeoutMs` / `evaluateMaxRetries` still apply, but to\n * far fewer calls: they bound a cache miss rather than every request.\n */\nfunction buildAuthorizer<TRequest>(\n client: Canopy,\n options: CanopyModuleOptions<TRequest>,\n): LocalAuthorizer {\n return new LocalAuthorizer(client.client, {\n ...(options.authorizationTtlMs === undefined\n ? {}\n : { ttlMs: options.authorizationTtlMs }),\n timeoutMs: options.evaluateTimeoutMs ?? DEFAULT_EVALUATE_TIMEOUT_MS,\n maxRetries: options.evaluateMaxRetries ?? DEFAULT_EVALUATE_MAX_RETRIES,\n ...(options.onDecision === undefined\n ? {}\n : { onDecision: options.onDecision }),\n ...(options.onDenied === undefined ? {} : { onDenied: options.onDenied }),\n });\n}\n\n@Module({})\nexport class CanopyModule {\n static forRoot<TRequest = unknown>(\n options: CanopyModuleOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n { provide: CANOPY_OPTIONS, useValue: options },\n {\n provide: CANOPY_CLIENT,\n useFactory: () => new Canopy(options),\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: () => new TokenVerifier(options.verify),\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy) => buildAuthorizer(client, options),\n inject: [CANOPY_CLIENT],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n\n /**\n * The same wiring when the API key comes from something injectable, such as\n * `ConfigService`, rather than being available at module-definition time.\n */\n static forRootAsync<TRequest = unknown>(\n options: CanopyModuleAsyncOptions<TRequest>,\n ): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CANOPY_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: CANOPY_CLIENT,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new Canopy(resolved),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_TOKEN_VERIFIER,\n useFactory: (resolved: CanopyModuleOptions<TRequest>) =>\n new TokenVerifier(resolved.verify),\n inject: [CANOPY_OPTIONS],\n },\n {\n provide: CANOPY_AUTHORIZER,\n useFactory: (client: Canopy, resolved: CanopyModuleOptions<TRequest>) =>\n buildAuthorizer(client, resolved),\n inject: [CANOPY_CLIENT, CANOPY_OPTIONS],\n },\n CanopyGuard,\n CanopyTokenGuard,\n ];\n\n return {\n module: CanopyModule,\n global: options.isGlobal ?? false,\n // Spread rather than assigned: under exactOptionalPropertyTypes an\n // explicit `imports: undefined` is not the same as no `imports` at all.\n ...(options.imports ? { imports: options.imports } : {}),\n providers,\n exports: [\n CANOPY_CLIENT,\n CANOPY_OPTIONS,\n CANOPY_TOKEN_VERIFIER,\n CANOPY_AUTHORIZER,\n CanopyGuard,\n CanopyTokenGuard,\n ],\n };\n }\n}\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_DELEGATED_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client acting for a person on this route or controller.\n *\n * A machine client with token exchange on trades a signed-in person's access\n * token for a `delegated` one: `sub` is the person, `act.sub` the client.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route never\n * lets an agent act for someone by accident. Here it is accepted beside the\n * types the verifier already allows, and `CanopyGuard` allows the request\n * only when the person and the client both hold the permission.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowDelegatedTokens()\n * @RequirePermission(\"deals.read\", { scope: \"org\" })\n * @Get()\n * list() {}\n * ```\n *\n * The verifier holds a delegated token to `verify.serviceAudience`, as it\n * does a service token. Read `request.canopyToken.act?.sub` in the handler\n * to record which client acted.\n */\nexport const AllowDelegatedTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_DELEGATED_TOKENS, true);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_ALLOW_SERVICE_TOKENS } from \"./tokens.js\";\n\n/**\n * Admit a machine client's token on this route or controller.\n *\n * A machine client obtains a token for itself with the `client_credentials`\n * grant; its `type` is `service` and its `sub` is the client's `client_id`.\n * `CanopyTokenGuard` refuses such a token everywhere else, so a route built\n * for people never admits a machine by accident. Here it is accepted beside\n * the types the verifier already allows, and `CanopyGuard` authorizes it from\n * the client's own grants.\n *\n * ```ts\n * @UseGuards(CanopyTokenGuard, CanopyGuard)\n * @AllowServiceTokens()\n * @RequirePermission(\"orders.import\", { scope: \"org\" })\n * @Post(\"import\")\n * import() {}\n * ```\n *\n * Read `request.canopyToken.type` in the handler when people and machines\n * should be treated differently.\n */\nexport const AllowServiceTokens = (): MethodDecorator & ClassDecorator =>\n SetMetadata(CANOPY_ALLOW_SERVICE_TOKENS, true);\n","import { Inject } from \"@nestjs/common\";\n\nimport { CANOPY_CLIENT } from \"./tokens.js\";\n\n/**\n * Injects the configured client.\n *\n * ```ts\n * constructor(@InjectCanopy() private readonly canopy: Canopy) {}\n * ```\n *\n * Named rather than resolved by type because this package is bundled with\n * esbuild, which emits no `design:paramtypes` — so type-only injection would\n * fail at runtime with a confusing \"cannot resolve dependency\" rather than at\n * build time.\n */\nexport const InjectCanopy = (): ParameterDecorator => Inject(CANOPY_CLIENT);\n","import { SetMetadata } from \"@nestjs/common\";\n\nimport { CANOPY_PERMISSION } from \"./tokens.js\";\n\n/**\n * Which question the guard asks Canopy.\n *\n * `node` walks the node's lineage, so a role granted on an ancestor is\n * inherited at the node being touched. `app_wide` asks only whether the\n * identity holds the permission anywhere in the Environment. `org` is the\n * node question asked at the organization the caller's token is acting in —\n * the `org_id` claim — so the route needs no `resolveNode` and no node in\n * its path.\n */\nexport type PermissionScope = \"node\" | \"app_wide\" | \"org\";\n\n/** What `@RequirePermission` records for the guard to read back. */\nexport interface PermissionRequirement {\n readonly permission: string;\n readonly scope: PermissionScope;\n}\n\nexport interface RequirePermissionOptions {\n /**\n * Defaults to `node`.\n *\n * `app_wide` is opt-in on purpose. It answers a coarser question and returns\n * no effective node, which makes it right for deciding whether to render a\n * menu item and wrong for guarding a resource that belongs to one — a\n * distinction that is easy to get backwards if the looser check is the\n * default.\n *\n * `org` evaluates at the organization on the caller's verified token\n * (`org_id`), read from the claims `CanopyTokenGuard` attaches or from\n * `resolveOrg` if configured. A caller acting in no organization is denied\n * — an org-scoped route has no meaning outside one.\n */\n readonly scope?: PermissionScope;\n}\n\n/**\n * Require a Canopy permission before a route runs.\n *\n * ```ts\n * @UseGuards(CanopyGuard)\n * @RequirePermission(\"orders.refund\")\n * @Post(\":orderId/refund\")\n * refund() {}\n * ```\n *\n * Applies to a single handler or to a whole controller; a handler's own\n * requirement wins over its controller's.\n */\nexport const RequirePermission = (\n permission: string,\n options: RequirePermissionOptions = {},\n): MethodDecorator & ClassDecorator =>\n SetMetadata<string, PermissionRequirement>(CANOPY_PERMISSION, {\n permission,\n scope: options.scope ?? \"node\",\n });\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canopy-io/nestjs",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "Official NestJS integration for Canopy \u2014 hierarchical identity and access management.",
5
5
  "license": "MIT",
6
6
  "author": "Canopy Identity Inc.",
@@ -62,7 +62,7 @@
62
62
  "test:watch": "vitest"
63
63
  },
64
64
  "dependencies": {
65
- "@canopy-io/node": "^0.21.0"
65
+ "@canopy-io/node": "^0.22.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "@nestjs/common": "^10.0.0 || ^11.0.0",