@schemavaults/auth-server-sdk 0.40.1 → 0.41.1

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/README.md CHANGED
@@ -304,6 +304,56 @@ A refused request (e.g. a JWKS access key that is not your active one) throws.
304
304
  Each call is a round trip to the auth server, so reserve it for requests where
305
305
  revocation must be honoured immediately.
306
306
 
307
+ ## Minting delegated tokens for agents (confidential clients)
308
+
309
+ A client app that runs agents for its users (in a sandbox, say) should hand each agent
310
+ a delegated token, not the user's own: the API server then sees who is calling (the
311
+ `act` claim names the app's service account), and the agent holds only the scope its
312
+ task needs. The app's backend swaps one of its users' access tokens for one with the
313
+ RFC 8693 token exchange grant (advertised in the discovery document's
314
+ `grant_types_supported`), authenticating with its client secret:
315
+
316
+ ```ts
317
+ import {
318
+ exchangeTokenForDelegatedToken,
319
+ revokeToken,
320
+ OAuthEndpointError,
321
+ } from "@schemavaults/auth-server-sdk/confidential-client";
322
+
323
+ const client = {
324
+ auth_server_url: getAuthServerUrl(),
325
+ client_id: process.env.SCHEMAVAULTS_CLIENT_APP_ID!,
326
+ client_secret: process.env.SCHEMAVAULTS_CLIENT_SECRET!, // server-side only
327
+ };
328
+
329
+ const delegated = await exchangeTokenForDelegatedToken({
330
+ ...client,
331
+ subject_token: usersAccessToken, // the user's access token for the API server the agent calls
332
+ scope: ["notes:read"], // optional: a subset of its scope (default: all of it)
333
+ });
334
+ delegated.access_token; // give this to the agent
335
+ delegated.expires_in; // seconds; there is no refresh token: exchange again for a fresh one
336
+ delegated.scope; // the granted scope
337
+
338
+ // When the agent's session ends:
339
+ await revokeToken({ ...client, token: delegated.access_token });
340
+ ```
341
+
342
+ - One delegated token per API server: it is minted for the subject token's own
343
+ audience. For an agent that calls several API servers (e.g. several MCP servers),
344
+ exchange one of the user's access tokens for each.
345
+ - The API server's managers must turn on **Accept delegated tokens** first; until
346
+ they do, the exchange fails with `OAuthEndpointError` `error: "invalid_target"`.
347
+ Other refusals: `invalid_request` (the subject token is expired, revoked, already
348
+ delegated, issued to another client, or the user withdrew the app's access) and
349
+ `invalid_scope` (more scope than the subject token holds).
350
+ - Revoking makes introspection and resource servers with an `isTokenRevoked` hook
351
+ refuse the token at once; resource servers that only verify tokens locally stop
352
+ accepting it when it expires.
353
+ - `revokeToken()` also revokes the client's users' refresh tokens (RFC 7009); it
354
+ resolves for tokens the auth server does not know.
355
+ - Keep the client secret out of the agent's sandbox: only the delegated token goes in.
356
+
307
357
  ## `UserData.sub`
308
358
 
309
359
  `UserData.sub` is the OIDC subject `<auth_server_app_id>|<uid>` (the value the
@@ -316,8 +366,10 @@ versions keep verifying them; `userDataSchema` upgrades a bare-uuid `sub` with
316
366
 
317
367
  An access token may say that someone acts on behalf of its user (an agent, say): its
318
368
  `sub` is still the user, and its `act` claim names the actor (RFC 8693 §4.1). The
319
- auth server does not issue such tokens yet; this SDK version accepts them so resource
320
- servers can upgrade before it does (older versions reject a token carrying `act`).
369
+ auth server mints them with the RFC 8693 token exchange grant, for confidential
370
+ clients that run agents for their users (see
371
+ [Minting delegated tokens for agents](#minting-delegated-tokens-for-agents-confidential-clients)).
372
+ SDK versions before 0.39.0 reject a token carrying `act`.
321
373
 
322
374
  The auth server mints delegated tokens only for API servers that accept them, and
323
375
  none does by default. Once your resource server runs this version, have one of the
@@ -408,26 +460,28 @@ Per request:
408
460
  access assertion with the JWKS access key and forward the token the user presented in
409
461
  `X-Subject-Token`.
410
462
 
411
- To keep agents away from a sensitive operation, refuse principals with an actor:
463
+ Once your API server accepts delegated tokens, every operation accepts them unless it
464
+ says otherwise. To keep agents away from a sensitive operation, declare
465
+ `delegatedCallers: "refused"` (`@schemavaults/openapi-operations` ≥ 0.7.0): the runtime
466
+ answers a principal with an actor 403 `delegated_caller_refused`, whatever scope its
467
+ token carries, and the OpenAPI document (`x-schemavaults-auth`) and `/docs` pages show it:
412
468
 
413
469
  ```ts
414
- import { OperationError } from "@schemavaults/openapi-operations";
415
-
416
470
  export const deleteAccount = defineOperation({
417
471
  // ...
472
+ auth: requireAuth({
473
+ schemes: userCredentialSchemes,
474
+ delegatedCallers: "refused", // only the user's own credential, never an agent's
475
+ }),
418
476
  handler: async (ctx) => {
419
- if (ctx.auth.actor) {
420
- // Someone (e.g. an agent) is acting on the user's behalf: only the user may do this.
421
- throw new OperationError(403, {
422
- error: "delegation_not_allowed",
423
- message: "This operation cannot be performed on your behalf",
424
- });
425
- }
426
- // ...
477
+ // ctx.auth.actor is always absent here
427
478
  },
428
479
  });
429
480
  ```
430
481
 
482
+ Handlers that need a finer rule (e.g. agents of one client only) read `ctx.auth.actor`
483
+ themselves and throw `OperationError(403, ...)`.
484
+
431
485
  ### Organization memberships
432
486
 
433
487
  By default an API server only sees memberships of the organization that owns it:
package/dist/cli.cjs CHANGED
@@ -89,7 +89,7 @@ var init_resolve_codegen_templates_directory = __esm({
89
89
 
90
90
  // src/NextjsAppDirectoryPlugin/codegen-marker.ts
91
91
  function getCodegenMarkerComment() {
92
- const version2 = true ? "0.40.1" : "unknown";
92
+ const version2 = true ? "0.41.1" : "unknown";
93
93
  return `${CODEGEN_MARKER_PREFIX}${version2}`;
94
94
  }
95
95
  function hasCodegenMarker(firstLine) {
@@ -23384,7 +23384,7 @@ async function main() {
23384
23384
  return;
23385
23385
  }
23386
23386
  if (args.includes("--version") || args.includes("-v")) {
23387
- console.log(`${PACKAGE_NAME}@${"0.40.1"}`);
23387
+ console.log(`${PACKAGE_NAME}@${"0.41.1"}`);
23388
23388
  return;
23389
23389
  }
23390
23390
  const command = findCommand(args, FLAGS_WITH_VALUES) ?? "codegen";
@@ -0,0 +1,57 @@
1
+ import { z } from "zod";
2
+ import { type ConfidentialClientCredentials } from "./shared";
3
+ export interface IExchangeTokenForDelegatedTokenOptions extends ConfidentialClientCredentials {
4
+ /**
5
+ * An access token one of this client's users holds for the API server the
6
+ * agent will call (the RFC 8693 `subject_token`). It must be the user's
7
+ * own token, issued to this client, and still live: not expired or
8
+ * revoked, and the user's authorization of the app still standing.
9
+ */
10
+ subject_token: string;
11
+ /**
12
+ * The scope of the delegated token, a subset of the subject token's
13
+ * (space-delimited, or a list). Omit to keep the subject token's whole
14
+ * scope. Asking for more answers `invalid_scope`.
15
+ */
16
+ scope?: string | readonly string[];
17
+ /**
18
+ * RFC 8707 resource indicator. Optional: a delegated token is always
19
+ * minted for the subject token's own audience, and any other value
20
+ * answers `invalid_target`. To act at another API server, exchange an
21
+ * access token for that one.
22
+ */
23
+ resource?: string;
24
+ }
25
+ /** The auth server's RFC 8693 §2.2.1 token exchange response. */
26
+ export declare const delegatedTokenResponseSchema: z.ZodObject<{
27
+ access_token: z.ZodString;
28
+ issued_token_type: z.ZodLiteral<"urn:ietf:params:oauth:token-type:access_token">;
29
+ token_type: z.ZodLiteral<"Bearer">;
30
+ expires_in: z.ZodNumber;
31
+ scope: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$loose>;
33
+ export type DelegatedTokenResponse = z.infer<typeof delegatedTokenResponseSchema>;
34
+ /**
35
+ * Swaps an access token of one of this client's users for a DELEGATED
36
+ * access token (RFC 8693 token exchange): same user (`sub`), same API
37
+ * server, at most the same scope, with the client's service account named
38
+ * as the actor (`act`). Hand the delegated token, not the user's, to an
39
+ * agent acting for the user (e.g. one running in a sandbox), so the API
40
+ * server can tell the agent from the user and the agent holds only the
41
+ * scope it needs.
42
+ *
43
+ * Only confidential clients can exchange (they authenticate with
44
+ * `client_secret_basic` here), and only for API servers whose managers
45
+ * accept delegated tokens (otherwise `invalid_target`). The response holds
46
+ * an access token alone: when it expires, exchange a fresh access token of
47
+ * the user's again. End the delegation early with `revokeToken()`.
48
+ *
49
+ * @throws {OAuthEndpointError} when the auth server refuses the exchange.
50
+ * Notable codes: `invalid_request` (the subject token is invalid, expired,
51
+ * revoked, already delegated, or the user's access behind it was
52
+ * withdrawn), `invalid_scope` (wider than the subject token's), and
53
+ * `invalid_target` (another audience, or an API server that does not
54
+ * accept delegated tokens).
55
+ */
56
+ export declare function exchangeTokenForDelegatedToken({ subject_token, scope, resource, ...credentials }: IExchangeTokenForDelegatedTokenOptions): Promise<DelegatedTokenResponse>;
57
+ export default exchangeTokenForDelegatedToken;
@@ -0,0 +1,72 @@
1
+ import { getOidcEndpointUrl, OAUTH_ACCESS_TOKEN_TYPE, OAUTH_TOKEN_EXCHANGE_GRANT_TYPE, } from "@schemavaults/auth-common";
2
+ import { z } from "zod";
3
+ import { postAsConfidentialClient, } from "./shared";
4
+ /** The auth server's RFC 8693 §2.2.1 token exchange response. */
5
+ export const delegatedTokenResponseSchema = z.looseObject({
6
+ /** The delegated access token: hand it to the agent. */
7
+ access_token: z.string().min(1),
8
+ issued_token_type: z.literal(OAUTH_ACCESS_TOKEN_TYPE),
9
+ token_type: z.literal("Bearer"),
10
+ /** Lifetime in seconds. Exchange again for a fresh token; there is no refresh token. */
11
+ expires_in: z.number().int().positive(),
12
+ /** Space-delimited granted scope; absent when the token carries none. */
13
+ scope: z.string().optional(),
14
+ });
15
+ function serializeScope(scope) {
16
+ const values = (typeof scope === "string" ? scope.split(" ") : [...scope])
17
+ .map((value) => value.trim())
18
+ .filter((value) => value.length > 0);
19
+ if (values.length === 0) {
20
+ throw new TypeError("Expected a non-empty 'scope'; omit it to keep the subject token's scope.");
21
+ }
22
+ return values.join(" ");
23
+ }
24
+ /**
25
+ * Swaps an access token of one of this client's users for a DELEGATED
26
+ * access token (RFC 8693 token exchange): same user (`sub`), same API
27
+ * server, at most the same scope, with the client's service account named
28
+ * as the actor (`act`). Hand the delegated token, not the user's, to an
29
+ * agent acting for the user (e.g. one running in a sandbox), so the API
30
+ * server can tell the agent from the user and the agent holds only the
31
+ * scope it needs.
32
+ *
33
+ * Only confidential clients can exchange (they authenticate with
34
+ * `client_secret_basic` here), and only for API servers whose managers
35
+ * accept delegated tokens (otherwise `invalid_target`). The response holds
36
+ * an access token alone: when it expires, exchange a fresh access token of
37
+ * the user's again. End the delegation early with `revokeToken()`.
38
+ *
39
+ * @throws {OAuthEndpointError} when the auth server refuses the exchange.
40
+ * Notable codes: `invalid_request` (the subject token is invalid, expired,
41
+ * revoked, already delegated, or the user's access behind it was
42
+ * withdrawn), `invalid_scope` (wider than the subject token's), and
43
+ * `invalid_target` (another audience, or an API server that does not
44
+ * accept delegated tokens).
45
+ */
46
+ export async function exchangeTokenForDelegatedToken({ subject_token, scope, resource, ...credentials }) {
47
+ if (typeof subject_token !== "string" || subject_token.length === 0) {
48
+ throw new TypeError("Expected a subject_token to exchange!");
49
+ }
50
+ if (resource !== undefined && (typeof resource !== "string" || resource.length === 0)) {
51
+ throw new TypeError("Expected 'resource' to be a non-empty string when set!");
52
+ }
53
+ const form = new URLSearchParams({
54
+ grant_type: OAUTH_TOKEN_EXCHANGE_GRANT_TYPE,
55
+ subject_token,
56
+ subject_token_type: OAUTH_ACCESS_TOKEN_TYPE,
57
+ });
58
+ if (scope !== undefined) {
59
+ form.set("scope", serializeScope(scope));
60
+ }
61
+ if (resource !== undefined) {
62
+ form.set("resource", resource);
63
+ }
64
+ const response = await postAsConfidentialClient(credentials, "token", getOidcEndpointUrl(credentials.auth_server_url, "token"), form);
65
+ const parsed = delegatedTokenResponseSchema.safeParse(await response.json());
66
+ if (!parsed.success) {
67
+ throw new Error("Received an unexpected token exchange response from the auth server", { cause: parsed.error });
68
+ }
69
+ return parsed.data;
70
+ }
71
+ export default exchangeTokenForDelegatedToken;
72
+ //# sourceMappingURL=exchange-token-for-delegated-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exchange-token-for-delegated-token.js","sourceRoot":"","sources":["../../src/confidential-client/exchange-token-for-delegated-token.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAEL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AA0BlB,iEAAiE;AACjE,MAAM,CAAC,MAAM,4B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CAAC,CAAC;IAC/D,CAAC;IACD,IAAI,QAAQ,KAAK,SAAS,IAAI,CAAC,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,EAAE,CAAC;QACtF,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;IAChF,CAAC;IAED,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC;QAC/B,UAAU,EAAE,+BAA+B;QAC3C,aAAa;QACb,kBAAkB,EAAE,uBAAuB;KAC5C,CAAC,CAAC;IACH,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACjC,CAAC;IAED,MAAM,QAAQ,GAAa,MAAM,wBAAwB,CACvD,WAAW,EACX,OAAO,EACP,kBAAkB,CAAC,WAAW,CAAC,eAAe,EAAE,OAAO,CAAC,EACxD,IAAI,CACL,CAAC;IAEF,MAAM,MAAM,GAAG,4BAA4B,CAAC,SAAS,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7E,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACb,qEAAqE,EACrE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CACxB,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC;AAED,eAAe,8BAA8B,CAAC"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Calls a confidential client application's backend makes to the auth
3
+ * server with its client secret: minting delegated tokens for the agents it
4
+ * runs for its users (RFC 8693 token exchange) and revoking tokens issued to
5
+ * it (RFC 7009). Server-side only: never ship the client secret to a browser
6
+ * or into an agent's sandbox.
7
+ */
8
+ export { exchangeTokenForDelegatedToken, delegatedTokenResponseSchema, } from "./exchange-token-for-delegated-token";
9
+ export type { DelegatedTokenResponse, IExchangeTokenForDelegatedTokenOptions, } from "./exchange-token-for-delegated-token";
10
+ export { revokeToken } from "./revoke-token";
11
+ export type { IRevokeTokenOptions } from "./revoke-token";
12
+ export { OAuthEndpointError, clientSecretBasicAuthorization } from "./shared";
13
+ export type { ConfidentialClientCredentials } from "./shared";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Calls a confidential client application's backend makes to the auth
3
+ * server with its client secret: minting delegated tokens for the agents it
4
+ * runs for its users (RFC 8693 token exchange) and revoking tokens issued to
5
+ * it (RFC 7009). Server-side only: never ship the client secret to a browser
6
+ * or into an agent's sandbox.
7
+ */
8
+ export { exchangeTokenForDelegatedToken, delegatedTokenResponseSchema, } from "./exchange-token-for-delegated-token";
9
+ export { revokeToken } from "./revoke-token";
10
+ export { OAuthEndpointError, clientSecretBasicAuthorization } from "./shared";
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/confidential-client/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,8BAA8B,EAC9B,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAM9C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,8BAA8B,EAAE,MAAM,UAAU,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { type ConfidentialClientCredentials } from "./shared";
2
+ export interface IRevokeTokenOptions extends ConfidentialClientCredentials {
3
+ /**
4
+ * A token issued to this client: a delegated access token it obtained by
5
+ * token exchange, or one of its users' refresh tokens.
6
+ */
7
+ token: string;
8
+ /** RFC 7009 §2.1 hint; the auth server reads the kind from the token itself. */
9
+ token_type_hint?: "access_token" | "refresh_token";
10
+ }
11
+ /**
12
+ * Revokes a token issued to this confidential client (RFC 7009), e.g. the
13
+ * delegated token of an agent whose session ended, so that introspection and
14
+ * resource servers checking revocation refuse it before it expires.
15
+ *
16
+ * Resolves for any token the auth server does not know (RFC 7009 §2.2: an
17
+ * invalid token is not an error); revoking twice is harmless.
18
+ *
19
+ * @throws {OAuthEndpointError} when the auth server refuses the request:
20
+ * `invalid_client` (bad credentials), `invalid_grant` (the token was issued
21
+ * to another client), `unsupported_token_type` (a token the client cannot
22
+ * revoke, such as a user's own access token for an API server).
23
+ */
24
+ export declare function revokeToken({ token, token_type_hint, ...credentials }: IRevokeTokenOptions): Promise<void>;
25
+ export default revokeToken;
@@ -0,0 +1,27 @@
1
+ import { getOidcEndpointUrl } from "@schemavaults/auth-common";
2
+ import { postAsConfidentialClient, } from "./shared";
3
+ /**
4
+ * Revokes a token issued to this confidential client (RFC 7009), e.g. the
5
+ * delegated token of an agent whose session ended, so that introspection and
6
+ * resource servers checking revocation refuse it before it expires.
7
+ *
8
+ * Resolves for any token the auth server does not know (RFC 7009 §2.2: an
9
+ * invalid token is not an error); revoking twice is harmless.
10
+ *
11
+ * @throws {OAuthEndpointError} when the auth server refuses the request:
12
+ * `invalid_client` (bad credentials), `invalid_grant` (the token was issued
13
+ * to another client), `unsupported_token_type` (a token the client cannot
14
+ * revoke, such as a user's own access token for an API server).
15
+ */
16
+ export async function revokeToken({ token, token_type_hint, ...credentials }) {
17
+ if (typeof token !== "string" || token.length === 0) {
18
+ throw new TypeError("Expected a token to revoke!");
19
+ }
20
+ const form = new URLSearchParams({ token });
21
+ if (token_type_hint !== undefined) {
22
+ form.set("token_type_hint", token_type_hint);
23
+ }
24
+ await postAsConfidentialClient(credentials, "revocation", getOidcEndpointUrl(credentials.auth_server_url, "revocation"), form);
25
+ }
26
+ export default revokeToken;
27
+ //# sourceMappingURL=revoke-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revoke-token.js","sourceRoot":"","sources":["../../src/confidential-client/revoke-token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAEL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAYlB;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,EAChC,KAAK,EACL,eAAe,EACf,GAAG,WAAW,EACM;IACpB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAC;IACrD,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM,wBAAwB,CAC5B,WAAW,EACX,YAAY,EACZ,kBAAkB,CAAC,WAAW,CAAC,eAAe,EAAE,YAAY,CAAC,EAC7D,IAAI,CACL,CAAC;AACJ,CAAC;AAED,eAAe,WAAW,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The credentials of a confidential client application: its app id and a
3
+ * client secret registered for it on the auth server. Keep the secret on the
4
+ * server; never ship it to a browser or into an agent's sandbox.
5
+ */
6
+ export interface ConfidentialClientCredentials {
7
+ /** The auth server URL (the issuer). */
8
+ auth_server_url: string;
9
+ /** The client application's id. */
10
+ client_id: string;
11
+ /** A client secret registered for the application. */
12
+ client_secret: string;
13
+ /** Defaults to the global `fetch`. */
14
+ fetch?: typeof fetch;
15
+ }
16
+ /**
17
+ * An OAuth 2.0 error answered by one of the auth server's endpoints
18
+ * (RFC 6749 §5.2, RFC 7009 §2.2.1, RFC 8693 §2.2.2): `error` is the
19
+ * machine-readable code (e.g. `invalid_request`, `invalid_scope`,
20
+ * `invalid_target`, `unauthorized_client`), or null when the auth server
21
+ * answered without one (an unreachable or misconfigured server).
22
+ */
23
+ export declare class OAuthEndpointError extends Error {
24
+ readonly status: number;
25
+ readonly error: string | null;
26
+ readonly error_description: string | null;
27
+ constructor(endpoint: string, status: number, error: string | null, error_description: string | null);
28
+ }
29
+ /**
30
+ * The `client_secret_basic` Authorization header (RFC 6749 §2.3.1): the id
31
+ * and secret are URL-encoded, joined by a colon and base64-encoded. The URL
32
+ * encoding keeps the input ASCII, so `btoa` is safe for any secret.
33
+ */
34
+ export declare function clientSecretBasicAuthorization({ client_id, client_secret, }: Pick<ConfidentialClientCredentials, "client_id" | "client_secret">): string;
35
+ /**
36
+ * POSTs an `application/x-www-form-urlencoded` request authenticated as the
37
+ * confidential client. Resolves with the response when it is a 2xx and
38
+ * throws {@link OAuthEndpointError} otherwise.
39
+ */
40
+ export declare function postAsConfidentialClient(credentials: ConfidentialClientCredentials, endpoint_name: string, url: string, form: URLSearchParams): Promise<Response>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * An OAuth 2.0 error answered by one of the auth server's endpoints
3
+ * (RFC 6749 §5.2, RFC 7009 §2.2.1, RFC 8693 §2.2.2): `error` is the
4
+ * machine-readable code (e.g. `invalid_request`, `invalid_scope`,
5
+ * `invalid_target`, `unauthorized_client`), or null when the auth server
6
+ * answered without one (an unreachable or misconfigured server).
7
+ */
8
+ export class OAuthEndpointError extends Error {
9
+ status;
10
+ error;
11
+ error_description;
12
+ constructor(endpoint, status, error, error_description) {
13
+ super(`The auth server's ${endpoint} endpoint refused the request (status: ${status}` +
14
+ `${error ? `, error: ${error}` : ""})` +
15
+ `${error_description ? `: ${error_description}` : ""}`);
16
+ this.name = "OAuthEndpointError";
17
+ this.status = status;
18
+ this.error = error;
19
+ this.error_description = error_description;
20
+ }
21
+ }
22
+ /**
23
+ * The `client_secret_basic` Authorization header (RFC 6749 §2.3.1): the id
24
+ * and secret are URL-encoded, joined by a colon and base64-encoded. The URL
25
+ * encoding keeps the input ASCII, so `btoa` is safe for any secret.
26
+ */
27
+ export function clientSecretBasicAuthorization({ client_id, client_secret, }) {
28
+ if (typeof client_id !== "string" || client_id.length === 0) {
29
+ throw new TypeError("Expected a client_id!");
30
+ }
31
+ if (typeof client_secret !== "string" || client_secret.length === 0) {
32
+ throw new TypeError("Expected a client_secret!");
33
+ }
34
+ return `Basic ${btoa(`${encodeURIComponent(client_id)}:${encodeURIComponent(client_secret)}`)}`;
35
+ }
36
+ /**
37
+ * POSTs an `application/x-www-form-urlencoded` request authenticated as the
38
+ * confidential client. Resolves with the response when it is a 2xx and
39
+ * throws {@link OAuthEndpointError} otherwise.
40
+ */
41
+ export async function postAsConfidentialClient(credentials, endpoint_name, url, form) {
42
+ const fetchImpl = credentials.fetch ?? fetch;
43
+ const response = await fetchImpl(url, {
44
+ method: "POST",
45
+ headers: new Headers({
46
+ Authorization: clientSecretBasicAuthorization(credentials),
47
+ "Content-Type": "application/x-www-form-urlencoded",
48
+ Accept: "application/json",
49
+ }),
50
+ body: form.toString(),
51
+ });
52
+ if (response.ok) {
53
+ return response;
54
+ }
55
+ let error = null;
56
+ let error_description = null;
57
+ try {
58
+ const body = await response.json();
59
+ if (typeof body === "object" && body !== null) {
60
+ const record = body;
61
+ if (typeof record.error === "string")
62
+ error = record.error;
63
+ if (typeof record.error_description === "string") {
64
+ error_description = record.error_description;
65
+ }
66
+ }
67
+ }
68
+ catch {
69
+ // Not a JSON error body.
70
+ }
71
+ throw new OAuthEndpointError(endpoint_name, response.status, error, error_description);
72
+ }
73
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/confidential-client/shared.ts"],"names":[],"mappings":"AAgBA;;;;;;GAMG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAClC,MAAM,CAAS;IACf,KAAK,CAAgB;IACrB,iBAAiB,CAAgB;IAE1C,YACE,QAAgB,EAChB,MAAc,EACd,KAAoB,EACpB,iBAAgC;QAEhC,KAAK,CACH,qBAAqB,QAAQ,0CAA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cAAc,EAAE,mCAAmC;YACnD,MAAM,EAAE,kBAAkB;SAC3B,CAAC;QACF,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE;KACtB,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,IAAI,KAAK,GAAkB,IAAI,CAAC;IAChC,IAAI,iBAAiB,GAAkB,IAAI,CAAC;IAC5C,IAAI,CAAC;QACH,MAAM,IAAI,GAAY,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAC9C,MAAM,MAAM,GAAG,IAA+B,CAAC;YAC/C,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ;gBAAE,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;YAC3D,IAAI,OAAO,MAAM,CAAC,iBAAiB,KAAK,QAAQ,EAAE,CAAC;gBACjD,iBAAiB,GAAG,MAAM,CAAC,iBAAiB,CAAC;YAC/C,CAAC;QACH,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,yBAAyB;IAC3B,CAAC;IACD,MAAM,IAAI,kBAAkB,CAAC,aAAa,EAAE,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC;AACzF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -36,6 +36,8 @@ export { listUserOrganizations, SUBJECT_TOKEN_HEADER_NAME, } from "./listUserOrg
36
36
  export type { IListUserOrganizationsOptions } from "./listUserOrganizations";
37
37
  export { getActorFromIntrospectionResult, introspectToken, tokenIntrospectionResultSchema, } from "./introspectToken";
38
38
  export type { IIntrospectTokenOptions, IntrospectedTokenActor, TokenIntrospectionResult, } from "./introspectToken";
39
+ export { exchangeTokenForDelegatedToken, delegatedTokenResponseSchema, revokeToken, OAuthEndpointError, } from "./confidential-client";
40
+ export type { ConfidentialClientCredentials, DelegatedTokenResponse, IExchangeTokenForDelegatedTokenOptions, IRevokeTokenOptions, } from "./confidential-client";
39
41
  export { userDataSchema } from "@schemavaults/auth-common";
40
42
  export type { UserData } from "@schemavaults/auth-common";
41
43
  export { organizationIdSchema, organizationDefinitionSchema, isValidOrganizationID, getAuthServerOwnerOrganizationId, DEFAULT_AUTH_SERVER_OWNER_ORGANIZATION_ID, isValidOrganizationMembershipRoleType, organizationMembershipRoleTypes, organizationMembershipRoleTypeSchema, } from "@schemavaults/auth-common/organizations";
package/dist/index.js CHANGED
@@ -28,6 +28,9 @@ export { isUserInOrganization } from "./isUserInOrganization";
28
28
  export { listUserOrganizations, SUBJECT_TOKEN_HEADER_NAME, } from "./listUserOrganizations";
29
29
  // RFC 7662 token introspection of this API server's access tokens
30
30
  export { getActorFromIntrospectionResult, introspectToken, tokenIntrospectionResultSchema, } from "./introspectToken";
31
+ // Confidential clients: delegated tokens for agents (RFC 8693 token
32
+ // exchange) and token revocation (RFC 7009)
33
+ export { exchangeTokenForDelegatedToken, delegatedTokenResponseSchema, revokeToken, OAuthEndpointError, } from "./confidential-client";
31
34
  // Re-export user data types
32
35
  export { userDataSchema } from "@schemavaults/auth-common";
33
36
  // Re-export organization types
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAG7B,cAAc,gBAAgB,CAAC;AAG/B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,yBAAyB,CAAC;AAGxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG1D,OAAO,EACL,qBAAqB,EACrB,cAAc,GACf,MAAM,qCAAqC,CAAC;AAG7C,OAAO,wBAAwB,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,CAAC;AAEpC,iBAAiB;AACjB,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,IAAI,0BAA0B,E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AAM,+BAA+B,CAAC;AAEjF,gBAAgB;AAChB,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAO1E,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAC3B,MAAM,mCAAmC,CAAC;AAE3C,6EAA6E;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,EACL,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AAGjC,kEAAkE;AAClE,OAAO,EACL,+BAA+B,EAC/B,eAAe,EACf,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAO3B,oEAAoE;AACpE,4CAA4C;AAC5C,OAAO,EACL,8BAA8B,EAC9B,4BAA4B,EAC5B,WAAW,EACX,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAQ/B,4BAA4B;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAG3D,+BAA+B;AAC/B,OAAO,EACL,oBAAoB,EACpB,4BAA4B,EAC5B,qBAAqB,EACrB,gCAAgC,EAChC,yCAAyC,EACzC,qCAAqC,EACrC,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,yCAAyC,CAAC;AAmBjD,8BAA8B;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEjE,kDAAkD;AAClD,OAAO,EAAE,OAAO,IAAI,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AAEjG,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schemavaults/auth-server-sdk",
3
3
  "description": "TypeScript SDK for building authenticated endpoints/middlewares for the Auth Server and Resource Servers",
4
- "version": "0.40.1",
4
+ "version": "0.41.1",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
7
7
  "repository": {
@@ -18,8 +18,8 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "zod": "4.6.7",
21
- "@schemavaults/jwt": "0.16.1",
22
- "@schemavaults/auth-common": "0.37.1",
21
+ "@schemavaults/jwt": "0.16.2",
22
+ "@schemavaults/auth-common": "0.38.0",
23
23
  "@schemavaults/app-definitions": "0.17.0"
24
24
  },
25
25
  "scripts": {
@@ -46,7 +46,7 @@
46
46
  "@typescript-eslint/eslint-plugin": "8.48.1",
47
47
  "@typescript-eslint/parser": "8.48.1",
48
48
  "esbuild": "0.27.3",
49
- "@schemavaults/openapi-operations": "0.6.1"
49
+ "@schemavaults/openapi-operations": "0.7.0"
50
50
  },
51
51
  "publishConfig": {
52
52
  "access": "public"
@@ -172,10 +172,15 @@
172
172
  "types": "./dist/api-scopes/index.d.ts",
173
173
  "import": "./dist/api-scopes/index.js",
174
174
  "require": "./dist/api-scopes/index.js"
175
+ },
176
+ "./confidential-client": {
177
+ "types": "./dist/confidential-client/index.d.ts",
178
+ "import": "./dist/confidential-client/index.js",
179
+ "require": "./dist/confidential-client/index.js"
175
180
  }
176
181
  },
177
182
  "peerDependencies": {
178
- "@schemavaults/openapi-operations": "0.6.1"
183
+ "@schemavaults/openapi-operations": "0.7.0"
179
184
  },
180
185
  "peerDependenciesMeta": {
181
186
  "@schemavaults/openapi-operations": {