@canopy-io/node 0.16.0 → 0.18.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,30 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.18.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4a092d0: `CANOPY_BASE_URL` sets the Canopy origin for the whole process: `Canopy` and `CanopyClient` call it instead of the hosted API, and `TokenVerifier` resolves `environmentId` to an issuer under it. A self-hosted instance, a proxy or a test stack sets the one variable and keeps the code it would write for hosted Canopy. An explicit `baseUrl` or `issuer` still wins. Read through `globalThis`, so browsers, Workers and Deno are unaffected.
8
+
9
+ ### Patch Changes
10
+
11
+ - 056f64d: Generated types follow the API as Canopy now publishes it: an audit event carries `channel` (`"mcp"` for a change an AI assistant made through the account MCP server, `null` for a direct call), the audit event list takes a `channel` filter, and the API key scope list matches the current catalogue.
12
+
13
+ ## 0.17.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 3b4bc7f: Generated types follow the API as Canopy now publishes it. The spec has 199 operations.
18
+
19
+ - Access previews are stored: the node move and delete, role permission and organization node previews answer an `id` and `expires_at` with their counts and no longer carry `people`. The people are read from `GET /api/v1/access-previews/{previewId}/people`, or as CSV from `.../people.csv`, by the principal that made the preview. Code that read `people` from a preview's type reads the new route instead.
20
+ - Identities can be created with a password hash: `password_hash` and `password_hash_algorithm` on create and bulk create. The request schemas are now `ApiCreateIdentityDto` and `ApiBulkCreateIdentitiesDto` in `components["schemas"]`, so a reference to `CreateIdentityDto` or `BulkCreateIdentitiesDto` takes the new name.
21
+ - 5de853f: Webhooks reach the `LocalAuthorizer` cache, so a revocation lands on the next local check instead of waiting out `ttlMs`.
22
+
23
+ - `verifyWebhookSignature({ headers, rawBody, secret })` checks a delivery's `X-Canopy-Signature`: HMAC-SHA256 over `{id}.{timestamp}.{raw body}`, compared in constant time on Web Crypto, so it runs in edge workers as well as Node. It accepts either signature while a rotation's window is open, takes several secrets while you roll one out, and refuses a timestamp more than five minutes from the clock (`toleranceSeconds`). It resolves `false`, never rejects.
24
+ - `authorizer.applyEvent(delivery)` drops what a webhook delivery or change-feed entry makes stale and answers what it dropped: the subjects an assignment, membership, identity-status, single-person deny or machine-client change names; everything for a role, permission, node, schema, organization creation or deletion, role deny or directory group mapping; nothing for a change that moves no one's access. An event this version does not know drops everything.
25
+ - `authorizer.replayChanges({ cursor })` reads `GET /api/v1/changes` to the newest change, applies each, and answers the cursor to resume from: for catching up after a restart, or polled on every instance in place of webhooks.
26
+ - `invalidate` now also discards a read already in flight, so a check that began before a change cannot put the access it revoked back in the cache for a whole window.
27
+
3
28
  ## 0.16.0
4
29
 
5
30
  ### Minor Changes
package/README.md CHANGED
@@ -26,6 +26,7 @@ Despite the name, it is not Node-only: the client is `fetch` and nothing else, s
26
26
  - **Typed errors.** `CanopyError` carries a stable `code`, `CanopyConnectionError` marks a transport failure, `CanopyTokenError` a rejected token, `CanopyAuthorizerError` a check that could not be decided — each with a type guard.
27
27
  - **Local access-token verification.** `TokenVerifier` checks Canopy's RS256 signatures against the published key set: one JWKS fetch, then no network on any verification after it.
28
28
  - **Local authorization.** `LocalAuthorizer` answers permission checks in-process from an identity's grant roots and a shared copy of your hierarchy, so a check costs a walk up the tree rather than a round trip.
29
+ - **Webhooks wired to the cache.** `verifyWebhookSignature` checks a delivery in constant time, `authorizer.applyEvent` drops exactly what the change made stale, and `authorizer.replayChanges` catches up from the change feed.
29
30
  - **Conditional reads.** `requestConditional` sends the validator you already hold and tells you whether anything changed, so something expensive can be held and revalidated cheaply.
30
31
  - **Deadlines and cancellation.** A per-attempt timeout and a caller's own `AbortSignal`, settable client-wide or per call.
31
32
  - **Types generated from the published spec**, with CI failing on drift.
@@ -168,6 +169,11 @@ On a custom auth domain or a self-hosted instance, set `issuer` instead
168
169
  throws with neither. Getting it wrong fails closed: tokens are rejected, never
169
170
  mistakenly accepted.
170
171
 
172
+ A self-hosted instance can instead set `CANOPY_BASE_URL` once for the process:
173
+ the client calls it and `environmentId` resolves to an issuer under it, so the
174
+ code stays what it is on hosted Canopy. An explicit `baseUrl` or `issuer` still
175
+ wins.
176
+
171
177
  With an Environment's **organizations** container on, an identity token also
172
178
  names the organization the session is acting in and the roles held at that
173
179
  organization's node, by name and by id. Read them through `orgContext` rather
@@ -203,8 +209,8 @@ beneath the organization. Authorize by evaluating, never by the list.
203
209
  A grant inside an organization counts only while the membership is active.
204
210
  The grants `LocalAuthorizer` caches already apply that: a deactivated
205
211
  membership drops every grant inside the organization from the next read, so
206
- the authorizer sees it within the cache TTL, and sooner on
207
- `invalidate(identityId)` when an `organization.member.removed` webhook arrives.
212
+ the authorizer sees it within the cache TTL, and at once when the
213
+ `organization.member.removed` webhook is passed to `authorizer.applyEvent`.
208
214
 
209
215
  Tokens also carry `amr`, how the session was proven (`pwd`, `otp` or `sso`,
210
216
  plus `mfa` once a second factor was verified), so a backend can insist on
@@ -260,29 +266,64 @@ const { token, base_url } = await canopy.organizations.mintDirectoryToken(
260
266
 
261
267
  ### Handling webhooks
262
268
 
269
+ Check every delivery's signature before acting on it, over the body exactly
270
+ as it arrived, then hand it to the authorizer and to your own handlers.
263
271
  Every webhook event has a published schema, and the SDK types deliveries from
264
- it. Narrow by event name and read that event's `metadata` without a cast; a
265
- field the API adds arrives with the next `npm run generate`.
272
+ it: narrow by event name and read that event's `metadata` without a cast.
266
273
 
267
274
  ```ts
268
- import { isWebhookEvent, type WebhookDelivery } from "@canopy-io/node";
275
+ import express from "express";
276
+ import {
277
+ isWebhookEvent,
278
+ verifyWebhookSignature,
279
+ type WebhookDelivery,
280
+ } from "@canopy-io/node";
281
+
282
+ app.post(
283
+ "/webhooks/canopy",
284
+ express.raw({ type: "application/json" }),
285
+ async (req, res) => {
286
+ const valid = await verifyWebhookSignature({
287
+ headers: req.headers,
288
+ rawBody: req.body,
289
+ secret: process.env.CANOPY_WEBHOOK_SECRET,
290
+ });
291
+
292
+ if (!valid) {
293
+ return res.sendStatus(401);
294
+ }
295
+
296
+ const delivery = JSON.parse(req.body.toString()) as WebhookDelivery;
297
+
298
+ authorizer.applyEvent(delivery);
299
+
300
+ if (isWebhookEvent(delivery, "organization.member.added")) {
301
+ const { identity_id, role_id } = delivery.data.metadata;
302
+ // ...
303
+ }
304
+
305
+ res.sendStatus(204);
306
+ },
307
+ );
308
+ ```
269
309
 
270
- app.post("/webhooks/canopy", (req, res) => {
271
- const delivery = req.body as WebhookDelivery;
310
+ `verifyWebhookSignature` resolves `false` for a missing header, a signature
311
+ that matches no secret, or an `X-Canopy-Timestamp` more than five minutes
312
+ from this machine's clock (`toleranceSeconds` changes it). For a while after
313
+ you rotate the secret the header carries two signatures, the new secret's
314
+ first, so a receiver still holding the old secret keeps verifying. To roll
315
+ the new secret out without a gap, pass both: `secret: [newSecret, oldSecret]`.
316
+ It runs on Web Crypto, so it works in edge workers as well as Node.
272
317
 
273
- if (isWebhookEvent(delivery, "organization.member.added")) {
274
- const { identity_id, role_id } = delivery.data.metadata;
275
- // ...
276
- }
277
-
278
- res.sendStatus(204);
279
- });
280
- ```
318
+ Deliveries are at least once. `X-Canopy-Webhook-Id` is the same across
319
+ retries: use it as an idempotency key for your own handlers. `applyEvent` is
320
+ safe to repeat.
281
321
 
282
322
  `WebhookEvent<"assignment.updated">` is the delivery of one event, and
283
323
  `WebhookEventName` is every event a subscription can receive. The API's
284
324
  `GET /api/v1/webhooks/event-types` names each event's schema in
285
- `payload_schema`.
325
+ `payload_schema`. A field the API adds arrives with the next
326
+ `npm run generate`.
286
327
 
287
328
  ### Authorizing without a call per request
288
329
 
@@ -320,7 +361,8 @@ and read again if the hierarchy changed while its pages were being read. At
320
361
  50,000 nodes a rebuild is 501 requests, and a revalidation is one.
321
362
 
322
363
  Both are held for at most 60 seconds, which is the delay between an access
323
- change and it taking effect, including a moved node. Set `ttlMs` to change it,
364
+ change and it taking effect, including a moved node, unless a webhook or the
365
+ change feed drops them sooner (see "Revoking before the window lapses"). Set `ttlMs` to change it,
324
366
  up to five minutes (`300_000`); a longer value throws when the authorizer is
325
367
  created. Shortening it below the gap between a user's requests saves nothing:
326
368
  every request then finds the cache expired and refetches.
@@ -342,16 +384,17 @@ roles that spare it), so a check refuses with `denied` when a deny root for
342
384
  the permission is at the node or above it, before any grant is looked at. An
343
385
  `app_wide` check holds while one grant in effect stands clear of every deny.
344
386
  Denies ride the same cache and TTL as grants: a deny created or deleted
345
- reaches this authorizer within `ttlMs`, and `invalidate()` with no argument
346
- picks it up at once, since a deny on a role binds everyone holding it.
387
+ reaches this authorizer within `ttlMs`, and at once through `applyEvent`,
388
+ which drops the one person a deny names and everything for a deny on a role,
389
+ since a deny on a role binds everyone holding it.
347
390
 
348
391
  A machine client's grants are its own, read from
349
392
  `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
350
393
  the client's `client_id` as `identity_id`; the list reads and `invalidate` take
351
394
  `{ principalType: "service" }`. The two kinds are cached apart, so a client
352
395
  never answers from a person's grants. An assignment webhook naming a machine
353
- client carries its `client_id` in `data.metadata.client_id`, the id to
354
- invalidate:
396
+ client carries its `client_id` in `data.metadata.client_id`, the id it is
397
+ cached under; `applyEvent` reads it from there. By hand:
355
398
 
356
399
  ```ts
357
400
  await authorizer.evaluate({
@@ -430,10 +473,52 @@ authorizer, as `canopy.identities.accessibleNodes(id, { permission })`.
430
473
 
431
474
  `canopy.permissions.evaluate` remains for a decision with no staleness at all.
432
475
 
433
- `authorizer.invalidate(identityId)` drops one identity's cached grants, so
434
- the next check reads them fresh. It reaches only this process: with several
435
- instances behind a load balancer, each keeps its own cache until its TTL runs
436
- out or it is told to invalidate too.
476
+ #### Revoking before the window lapses
477
+
478
+ `authorizer.applyEvent(delivery)` takes a webhook delivery and drops what
479
+ it makes stale, and answers what it dropped:
480
+
481
+ - A change naming whose access moved (an assignment, an Environment or
482
+ organization membership, an identity's status, a deny on one person, a
483
+ machine client disabled or deleted) drops those subjects' grants and keeps
484
+ everyone else's, and the hierarchy, warm.
485
+ - A change whose reach it cannot name (a role, a permission, a node, the
486
+ hierarchy schema, an organization created or deleted, a deny on a role, a
487
+ directory group mapped) drops everything.
488
+ - A change that moves no one's access (a profile edit, a sign-in policy, a
489
+ session revoked) drops nothing. An event this version does not know drops
490
+ everything, since guessing it harmless is the unsafe direction.
491
+
492
+ A check already reading from Canopy when the change lands answers from what
493
+ it read, but what it read is not kept, so the next check sees the change.
494
+
495
+ `authorizer.replayChanges({ cursor })` reads `GET /api/v1/changes` from
496
+ `cursor` to the newest change, applies each one the same way, and answers the
497
+ cursor to keep for next time. Run it at startup to catch up on what a process
498
+ missed while it was down, or on an interval in place of webhooks:
499
+
500
+ ```ts
501
+ let cursor: string | null = await loadCursor();
502
+
503
+ setInterval(async () => {
504
+ ({ cursor } = await authorizer.replayChanges({ cursor }));
505
+ await saveCursor(cursor);
506
+ }, 15_000);
507
+ ```
508
+
509
+ With no cursor it starts at the oldest change Canopy still retains, so the
510
+ first replay walks that window once.
511
+
512
+ A webhook reaches one process. With several instances behind a load
513
+ balancer, `applyEvent` drops the cache of the one that received it, and the
514
+ others keep theirs until their own TTL runs out. Either fan the delivery out
515
+ to every instance over your own pub/sub, or have every instance run
516
+ `replayChanges` on an interval shorter than `ttlMs`. Otherwise the TTL stays
517
+ the fleet-wide revocation guarantee.
518
+
519
+ `authorizer.invalidate(identityId)` remains for a change your own backend
520
+ makes and knows about: it drops one identity's cached grants, and with no
521
+ argument everything.
437
522
 
438
523
  A failed check (Canopy unreachable, a credential that cannot read the
439
524
  hierarchy, an identity not in the Environment, or a Canopy serving an