@canopy-io/node 0.15.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/dist/index.cjs CHANGED
@@ -288,13 +288,13 @@ var CanopyClient = class {
288
288
  if (response.status === 204) {
289
289
  return void 0;
290
290
  }
291
- const text = await response.text();
292
- if (text === "") {
291
+ const text2 = await response.text();
292
+ if (text2 === "") {
293
293
  return void 0;
294
294
  }
295
295
  let parsed;
296
296
  try {
297
- parsed = JSON.parse(text);
297
+ parsed = JSON.parse(text2);
298
298
  } catch {
299
299
  throw new CanopyError(
300
300
  {
@@ -330,15 +330,15 @@ var CanopyClient = class {
330
330
  return new CanopyError(body, { method, path }, retryAfter ?? void 0);
331
331
  }
332
332
  };
333
- function parseRetryAfter(header) {
334
- if (!header) {
333
+ function parseRetryAfter(header2) {
334
+ if (!header2) {
335
335
  return null;
336
336
  }
337
- const seconds = Number(header);
337
+ const seconds = Number(header2);
338
338
  if (Number.isFinite(seconds)) {
339
339
  return Math.max(0, seconds * 1e3);
340
340
  }
341
- const date = Date.parse(header);
341
+ const date = Date.parse(header2);
342
342
  if (Number.isNaN(date)) {
343
343
  return null;
344
344
  }
@@ -1193,6 +1193,113 @@ var Canopy = class {
1193
1193
  }
1194
1194
  };
1195
1195
 
1196
+ // src/invalidation.ts
1197
+ var NO_ACCESS_CHANGE = /* @__PURE__ */ new Set([
1198
+ "identity.created",
1199
+ "identity.updated",
1200
+ "account_member.added",
1201
+ "account_member.removed",
1202
+ "session.all_revoked",
1203
+ "oauth_client.secret_rotated",
1204
+ "organization.updated",
1205
+ "organization.policy.updated",
1206
+ "organization.sso_connection.bound",
1207
+ "organization.sso_connection.unbound",
1208
+ // A pushed group grants nothing until it is mapped, which is its own event.
1209
+ "scim.group.created"
1210
+ ]);
1211
+ var IDENTITY_RESOURCE = /* @__PURE__ */ new Set([
1212
+ "identity.status_set",
1213
+ "identity.erased",
1214
+ "identity.env_membership.added",
1215
+ "identity.env_membership.removed",
1216
+ "scim.user.provisioned",
1217
+ "scim.user.updated",
1218
+ "scim.user.deprovisioned",
1219
+ "scim.user.reactivated"
1220
+ ]);
1221
+ var ONE_ASSIGNMENT = /* @__PURE__ */ new Set([
1222
+ "assignment.created",
1223
+ "assignment.updated",
1224
+ "assignment.removed",
1225
+ "assignment.activated",
1226
+ "assignment.expired"
1227
+ ]);
1228
+ var AFFECTED_ASSIGNMENTS = /* @__PURE__ */ new Set([
1229
+ "assignment.bulk_removed",
1230
+ "assignment.bulk_role_changed"
1231
+ ]);
1232
+ var IDENTITY_IN_METADATA = /* @__PURE__ */ new Set([
1233
+ "organization.member.added",
1234
+ "organization.member.role_changed",
1235
+ "organization.member.removed",
1236
+ "scim.group.member_added",
1237
+ "scim.group.member_removed"
1238
+ ]);
1239
+ var MACHINE_CLIENT = /* @__PURE__ */ new Set([
1240
+ "oauth_client.updated",
1241
+ "oauth_client.deleted"
1242
+ ]);
1243
+ function holderOf(metadata) {
1244
+ const identityId = text(metadata["identity_id"]);
1245
+ if (identityId) {
1246
+ return { principalType: "identity", id: identityId };
1247
+ }
1248
+ const clientId = text(metadata["client_id"]);
1249
+ if (clientId) {
1250
+ return { principalType: "service", id: clientId };
1251
+ }
1252
+ return void 0;
1253
+ }
1254
+ function invalidationFor(change) {
1255
+ const { event, data } = change;
1256
+ const metadata = data.metadata ?? {};
1257
+ if (NO_ACCESS_CHANGE.has(event)) {
1258
+ return "none";
1259
+ }
1260
+ if (IDENTITY_RESOURCE.has(event)) {
1261
+ const id = data.resource_type === "identity" ? text(data.resource_id) : "";
1262
+ return id ? [{ principalType: "identity", id }] : "all";
1263
+ }
1264
+ if (ONE_ASSIGNMENT.has(event)) {
1265
+ const holder = holderOf(metadata);
1266
+ return holder ? [holder] : "all";
1267
+ }
1268
+ if (AFFECTED_ASSIGNMENTS.has(event)) {
1269
+ const affected = Array.isArray(metadata["affected"]) ? metadata["affected"] : [];
1270
+ const holders = affected.map(
1271
+ (entry) => entry !== null && typeof entry === "object" ? holderOf(entry) : void 0
1272
+ );
1273
+ if (holders.length === 0 || holders.some((holder) => !holder)) {
1274
+ return "all";
1275
+ }
1276
+ return unique(holders);
1277
+ }
1278
+ if (IDENTITY_IN_METADATA.has(event)) {
1279
+ const id = text(metadata["identity_id"]);
1280
+ return id ? [{ principalType: "identity", id }] : "all";
1281
+ }
1282
+ if (MACHINE_CLIENT.has(event)) {
1283
+ const clientId = text(metadata["client_id"]);
1284
+ return clientId ? [{ principalType: "service", id: clientId }] : "all";
1285
+ }
1286
+ if (event === "deny.created" || event === "deny.deleted") {
1287
+ const id = metadata["target_type"] === "identity" ? text(metadata["identity_id"]) : "";
1288
+ return id ? [{ principalType: "identity", id }] : "all";
1289
+ }
1290
+ return "all";
1291
+ }
1292
+ function text(value) {
1293
+ return typeof value === "string" ? value : "";
1294
+ }
1295
+ function unique(subjects) {
1296
+ const seen = /* @__PURE__ */ new Map();
1297
+ for (const subject of subjects) {
1298
+ seen.set(`${subject.principalType}:${subject.id}`, subject);
1299
+ }
1300
+ return [...seen.values()];
1301
+ }
1302
+
1196
1303
  // src/authorizer.ts
1197
1304
  var DEFAULT_TTL_MS = 6e4;
1198
1305
  var MAX_TTL_MS = 3e5;
@@ -1201,7 +1308,9 @@ var MAX_WALK_DEPTH = 256;
1201
1308
  var PAGE_SIZE = 100;
1202
1309
  var MAX_PAGES = 1e4;
1203
1310
  var MAX_TREE_WALKS = 3;
1204
- var KNOWN_MODEL_VERSIONS = /* @__PURE__ */ new Set([1]);
1311
+ var CHANGES_PATH = "/api/v1/changes";
1312
+ var CHANGES_PAGE_SIZE = 200;
1313
+ var KNOWN_MODEL_VERSIONS = /* @__PURE__ */ new Set([1, 2]);
1205
1314
  function understood(page, path) {
1206
1315
  if (!KNOWN_MODEL_VERSIONS.has(page.model_version)) {
1207
1316
  throw new CanopyAuthorizerError(
@@ -1220,6 +1329,17 @@ function inEffect(window, now) {
1220
1329
  function reasonAmong(windows, now) {
1221
1330
  return windows.some((window) => window.to !== null && window.to <= now) ? "expired" : "not_yet_effective";
1222
1331
  }
1332
+ function refusedOn(denied, lineage) {
1333
+ if (!denied) {
1334
+ return false;
1335
+ }
1336
+ for (const node of lineage) {
1337
+ if (denied.has(node)) {
1338
+ return true;
1339
+ }
1340
+ }
1341
+ return false;
1342
+ }
1223
1343
  var LocalAuthorizer = class {
1224
1344
  client;
1225
1345
  ttlMs;
@@ -1240,6 +1360,13 @@ var LocalAuthorizer = class {
1240
1360
  */
1241
1361
  pendingGrants = /* @__PURE__ */ new Map();
1242
1362
  pendingTree;
1363
+ /**
1364
+ * Bumped by every full invalidation. A hierarchy read that began before
1365
+ * the bump answers the caller that was waiting on it but is not kept, so
1366
+ * a read already in flight when a change lands cannot cache what the
1367
+ * change replaced. Grants use the pending map for the same purpose.
1368
+ */
1369
+ treeGeneration = 0;
1243
1370
  stats = {
1244
1371
  grantFetches: 0,
1245
1372
  grantPages: 0,
@@ -1317,55 +1444,63 @@ var LocalAuthorizer = class {
1317
1444
  * that keeps a closure table or a materialised path: it filters by "beneath
1318
1445
  * one of these" without an expanded set.
1319
1446
  *
1447
+ * A grant a deny refuses (a deny root at its node or above it) is left out,
1448
+ * and a deny root beneath a root is named in `excludedRoots`, so the filter
1449
+ * becomes "beneath one of the roots and not beneath an excluded one".
1450
+ * `envWide` holds only while nothing is excluded.
1451
+ *
1320
1452
  * Reads the tree, since minimality and `envWide` are questions about it; a
1321
1453
  * root the readable hierarchy does not contain raises
1322
1454
  * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1323
1455
  */
1324
1456
  async grantRoots(identityId, permission, subject = {}) {
1325
1457
  const now = this.now();
1326
- const held = (await this.grantRootsFor(
1458
+ const holdings = await this.grantRootsFor(
1327
1459
  identityId,
1328
1460
  subject.principalType ?? "identity"
1329
- )).get(permission) ?? [];
1461
+ );
1330
1462
  const granted = new Set(
1331
- held.filter((window) => inEffect(window, now)).map((w) => w.node)
1463
+ (holdings.roots.get(permission) ?? []).filter((window) => inEffect(window, now)).map((w) => w.node)
1332
1464
  );
1333
1465
  if (granted.size === 0) {
1334
- return { roots: [], envWide: false };
1466
+ return { roots: [], excludedRoots: [], envWide: false };
1335
1467
  }
1468
+ const denied = holdings.denies.get(permission);
1336
1469
  const { parents } = await this.treeEntry();
1337
1470
  const roots = [];
1338
- let envWide = false;
1471
+ let rootGranted = false;
1339
1472
  for (const node of granted) {
1340
1473
  if (!parents.has(node)) {
1341
1474
  throw this.hierarchyIncomplete(node);
1342
1475
  }
1343
- if (parents.get(node) === null) {
1344
- envWide = true;
1476
+ const path = this.lineage(parents, node);
1477
+ if (refusedOn(denied, path)) {
1478
+ continue;
1345
1479
  }
1346
- let covered = false;
1347
- let depth = 0;
1348
- for (let current = parents.get(node); current && depth < MAX_WALK_DEPTH; current = parents.get(current), depth += 1) {
1349
- if (granted.has(current)) {
1350
- covered = true;
1351
- break;
1352
- }
1480
+ if (parents.get(node) === null) {
1481
+ rootGranted = true;
1353
1482
  }
1354
- if (!covered) {
1483
+ if (!path.slice(1).some((n) => granted.has(n))) {
1355
1484
  roots.push(node);
1356
1485
  }
1357
1486
  }
1358
- return { roots, envWide };
1487
+ const excludedRoots = this.excludedBeneath(parents, denied, roots);
1488
+ return {
1489
+ roots,
1490
+ excludedRoots,
1491
+ envWide: rootGranted && excludedRoots.length === 0
1492
+ };
1359
1493
  }
1360
1494
  /**
1361
1495
  * Where the identity may act with the permission, as the set a list query
1362
- * filters by: {@link grantRoots} expanded through their descendants, up to
1363
- * `maxNodes` (the authorizer's default unless given here).
1496
+ * filters by: {@link grantRoots} expanded through their descendants, the
1497
+ * subtrees beneath `excludedRoots` left out, up to `maxNodes` (the
1498
+ * authorizer's default unless given here).
1364
1499
  *
1365
1500
  * Past the cap `nodes` is null and `complete` false: the set is too large
1366
- * to be worth an `IN (...)` list, and the caller filters by `roots`
1367
- * instead. An `envWide` answer carries no set either, since every node
1368
- * qualifies and a filter would only slow the query down.
1501
+ * to be worth an `IN (...)` list, and the caller filters by `roots` and
1502
+ * `excludedRoots` instead. An `envWide` answer carries no set either, since
1503
+ * every node qualifies and a filter would only slow the query down.
1369
1504
  *
1370
1505
  * Computed from the same cached grant roots and tree a check uses, so a
1371
1506
  * list filtered by it and the check on a write cannot disagree, and it goes
@@ -1373,32 +1508,55 @@ var LocalAuthorizer = class {
1373
1508
  */
1374
1509
  async accessibleNodes(identityId, permission, options = {}) {
1375
1510
  const cap = options.maxNodes ?? this.maxNodes;
1376
- const { roots, envWide } = await this.grantRoots(identityId, permission, {
1377
- ...options.principalType ? { principalType: options.principalType } : {}
1378
- });
1511
+ const { roots, excludedRoots, envWide } = await this.grantRoots(
1512
+ identityId,
1513
+ permission,
1514
+ {
1515
+ ...options.principalType ? { principalType: options.principalType } : {}
1516
+ }
1517
+ );
1379
1518
  if (envWide) {
1380
- return { roots, envWide: true, nodes: null, complete: true };
1519
+ return {
1520
+ roots,
1521
+ excludedRoots,
1522
+ envWide: true,
1523
+ nodes: null,
1524
+ complete: true
1525
+ };
1381
1526
  }
1382
1527
  if (roots.length === 0) {
1383
- return { roots, envWide: false, nodes: /* @__PURE__ */ new Set(), complete: true };
1528
+ return {
1529
+ roots,
1530
+ excludedRoots,
1531
+ envWide: false,
1532
+ nodes: /* @__PURE__ */ new Set(),
1533
+ complete: true
1534
+ };
1384
1535
  }
1385
1536
  const { children } = await this.treeEntry();
1537
+ const excluded = new Set(excludedRoots);
1386
1538
  const nodes = /* @__PURE__ */ new Set();
1387
1539
  const pending = [...roots];
1388
1540
  while (pending.length > 0) {
1389
1541
  const node = pending.pop();
1390
- if (nodes.has(node)) {
1542
+ if (nodes.has(node) || excluded.has(node)) {
1391
1543
  continue;
1392
1544
  }
1393
1545
  nodes.add(node);
1394
1546
  if (nodes.size > cap) {
1395
- return { roots, envWide: false, nodes: null, complete: false };
1547
+ return {
1548
+ roots,
1549
+ excludedRoots,
1550
+ envWide: false,
1551
+ nodes: null,
1552
+ complete: false
1553
+ };
1396
1554
  }
1397
1555
  for (const child of children.get(node) ?? []) {
1398
1556
  pending.push(child);
1399
1557
  }
1400
1558
  }
1401
- return { roots, envWide: false, nodes, complete: true };
1559
+ return { roots, excludedRoots, envWide: false, nodes, complete: true };
1402
1560
  }
1403
1561
  /**
1404
1562
  * Whether the identity holds the permission anywhere at or beneath a node,
@@ -1409,7 +1567,9 @@ var LocalAuthorizer = class {
1409
1567
  * `roots` is `[subtreeRootId]` when a grant at the node or above it reaches
1410
1568
  * the whole subtree; otherwise the topmost granted nodes inside it, the
1411
1569
  * ones no other granted node inside it already covers. A list query filters
1412
- * by "beneath one of these".
1570
+ * by "beneath one of these and not beneath one of `excludedRoots`", the
1571
+ * deny roots inside them. A deny at the node or above it refuses the whole
1572
+ * subtree, and a grant a deny refuses counts for nothing.
1413
1573
  *
1414
1574
  * **A read for menus and lists, never a guard.** Holding the permission
1415
1575
  * somewhere in the subtree says nothing about the record a write touches:
@@ -1422,34 +1582,48 @@ var LocalAuthorizer = class {
1422
1582
  */
1423
1583
  async holdsAnywhereUnder(identityId, permission, subtreeRootId, subject = {}) {
1424
1584
  const now = this.now();
1425
- const held = (await this.grantRootsFor(
1585
+ const holdings = await this.grantRootsFor(
1426
1586
  identityId,
1427
1587
  subject.principalType ?? "identity"
1428
- )).get(permission) ?? [];
1588
+ );
1429
1589
  const granted = new Set(
1430
- held.filter((window) => inEffect(window, now)).map((w) => w.node)
1590
+ (holdings.roots.get(permission) ?? []).filter((window) => inEffect(window, now)).map((w) => w.node)
1431
1591
  );
1592
+ const denied = holdings.denies.get(permission);
1432
1593
  const { parents } = await this.treeEntry();
1433
1594
  if (!parents.has(subtreeRootId)) {
1434
1595
  throw this.hierarchyIncomplete(subtreeRootId);
1435
1596
  }
1436
- if (granted.size === 0) {
1437
- return { held: false, roots: [] };
1597
+ const above = this.lineage(parents, subtreeRootId);
1598
+ if (granted.size === 0 || refusedOn(denied, above)) {
1599
+ return { held: false, roots: [], excludedRoots: [] };
1438
1600
  }
1439
- if (this.lineage(parents, subtreeRootId).some((n) => granted.has(n))) {
1440
- return { held: true, roots: [subtreeRootId] };
1601
+ if (above.some((n) => granted.has(n))) {
1602
+ return {
1603
+ held: true,
1604
+ roots: [subtreeRootId],
1605
+ excludedRoots: this.excludedBeneath(parents, denied, [subtreeRootId])
1606
+ };
1441
1607
  }
1442
1608
  const roots = [];
1443
1609
  for (const node of granted) {
1444
1610
  if (!parents.has(node)) {
1445
1611
  throw this.hierarchyIncomplete(node);
1446
1612
  }
1447
- const above = this.lineage(parents, node).slice(1);
1448
- if (above.includes(subtreeRootId) && !above.some((n) => granted.has(n))) {
1613
+ const path = this.lineage(parents, node);
1614
+ if (refusedOn(denied, path)) {
1615
+ continue;
1616
+ }
1617
+ const ancestors = path.slice(1);
1618
+ if (ancestors.includes(subtreeRootId) && !ancestors.some((n) => granted.has(n))) {
1449
1619
  roots.push(node);
1450
1620
  }
1451
1621
  }
1452
- return { held: roots.length > 0, roots };
1622
+ return {
1623
+ held: roots.length > 0,
1624
+ roots,
1625
+ excludedRoots: this.excludedBeneath(parents, denied, roots)
1626
+ };
1453
1627
  }
1454
1628
  /** The node and every ancestor up to the root, nearest first. */
1455
1629
  lineage(parents, nodeId) {
@@ -1460,10 +1634,32 @@ var LocalAuthorizer = class {
1460
1634
  }
1461
1635
  return path;
1462
1636
  }
1637
+ /**
1638
+ * The deny roots strictly beneath one of `roots`: the subtrees a filter by
1639
+ * those roots has to cut out. A deny root at a root or above it never
1640
+ * reaches here, because that root was refused and left out.
1641
+ */
1642
+ excludedBeneath(parents, denied, roots) {
1643
+ if (!denied || roots.length === 0) {
1644
+ return [];
1645
+ }
1646
+ const rootSet = new Set(roots);
1647
+ const excluded = [];
1648
+ for (const node of denied) {
1649
+ if (!parents.has(node)) {
1650
+ throw this.hierarchyIncomplete(node);
1651
+ }
1652
+ if (this.lineage(parents, node).slice(1).some((n) => rootSet.has(n))) {
1653
+ excluded.push(node);
1654
+ }
1655
+ }
1656
+ return excluded;
1657
+ }
1463
1658
  /**
1464
1659
  * Every permission the identity holds at the node, by grant or by
1465
- * inheritance: the list a screen renders its controls from, answered from
1466
- * the same cached grant roots and tree a check uses.
1660
+ * inheritance, less those a deny refuses there: the list a screen renders
1661
+ * its controls from, answered from the same cached grant roots and tree a
1662
+ * check uses.
1467
1663
  */
1468
1664
  async permissionsAt(identityId, nodeId, subject = {}) {
1469
1665
  const answers = await this.permissionsAtMany(identityId, [nodeId], subject);
@@ -1476,7 +1672,7 @@ var LocalAuthorizer = class {
1476
1672
  */
1477
1673
  async permissionsAtMany(identityId, nodeIds, subject = {}) {
1478
1674
  const now = this.now();
1479
- const roots = await this.grantRootsFor(
1675
+ const holdings = await this.grantRootsFor(
1480
1676
  identityId,
1481
1677
  subject.principalType ?? "identity"
1482
1678
  );
@@ -1484,7 +1680,10 @@ var LocalAuthorizer = class {
1484
1680
  for (const nodeId of new Set(nodeIds)) {
1485
1681
  const path = await this.lineageOf(nodeId);
1486
1682
  const held = [];
1487
- for (const [permission, windows] of roots) {
1683
+ for (const [permission, windows] of holdings.roots) {
1684
+ if (refusedOn(holdings.denies.get(permission), path)) {
1685
+ continue;
1686
+ }
1488
1687
  if (windows.some(
1489
1688
  (window) => path.has(window.node) && inEffect(window, now)
1490
1689
  )) {
@@ -1497,19 +1696,34 @@ var LocalAuthorizer = class {
1497
1696
  }
1498
1697
  async decide(query) {
1499
1698
  const now = this.now();
1500
- const held = (await this.grantRootsFor(
1699
+ const holdings = await this.grantRootsFor(
1501
1700
  query.identity_id,
1502
1701
  query.principal_type ?? "identity"
1503
- )).get(query.permission);
1504
- if (!held || held.length === 0) {
1505
- return { allowed: false, reason: "permission_not_held" };
1506
- }
1702
+ );
1703
+ const held = holdings.roots.get(query.permission) ?? [];
1704
+ const denied = holdings.denies.get(query.permission);
1507
1705
  if ((query.scope ?? "node") === "app_wide") {
1508
- return held.some((window) => inEffect(window, now)) ? { allowed: true, reason: null } : { allowed: false, reason: reasonAmong(held, now) };
1706
+ if (held.length === 0) {
1707
+ return { allowed: false, reason: "permission_not_held" };
1708
+ }
1709
+ const standing = held.filter((window) => inEffect(window, now));
1710
+ if (standing.length === 0) {
1711
+ return { allowed: false, reason: reasonAmong(held, now) };
1712
+ }
1713
+ return await this.anyClearOf(denied, standing) ? { allowed: true, reason: null } : { allowed: false, reason: "denied" };
1714
+ }
1715
+ if (held.length === 0 && !denied) {
1716
+ return { allowed: false, reason: "permission_not_held" };
1509
1717
  }
1510
1718
  if (!query.node_id) {
1511
1719
  return { allowed: false, reason: "node_missing" };
1512
1720
  }
1721
+ if (denied && refusedOn(denied, await this.lineageOf(query.node_id))) {
1722
+ return { allowed: false, reason: "denied" };
1723
+ }
1724
+ if (held.length === 0) {
1725
+ return { allowed: false, reason: "permission_not_held" };
1726
+ }
1513
1727
  if (held.some(
1514
1728
  (window) => window.node === query.node_id && inEffect(window, now)
1515
1729
  )) {
@@ -1525,6 +1739,22 @@ var LocalAuthorizer = class {
1525
1739
  }
1526
1740
  return { allowed: false, reason: reasonAmong(reachable, now) };
1527
1741
  }
1742
+ /**
1743
+ * Whether one of the grants stands clear of every deny root: none at its
1744
+ * node or above it. A grant with a deny strictly beneath it still reaches
1745
+ * the rest of its subtree. Reads the tree only when there is a deny.
1746
+ */
1747
+ async anyClearOf(denied, windows) {
1748
+ if (!denied) {
1749
+ return true;
1750
+ }
1751
+ for (const window of windows) {
1752
+ if (!refusedOn(denied, await this.lineageOf(window.node))) {
1753
+ return true;
1754
+ }
1755
+ }
1756
+ return false;
1757
+ }
1528
1758
  /** Counters for observability — how much traffic the cache is actually saving. */
1529
1759
  snapshot() {
1530
1760
  return { ...this.stats };
@@ -1542,7 +1772,9 @@ var LocalAuthorizer = class {
1542
1772
  * With no argument, everything goes: grants and the hierarchy tree. Not
1543
1773
  * needed in normal operation, where entries expire on their own; useful in
1544
1774
  * tests and after a change whose reach you cannot name (a role's
1545
- * permissions edited, a role deactivated or reactivated, a node moved). A
1775
+ * permissions edited, a role deactivated or reactivated, a node moved, a
1776
+ * deny created or deleted, since a deny on a role binds everyone holding
1777
+ * it). A
1546
1778
  * deactivated role grants nothing to anyone holding it, so until the cache
1547
1779
  * is cleared or expires, its holders keep being allowed locally.
1548
1780
  *
@@ -1555,13 +1787,99 @@ var LocalAuthorizer = class {
1555
1787
  */
1556
1788
  invalidate(identityId, subject = {}) {
1557
1789
  if (identityId !== void 0) {
1558
- this.grants.delete(
1559
- subjectKey(subject.principalType ?? "identity", identityId)
1560
- );
1790
+ const key = subjectKey(subject.principalType ?? "identity", identityId);
1791
+ this.grants.delete(key);
1792
+ this.pendingGrants.delete(key);
1561
1793
  return;
1562
1794
  }
1563
1795
  this.grants.clear();
1796
+ this.pendingGrants.clear();
1564
1797
  this.tree = void 0;
1798
+ this.pendingTree = void 0;
1799
+ this.treeGeneration += 1;
1800
+ }
1801
+ /**
1802
+ * Drop what one change makes stale, from a webhook delivery or a
1803
+ * change-feed entry (the two share one shape). Answers what it dropped.
1804
+ *
1805
+ * A change naming whose access moved (an assignment, an Environment or
1806
+ * organization membership, an identity's status, a deny on one person,
1807
+ * a machine client disabled or deleted) drops those subjects' grants and
1808
+ * keeps everyone else's and the hierarchy warm. A change whose reach it
1809
+ * cannot name (a role, a permission, a node, the hierarchy schema, an
1810
+ * organization created or deleted, a deny on a role or a machine client,
1811
+ * a directory group mapped) drops everything. A change that moves no
1812
+ * one's access (a profile edit, a sign-in policy, a session revoked)
1813
+ * drops nothing. An event this SDK does not know drops everything.
1814
+ *
1815
+ * Check the delivery's signature first (`verifyWebhookSignature`): this
1816
+ * trusts what it is given. Like {@link invalidate}, it reaches this
1817
+ * process only; see there for what that means across several instances.
1818
+ */
1819
+ applyEvent(change) {
1820
+ const reach = invalidationFor(change);
1821
+ if (reach === "none") {
1822
+ return { event: change.event, invalidated: "none" };
1823
+ }
1824
+ if (reach === "all") {
1825
+ this.invalidate();
1826
+ return { event: change.event, invalidated: "all" };
1827
+ }
1828
+ for (const subject of reach) {
1829
+ this.invalidate(subject.id, { principalType: subject.principalType });
1830
+ }
1831
+ return { event: change.event, invalidated: "subjects", subjects: reach };
1832
+ }
1833
+ /**
1834
+ * Read `GET /api/v1/changes` from `cursor` to the newest change and apply
1835
+ * each one, as {@link applyEvent} would a webhook. Answers the cursor to
1836
+ * resume from next time.
1837
+ *
1838
+ * Two uses. After a restart, to catch up on deliveries a process missed
1839
+ * while it was down, before it serves from a cache warmed elsewhere. And
1840
+ * in place of webhooks: every instance polling on an interval shorter
1841
+ * than `ttlMs` sees every change, which a webhook (delivered to one
1842
+ * instance) does not give a fleet.
1843
+ *
1844
+ * The feed holds what the audit log retains, so a cursor older than that
1845
+ * resumes at the oldest change still held. Each page is one request; a
1846
+ * replay with no cursor walks the whole retained window once.
1847
+ */
1848
+ async replayChanges(options = {}) {
1849
+ let cursor = options.cursor ?? null;
1850
+ let changes = 0;
1851
+ let invalidatedAll = false;
1852
+ let subjectsInvalidated = 0;
1853
+ for (let page = 0; page < MAX_PAGES; page++) {
1854
+ const read = await this.client.request(
1855
+ "GET",
1856
+ CHANGES_PATH,
1857
+ {
1858
+ ...this.readOptions,
1859
+ query: {
1860
+ limit: CHANGES_PAGE_SIZE,
1861
+ ...cursor === null ? {} : { cursor }
1862
+ }
1863
+ }
1864
+ );
1865
+ for (const change of read.items) {
1866
+ const applied = this.applyEvent(change);
1867
+ changes += 1;
1868
+ if (applied.invalidated === "all") {
1869
+ invalidatedAll = true;
1870
+ }
1871
+ if (applied.invalidated === "subjects") {
1872
+ subjectsInvalidated += applied.subjects.length;
1873
+ }
1874
+ }
1875
+ const next = read.pagination.next_cursor;
1876
+ const caughtUp = read.items.length < CHANGES_PAGE_SIZE || next === null || next === cursor;
1877
+ cursor = next ?? cursor;
1878
+ if (caughtUp) {
1879
+ break;
1880
+ }
1881
+ }
1882
+ return { cursor, changes, invalidatedAll, subjectsInvalidated };
1565
1883
  }
1566
1884
  /** Fire the decision hooks, after the verdict and without waiting on them. */
1567
1885
  announce(event) {
@@ -1604,14 +1922,20 @@ var LocalAuthorizer = class {
1604
1922
  const key = subjectKey(type, identityId);
1605
1923
  const cached = this.grants.get(key);
1606
1924
  if (cached && cached.expiresAt > this.now()) {
1607
- return cached.roots;
1925
+ return cached.holdings;
1608
1926
  }
1609
1927
  const pending = this.pendingGrants.get(key);
1610
1928
  if (pending) {
1611
1929
  return pending;
1612
1930
  }
1613
- const read = this.fetchGrantRoots(identityId, type).finally(() => {
1614
- this.pendingGrants.delete(key);
1931
+ const read = this.fetchGrantRoots(
1932
+ identityId,
1933
+ type,
1934
+ () => this.pendingGrants.get(key) === read
1935
+ ).finally(() => {
1936
+ if (this.pendingGrants.get(key) === read) {
1937
+ this.pendingGrants.delete(key);
1938
+ }
1615
1939
  });
1616
1940
  this.pendingGrants.set(key, read);
1617
1941
  return read;
@@ -1630,17 +1954,35 @@ var LocalAuthorizer = class {
1630
1954
  * `expired` or `not_yet_effective`, and the entry expires at the nearest
1631
1955
  * window boundary when that comes before the TTL, so a grant takes effect
1632
1956
  * or ends on time rather than up to `ttlMs` late.
1957
+ *
1958
+ * Every page carries the subject's deny roots whole, beside its rows; they
1959
+ * are gathered from each page, so a read is one snapshot of both.
1633
1960
  */
1634
- async fetchGrantRoots(identityId, type) {
1961
+ async fetchGrantRoots(identityId, type, stillCurrent = () => true) {
1635
1962
  this.stats.grantFetches += 1;
1636
1963
  const path = GRANTS_PATH(type, identityId);
1964
+ const denies = /* @__PURE__ */ new Map();
1637
1965
  const rows = paginate(
1638
1966
  (query) => {
1639
1967
  this.stats.grantPages += 1;
1640
1968
  return this.client.request("GET", path, {
1641
1969
  ...this.readOptions,
1642
1970
  query: { ...query, include: "windows" }
1643
- }).then((page) => understood(page, path));
1971
+ }).then((page) => {
1972
+ const read = understood(
1973
+ page,
1974
+ path
1975
+ ).denies;
1976
+ for (const deny of read ?? []) {
1977
+ const nodes = denies.get(deny.permission);
1978
+ if (nodes) {
1979
+ nodes.add(deny.node_id);
1980
+ } else {
1981
+ denies.set(deny.permission, /* @__PURE__ */ new Set([deny.node_id]));
1982
+ }
1983
+ }
1984
+ return page;
1985
+ });
1644
1986
  },
1645
1987
  { page: 1, take: PAGE_SIZE },
1646
1988
  { maxPages: MAX_PAGES }
@@ -1666,11 +2008,14 @@ var LocalAuthorizer = class {
1666
2008
  roots.set(row.permission, [window]);
1667
2009
  }
1668
2010
  }
1669
- this.grants.set(subjectKey(type, identityId), {
1670
- roots,
1671
- expiresAt: Math.min(now + this.ttlMs, boundary)
1672
- });
1673
- return roots;
2011
+ const holdings = { roots, denies };
2012
+ if (stillCurrent()) {
2013
+ this.grants.set(subjectKey(type, identityId), {
2014
+ holdings,
2015
+ expiresAt: Math.min(now + this.ttlMs, boundary)
2016
+ });
2017
+ }
2018
+ return holdings;
1674
2019
  }
1675
2020
  async treeEntry() {
1676
2021
  if (this.tree && this.tree.expiresAt > this.now()) {
@@ -1680,7 +2025,9 @@ var LocalAuthorizer = class {
1680
2025
  return this.pendingTree;
1681
2026
  }
1682
2027
  const read = this.fetchTree().finally(() => {
1683
- this.pendingTree = void 0;
2028
+ if (this.pendingTree === read) {
2029
+ this.pendingTree = void 0;
2030
+ }
1684
2031
  });
1685
2032
  this.pendingTree = read;
1686
2033
  return read;
@@ -1706,26 +2053,30 @@ var LocalAuthorizer = class {
1706
2053
  async fetchTree() {
1707
2054
  this.stats.treeRequests += 1;
1708
2055
  const held = this.tree;
2056
+ const generation = this.treeGeneration;
1709
2057
  let first = await this.parentsFirstPage(held?.etag ?? void 0);
1710
2058
  if (!first.modified) {
1711
2059
  if (held) {
1712
2060
  this.stats.treeNotModified += 1;
1713
- this.tree = { ...held, expiresAt: this.now() + this.ttlMs };
1714
- return this.tree;
2061
+ const renewed = { ...held, expiresAt: this.now() + this.ttlMs };
2062
+ if (generation === this.treeGeneration) {
2063
+ this.tree = renewed;
2064
+ }
2065
+ return renewed;
1715
2066
  }
1716
- return this.keepTree([], null);
2067
+ return this.keepTree([], null, generation);
1717
2068
  }
1718
2069
  for (let walk = 1; ; walk++) {
1719
2070
  const edges = await this.parentsRemainingPages(first.data);
1720
2071
  if (!spansPages(first.data) || first.etag === null) {
1721
- return this.keepTree(edges, first.etag);
2072
+ return this.keepTree(edges, first.etag, generation);
1722
2073
  }
1723
2074
  const confirm = await this.parentsFirstPage(first.etag);
1724
2075
  if (!confirm.modified) {
1725
- return this.keepTree(edges, first.etag);
2076
+ return this.keepTree(edges, first.etag, generation);
1726
2077
  }
1727
2078
  if (walk >= MAX_TREE_WALKS) {
1728
- return this.keepTree(edges, null);
2079
+ return this.keepTree(edges, null, generation);
1729
2080
  }
1730
2081
  first = confirm;
1731
2082
  }
@@ -1766,7 +2117,7 @@ var LocalAuthorizer = class {
1766
2117
  }
1767
2118
  return edges;
1768
2119
  }
1769
- keepTree(edges, etag) {
2120
+ keepTree(edges, etag, generation) {
1770
2121
  const ids = /* @__PURE__ */ new Map();
1771
2122
  for (const edge of edges) {
1772
2123
  ids.set(edge.id, edge.id);
@@ -1785,13 +2136,16 @@ var LocalAuthorizer = class {
1785
2136
  }
1786
2137
  }
1787
2138
  }
1788
- this.tree = {
2139
+ const entry = {
1789
2140
  parents,
1790
2141
  children,
1791
2142
  etag,
1792
2143
  expiresAt: this.now() + this.ttlMs
1793
2144
  };
1794
- return this.tree;
2145
+ if (generation === this.treeGeneration) {
2146
+ this.tree = entry;
2147
+ }
2148
+ return entry;
1795
2149
  }
1796
2150
  };
1797
2151
  function spansPages(first) {
@@ -1966,14 +2320,14 @@ var TokenVerifier = class {
1966
2320
  );
1967
2321
  }
1968
2322
  const [encodedHeader, encodedPayload, encodedSignature] = parts;
1969
- const header = decodeJsonSegment(encodedHeader, "header");
1970
- if (header.alg !== "RS256") {
2323
+ const header2 = decodeJsonSegment(encodedHeader, "header");
2324
+ if (header2.alg !== "RS256") {
1971
2325
  throw new CanopyTokenError(
1972
2326
  "token.unsupported_algorithm",
1973
- `Token is signed with "${header.alg ?? "none"}"; Canopy issues RS256.`
2327
+ `Token is signed with "${header2.alg ?? "none"}"; Canopy issues RS256.`
1974
2328
  );
1975
2329
  }
1976
- const key = await this.resolveKey(header.kid);
2330
+ const key = await this.resolveKey(header2.kid);
1977
2331
  const signed = new TextEncoder().encode(
1978
2332
  `${encodedHeader}.${encodedPayload}`
1979
2333
  );
@@ -2262,6 +2616,64 @@ var TokenVerifier = class {
2262
2616
  function isWebhookEvent(delivery, name) {
2263
2617
  return delivery.event === name;
2264
2618
  }
2619
+ var WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
2620
+ var SIGNATURE_PREFIX = "v1,";
2621
+ var SIGNATURE_HEX = /^[0-9a-f]{64}$/i;
2622
+ async function verifyWebhookSignature(input) {
2623
+ const id = header(input.headers, "x-canopy-webhook-id");
2624
+ const timestamp = header(input.headers, "x-canopy-timestamp");
2625
+ const signature = header(input.headers, "x-canopy-signature");
2626
+ if (!id || !timestamp || !signature || !/^\d+$/.test(timestamp)) {
2627
+ return false;
2628
+ }
2629
+ const tolerance = input.toleranceSeconds ?? WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS;
2630
+ const nowSeconds = Math.floor((input.now ?? Date.now)() / 1e3);
2631
+ if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) {
2632
+ return false;
2633
+ }
2634
+ const secrets = (typeof input.secret === "string" ? [input.secret] : input.secret).filter((secret) => typeof secret === "string" && secret.length > 0);
2635
+ const received = signature.split(/\s+/).filter((value) => value.startsWith(SIGNATURE_PREFIX)).map((value) => value.slice(SIGNATURE_PREFIX.length)).filter((hex) => SIGNATURE_HEX.test(hex)).map(hexToBytes);
2636
+ if (secrets.length === 0 || received.length === 0) {
2637
+ return false;
2638
+ }
2639
+ const encoder = new TextEncoder();
2640
+ const body = typeof input.rawBody === "string" ? encoder.encode(input.rawBody) : input.rawBody;
2641
+ const prefix = encoder.encode(`${id}.${timestamp}.`);
2642
+ const signed = new Uint8Array(new ArrayBuffer(prefix.length + body.length));
2643
+ signed.set(prefix, 0);
2644
+ signed.set(body, prefix.length);
2645
+ const checks = await Promise.all(
2646
+ secrets.flatMap((secret) => {
2647
+ const key = crypto.subtle.importKey(
2648
+ "raw",
2649
+ encoder.encode(secret),
2650
+ { name: "HMAC", hash: "SHA-256" },
2651
+ false,
2652
+ ["verify"]
2653
+ );
2654
+ return received.map(
2655
+ async (value) => crypto.subtle.verify("HMAC", await key, value, signed)
2656
+ );
2657
+ })
2658
+ );
2659
+ return checks.some(Boolean);
2660
+ }
2661
+ function header(headers, name) {
2662
+ if (typeof headers.get === "function") {
2663
+ return headers.get(name) ?? void 0;
2664
+ }
2665
+ const record = headers;
2666
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name);
2667
+ const value = key === void 0 ? void 0 : record[key];
2668
+ return Array.isArray(value) ? value.join(" ") : value;
2669
+ }
2670
+ function hexToBytes(hex) {
2671
+ const bytes = new Uint8Array(new ArrayBuffer(hex.length / 2));
2672
+ for (let i = 0; i < bytes.length; i++) {
2673
+ bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2674
+ }
2675
+ return bytes;
2676
+ }
2265
2677
 
2266
2678
  exports.Assignments = Assignments;
2267
2679
  exports.Canopy = Canopy;
@@ -2279,6 +2691,7 @@ exports.Paginator = Paginator;
2279
2691
  exports.Permissions = Permissions;
2280
2692
  exports.Roles = Roles;
2281
2693
  exports.TokenVerifier = TokenVerifier;
2694
+ exports.WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS;
2282
2695
  exports.authorizationErrorStatus = authorizationErrorStatus;
2283
2696
  exports.isCanopyAuthorizerError = isCanopyAuthorizerError;
2284
2697
  exports.isCanopyConnectionError = isCanopyConnectionError;
@@ -2289,6 +2702,7 @@ exports.isWebhookEvent = isWebhookEvent;
2289
2702
  exports.orgContext = orgContext;
2290
2703
  exports.paginate = paginate;
2291
2704
  exports.tokenErrorStatus = tokenErrorStatus;
2705
+ exports.verifyWebhookSignature = verifyWebhookSignature;
2292
2706
  exports.withConcurrency = withConcurrency;
2293
2707
  //# sourceMappingURL=index.cjs.map
2294
2708
  //# sourceMappingURL=index.cjs.map