@canopy-io/node 0.20.0 → 0.22.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,17 @@
1
1
  # @canopy-io/node
2
2
 
3
+ ## 0.22.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2c9163d: A machine client can act for a signed-in person. `exchangeToken` trades the person's access token for a `delegated` one (RFC 8693 token exchange); the verifier accepts the `delegated` type per call with `alsoAllow: ["delegated"]`, holds it to `serviceAudience` and requires its `act.sub`, and `delegation(claims)` reads the person and the client off it. `LocalAuthorizer.evaluate` takes `acting_client_id` and allows only when the identity and the client both hold the permission (`acting_client_not_granted` otherwise). In NestJS, `@AllowDelegatedTokens()` admits the token on a route, and `CanopyGuard` then checks both. The generated types carry `acting_client_id` and `acting_client_allowed` on evaluate. The skill says which credential an agent holds, names three mistakes (a full-access key, an account key it does not need, the person's own token) and shows an agent acting for a person.
8
+
9
+ ## 0.21.0
10
+
11
+ ### Minor Changes
12
+
13
+ - a7fda0b: An `environmentId` option on the client sends `X-Canopy-Environment`, so an account API key can reach the routes that act in an Environment; `RequestOptions.environmentId` names another Environment for one call, or `null` none. The generated types cover the management API: Applications and Environments with their settings, single sign-on, the auth domain and SCIM, administrator roles, grants and administrators, billing reads, the Account and account webhooks (298 operations, up from 201). The skill's choosing, node and mistakes references say which key goes where and how to provision an Environment with an account key.
14
+
3
15
  ## 0.20.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -144,6 +144,32 @@ if (claims.type === "service") {
144
144
  A machine client pinned to an organization carries that organization's claims,
145
145
  read through `orgContext` like a person's.
146
146
 
147
+ A machine client with token exchange on can also **act for a signed-in
148
+ person**. `exchangeToken` trades the person's access token for a `delegated`
149
+ one: `sub` is the person, `act.sub` the client, `gty` is `token-exchange`, and
150
+ it reaches only what both hold. Like a service token it names your API in
151
+ `aud` and is held to `serviceAudience`; admit it per call with
152
+ `alsoAllow: ["delegated"]`, and read both principals with `delegation`:
153
+
154
+ ```ts
155
+ // The agent's side.
156
+ const { accessToken } = await exchangeToken({
157
+ clientId: process.env.AGENT_CLIENT_ID!,
158
+ clientSecret: process.env.AGENT_CLIENT_SECRET!,
159
+ subjectToken: personAccessToken,
160
+ audience: "https://api.example.com",
161
+ });
162
+
163
+ // Your API's side.
164
+ const claims = await verifier.verify(bearerToken, { alsoAllow: ["delegated"] });
165
+ const acting = delegation(claims); // { identityId, actingClientId }
166
+ ```
167
+
168
+ Authorize it with `acting_client_id` (below). Canopy's own API refuses a
169
+ delegated token, and it has no refresh token: exchange again when it expires.
170
+ A refusal throws `CanopyError` with the OAuth error as its code
171
+ (`oauth.invalid_grant` once the person has signed out).
172
+
147
173
  If Canopy cannot be reached when the cached keys are due for a refresh, the
148
174
  verifier keeps verifying with the keys it holds; only a verifier that has never
149
175
  loaded a key set, or a token signed by a key it has never seen, answers
@@ -415,6 +441,19 @@ await authorizer.evaluate({
415
441
  authorizer.invalidate(clientId, { principalType: "service" });
416
442
  ```
417
443
 
444
+ For a `delegated` token, ask about the person and pass the acting client: the
445
+ check allows only when both hold the permission there, and refuses with
446
+ `acting_client_not_granted` when the client does not.
447
+
448
+ ```ts
449
+ await authorizer.evaluate({
450
+ identity_id: claims.sub,
451
+ permission: "deals.read",
452
+ node_id: nodeId,
453
+ ...(acting ? { acting_client_id: acting.actingClientId } : {}),
454
+ });
455
+ ```
456
+
418
457
  ```ts
419
458
  const authorizer = new LocalAuthorizer(canopy.client, {
420
459
  onDenied: ({ query, decision }) =>
package/dist/index.cjs CHANGED
@@ -119,6 +119,7 @@ var CanopyClient = class {
119
119
  maxBackoffMs;
120
120
  authHeaders;
121
121
  extraHeaders;
122
+ environmentId;
122
123
  fetchImpl;
123
124
  constructor(options = {}) {
124
125
  if (!options.apiKey && !options.accessToken) {
@@ -131,6 +132,7 @@ var CanopyClient = class {
131
132
  this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
132
133
  this.maxBackoffMs = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
133
134
  this.extraHeaders = options.headers ?? {};
135
+ this.environmentId = options.environmentId;
134
136
  this.fetchImpl = options.fetch ?? globalThis.fetch;
135
137
  if (typeof this.fetchImpl !== "function") {
136
138
  throw new TypeError(
@@ -264,6 +266,10 @@ var CanopyClient = class {
264
266
  if (options.body !== void 0) {
265
267
  headers["Content-Type"] = "application/json";
266
268
  }
269
+ const environmentId = options.environmentId === void 0 ? this.environmentId : options.environmentId;
270
+ if (environmentId) {
271
+ headers["X-Canopy-Environment"] = environmentId;
272
+ }
267
273
  Object.assign(headers, options.headers, this.authHeaders);
268
274
  const init = { method, headers, signal: controller.signal };
269
275
  if (options.body !== void 0) {
@@ -1705,6 +1711,29 @@ var LocalAuthorizer = class {
1705
1711
  return answers;
1706
1712
  }
1707
1713
  async decide(query) {
1714
+ const decision = await this.decideFor(query);
1715
+ if (!decision.allowed || query.acting_client_id === void 0) {
1716
+ return decision;
1717
+ }
1718
+ if (query.acting_client_id === "") {
1719
+ return { allowed: false, reason: "acting_client_not_granted" };
1720
+ }
1721
+ const its = await this.decideFor({
1722
+ identity_id: query.acting_client_id,
1723
+ principal_type: "service",
1724
+ permission: query.permission,
1725
+ ...query.scope ? { scope: query.scope } : {},
1726
+ ...query.node_id ? { node_id: query.node_id } : {}
1727
+ });
1728
+ if (its.allowed) {
1729
+ return its;
1730
+ }
1731
+ return {
1732
+ allowed: false,
1733
+ reason: its.reason === "denied" ? "denied" : "acting_client_not_granted"
1734
+ };
1735
+ }
1736
+ async decideFor(query) {
1708
1737
  const now = this.now();
1709
1738
  const holdings = await this.grantRootsFor(
1710
1739
  query.identity_id,
@@ -2212,6 +2241,84 @@ function authorizationErrorStatus(error) {
2212
2241
  return { status: 500, message: "Authorization could not be evaluated." };
2213
2242
  }
2214
2243
 
2244
+ // src/exchange.ts
2245
+ var TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
2246
+ var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
2247
+ var TOKEN_PATH = "/oauth/token";
2248
+ async function exchangeToken(options) {
2249
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2250
+ const origin = withoutTrailingSlashes(options.baseUrl ?? hostedOrigin());
2251
+ const request = { method: "POST", path: TOKEN_PATH };
2252
+ const body = new URLSearchParams({
2253
+ grant_type: TOKEN_EXCHANGE_GRANT,
2254
+ subject_token: options.subjectToken,
2255
+ subject_token_type: ACCESS_TOKEN_TYPE
2256
+ });
2257
+ if (options.audience !== void 0) {
2258
+ body.set("audience", options.audience);
2259
+ }
2260
+ if (options.scope !== void 0) {
2261
+ body.set("scope", options.scope);
2262
+ }
2263
+ const credentials = btoa(
2264
+ `${encodeURIComponent(options.clientId)}:${encodeURIComponent(options.clientSecret)}`
2265
+ );
2266
+ let response;
2267
+ try {
2268
+ response = await fetchImpl(`${origin}${TOKEN_PATH}`, {
2269
+ method: "POST",
2270
+ headers: {
2271
+ Authorization: `Basic ${credentials}`,
2272
+ "Content-Type": "application/x-www-form-urlencoded",
2273
+ Accept: "application/json"
2274
+ },
2275
+ body: body.toString(),
2276
+ ...options.signal ? { signal: options.signal } : {}
2277
+ });
2278
+ } catch (error) {
2279
+ if (options.signal?.aborted) {
2280
+ throw error;
2281
+ }
2282
+ throw new CanopyConnectionError(
2283
+ `Could not reach ${origin}${TOKEN_PATH}.`,
2284
+ request,
2285
+ { cause: error }
2286
+ );
2287
+ }
2288
+ const payload = await response.json().catch(() => null);
2289
+ if (!response.ok) {
2290
+ const error = typeof payload?.["error"] === "string" ? payload["error"] : null;
2291
+ const description = typeof payload?.["error_description"] === "string" ? payload["error_description"] : `The token endpoint answered ${response.status}.`;
2292
+ const retryAfter = Number(response.headers.get("retry-after"));
2293
+ throw new CanopyError(
2294
+ {
2295
+ statusCode: response.status,
2296
+ code: error ? `oauth.${error}` : null,
2297
+ message: description
2298
+ },
2299
+ request,
2300
+ Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1e3 : void 0
2301
+ );
2302
+ }
2303
+ if (typeof payload?.["access_token"] !== "string" || typeof payload["expires_in"] !== "number") {
2304
+ throw new CanopyError(
2305
+ {
2306
+ statusCode: response.status,
2307
+ code: null,
2308
+ message: "The token endpoint answered without an access token."
2309
+ },
2310
+ request
2311
+ );
2312
+ }
2313
+ return {
2314
+ accessToken: payload["access_token"],
2315
+ tokenType: "Bearer",
2316
+ expiresIn: payload["expires_in"],
2317
+ ...typeof payload["scope"] === "string" ? { scope: payload["scope"] } : {},
2318
+ issuedTokenType: typeof payload["issued_token_type"] === "string" ? payload["issued_token_type"] : ACCESS_TOKEN_TYPE
2319
+ };
2320
+ }
2321
+
2215
2322
  // src/verify.ts
2216
2323
  var DEFAULT_JWKS_CACHE_MAX_AGE_MS = 10 * 60 * 1e3;
2217
2324
  var DEFAULT_JWKS_MIN_REFETCH_INTERVAL_MS = 30 * 1e3;
@@ -2220,6 +2327,7 @@ var PRINCIPAL_TYPES = /* @__PURE__ */ new Set([
2220
2327
  "user",
2221
2328
  "identity",
2222
2329
  "service",
2330
+ "delegated",
2223
2331
  "api_key",
2224
2332
  "platform"
2225
2333
  ]);
@@ -2254,6 +2362,16 @@ function orgContext(claims) {
2254
2362
  staff: claims.org_scope === "all"
2255
2363
  };
2256
2364
  }
2365
+ function delegation(claims) {
2366
+ if (claims.type !== "delegated") {
2367
+ return null;
2368
+ }
2369
+ const actingClientId = claims.act?.sub;
2370
+ if (typeof actingClientId !== "string" || actingClientId === "") {
2371
+ return null;
2372
+ }
2373
+ return { identityId: claims.sub, actingClientId };
2374
+ }
2257
2375
  function decodeBase64Url(value) {
2258
2376
  const padded = value.replace(/-/g, "+").replace(/_/g, "/");
2259
2377
  const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, "="));
@@ -2388,6 +2506,12 @@ var TokenVerifier = class {
2388
2506
  `Token has an unrecognised \`type\` claim: ${JSON.stringify(claims.type)}.`
2389
2507
  );
2390
2508
  }
2509
+ if (claims.type === "delegated" && (typeof claims.act?.sub !== "string" || claims.act.sub === "")) {
2510
+ throw new CanopyTokenError(
2511
+ "token.malformed",
2512
+ "Token is delegated but has no `act.sub` claim naming the client acting for its subject."
2513
+ );
2514
+ }
2391
2515
  const accepted = /* @__PURE__ */ new Set([
2392
2516
  ...this.allowedTypes,
2393
2517
  ...options.alsoAllow ?? []
@@ -2439,16 +2563,17 @@ var TokenVerifier = class {
2439
2563
  * ignoring it would accept a token minted for a different client. So it
2440
2564
  * throws and names the option.
2441
2565
  *
2442
- * A service token names the API it was minted for, never a client, so it
2443
- * is held to `serviceAudience` alone, which it must name.
2566
+ * A machine client's token (`service` or `delegated`) names the API it was
2567
+ * minted for, never a client, so it is held to `serviceAudience` alone,
2568
+ * which it must name.
2444
2569
  */
2445
2570
  assertAudience(claims) {
2446
2571
  const audiences = claims.aud === void 0 ? [] : Array.isArray(claims.aud) ? claims.aud : [claims.aud];
2447
- if (claims.type === "service") {
2572
+ if (claims.type === "service" || claims.type === "delegated") {
2448
2573
  if (this.serviceAudience === void 0) {
2449
2574
  throw new CanopyTokenError(
2450
2575
  "token.audience_unverified",
2451
- "This is a machine client's service token, and the verifier has no `serviceAudience` configured. Set `serviceAudience` to the audience your API answers to."
2576
+ `This is a machine client's ${claims.type} token, and the verifier has no \`serviceAudience\` configured. Set \`serviceAudience\` to the audience your API answers to.`
2452
2577
  );
2453
2578
  }
2454
2579
  if (!audiences.includes(this.serviceAudience)) {
@@ -2690,6 +2815,7 @@ function hexToBytes(hex) {
2690
2815
  return bytes;
2691
2816
  }
2692
2817
 
2818
+ exports.ACCESS_TOKEN_TYPE = ACCESS_TOKEN_TYPE;
2693
2819
  exports.Assignments = Assignments;
2694
2820
  exports.Canopy = Canopy;
2695
2821
  exports.CanopyAuthorizerError = CanopyAuthorizerError;
@@ -2705,9 +2831,12 @@ exports.Organizations = Organizations;
2705
2831
  exports.Paginator = Paginator;
2706
2832
  exports.Permissions = Permissions;
2707
2833
  exports.Roles = Roles;
2834
+ exports.TOKEN_EXCHANGE_GRANT = TOKEN_EXCHANGE_GRANT;
2708
2835
  exports.TokenVerifier = TokenVerifier;
2709
2836
  exports.WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS;
2710
2837
  exports.authorizationErrorStatus = authorizationErrorStatus;
2838
+ exports.delegation = delegation;
2839
+ exports.exchangeToken = exchangeToken;
2711
2840
  exports.isCanopyAuthorizerError = isCanopyAuthorizerError;
2712
2841
  exports.isCanopyConnectionError = isCanopyConnectionError;
2713
2842
  exports.isCanopyError = isCanopyError;