@canopy-io/node 0.13.0 → 0.15.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,29 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+
9
+ 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`.
10
+
11
+ 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.
12
+
13
+ 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.
14
+
15
+ ## 0.14.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 174f157: Machine clients. An OAuth client registered with `client_kind: machine` holds roles of its own and obtains tokens for itself with the `client_credentials` grant: `type: "service"`, `sub` and `client_id` set to its `client_id`, `gty: "client_credentials"`, and its organization's claims when it is pinned to one. `TokenVerifier` still accepts identity tokens only by default; `verify(token, { alsoAllow: ["service"] })` admits a service token on that one call, held to the new `serviceAudience` option (the audience your API answers to, which the token's `aud` names); without it a service token answers `token.audience_unverified`. In NestJS, `@AllowServiceTokens()` on a route or controller makes `CanopyTokenGuard` admit it there, and `CanopyGuard` then evaluates the client's own grants, chosen from the verified claims.
20
+
21
+ `LocalAuthorizer` reads a machine client's grants from `GET /api/v1/oauth-clients/:id/grants` when a check carries `principal_type: "service"`; `grantRoots`, `accessibleNodes`, `permissionsAt`, `permissionsAtMany` and `invalidate` take `{ principalType: "service" }`. A client and an identity are cached apart, and an assignment webhook naming a machine client carries its `client_id` (`data.metadata.client_id`) to invalidate by. The conformance bundle gains the `machine-clients` vector, replayed as service-token checks against each client's own grants.
22
+
23
+ `orgContext(claims)` returns `{ orgId, orgRoles, orgRoleIds }` and now requires `org_role_ids` beside `org_id` and `org_roles`, paired with the names position for position; a token missing it, or with lists of different lengths, answers `null`. A `CanopyGuard` denial reads "Caller does not hold" in place of "Identity does not hold".
24
+
25
+ The spec now has 157 operations. Generated types cover machine clients (`client_kind`, `organization_node_id`, `allowed_audiences`), their assignment and grant routes, and roles that belong to one organization.
26
+
3
27
  ## 0.13.0
4
28
 
5
29
  ### Minor Changes
package/README.md CHANGED
@@ -117,6 +117,32 @@ staff (`platform`) and some API key flows (`api_key`) with the same keys and
117
117
  issuer, so they are refused with `token.type_not_allowed` unless you name them:
118
118
  `new TokenVerifier({ ..., allowedTypes: ["identity", "user"] })`.
119
119
 
120
+ A **machine client** (an OAuth client registered with `client_kind: machine`)
121
+ obtains tokens for itself with the `client_credentials` grant. Its token's
122
+ `type` is `service`, its `sub` and `client_id` are the client's `client_id`,
123
+ and `gty` is `client_credentials`. Its `aud` names the API it was minted for
124
+ (the `audience` the client asked for, or the Environment's default audience),
125
+ so name yours as `serviceAudience`; `audience` stays the OAuth client a
126
+ person's token is for. Admit service tokens on the one call that serves
127
+ machines rather than on the whole verifier, so routes built for people keep
128
+ refusing them:
129
+
130
+ ```ts
131
+ const verifier = new TokenVerifier({
132
+ environmentId: process.env.CANOPY_ENVIRONMENT_ID,
133
+ serviceAudience: "https://api.example.com",
134
+ });
135
+
136
+ const claims = await verifier.verify(bearerToken, { alsoAllow: ["service"] });
137
+
138
+ if (claims.type === "service") {
139
+ claims.sub; // the machine client's client_id
140
+ }
141
+ ```
142
+
143
+ A machine client pinned to an organization carries that organization's claims,
144
+ read through `orgContext` like a person's.
145
+
120
146
  If Canopy cannot be reached when the cached keys are due for a refresh, the
121
147
  verifier keeps verifying with the keys it holds; only a verifier that has never
122
148
  loaded a key set, or a token signed by a key it has never seen, answers
@@ -144,9 +170,10 @@ mistakenly accepted.
144
170
 
145
171
  With an Environment's **organizations** container on, an identity token also
146
172
  names the organization the session is acting in and the roles held at that
147
- organization's node. Read the pair through `orgContext` rather than off the raw
148
- claims — Canopy mints the two together, and the helper refuses a half-present
149
- pair:
173
+ organization's node, by name and by id. Read them through `orgContext` rather
174
+ than off the raw claims: Canopy mints `org_id`, `org_roles` and `org_role_ids`
175
+ together, and the helper refuses a partial set or names and ids that do not
176
+ pair up:
150
177
 
151
178
  ```ts
152
179
  import { orgContext } from "@canopy-io/node";
@@ -156,9 +183,18 @@ const org = orgContext(claims);
156
183
  if (org) {
157
184
  org.orgId; // the organization — also a hierarchy node id
158
185
  org.orgRoles; // the roles held at its node, by name; [] for a member holding none there
186
+ org.orgRoleIds; // the same roles' ids, in the same order
187
+ org.staff; // true for your staff inside a customer's organization
159
188
  }
160
189
  ```
161
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
+
162
198
  `null` is an ordinary answer: every token from an Environment without the
163
199
  container on, and every identity that belongs to no organization yet. An empty
164
200
  `orgRoles` is not: membership is admission, and a member may hold roles only
@@ -298,6 +334,25 @@ TTL is dropped at its boundary, not at the next expiry. `onDecision` and
298
334
  never able to change it, for audit trails and alerting without a fork of the
299
335
  guard.
300
336
 
337
+ A machine client's grants are its own, read from
338
+ `GET /api/v1/oauth-clients/:id/grants`. Pass `principal_type: "service"` with
339
+ the client's `client_id` as `identity_id`; the list reads and `invalidate` take
340
+ `{ principalType: "service" }`. The two kinds are cached apart, so a client
341
+ never answers from a person's grants. An assignment webhook naming a machine
342
+ client carries its `client_id` in `data.metadata.client_id`, the id to
343
+ invalidate:
344
+
345
+ ```ts
346
+ await authorizer.evaluate({
347
+ identity_id: claims.sub,
348
+ principal_type: claims.type === "service" ? "service" : "identity",
349
+ permission: "orders.import",
350
+ node_id: nodeId,
351
+ });
352
+
353
+ authorizer.invalidate(clientId, { principalType: "service" });
354
+ ```
355
+
301
356
  ```ts
302
357
  const authorizer = new LocalAuthorizer(canopy.client, {
303
358
  onDenied: ({ query, decision }) =>
@@ -332,6 +387,27 @@ if (!access.complete) {
332
387
  return db.reports.findMany({ where: { nodeId: { in: [...access.nodes] } } });
333
388
  ```
334
389
 
390
+ A menu inside an organization asks something narrower: does this person
391
+ hold the permission anywhere in it? `app_wide` cannot say, since it covers the
392
+ whole Environment, so a grant in another organization would show the menu
393
+ here too. `holdsAnywhereUnder` answers for one subtree, with `roots` as the
394
+ subtree root alone when a grant at or above it reaches all of it, and
395
+ otherwise the topmost granted nodes inside it:
396
+
397
+ ```ts
398
+ const { held, roots } = await authorizer.holdsAnywhereUnder(
399
+ identityId,
400
+ "invoice.approve",
401
+ org.orgId,
402
+ );
403
+
404
+ // held: show the Invoices menu. roots: the teams whose invoices to list.
405
+ ```
406
+
407
+ It is a read for menus and lists, never a guard: holding the permission
408
+ somewhere in Acme approves no particular invoice, so the write checks the
409
+ invoice's own node.
410
+
335
411
  A list filtered this way is what to show; the write that follows still checks
336
412
  its node. Canopy answers the same question fresh, for a process without the
337
413
  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
  *
@@ -1187,7 +1211,8 @@ function understood(page, path) {
1187
1211
  }
1188
1212
  return page;
1189
1213
  }
1190
- var GRANTS_PATH = (identityId) => `/api/v1/identities/${encodeURIComponent(identityId)}/grants`;
1214
+ var GRANTS_PATH = (type, id) => type === "service" ? `/api/v1/oauth-clients/${encodeURIComponent(id)}/grants` : `/api/v1/identities/${encodeURIComponent(id)}/grants`;
1215
+ var subjectKey = (type, id) => `${type}:${id}`;
1191
1216
  var PARENTS_PATH = "/api/v1/nodes/parents";
1192
1217
  function inEffect(window, now) {
1193
1218
  return (window.from === null || window.from <= now) && (window.to === null || window.to > now);
@@ -1296,9 +1321,12 @@ var LocalAuthorizer = class {
1296
1321
  * root the readable hierarchy does not contain raises
1297
1322
  * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1298
1323
  */
1299
- async grantRoots(identityId, permission) {
1324
+ async grantRoots(identityId, permission, subject = {}) {
1300
1325
  const now = this.now();
1301
- const held = (await this.grantRootsFor(identityId)).get(permission) ?? [];
1326
+ const held = (await this.grantRootsFor(
1327
+ identityId,
1328
+ subject.principalType ?? "identity"
1329
+ )).get(permission) ?? [];
1302
1330
  const granted = new Set(
1303
1331
  held.filter((window) => inEffect(window, now)).map((w) => w.node)
1304
1332
  );
@@ -1345,7 +1373,9 @@ var LocalAuthorizer = class {
1345
1373
  */
1346
1374
  async accessibleNodes(identityId, permission, options = {}) {
1347
1375
  const cap = options.maxNodes ?? this.maxNodes;
1348
- const { roots, envWide } = await this.grantRoots(identityId, permission);
1376
+ const { roots, envWide } = await this.grantRoots(identityId, permission, {
1377
+ ...options.principalType ? { principalType: options.principalType } : {}
1378
+ });
1349
1379
  if (envWide) {
1350
1380
  return { roots, envWide: true, nodes: null, complete: true };
1351
1381
  }
@@ -1370,13 +1400,73 @@ var LocalAuthorizer = class {
1370
1400
  }
1371
1401
  return { roots, envWide: false, nodes, complete: true };
1372
1402
  }
1403
+ /**
1404
+ * Whether the identity holds the permission anywhere at or beneath a node,
1405
+ * and where: the question a menu inside an organization asks ("show
1406
+ * Invoices to someone who approves invoices for any team in Acme"), which
1407
+ * `app_wide` cannot answer because it covers the whole Environment.
1408
+ *
1409
+ * `roots` is `[subtreeRootId]` when a grant at the node or above it reaches
1410
+ * the whole subtree; otherwise the topmost granted nodes inside it, the
1411
+ * ones no other granted node inside it already covers. A list query filters
1412
+ * by "beneath one of these".
1413
+ *
1414
+ * **A read for menus and lists, never a guard.** Holding the permission
1415
+ * somewhere in the subtree says nothing about the record a write touches:
1416
+ * check the node the action writes to, with `evaluate`. No `scope` value
1417
+ * asks this question, on purpose.
1418
+ *
1419
+ * Computed from the same cached grant roots and tree a check uses. A grant
1420
+ * or a subtree root the readable hierarchy does not contain raises
1421
+ * `authorizer.hierarchy_incomplete`, as a check at such a node does.
1422
+ */
1423
+ async holdsAnywhereUnder(identityId, permission, subtreeRootId, subject = {}) {
1424
+ const now = this.now();
1425
+ const held = (await this.grantRootsFor(
1426
+ identityId,
1427
+ subject.principalType ?? "identity"
1428
+ )).get(permission) ?? [];
1429
+ const granted = new Set(
1430
+ held.filter((window) => inEffect(window, now)).map((w) => w.node)
1431
+ );
1432
+ const { parents } = await this.treeEntry();
1433
+ if (!parents.has(subtreeRootId)) {
1434
+ throw this.hierarchyIncomplete(subtreeRootId);
1435
+ }
1436
+ if (granted.size === 0) {
1437
+ return { held: false, roots: [] };
1438
+ }
1439
+ if (this.lineage(parents, subtreeRootId).some((n) => granted.has(n))) {
1440
+ return { held: true, roots: [subtreeRootId] };
1441
+ }
1442
+ const roots = [];
1443
+ for (const node of granted) {
1444
+ if (!parents.has(node)) {
1445
+ throw this.hierarchyIncomplete(node);
1446
+ }
1447
+ const above = this.lineage(parents, node).slice(1);
1448
+ if (above.includes(subtreeRootId) && !above.some((n) => granted.has(n))) {
1449
+ roots.push(node);
1450
+ }
1451
+ }
1452
+ return { held: roots.length > 0, roots };
1453
+ }
1454
+ /** The node and every ancestor up to the root, nearest first. */
1455
+ lineage(parents, nodeId) {
1456
+ const path = [];
1457
+ let depth = 0;
1458
+ for (let current = nodeId; current && depth < MAX_WALK_DEPTH; current = parents.get(current), depth += 1) {
1459
+ path.push(current);
1460
+ }
1461
+ return path;
1462
+ }
1373
1463
  /**
1374
1464
  * Every permission the identity holds at the node, by grant or by
1375
1465
  * inheritance: the list a screen renders its controls from, answered from
1376
1466
  * the same cached grant roots and tree a check uses.
1377
1467
  */
1378
- async permissionsAt(identityId, nodeId) {
1379
- const answers = await this.permissionsAtMany(identityId, [nodeId]);
1468
+ async permissionsAt(identityId, nodeId, subject = {}) {
1469
+ const answers = await this.permissionsAtMany(identityId, [nodeId], subject);
1380
1470
  return answers.get(nodeId) ?? [];
1381
1471
  }
1382
1472
  /**
@@ -1384,9 +1474,12 @@ var LocalAuthorizer = class {
1384
1474
  * the rows of a list each with their own controls, answered from one read
1385
1475
  * of the grant roots and one walk per node.
1386
1476
  */
1387
- async permissionsAtMany(identityId, nodeIds) {
1477
+ async permissionsAtMany(identityId, nodeIds, subject = {}) {
1388
1478
  const now = this.now();
1389
- const roots = await this.grantRootsFor(identityId);
1479
+ const roots = await this.grantRootsFor(
1480
+ identityId,
1481
+ subject.principalType ?? "identity"
1482
+ );
1390
1483
  const answers = /* @__PURE__ */ new Map();
1391
1484
  for (const nodeId of new Set(nodeIds)) {
1392
1485
  const path = await this.lineageOf(nodeId);
@@ -1404,9 +1497,10 @@ var LocalAuthorizer = class {
1404
1497
  }
1405
1498
  async decide(query) {
1406
1499
  const now = this.now();
1407
- const held = (await this.grantRootsFor(query.identity_id)).get(
1408
- query.permission
1409
- );
1500
+ const held = (await this.grantRootsFor(
1501
+ query.identity_id,
1502
+ query.principal_type ?? "identity"
1503
+ )).get(query.permission);
1410
1504
  if (!held || held.length === 0) {
1411
1505
  return { allowed: false, reason: "permission_not_held" };
1412
1506
  }
@@ -1442,6 +1536,8 @@ var LocalAuthorizer = class {
1442
1536
  * cached hierarchy and every other identity's entries stay warm. This is
1443
1537
  * the shape an assignment webhook wants: the event names the identity
1444
1538
  * whose authority moved, and nothing else needs to pay a refetch for it.
1539
+ * An event naming a machine client (`oauth_client_id`, with `identity_id`
1540
+ * null) passes that client's `client_id` with `principalType: "service"`.
1445
1541
  *
1446
1542
  * With no argument, everything goes: grants and the hierarchy tree. Not
1447
1543
  * needed in normal operation, where entries expire on their own; useful in
@@ -1457,9 +1553,11 @@ var LocalAuthorizer = class {
1457
1553
  * the TTL, and webhook-driven invalidation is a latency optimization on
1458
1554
  * top of it — size the TTL to the revocation latency you can promise.
1459
1555
  */
1460
- invalidate(identityId) {
1556
+ invalidate(identityId, subject = {}) {
1461
1557
  if (identityId !== void 0) {
1462
- this.grants.delete(identityId);
1558
+ this.grants.delete(
1559
+ subjectKey(subject.principalType ?? "identity", identityId)
1560
+ );
1463
1561
  return;
1464
1562
  }
1465
1563
  this.grants.clear();
@@ -1502,19 +1600,20 @@ var LocalAuthorizer = class {
1502
1600
  `The hierarchy this client can read does not contain node "${nodeId}", so authorization at that node cannot be decided. A scoped API key needs the \`hierarchy.view\` scope to read the tree.`
1503
1601
  );
1504
1602
  }
1505
- async grantRootsFor(identityId) {
1506
- const cached = this.grants.get(identityId);
1603
+ async grantRootsFor(identityId, type) {
1604
+ const key = subjectKey(type, identityId);
1605
+ const cached = this.grants.get(key);
1507
1606
  if (cached && cached.expiresAt > this.now()) {
1508
1607
  return cached.roots;
1509
1608
  }
1510
- const pending = this.pendingGrants.get(identityId);
1609
+ const pending = this.pendingGrants.get(key);
1511
1610
  if (pending) {
1512
1611
  return pending;
1513
1612
  }
1514
- const read = this.fetchGrantRoots(identityId).finally(() => {
1515
- this.pendingGrants.delete(identityId);
1613
+ const read = this.fetchGrantRoots(identityId, type).finally(() => {
1614
+ this.pendingGrants.delete(key);
1516
1615
  });
1517
- this.pendingGrants.set(identityId, read);
1616
+ this.pendingGrants.set(key, read);
1518
1617
  return read;
1519
1618
  }
1520
1619
  /**
@@ -1532,9 +1631,9 @@ var LocalAuthorizer = class {
1532
1631
  * window boundary when that comes before the TTL, so a grant takes effect
1533
1632
  * or ends on time rather than up to `ttlMs` late.
1534
1633
  */
1535
- async fetchGrantRoots(identityId) {
1634
+ async fetchGrantRoots(identityId, type) {
1536
1635
  this.stats.grantFetches += 1;
1537
- const path = GRANTS_PATH(identityId);
1636
+ const path = GRANTS_PATH(type, identityId);
1538
1637
  const rows = paginate(
1539
1638
  (query) => {
1540
1639
  this.stats.grantPages += 1;
@@ -1567,7 +1666,7 @@ var LocalAuthorizer = class {
1567
1666
  roots.set(row.permission, [window]);
1568
1667
  }
1569
1668
  }
1570
- this.grants.set(identityId, {
1669
+ this.grants.set(subjectKey(type, identityId), {
1571
1670
  roots,
1572
1671
  expiresAt: Math.min(now + this.ttlMs, boundary)
1573
1672
  });
@@ -1754,7 +1853,13 @@ var HOSTED_ORIGIN = "https://auth.canopy-io.com";
1754
1853
  var DEFAULT_JWKS_CACHE_MAX_AGE_MS = 10 * 60 * 1e3;
1755
1854
  var DEFAULT_JWKS_MIN_REFETCH_INTERVAL_MS = 30 * 1e3;
1756
1855
  var DEFAULT_JWKS_TIMEOUT_MS = 5e3;
1757
- var PRINCIPAL_TYPES = /* @__PURE__ */ new Set(["user", "identity", "api_key", "platform"]);
1856
+ var PRINCIPAL_TYPES = /* @__PURE__ */ new Set([
1857
+ "user",
1858
+ "identity",
1859
+ "service",
1860
+ "api_key",
1861
+ "platform"
1862
+ ]);
1758
1863
  var DEFAULT_CLOCK_TOLERANCE_SEC = 60;
1759
1864
  function resolveIssuer(options) {
1760
1865
  const { environmentId, issuer } = options;
@@ -1774,11 +1879,17 @@ function resolveIssuer(options) {
1774
1879
  );
1775
1880
  }
1776
1881
  function orgContext(claims) {
1777
- const { org_id, org_roles } = claims;
1778
- if (typeof org_id !== "string" || org_id === "" || !Array.isArray(org_roles) || org_roles.some((role) => typeof role !== "string" || role === "")) {
1882
+ const { org_id, org_roles, org_role_ids } = claims;
1883
+ const isNameList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry !== "");
1884
+ if (typeof org_id !== "string" || org_id === "" || !isNameList(org_roles) || !isNameList(org_role_ids) || org_role_ids.length !== org_roles.length) {
1779
1885
  return null;
1780
1886
  }
1781
- return { orgId: org_id, orgRoles: [...org_roles] };
1887
+ return {
1888
+ orgId: org_id,
1889
+ orgRoles: [...org_roles],
1890
+ orgRoleIds: [...org_role_ids],
1891
+ staff: claims.org_scope === "all"
1892
+ };
1782
1893
  }
1783
1894
  function decodeBase64Url(value) {
1784
1895
  const padded = value.replace(/-/g, "+").replace(/_/g, "/");
@@ -1803,6 +1914,7 @@ function decodeJsonSegment(segment, what) {
1803
1914
  var TokenVerifier = class {
1804
1915
  issuer;
1805
1916
  audience;
1917
+ serviceAudience;
1806
1918
  jwksUri;
1807
1919
  jwksCacheMaxAgeMs;
1808
1920
  jwksMinRefetchIntervalMs;
@@ -1822,6 +1934,7 @@ var TokenVerifier = class {
1822
1934
  constructor(options = {}) {
1823
1935
  this.issuer = resolveIssuer(options);
1824
1936
  this.audience = options.audience;
1937
+ this.serviceAudience = options.serviceAudience;
1825
1938
  this.jwksUri = options.jwksUri ?? `${this.issuer}/.well-known/jwks.json`;
1826
1939
  this.jwksCacheMaxAgeMs = options.jwksCacheMaxAgeMs ?? DEFAULT_JWKS_CACHE_MAX_AGE_MS;
1827
1940
  this.jwksMinRefetchIntervalMs = options.jwksMinRefetchIntervalMs ?? DEFAULT_JWKS_MIN_REFETCH_INTERVAL_MS;
@@ -1844,7 +1957,7 @@ var TokenVerifier = class {
1844
1957
  * Order matters: the signature is checked before any claim is believed, so
1845
1958
  * nothing downstream ever reads an unverified payload.
1846
1959
  */
1847
- async verify(token) {
1960
+ async verify(token, options = {}) {
1848
1961
  const parts = token.split(".");
1849
1962
  if (parts.length !== 3) {
1850
1963
  throw new CanopyTokenError(
@@ -1889,11 +2002,11 @@ var TokenVerifier = class {
1889
2002
  encodedPayload,
1890
2003
  "payload"
1891
2004
  );
1892
- this.assertClaims(claims);
2005
+ this.assertClaims(claims, options);
1893
2006
  return claims;
1894
2007
  }
1895
2008
  /** Everything checked after the signature is known good. */
1896
- assertClaims(claims) {
2009
+ assertClaims(claims, options) {
1897
2010
  if (typeof claims.sub !== "string" || claims.sub === "") {
1898
2011
  throw new CanopyTokenError(
1899
2012
  "token.malformed",
@@ -1906,11 +2019,15 @@ var TokenVerifier = class {
1906
2019
  `Token has an unrecognised \`type\` claim: ${JSON.stringify(claims.type)}.`
1907
2020
  );
1908
2021
  }
1909
- if (!this.allowedTypes.has(claims.type)) {
2022
+ const accepted = /* @__PURE__ */ new Set([
2023
+ ...this.allowedTypes,
2024
+ ...options.alsoAllow ?? []
2025
+ ]);
2026
+ if (!accepted.has(claims.type)) {
1910
2027
  throw new CanopyTokenError(
1911
2028
  "token.type_not_allowed",
1912
2029
  `Token is for a "${claims.type}" principal; this verifier accepts ${[
1913
- ...this.allowedTypes
2030
+ ...accepted
1914
2031
  ].map((type) => `"${type}"`).join(", ")}. Set \`allowedTypes\` to accept another.`
1915
2032
  );
1916
2033
  }
@@ -1952,9 +2069,27 @@ var TokenVerifier = class {
1952
2069
  * token being verified by something that never said which client it is, and
1953
2070
  * ignoring it would accept a token minted for a different client. So it
1954
2071
  * throws and names the option.
2072
+ *
2073
+ * A service token names the API it was minted for, never a client, so it
2074
+ * is held to `serviceAudience` alone, which it must name.
1955
2075
  */
1956
2076
  assertAudience(claims) {
1957
2077
  const audiences = claims.aud === void 0 ? [] : Array.isArray(claims.aud) ? claims.aud : [claims.aud];
2078
+ if (claims.type === "service") {
2079
+ if (this.serviceAudience === void 0) {
2080
+ throw new CanopyTokenError(
2081
+ "token.audience_unverified",
2082
+ "This is a machine client's service token, and the verifier has no `serviceAudience` configured. Set `serviceAudience` to the audience your API answers to."
2083
+ );
2084
+ }
2085
+ if (!audiences.includes(this.serviceAudience)) {
2086
+ throw new CanopyTokenError(
2087
+ "token.audience_mismatch",
2088
+ `Token audience does not include "${this.serviceAudience}".`
2089
+ );
2090
+ }
2091
+ return;
2092
+ }
1958
2093
  if (this.audience === void 0) {
1959
2094
  if (audiences.length > 0) {
1960
2095
  throw new CanopyTokenError(