@canopy-io/node 0.16.0 → 0.17.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,20 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.17.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3b4bc7f: Generated types follow the API as Canopy now publishes it. The spec has 199 operations.
8
+
9
+ - 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.
10
+ - 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.
11
+ - 5de853f: Webhooks reach the `LocalAuthorizer` cache, so a revocation lands on the next local check instead of waiting out `ttlMs`.
12
+
13
+ - `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.
14
+ - `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.
15
+ - `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.
16
+ - `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.
17
+
3
18
  ## 0.16.0
4
19
 
5
20
  ### 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.
@@ -203,8 +204,8 @@ beneath the organization. Authorize by evaluating, never by the list.
203
204
  A grant inside an organization counts only while the membership is active.
204
205
  The grants `LocalAuthorizer` caches already apply that: a deactivated
205
206
  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.
207
+ the authorizer sees it within the cache TTL, and at once when the
208
+ `organization.member.removed` webhook is passed to `authorizer.applyEvent`.
208
209
 
209
210
  Tokens also carry `amr`, how the session was proven (`pwd`, `otp` or `sso`,
210
211
  plus `mfa` once a second factor was verified), so a backend can insist on
@@ -260,29 +261,64 @@ const { token, base_url } = await canopy.organizations.mintDirectoryToken(
260
261
 
261
262
  ### Handling webhooks
262
263
 
264
+ Check every delivery's signature before acting on it, over the body exactly
265
+ as it arrived, then hand it to the authorizer and to your own handlers.
263
266
  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`.
267
+ it: narrow by event name and read that event's `metadata` without a cast.
266
268
 
267
269
  ```ts
268
- import { isWebhookEvent, type WebhookDelivery } from "@canopy-io/node";
270
+ import express from "express";
271
+ import {
272
+ isWebhookEvent,
273
+ verifyWebhookSignature,
274
+ type WebhookDelivery,
275
+ } from "@canopy-io/node";
276
+
277
+ app.post(
278
+ "/webhooks/canopy",
279
+ express.raw({ type: "application/json" }),
280
+ async (req, res) => {
281
+ const valid = await verifyWebhookSignature({
282
+ headers: req.headers,
283
+ rawBody: req.body,
284
+ secret: process.env.CANOPY_WEBHOOK_SECRET,
285
+ });
286
+
287
+ if (!valid) {
288
+ return res.sendStatus(401);
289
+ }
290
+
291
+ const delivery = JSON.parse(req.body.toString()) as WebhookDelivery;
292
+
293
+ authorizer.applyEvent(delivery);
294
+
295
+ if (isWebhookEvent(delivery, "organization.member.added")) {
296
+ const { identity_id, role_id } = delivery.data.metadata;
297
+ // ...
298
+ }
299
+
300
+ res.sendStatus(204);
301
+ },
302
+ );
303
+ ```
269
304
 
270
- app.post("/webhooks/canopy", (req, res) => {
271
- const delivery = req.body as WebhookDelivery;
305
+ `verifyWebhookSignature` resolves `false` for a missing header, a signature
306
+ that matches no secret, or an `X-Canopy-Timestamp` more than five minutes
307
+ from this machine's clock (`toleranceSeconds` changes it). For a while after
308
+ you rotate the secret the header carries two signatures, the new secret's
309
+ first, so a receiver still holding the old secret keeps verifying. To roll
310
+ the new secret out without a gap, pass both: `secret: [newSecret, oldSecret]`.
311
+ It runs on Web Crypto, so it works in edge workers as well as Node.
272
312
 
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
- ```
313
+ Deliveries are at least once. `X-Canopy-Webhook-Id` is the same across
314
+ retries: use it as an idempotency key for your own handlers. `applyEvent` is
315
+ safe to repeat.
281
316
 
282
317
  `WebhookEvent<"assignment.updated">` is the delivery of one event, and
283
318
  `WebhookEventName` is every event a subscription can receive. The API's
284
319
  `GET /api/v1/webhooks/event-types` names each event's schema in
285
- `payload_schema`.
320
+ `payload_schema`. A field the API adds arrives with the next
321
+ `npm run generate`.
286
322
 
287
323
  ### Authorizing without a call per request
288
324
 
@@ -320,7 +356,8 @@ and read again if the hierarchy changed while its pages were being read. At
320
356
  50,000 nodes a rebuild is 501 requests, and a revalidation is one.
321
357
 
322
358
  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,
359
+ change and it taking effect, including a moved node, unless a webhook or the
360
+ change feed drops them sooner (see "Revoking before the window lapses"). Set `ttlMs` to change it,
324
361
  up to five minutes (`300_000`); a longer value throws when the authorizer is
325
362
  created. Shortening it below the gap between a user's requests saves nothing:
326
363
  every request then finds the cache expired and refetches.
@@ -342,16 +379,17 @@ roles that spare it), so a check refuses with `denied` when a deny root for
342
379
  the permission is at the node or above it, before any grant is looked at. An
343
380
  `app_wide` check holds while one grant in effect stands clear of every deny.
344
381
  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.
382
+ reaches this authorizer within `ttlMs`, and at once through `applyEvent`,
383
+ which drops the one person a deny names and everything for a deny on a role,
384
+ since a deny on a role binds everyone holding it.
347
385
 
348
386
  A machine client's grants are its own, read from
349
387
  `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
350
388
  the client's `client_id` as `identity_id`; the list reads and `invalidate` take
351
389
  `{ principalType: "service" }`. The two kinds are cached apart, so a client
352
390
  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:
391
+ client carries its `client_id` in `data.metadata.client_id`, the id it is
392
+ cached under; `applyEvent` reads it from there. By hand:
355
393
 
356
394
  ```ts
357
395
  await authorizer.evaluate({
@@ -430,10 +468,52 @@ authorizer, as `canopy.identities.accessibleNodes(id, { permission })`.
430
468
 
431
469
  `canopy.permissions.evaluate` remains for a decision with no staleness at all.
432
470
 
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.
471
+ #### Revoking before the window lapses
472
+
473
+ `authorizer.applyEvent(delivery)` takes a webhook delivery and drops what
474
+ it makes stale, and answers what it dropped:
475
+
476
+ - A change naming whose access moved (an assignment, an Environment or
477
+ organization membership, an identity's status, a deny on one person, a
478
+ machine client disabled or deleted) drops those subjects' grants and keeps
479
+ everyone else's, and the hierarchy, warm.
480
+ - A change whose reach it cannot name (a role, a permission, a node, the
481
+ hierarchy schema, an organization created or deleted, a deny on a role, a
482
+ directory group mapped) drops everything.
483
+ - A change that moves no one's access (a profile edit, a sign-in policy, a
484
+ session revoked) drops nothing. An event this version does not know drops
485
+ everything, since guessing it harmless is the unsafe direction.
486
+
487
+ A check already reading from Canopy when the change lands answers from what
488
+ it read, but what it read is not kept, so the next check sees the change.
489
+
490
+ `authorizer.replayChanges({ cursor })` reads `GET /api/v1/changes` from
491
+ `cursor` to the newest change, applies each one the same way, and answers the
492
+ cursor to keep for next time. Run it at startup to catch up on what a process
493
+ missed while it was down, or on an interval in place of webhooks:
494
+
495
+ ```ts
496
+ let cursor: string | null = await loadCursor();
497
+
498
+ setInterval(async () => {
499
+ ({ cursor } = await authorizer.replayChanges({ cursor }));
500
+ await saveCursor(cursor);
501
+ }, 15_000);
502
+ ```
503
+
504
+ With no cursor it starts at the oldest change Canopy still retains, so the
505
+ first replay walks that window once.
506
+
507
+ A webhook reaches one process. With several instances behind a load
508
+ balancer, `applyEvent` drops the cache of the one that received it, and the
509
+ others keep theirs until their own TTL runs out. Either fan the delivery out
510
+ to every instance over your own pub/sub, or have every instance run
511
+ `replayChanges` on an interval shorter than `ttlMs`. Otherwise the TTL stays
512
+ the fleet-wide revocation guarantee.
513
+
514
+ `authorizer.invalidate(identityId)` remains for a change your own backend
515
+ makes and knows about: it drops one identity's cached grants, and with no
516
+ argument everything.
437
517
 
438
518
  A failed check (Canopy unreachable, a credential that cannot read the
439
519
  hierarchy, an identity not in the Environment, or a Canopy serving an