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