@canopy-io/node 0.14.0 → 0.16.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,32 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7d31f2f: `LocalAuthorizer` understands authorization model version 2, which Canopy answers in an Environment that holds a deny. A deny refuses a permission to an identity, a machine client or a role's holders at a node and everything beneath it, whatever the grants allow. The grants read carries the subject's deny roots beside its grant roots, already resolved by Canopy (the roles it holds, the exception roles that spare it), and the authorizer applies them from the same cache and TTL:
8
+
9
+ - `evaluate` refuses with the new reason `denied` when a deny root for the permission is at the node or above it, before any grant is looked at. An `app_wide` check holds while one grant in effect stands clear of every deny, and is `denied` when none does. A check on a permission with a deny reads the tree even for a grant at the node itself.
10
+ - `grantRoots` and `accessibleNodes` leave out a root a deny refuses and name `excludedRoots`, the deny roots beneath a root, each cutting out its subtree. `accessibleNodes` leaves those subtrees out of `nodes`, and `envWide` is false while anything is excluded. A filter by roots must exclude `excludedRoots` too.
11
+ - `holdsAnywhereUnder` answers `{ held, roots, excludedRoots }`; a deny at the subtree's root or above it refuses the whole subtree.
12
+ - `permissionsAt` and `permissionsAtMany` leave out a permission a deny refuses at the node.
13
+
14
+ `LocalDenialReason` gains `denied`, so an exhaustive `switch` over it needs the new case. A version 1 answer, from a Canopy without denies, carries none and is read as before. The conformance bundle gains the `denies` vector, which the authorizer answers, and is published at model version 2.
15
+
16
+ The spec now has 197 operations. Generated types cover the Denies routes (`/api/v1/denies`: list, get, create, preview, reach, remove), unwrapped like the other management routes, `deny_id` on an evaluation refused by a deny, and the reads and previews released beside them.
17
+
18
+ ## 0.15.0
19
+
20
+ ### Minor Changes
21
+
22
+ - e957aa1: `authorizer.holdsAnywhereUnder(identityId, permission, subtreeRootId)` answers whether the identity holds the permission at a node or anywhere beneath it, as `{ held, roots }`: `roots` is the subtree root alone when a grant at or above it reaches the whole subtree, otherwise the topmost granted nodes inside it. It is the question a menu inside an organization asks, which `app_wide` cannot, since that covers the whole Environment. It is a read for menus and lists, never a guard: a write still checks the node it writes to. It answers from the same cached grants and tree as a check, takes `{ principalType: "service" }` like the other reads, and raises `authorizer.hierarchy_incomplete` for a node the readable hierarchy does not contain. The conformance bundle gains the `holds-anywhere-under` vector, which the authorizer answers.
23
+
24
+ Your own staff (identities holding a role at the Environment root) carry `org_scope: "all"` on their tokens, now typed on `CanopyTokenClaims`. `orgContext(claims)` gains `staff`, true when a staff session is inside a customer's organization. `canopy.organizations.listStaffActivity(id, query)` pages through every staff entry into an organization and every refusal, filtered by `kind` (`entered` or `refused`), searched by `q`, sorted by `created` or `actor`.
25
+
26
+ The spec now has 176 operations. Generated types cover the staff activity, the organization policy's `staff_entry`, and an organization's own roles and integrations, which stay unwrapped like its other delegated administration routes.
27
+
28
+ In `@canopy-io/nestjs`, `scope: "org"` still evaluates only at the token's `org_id`. A staff token that has not entered an organization is denied with a message saying it enters with `switch-organization`; the guard never takes the organization from the route, since entering is what the customer's organization records and may refuse.
29
+
3
30
  ## 0.14.0
4
31
 
5
32
  ### Minor Changes
package/README.md CHANGED
@@ -184,9 +184,17 @@ if (org) {
184
184
  org.orgId; // the organization — also a hierarchy node id
185
185
  org.orgRoles; // the roles held at its node, by name; [] for a member holding none there
186
186
  org.orgRoleIds; // the same roles' ids, in the same order
187
+ org.staff; // true for your staff inside a customer's organization
187
188
  }
188
189
  ```
189
190
 
191
+ Your own staff are identities holding a role at the Environment root. Their
192
+ tokens carry `org_scope: "all"`, and once one enters a customer's
193
+ organization `orgContext` answers with `staff: true` and the root roles as
194
+ `orgRoles`. The organization sees every entry in its staff activity
195
+ (`canopy.organizations.listStaffActivity(id)`) and can refuse staff
196
+ altogether, so say in your interface when a session is staff.
197
+
190
198
  `null` is an ordinary answer: every token from an Environment without the
191
199
  container on, and every identity that belongs to no organization yet. An empty
192
200
  `orgRoles` is not: membership is admission, and a member may hold roles only
@@ -319,13 +327,24 @@ every request then finds the cache expired and refetches.
319
327
 
320
328
  Each answer carries a reason when it is no, from what the grant roots and the
321
329
  tree can say: `permission_not_held`, `outside_grants`, `expired`,
322
- `not_yet_effective`, or `node_missing` for a `node` check with no node. The
330
+ `not_yet_effective`, `denied`, or `node_missing` for a `node` check with no
331
+ node. The
323
332
  grant roots are read with their windows, so a grant that ends sooner than the
324
333
  TTL is dropped at its boundary, not at the next expiry. `onDecision` and
325
334
  `onDenied` hooks hear every verdict after it is reached, never awaited and
326
335
  never able to change it, for audit trails and alerting without a fork of the
327
336
  guard.
328
337
 
338
+ A deny refuses a permission at a node and everything beneath it, whatever the
339
+ grants allow. The grants read carries the identity's deny roots beside its
340
+ grant roots, already resolved by Canopy (the roles it holds, the exception
341
+ roles that spare it), so a check refuses with `denied` when a deny root for
342
+ the permission is at the node or above it, before any grant is looked at. An
343
+ `app_wide` check holds while one grant in effect stands clear of every deny.
344
+ 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.
347
+
329
348
  A machine client's grants are its own, read from
330
349
  `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
331
350
  the client's `client_id` as `identity_id`; the list reads and `invalidate` take
@@ -355,13 +374,15 @@ const authorizer = new LocalAuthorizer(canopy.client, {
355
374
  A list needs the other direction: which nodes may this identity see. The same
356
375
  cache answers it, in the shape your query wants. `grantRoots` names the nodes
357
376
  the permission is granted at, in effect now, minus the ones another root
358
- already covers, and says whether one is the Environment's root (`envWide`:
359
- every node qualifies, so no filter). `accessibleNodes` expands those roots
360
- through their descendants into a `Set` for an `IN (...)` filter, capped at
361
- `maxNodes` (10,000 by default, per authorizer or per call); past the cap it
362
- hands back the roots with `nodes: null` and `complete: false`, so an
363
- application with a closure table or a materialised path filters by "beneath a
364
- root" instead. `permissionsAt` lists what the identity holds at one node, for
377
+ already covers or a deny refuses, and says whether one is the Environment's
378
+ root (`envWide`: every node qualifies, so no filter). `excludedRoots` names
379
+ the deny roots beneath those roots; each cuts out its subtree, and `envWide`
380
+ is false while there are any. `accessibleNodes` expands the roots through
381
+ their descendants, leaving the excluded subtrees out, into a `Set` for an
382
+ `IN (...)` filter, capped at `maxNodes` (10,000 by default, per authorizer or
383
+ per call); past the cap it hands back the roots with `nodes: null` and
384
+ `complete: false`, so an application with a closure table or a materialised
385
+ path filters by "beneath a root and not beneath an excluded root" instead. `permissionsAt` lists what the identity holds at one node, for
365
386
  rendering a screen's controls, and `permissionsAtMany` answers several nodes
366
387
  from one read, for the rows of a list.
367
388
 
@@ -373,12 +394,36 @@ if (access.envWide) {
373
394
  }
374
395
 
375
396
  if (!access.complete) {
376
- // Too large for an IN (...) list: filter beneath access.roots instead.
397
+ // Too large for an IN (...) list: filter beneath access.roots, and not
398
+ // beneath access.excludedRoots, instead.
377
399
  }
378
400
 
379
401
  return db.reports.findMany({ where: { nodeId: { in: [...access.nodes] } } });
380
402
  ```
381
403
 
404
+ A menu inside an organization asks something narrower: does this person
405
+ hold the permission anywhere in it? `app_wide` cannot say, since it covers the
406
+ whole Environment, so a grant in another organization would show the menu
407
+ here too. `holdsAnywhereUnder` answers for one subtree, with `roots` as the
408
+ subtree root alone when a grant at or above it reaches all of it, and
409
+ otherwise the topmost granted nodes inside it, with `excludedRoots` as the
410
+ deny roots inside those. A deny at the subtree's root or above it refuses the
411
+ whole subtree:
412
+
413
+ ```ts
414
+ const { held, roots } = await authorizer.holdsAnywhereUnder(
415
+ identityId,
416
+ "invoice.approve",
417
+ org.orgId,
418
+ );
419
+
420
+ // held: show the Invoices menu. roots: the teams whose invoices to list.
421
+ ```
422
+
423
+ It is a read for menus and lists, never a guard: holding the permission
424
+ somewhere in Acme approves no particular invoice, so the write checks the
425
+ invoice's own node.
426
+
382
427
  A list filtered this way is what to show; the write that follows still checks
383
428
  its node. Canopy answers the same question fresh, for a process without the
384
429
  authorizer, as `canopy.identities.accessibleNodes(id, { permission })`.
package/dist/index.cjs CHANGED
@@ -948,6 +948,30 @@ var Organizations = class {
948
948
  `/api/v1/organizations/${enc(id)}/directory/activity`
949
949
  );
950
950
  }
951
+ /**
952
+ * Every time your staff entered the organization or were refused, newest
953
+ * first: who, with which roles held at the Environment root, and why a
954
+ * refusal happened (`staff_entry_refused` while the organization's policy
955
+ * says `staff_entry: "refused"`).
956
+ *
957
+ * Paginated (20 per page by default, `take` up to 100), so this returns a
958
+ * `Paginator`. `kind` narrows to `entered` or `refused`; `q` searches who
959
+ * and the role names; `sort_by` is `created` (the default) or `actor`.
960
+ *
961
+ * ```ts
962
+ * for await (const entry of canopy.organizations.listStaffActivity(id)) { … }
963
+ * ```
964
+ */
965
+ listStaffActivity(id, query = {}) {
966
+ return paginate(
967
+ (params) => this.client.request(
968
+ "GET",
969
+ `/api/v1/organizations/${enc(id)}/staff-activity`,
970
+ { query: params }
971
+ ),
972
+ { ...query }
973
+ );
974
+ }
951
975
  /**
952
976
  * The groups the provider has pushed, each with its role mapping.
953
977
  *
@@ -1177,7 +1201,7 @@ var MAX_WALK_DEPTH = 256;
1177
1201
  var PAGE_SIZE = 100;
1178
1202
  var MAX_PAGES = 1e4;
1179
1203
  var MAX_TREE_WALKS = 3;
1180
- var KNOWN_MODEL_VERSIONS = /* @__PURE__ */ new Set([1]);
1204
+ var KNOWN_MODEL_VERSIONS = /* @__PURE__ */ new Set([1, 2]);
1181
1205
  function understood(page, path) {
1182
1206
  if (!KNOWN_MODEL_VERSIONS.has(page.model_version)) {
1183
1207
  throw new CanopyAuthorizerError(
@@ -1196,6 +1220,17 @@ function inEffect(window, now) {
1196
1220
  function reasonAmong(windows, now) {
1197
1221
  return windows.some((window) => window.to !== null && window.to <= now) ? "expired" : "not_yet_effective";
1198
1222
  }
1223
+ function refusedOn(denied, lineage) {
1224
+ if (!denied) {
1225
+ return false;
1226
+ }
1227
+ for (const node of lineage) {
1228
+ if (denied.has(node)) {
1229
+ return true;
1230
+ }
1231
+ }
1232
+ return false;
1233
+ }
1199
1234
  var LocalAuthorizer = class {
1200
1235
  client;
1201
1236
  ttlMs;
@@ -1293,55 +1328,63 @@ var LocalAuthorizer = class {
1293
1328
  * that keeps a closure table or a materialised path: it filters by "beneath
1294
1329
  * one of these" without an expanded set.
1295
1330
  *
1331
+ * A grant a deny refuses (a deny root at its node or above it) is left out,
1332
+ * and a deny root beneath a root is named in `excludedRoots`, so the filter
1333
+ * becomes "beneath one of the roots and not beneath an excluded one".
1334
+ * `envWide` holds only while nothing is excluded.
1335
+ *
1296
1336
  * Reads the tree, since minimality and `envWide` are questions about it; a
1297
1337
  * root the readable hierarchy does not contain raises
1298
1338
  * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1299
1339
  */
1300
1340
  async grantRoots(identityId, permission, subject = {}) {
1301
1341
  const now = this.now();
1302
- const held = (await this.grantRootsFor(
1342
+ const holdings = await this.grantRootsFor(
1303
1343
  identityId,
1304
1344
  subject.principalType ?? "identity"
1305
- )).get(permission) ?? [];
1345
+ );
1306
1346
  const granted = new Set(
1307
- held.filter((window) => inEffect(window, now)).map((w) => w.node)
1347
+ (holdings.roots.get(permission) ?? []).filter((window) => inEffect(window, now)).map((w) => w.node)
1308
1348
  );
1309
1349
  if (granted.size === 0) {
1310
- return { roots: [], envWide: false };
1350
+ return { roots: [], excludedRoots: [], envWide: false };
1311
1351
  }
1352
+ const denied = holdings.denies.get(permission);
1312
1353
  const { parents } = await this.treeEntry();
1313
1354
  const roots = [];
1314
- let envWide = false;
1355
+ let rootGranted = false;
1315
1356
  for (const node of granted) {
1316
1357
  if (!parents.has(node)) {
1317
1358
  throw this.hierarchyIncomplete(node);
1318
1359
  }
1319
- if (parents.get(node) === null) {
1320
- envWide = true;
1360
+ const path = this.lineage(parents, node);
1361
+ if (refusedOn(denied, path)) {
1362
+ continue;
1321
1363
  }
1322
- let covered = false;
1323
- let depth = 0;
1324
- for (let current = parents.get(node); current && depth < MAX_WALK_DEPTH; current = parents.get(current), depth += 1) {
1325
- if (granted.has(current)) {
1326
- covered = true;
1327
- break;
1328
- }
1364
+ if (parents.get(node) === null) {
1365
+ rootGranted = true;
1329
1366
  }
1330
- if (!covered) {
1367
+ if (!path.slice(1).some((n) => granted.has(n))) {
1331
1368
  roots.push(node);
1332
1369
  }
1333
1370
  }
1334
- return { roots, envWide };
1371
+ const excludedRoots = this.excludedBeneath(parents, denied, roots);
1372
+ return {
1373
+ roots,
1374
+ excludedRoots,
1375
+ envWide: rootGranted && excludedRoots.length === 0
1376
+ };
1335
1377
  }
1336
1378
  /**
1337
1379
  * Where the identity may act with the permission, as the set a list query
1338
- * filters by: {@link grantRoots} expanded through their descendants, up to
1339
- * `maxNodes` (the authorizer's default unless given here).
1380
+ * filters by: {@link grantRoots} expanded through their descendants, the
1381
+ * subtrees beneath `excludedRoots` left out, up to `maxNodes` (the
1382
+ * authorizer's default unless given here).
1340
1383
  *
1341
1384
  * Past the cap `nodes` is null and `complete` false: the set is too large
1342
- * to be worth an `IN (...)` list, and the caller filters by `roots`
1343
- * instead. An `envWide` answer carries no set either, since every node
1344
- * qualifies and a filter would only slow the query down.
1385
+ * to be worth an `IN (...)` list, and the caller filters by `roots` and
1386
+ * `excludedRoots` instead. An `envWide` answer carries no set either, since
1387
+ * every node qualifies and a filter would only slow the query down.
1345
1388
  *
1346
1389
  * Computed from the same cached grant roots and tree a check uses, so a
1347
1390
  * list filtered by it and the check on a write cannot disagree, and it goes
@@ -1349,37 +1392,158 @@ var LocalAuthorizer = class {
1349
1392
  */
1350
1393
  async accessibleNodes(identityId, permission, options = {}) {
1351
1394
  const cap = options.maxNodes ?? this.maxNodes;
1352
- const { roots, envWide } = await this.grantRoots(identityId, permission, {
1353
- ...options.principalType ? { principalType: options.principalType } : {}
1354
- });
1395
+ const { roots, excludedRoots, envWide } = await this.grantRoots(
1396
+ identityId,
1397
+ permission,
1398
+ {
1399
+ ...options.principalType ? { principalType: options.principalType } : {}
1400
+ }
1401
+ );
1355
1402
  if (envWide) {
1356
- return { roots, envWide: true, nodes: null, complete: true };
1403
+ return {
1404
+ roots,
1405
+ excludedRoots,
1406
+ envWide: true,
1407
+ nodes: null,
1408
+ complete: true
1409
+ };
1357
1410
  }
1358
1411
  if (roots.length === 0) {
1359
- return { roots, envWide: false, nodes: /* @__PURE__ */ new Set(), complete: true };
1412
+ return {
1413
+ roots,
1414
+ excludedRoots,
1415
+ envWide: false,
1416
+ nodes: /* @__PURE__ */ new Set(),
1417
+ complete: true
1418
+ };
1360
1419
  }
1361
1420
  const { children } = await this.treeEntry();
1421
+ const excluded = new Set(excludedRoots);
1362
1422
  const nodes = /* @__PURE__ */ new Set();
1363
1423
  const pending = [...roots];
1364
1424
  while (pending.length > 0) {
1365
1425
  const node = pending.pop();
1366
- if (nodes.has(node)) {
1426
+ if (nodes.has(node) || excluded.has(node)) {
1367
1427
  continue;
1368
1428
  }
1369
1429
  nodes.add(node);
1370
1430
  if (nodes.size > cap) {
1371
- return { roots, envWide: false, nodes: null, complete: false };
1431
+ return {
1432
+ roots,
1433
+ excludedRoots,
1434
+ envWide: false,
1435
+ nodes: null,
1436
+ complete: false
1437
+ };
1372
1438
  }
1373
1439
  for (const child of children.get(node) ?? []) {
1374
1440
  pending.push(child);
1375
1441
  }
1376
1442
  }
1377
- return { roots, envWide: false, nodes, complete: true };
1443
+ return { roots, excludedRoots, envWide: false, nodes, complete: true };
1444
+ }
1445
+ /**
1446
+ * Whether the identity holds the permission anywhere at or beneath a node,
1447
+ * and where: the question a menu inside an organization asks ("show
1448
+ * Invoices to someone who approves invoices for any team in Acme"), which
1449
+ * `app_wide` cannot answer because it covers the whole Environment.
1450
+ *
1451
+ * `roots` is `[subtreeRootId]` when a grant at the node or above it reaches
1452
+ * the whole subtree; otherwise the topmost granted nodes inside it, the
1453
+ * ones no other granted node inside it already covers. A list query filters
1454
+ * by "beneath one of these and not beneath one of `excludedRoots`", the
1455
+ * deny roots inside them. A deny at the node or above it refuses the whole
1456
+ * subtree, and a grant a deny refuses counts for nothing.
1457
+ *
1458
+ * **A read for menus and lists, never a guard.** Holding the permission
1459
+ * somewhere in the subtree says nothing about the record a write touches:
1460
+ * check the node the action writes to, with `evaluate`. No `scope` value
1461
+ * asks this question, on purpose.
1462
+ *
1463
+ * Computed from the same cached grant roots and tree a check uses. A grant
1464
+ * or a subtree root the readable hierarchy does not contain raises
1465
+ * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1466
+ */
1467
+ async holdsAnywhereUnder(identityId, permission, subtreeRootId, subject = {}) {
1468
+ const now = this.now();
1469
+ const holdings = await this.grantRootsFor(
1470
+ identityId,
1471
+ subject.principalType ?? "identity"
1472
+ );
1473
+ const granted = new Set(
1474
+ (holdings.roots.get(permission) ?? []).filter((window) => inEffect(window, now)).map((w) => w.node)
1475
+ );
1476
+ const denied = holdings.denies.get(permission);
1477
+ const { parents } = await this.treeEntry();
1478
+ if (!parents.has(subtreeRootId)) {
1479
+ throw this.hierarchyIncomplete(subtreeRootId);
1480
+ }
1481
+ const above = this.lineage(parents, subtreeRootId);
1482
+ if (granted.size === 0 || refusedOn(denied, above)) {
1483
+ return { held: false, roots: [], excludedRoots: [] };
1484
+ }
1485
+ if (above.some((n) => granted.has(n))) {
1486
+ return {
1487
+ held: true,
1488
+ roots: [subtreeRootId],
1489
+ excludedRoots: this.excludedBeneath(parents, denied, [subtreeRootId])
1490
+ };
1491
+ }
1492
+ const roots = [];
1493
+ for (const node of granted) {
1494
+ if (!parents.has(node)) {
1495
+ throw this.hierarchyIncomplete(node);
1496
+ }
1497
+ const path = this.lineage(parents, node);
1498
+ if (refusedOn(denied, path)) {
1499
+ continue;
1500
+ }
1501
+ const ancestors = path.slice(1);
1502
+ if (ancestors.includes(subtreeRootId) && !ancestors.some((n) => granted.has(n))) {
1503
+ roots.push(node);
1504
+ }
1505
+ }
1506
+ return {
1507
+ held: roots.length > 0,
1508
+ roots,
1509
+ excludedRoots: this.excludedBeneath(parents, denied, roots)
1510
+ };
1511
+ }
1512
+ /** The node and every ancestor up to the root, nearest first. */
1513
+ lineage(parents, nodeId) {
1514
+ const path = [];
1515
+ let depth = 0;
1516
+ for (let current = nodeId; current && depth < MAX_WALK_DEPTH; current = parents.get(current), depth += 1) {
1517
+ path.push(current);
1518
+ }
1519
+ return path;
1520
+ }
1521
+ /**
1522
+ * The deny roots strictly beneath one of `roots`: the subtrees a filter by
1523
+ * those roots has to cut out. A deny root at a root or above it never
1524
+ * reaches here, because that root was refused and left out.
1525
+ */
1526
+ excludedBeneath(parents, denied, roots) {
1527
+ if (!denied || roots.length === 0) {
1528
+ return [];
1529
+ }
1530
+ const rootSet = new Set(roots);
1531
+ const excluded = [];
1532
+ for (const node of denied) {
1533
+ if (!parents.has(node)) {
1534
+ throw this.hierarchyIncomplete(node);
1535
+ }
1536
+ if (this.lineage(parents, node).slice(1).some((n) => rootSet.has(n))) {
1537
+ excluded.push(node);
1538
+ }
1539
+ }
1540
+ return excluded;
1378
1541
  }
1379
1542
  /**
1380
1543
  * Every permission the identity holds at the node, by grant or by
1381
- * inheritance: the list a screen renders its controls from, answered from
1382
- * the same cached grant roots and tree a check uses.
1544
+ * inheritance, less those a deny refuses there: the list a screen renders
1545
+ * its controls from, answered from the same cached grant roots and tree a
1546
+ * check uses.
1383
1547
  */
1384
1548
  async permissionsAt(identityId, nodeId, subject = {}) {
1385
1549
  const answers = await this.permissionsAtMany(identityId, [nodeId], subject);
@@ -1392,7 +1556,7 @@ var LocalAuthorizer = class {
1392
1556
  */
1393
1557
  async permissionsAtMany(identityId, nodeIds, subject = {}) {
1394
1558
  const now = this.now();
1395
- const roots = await this.grantRootsFor(
1559
+ const holdings = await this.grantRootsFor(
1396
1560
  identityId,
1397
1561
  subject.principalType ?? "identity"
1398
1562
  );
@@ -1400,7 +1564,10 @@ var LocalAuthorizer = class {
1400
1564
  for (const nodeId of new Set(nodeIds)) {
1401
1565
  const path = await this.lineageOf(nodeId);
1402
1566
  const held = [];
1403
- for (const [permission, windows] of roots) {
1567
+ for (const [permission, windows] of holdings.roots) {
1568
+ if (refusedOn(holdings.denies.get(permission), path)) {
1569
+ continue;
1570
+ }
1404
1571
  if (windows.some(
1405
1572
  (window) => path.has(window.node) && inEffect(window, now)
1406
1573
  )) {
@@ -1413,19 +1580,34 @@ var LocalAuthorizer = class {
1413
1580
  }
1414
1581
  async decide(query) {
1415
1582
  const now = this.now();
1416
- const held = (await this.grantRootsFor(
1583
+ const holdings = await this.grantRootsFor(
1417
1584
  query.identity_id,
1418
1585
  query.principal_type ?? "identity"
1419
- )).get(query.permission);
1420
- if (!held || held.length === 0) {
1421
- return { allowed: false, reason: "permission_not_held" };
1422
- }
1586
+ );
1587
+ const held = holdings.roots.get(query.permission) ?? [];
1588
+ const denied = holdings.denies.get(query.permission);
1423
1589
  if ((query.scope ?? "node") === "app_wide") {
1424
- return held.some((window) => inEffect(window, now)) ? { allowed: true, reason: null } : { allowed: false, reason: reasonAmong(held, now) };
1590
+ if (held.length === 0) {
1591
+ return { allowed: false, reason: "permission_not_held" };
1592
+ }
1593
+ const standing = held.filter((window) => inEffect(window, now));
1594
+ if (standing.length === 0) {
1595
+ return { allowed: false, reason: reasonAmong(held, now) };
1596
+ }
1597
+ return await this.anyClearOf(denied, standing) ? { allowed: true, reason: null } : { allowed: false, reason: "denied" };
1598
+ }
1599
+ if (held.length === 0 && !denied) {
1600
+ return { allowed: false, reason: "permission_not_held" };
1425
1601
  }
1426
1602
  if (!query.node_id) {
1427
1603
  return { allowed: false, reason: "node_missing" };
1428
1604
  }
1605
+ if (denied && refusedOn(denied, await this.lineageOf(query.node_id))) {
1606
+ return { allowed: false, reason: "denied" };
1607
+ }
1608
+ if (held.length === 0) {
1609
+ return { allowed: false, reason: "permission_not_held" };
1610
+ }
1429
1611
  if (held.some(
1430
1612
  (window) => window.node === query.node_id && inEffect(window, now)
1431
1613
  )) {
@@ -1441,6 +1623,22 @@ var LocalAuthorizer = class {
1441
1623
  }
1442
1624
  return { allowed: false, reason: reasonAmong(reachable, now) };
1443
1625
  }
1626
+ /**
1627
+ * Whether one of the grants stands clear of every deny root: none at its
1628
+ * node or above it. A grant with a deny strictly beneath it still reaches
1629
+ * the rest of its subtree. Reads the tree only when there is a deny.
1630
+ */
1631
+ async anyClearOf(denied, windows) {
1632
+ if (!denied) {
1633
+ return true;
1634
+ }
1635
+ for (const window of windows) {
1636
+ if (!refusedOn(denied, await this.lineageOf(window.node))) {
1637
+ return true;
1638
+ }
1639
+ }
1640
+ return false;
1641
+ }
1444
1642
  /** Counters for observability — how much traffic the cache is actually saving. */
1445
1643
  snapshot() {
1446
1644
  return { ...this.stats };
@@ -1458,7 +1656,9 @@ var LocalAuthorizer = class {
1458
1656
  * With no argument, everything goes: grants and the hierarchy tree. Not
1459
1657
  * needed in normal operation, where entries expire on their own; useful in
1460
1658
  * tests and after a change whose reach you cannot name (a role's
1461
- * permissions edited, a role deactivated or reactivated, a node moved). A
1659
+ * permissions edited, a role deactivated or reactivated, a node moved, a
1660
+ * deny created or deleted, since a deny on a role binds everyone holding
1661
+ * it). A
1462
1662
  * deactivated role grants nothing to anyone holding it, so until the cache
1463
1663
  * is cleared or expires, its holders keep being allowed locally.
1464
1664
  *
@@ -1520,7 +1720,7 @@ var LocalAuthorizer = class {
1520
1720
  const key = subjectKey(type, identityId);
1521
1721
  const cached = this.grants.get(key);
1522
1722
  if (cached && cached.expiresAt > this.now()) {
1523
- return cached.roots;
1723
+ return cached.holdings;
1524
1724
  }
1525
1725
  const pending = this.pendingGrants.get(key);
1526
1726
  if (pending) {
@@ -1546,17 +1746,35 @@ var LocalAuthorizer = class {
1546
1746
  * `expired` or `not_yet_effective`, and the entry expires at the nearest
1547
1747
  * window boundary when that comes before the TTL, so a grant takes effect
1548
1748
  * or ends on time rather than up to `ttlMs` late.
1749
+ *
1750
+ * Every page carries the subject's deny roots whole, beside its rows; they
1751
+ * are gathered from each page, so a read is one snapshot of both.
1549
1752
  */
1550
1753
  async fetchGrantRoots(identityId, type) {
1551
1754
  this.stats.grantFetches += 1;
1552
1755
  const path = GRANTS_PATH(type, identityId);
1756
+ const denies = /* @__PURE__ */ new Map();
1553
1757
  const rows = paginate(
1554
1758
  (query) => {
1555
1759
  this.stats.grantPages += 1;
1556
1760
  return this.client.request("GET", path, {
1557
1761
  ...this.readOptions,
1558
1762
  query: { ...query, include: "windows" }
1559
- }).then((page) => understood(page, path));
1763
+ }).then((page) => {
1764
+ const read = understood(
1765
+ page,
1766
+ path
1767
+ ).denies;
1768
+ for (const deny of read ?? []) {
1769
+ const nodes = denies.get(deny.permission);
1770
+ if (nodes) {
1771
+ nodes.add(deny.node_id);
1772
+ } else {
1773
+ denies.set(deny.permission, /* @__PURE__ */ new Set([deny.node_id]));
1774
+ }
1775
+ }
1776
+ return page;
1777
+ });
1560
1778
  },
1561
1779
  { page: 1, take: PAGE_SIZE },
1562
1780
  { maxPages: MAX_PAGES }
@@ -1582,11 +1800,12 @@ var LocalAuthorizer = class {
1582
1800
  roots.set(row.permission, [window]);
1583
1801
  }
1584
1802
  }
1803
+ const holdings = { roots, denies };
1585
1804
  this.grants.set(subjectKey(type, identityId), {
1586
- roots,
1805
+ holdings,
1587
1806
  expiresAt: Math.min(now + this.ttlMs, boundary)
1588
1807
  });
1589
- return roots;
1808
+ return holdings;
1590
1809
  }
1591
1810
  async treeEntry() {
1592
1811
  if (this.tree && this.tree.expiresAt > this.now()) {
@@ -1803,7 +2022,8 @@ function orgContext(claims) {
1803
2022
  return {
1804
2023
  orgId: org_id,
1805
2024
  orgRoles: [...org_roles],
1806
- orgRoleIds: [...org_role_ids]
2025
+ orgRoleIds: [...org_role_ids],
2026
+ staff: claims.org_scope === "all"
1807
2027
  };
1808
2028
  }
1809
2029
  function decodeBase64Url(value) {