@auth0/ai 4.0.2 → 5.0.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/dist/cjs/authorizers/{ciba/CIBAAuthorizationRequest.js → async-authorization/AsyncAuthorizationRequest.js} +1 -1
- package/dist/cjs/authorizers/async-authorization/AsyncAuthorizationRequest.js.map +1 -0
- package/dist/cjs/authorizers/{ciba/CIBAAuthorizerBase.js → async-authorization/AsyncAuthorizerBase.js} +4 -4
- package/dist/cjs/authorizers/async-authorization/AsyncAuthorizerBase.js.map +1 -0
- package/dist/cjs/authorizers/{ciba/CIBAAuthorizerParams.js → async-authorization/AsyncAuthorizerParams.js} +1 -1
- package/dist/cjs/authorizers/async-authorization/AsyncAuthorizerParams.js.map +1 -0
- package/dist/cjs/authorizers/{ciba → async-authorization}/asyncLocalStorage.js +4 -4
- package/dist/cjs/authorizers/async-authorization/asyncLocalStorage.js.map +1 -0
- package/dist/cjs/authorizers/async-authorization/index.js +9 -0
- package/dist/cjs/authorizers/async-authorization/index.js.map +1 -0
- package/dist/cjs/authorizers/device-authorizer/asyncLocalStorage.js +1 -1
- package/dist/cjs/authorizers/device-authorizer/asyncLocalStorage.js.map +1 -1
- package/dist/cjs/authorizers/{federated-connections/FederatedConnectionAuthorizerBase.js → token-vault/TokenVaultAuthorizerBase.js} +14 -14
- package/dist/cjs/authorizers/token-vault/TokenVaultAuthorizerBase.js.map +1 -0
- package/dist/cjs/authorizers/{federated-connections/FederatedConnectionAuthorizerParams.js → token-vault/TokenVaultAuthorizerParams.js} +1 -1
- package/dist/cjs/authorizers/token-vault/TokenVaultAuthorizerParams.js.map +1 -0
- package/dist/cjs/authorizers/{federated-connections → token-vault}/asyncLocalStorage.js +9 -9
- package/dist/cjs/authorizers/token-vault/asyncLocalStorage.js.map +1 -0
- package/dist/cjs/authorizers/token-vault/index.js +12 -0
- package/dist/cjs/authorizers/token-vault/index.js.map +1 -0
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/interrupts/{CIBAInterrupts.js → AsyncAuthorizationInterrupt.js} +19 -19
- package/dist/cjs/interrupts/AsyncAuthorizationInterrupt.js.map +1 -0
- package/dist/cjs/interrupts/{FederatedConnectionInterrupt.js → TokenVaultInterrupt.js} +9 -9
- package/dist/cjs/interrupts/TokenVaultInterrupt.js.map +1 -0
- package/dist/cjs/interrupts/index.js +12 -12
- package/dist/cjs/interrupts/index.js.map +1 -1
- package/dist/cjs/stores/Store.js +1 -1
- package/dist/cjs/stores/Store.js.map +1 -1
- package/dist/esm/authorizers/{ciba/CIBAAuthorizationRequest.d.ts → async-authorization/AsyncAuthorizationRequest.d.ts} +2 -2
- package/dist/esm/authorizers/async-authorization/AsyncAuthorizationRequest.js +2 -0
- package/dist/esm/authorizers/async-authorization/AsyncAuthorizationRequest.js.map +1 -0
- package/dist/esm/authorizers/{ciba/CIBAAuthorizerBase.d.ts → async-authorization/AsyncAuthorizerBase.d.ts} +7 -7
- package/dist/esm/authorizers/{ciba/CIBAAuthorizerBase.js → async-authorization/AsyncAuthorizerBase.js} +2 -2
- package/dist/esm/authorizers/async-authorization/AsyncAuthorizerBase.js.map +1 -0
- package/dist/esm/authorizers/{ciba/CIBAAuthorizerParams.d.ts → async-authorization/AsyncAuthorizerParams.d.ts} +6 -6
- package/dist/esm/authorizers/async-authorization/AsyncAuthorizerParams.js +2 -0
- package/dist/esm/authorizers/async-authorization/AsyncAuthorizerParams.js.map +1 -0
- package/dist/esm/authorizers/{ciba → async-authorization}/asyncLocalStorage.d.ts +1 -1
- package/dist/esm/authorizers/{ciba → async-authorization}/asyncLocalStorage.js +2 -2
- package/dist/esm/authorizers/async-authorization/asyncLocalStorage.js.map +1 -0
- package/dist/esm/authorizers/async-authorization/index.d.ts +4 -0
- package/dist/esm/authorizers/async-authorization/index.js +3 -0
- package/dist/esm/authorizers/async-authorization/index.js.map +1 -0
- package/dist/esm/authorizers/device-authorizer/asyncLocalStorage.js +1 -1
- package/dist/esm/authorizers/device-authorizer/asyncLocalStorage.js.map +1 -1
- package/dist/esm/authorizers/{federated-connections/FederatedConnectionAuthorizerBase.d.ts → token-vault/TokenVaultAuthorizerBase.d.ts} +6 -6
- package/dist/esm/authorizers/{federated-connections/FederatedConnectionAuthorizerBase.js → token-vault/TokenVaultAuthorizerBase.js} +12 -12
- package/dist/esm/authorizers/token-vault/TokenVaultAuthorizerBase.js.map +1 -0
- package/dist/esm/authorizers/{federated-connections/FederatedConnectionAuthorizerParams.d.ts → token-vault/TokenVaultAuthorizerParams.d.ts} +8 -8
- package/dist/esm/authorizers/{federated-connections/FederatedConnectionAuthorizerParams.js → token-vault/TokenVaultAuthorizerParams.js} +1 -1
- package/dist/esm/authorizers/token-vault/TokenVaultAuthorizerParams.js.map +1 -0
- package/dist/esm/authorizers/{federated-connections → token-vault}/asyncLocalStorage.d.ts +6 -6
- package/dist/esm/authorizers/{federated-connections → token-vault}/asyncLocalStorage.js +7 -7
- package/dist/esm/authorizers/token-vault/asyncLocalStorage.js.map +1 -0
- package/dist/esm/authorizers/token-vault/index.d.ts +6 -0
- package/dist/esm/authorizers/token-vault/index.js +4 -0
- package/dist/esm/authorizers/token-vault/index.js.map +1 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/interrupts/{CIBAInterrupts.d.ts → AsyncAuthorizationInterrupt.d.ts} +21 -21
- package/dist/esm/interrupts/{CIBAInterrupts.js → AsyncAuthorizationInterrupt.js} +17 -17
- package/dist/esm/interrupts/AsyncAuthorizationInterrupt.js.map +1 -0
- package/dist/esm/interrupts/{FederatedConnectionInterrupt.d.ts → TokenVaultInterrupt.d.ts} +5 -5
- package/dist/esm/interrupts/{FederatedConnectionInterrupt.js → TokenVaultInterrupt.js} +6 -6
- package/dist/esm/interrupts/TokenVaultInterrupt.js.map +1 -0
- package/dist/esm/interrupts/index.d.ts +2 -2
- package/dist/esm/interrupts/index.js +2 -2
- package/dist/esm/interrupts/index.js.map +1 -1
- package/dist/esm/stores/Store.d.ts +1 -1
- package/dist/esm/stores/Store.js +1 -1
- package/dist/esm/stores/Store.js.map +1 -1
- package/package.json +9 -9
- package/dist/cjs/authorizers/ciba/CIBAAuthorizationRequest.js.map +0 -1
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js.map +0 -1
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js.map +0 -1
- package/dist/cjs/authorizers/ciba/asyncLocalStorage.js.map +0 -1
- package/dist/cjs/authorizers/ciba/index.js +0 -9
- package/dist/cjs/authorizers/ciba/index.js.map +0 -1
- package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js.map +0 -1
- package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js.map +0 -1
- package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js.map +0 -1
- package/dist/cjs/authorizers/federated-connections/index.js +0 -12
- package/dist/cjs/authorizers/federated-connections/index.js.map +0 -1
- package/dist/cjs/interrupts/CIBAInterrupts.js.map +0 -1
- package/dist/cjs/interrupts/FederatedConnectionInterrupt.js.map +0 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizationRequest.js +0 -2
- package/dist/esm/authorizers/ciba/CIBAAuthorizationRequest.js.map +0 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js.map +0 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js +0 -2
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js.map +0 -1
- package/dist/esm/authorizers/ciba/asyncLocalStorage.js.map +0 -1
- package/dist/esm/authorizers/ciba/index.d.ts +0 -4
- package/dist/esm/authorizers/ciba/index.js +0 -3
- package/dist/esm/authorizers/ciba/index.js.map +0 -1
- package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js.map +0 -1
- package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js.map +0 -1
- package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js.map +0 -1
- package/dist/esm/authorizers/federated-connections/index.d.ts +0 -6
- package/dist/esm/authorizers/federated-connections/index.js +0 -4
- package/dist/esm/authorizers/federated-connections/index.js.map +0 -1
- package/dist/esm/interrupts/CIBAInterrupts.js.map +0 -1
- package/dist/esm/interrupts/FederatedConnectionInterrupt.js.map +0 -1
|
@@ -33,20 +33,20 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.DeviceInterrupt = exports.DeviceInterrupts = exports.InvalidGrantInterrupt = exports.AuthorizationPollingInterrupt = exports.AuthorizationPendingInterrupt = exports.AuthorizationRequestExpiredInterrupt = exports.UserDoesNotHavePushNotificationsInterrupt = exports.AccessDeniedInterrupt = exports.
|
|
36
|
+
exports.DeviceInterrupt = exports.DeviceInterrupts = exports.InvalidGrantInterrupt = exports.AuthorizationPollingInterrupt = exports.AuthorizationPendingInterrupt = exports.AuthorizationRequestExpiredInterrupt = exports.UserDoesNotHavePushNotificationsInterrupt = exports.AccessDeniedInterrupt = exports.AsyncAuthorizationInterrupt = exports.TokenVaultError = exports.TokenVaultInterrupt = exports.Auth0Interrupt = void 0;
|
|
37
37
|
var Auth0Interrupt_1 = require("./Auth0Interrupt");
|
|
38
38
|
Object.defineProperty(exports, "Auth0Interrupt", { enumerable: true, get: function () { return Auth0Interrupt_1.Auth0Interrupt; } });
|
|
39
|
-
var
|
|
40
|
-
Object.defineProperty(exports, "
|
|
41
|
-
Object.defineProperty(exports, "
|
|
42
|
-
var
|
|
43
|
-
Object.defineProperty(exports, "
|
|
44
|
-
Object.defineProperty(exports, "AccessDeniedInterrupt", { enumerable: true, get: function () { return
|
|
45
|
-
Object.defineProperty(exports, "UserDoesNotHavePushNotificationsInterrupt", { enumerable: true, get: function () { return
|
|
46
|
-
Object.defineProperty(exports, "AuthorizationRequestExpiredInterrupt", { enumerable: true, get: function () { return
|
|
47
|
-
Object.defineProperty(exports, "AuthorizationPendingInterrupt", { enumerable: true, get: function () { return
|
|
48
|
-
Object.defineProperty(exports, "AuthorizationPollingInterrupt", { enumerable: true, get: function () { return
|
|
49
|
-
Object.defineProperty(exports, "InvalidGrantInterrupt", { enumerable: true, get: function () { return
|
|
39
|
+
var TokenVaultInterrupt_1 = require("./TokenVaultInterrupt");
|
|
40
|
+
Object.defineProperty(exports, "TokenVaultInterrupt", { enumerable: true, get: function () { return TokenVaultInterrupt_1.TokenVaultInterrupt; } });
|
|
41
|
+
Object.defineProperty(exports, "TokenVaultError", { enumerable: true, get: function () { return TokenVaultInterrupt_1.TokenVaultError; } });
|
|
42
|
+
var AsyncAuthorizationInterrupt_1 = require("./AsyncAuthorizationInterrupt");
|
|
43
|
+
Object.defineProperty(exports, "AsyncAuthorizationInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.AsyncAuthorizationInterrupt; } });
|
|
44
|
+
Object.defineProperty(exports, "AccessDeniedInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.AccessDeniedInterrupt; } });
|
|
45
|
+
Object.defineProperty(exports, "UserDoesNotHavePushNotificationsInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.UserDoesNotHavePushNotificationsInterrupt; } });
|
|
46
|
+
Object.defineProperty(exports, "AuthorizationRequestExpiredInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.AuthorizationRequestExpiredInterrupt; } });
|
|
47
|
+
Object.defineProperty(exports, "AuthorizationPendingInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.AuthorizationPendingInterrupt; } });
|
|
48
|
+
Object.defineProperty(exports, "AuthorizationPollingInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.AuthorizationPollingInterrupt; } });
|
|
49
|
+
Object.defineProperty(exports, "InvalidGrantInterrupt", { enumerable: true, get: function () { return AsyncAuthorizationInterrupt_1.InvalidGrantInterrupt; } });
|
|
50
50
|
exports.DeviceInterrupts = __importStar(require("./DeviceInterrupts"));
|
|
51
51
|
var DeviceInterrupts_1 = require("./DeviceInterrupts");
|
|
52
52
|
Object.defineProperty(exports, "DeviceInterrupt", { enumerable: true, get: function () { return DeviceInterrupts_1.DeviceInterrupt; } });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interrupts/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interrupts/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,6DAG+B;AAF7B,0HAAA,mBAAmB,OAAA;AACnB,sHAAA,eAAe,OAAA;AAGjB,6EAQuC;AAPrC,0IAAA,2BAA2B,OAAA;AAC3B,oIAAA,qBAAqB,OAAA;AACrB,wJAAA,yCAAyC,OAAA;AACzC,mJAAA,oCAAoC,OAAA;AACpC,4IAAA,6BAA6B,OAAA;AAC7B,4IAAA,6BAA6B,OAAA;AAC7B,oIAAA,qBAAqB,OAAA;AAGvB,uEAAuD;AACvD,uDAAqD;AAA5C,mHAAA,eAAe,OAAA","sourcesContent":["export { Auth0Interrupt } from \"./Auth0Interrupt\";\n\nexport {\n TokenVaultInterrupt,\n TokenVaultError,\n} from \"./TokenVaultInterrupt\";\n\nexport {\n AsyncAuthorizationInterrupt,\n AccessDeniedInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n AuthorizationRequestExpiredInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n InvalidGrantInterrupt,\n} from \"./AsyncAuthorizationInterrupt\";\n\nexport * as DeviceInterrupts from \"./DeviceInterrupts\";\nexport { DeviceInterrupt } from \"./DeviceInterrupts\";\n"]}
|
package/dist/cjs/stores/Store.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Auth0AI uses this store in different stages:
|
|
6
6
|
*
|
|
7
7
|
* 1. to store the authorization request when an AI agent is interrupted (CIBA, Device Flow)
|
|
8
|
-
* 2. user credentials associated to threads to avoid re-authentication (CIBA, Device Flow,
|
|
8
|
+
* 2. user credentials associated to threads to avoid re-authentication (CIBA, Device Flow, Token Vault)
|
|
9
9
|
*
|
|
10
10
|
*/
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Store.js","sourceRoot":"","sources":["../../../src/stores/Store.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * A key-value store interface.\n *\n * Auth0AI uses this store in different stages:\n *\n * 1. to store the authorization request when an AI agent is interrupted (CIBA, Device Flow)\n * 2. user credentials associated to threads to avoid re-authentication (CIBA, Device Flow,
|
|
1
|
+
{"version":3,"file":"Store.js","sourceRoot":"","sources":["../../../src/stores/Store.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * A key-value store interface.\n *\n * Auth0AI uses this store in different stages:\n *\n * 1. to store the authorization request when an AI agent is interrupted (CIBA, Device Flow)\n * 2. user credentials associated to threads to avoid re-authentication (CIBA, Device Flow, Token Vault)\n *\n */\n\nexport interface Store<T = any> {\n /**\n *\n * Get a value from the store.\n *\n * @param namespace - The namespace of the key\n * @param key - The key\n */\n get(namespace: string[], key: string): Promise<T | undefined>;\n\n /**\n *\n * Delete a value from the store.\n * @param namespace - The namespace of the key\n * @param key - The key\n */\n delete(namespace: string[], key: string): Promise<void>;\n\n /**\n *\n * Put a value in the store.\n *\n * @param namespace - The namespace of the key\n * @param key - The key\n * @param value - The value to store\n * @param [options] - The options to store the value\n * @param [options.expiresIn] - The time in milliseconds to expire the value\n */\n put(\n namespace: string[],\n key: string,\n value: T,\n options?: { expiresIn?: number }\n ): Promise<void>;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type
|
|
1
|
+
export type AsyncAuthorizationRequest = {
|
|
2
2
|
/**
|
|
3
3
|
* The authorization request ID.
|
|
4
4
|
* Use this ID to check the status of the authorization request.
|
|
@@ -17,4 +17,4 @@ export type CIBAAuthorizationRequest = {
|
|
|
17
17
|
*/
|
|
18
18
|
interval: number;
|
|
19
19
|
};
|
|
20
|
-
//# sourceMappingURL=
|
|
20
|
+
//# sourceMappingURL=AsyncAuthorizationRequest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AsyncAuthorizationRequest.js","sourceRoot":"","sources":["../../../../src/authorizers/async-authorization/AsyncAuthorizationRequest.ts"],"names":[],"mappings":"","sourcesContent":["export type AsyncAuthorizationRequest = {\n /**\n * The authorization request ID.\n * Use this ID to check the status of the authorization request.\n */\n id: string;\n\n /**\n * The time the authorization request was made.\n */\n requestedAt: number;\n\n /**\n * The time in seconds for the authorization request to expire.\n */\n expiresIn: number;\n\n /**\n * The interval in seconds to use when polling the status.\n */\n interval: number;\n};\n"]}
|
|
@@ -2,24 +2,24 @@ import { TokenSet } from "../../credentials";
|
|
|
2
2
|
import { AuthorizationPendingInterrupt, AuthorizationPollingInterrupt } from "../../interrupts";
|
|
3
3
|
import { ContextGetter } from "../context";
|
|
4
4
|
import { Auth0ClientParams } from "../types";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { AsyncAuthorizationRequest } from "./AsyncAuthorizationRequest";
|
|
6
|
+
import { AsyncAuthorizerParams } from "./AsyncAuthorizerParams";
|
|
7
7
|
/**
|
|
8
8
|
* Requests authorization by prompting the user via an out-of-band channel from
|
|
9
9
|
* the backend.
|
|
10
10
|
*/
|
|
11
|
-
export declare class
|
|
11
|
+
export declare class AsyncAuthorizerBase<ToolExecuteArgs extends any[]> {
|
|
12
12
|
private readonly auth0;
|
|
13
13
|
private readonly authResponseStore;
|
|
14
14
|
private readonly credentialsStore;
|
|
15
15
|
private readonly params;
|
|
16
|
-
constructor(auth0: Partial<Auth0ClientParams>, params:
|
|
16
|
+
constructor(auth0: Partial<Auth0ClientParams>, params: AsyncAuthorizerParams<ToolExecuteArgs>);
|
|
17
17
|
private getInstanceID;
|
|
18
18
|
private start;
|
|
19
19
|
private getAuthorizeParams;
|
|
20
20
|
private getCredentialsInternal;
|
|
21
|
-
protected getCredentials(authRequest:
|
|
22
|
-
protected getCredentialsPolling(authRequest:
|
|
21
|
+
protected getCredentials(authRequest: AsyncAuthorizationRequest): Promise<TokenSet | undefined>;
|
|
22
|
+
protected getCredentialsPolling(authRequest: AsyncAuthorizationRequest): Promise<TokenSet | undefined>;
|
|
23
23
|
protected deleteAuthRequest(): Promise<void> | undefined;
|
|
24
24
|
/**
|
|
25
25
|
*
|
|
@@ -32,4 +32,4 @@ export declare class CIBAAuthorizerBase<ToolExecuteArgs extends any[]> {
|
|
|
32
32
|
protect(getContext: ContextGetter<ToolExecuteArgs>, execute: (...args: ToolExecuteArgs) => any): (...args: ToolExecuteArgs) => any;
|
|
33
33
|
protected handleAuthorizationInterrupts(err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt): Promise<void>;
|
|
34
34
|
}
|
|
35
|
-
//# sourceMappingURL=
|
|
35
|
+
//# sourceMappingURL=AsyncAuthorizerBase.d.ts.map
|
|
@@ -16,7 +16,7 @@ function ensureOpenIdScope(scopes) {
|
|
|
16
16
|
* Requests authorization by prompting the user via an out-of-band channel from
|
|
17
17
|
* the backend.
|
|
18
18
|
*/
|
|
19
|
-
export class
|
|
19
|
+
export class AsyncAuthorizerBase {
|
|
20
20
|
constructor(auth0, params) {
|
|
21
21
|
this.auth0 = new AuthenticationClient(Auth0ClientSchema.parse(auth0));
|
|
22
22
|
this.params = {
|
|
@@ -231,4 +231,4 @@ export class CIBAAuthorizerBase {
|
|
|
231
231
|
throw err;
|
|
232
232
|
}
|
|
233
233
|
}
|
|
234
|
-
//# sourceMappingURL=
|
|
234
|
+
//# sourceMappingURL=AsyncAuthorizerBase.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AsyncAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/async-authorization/AsyncAuthorizerBase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,UAAU,MAAM,aAAa,CAAC;AAErC,OAAO,EAAY,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EACL,qBAAqB,EACrB,6BAA6B,EAC7B,6BAA6B,EAC7B,oCAAoC,EACpC,qBAAqB,EACrB,yCAAyC,GAC1C,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAiB,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAqB,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAGhE,OAAO,EAAE,iBAAiB,EAAqB,MAAM,qBAAqB,CAAC;AAE3E,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAChF,SAAS,iBAAiB,CAAC,MAAgB;IACzC,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,CAAC;AACpE,CAAC;AACD;;;GAGG;AACH,MAAM,OAAO,mBAAmB;IAU9B,YACE,KAAiC,EACjC,MAA8C;QAE9C,IAAI,CAAC,KAAK,GAAG,IAAI,oB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iB,EAAE,CAAC;wBAC/B,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,KAAK,UAAU,EAAE,CAAC;4BACrD,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,GAAY,EAAE,GAAG,IAAI,CAAC,CAAC;wBAC3D,CAAC;6BAAM,CAAC;4BACN,OAAO,GAAG,CAAC;wBACb,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,UAAU,CAAC,WAAW,GAAG,WAAW,CAAC;gBACrC,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;IAES,KAAK,CAAC,6BAA6B,CAC3C,GAAkE;QAElE,IAAI,IAAI,CAAC,MAAM,CAAC,wBAAwB,EAAE,CAAC;YACzC,MAAM,KAAK,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;YAC3C,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;YACtE,CAAC;YACD,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;YAC1B,MAAM,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAC3D,CAAC;QACD,MAAM,GAAG,CAAC;IACZ,CAAC;CACF","sourcesContent":["import { AuthenticationClient } from \"auth0\";\nimport crypto from \"crypto\";\nimport stableHash from \"stable-hash\";\n\nimport { TokenSet, tokenSetFromTokenResponse } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\nimport { SubStore } from \"../../stores\";\nimport { RequireFields } from \"../../util\";\nimport { ContextGetter, nsFromContext } from \"../context\";\nimport { Auth0ClientParams, Auth0ClientSchema } from \"../types\";\nimport { AsyncAuthorizationRequest } from \"./AsyncAuthorizationRequest\";\nimport { AsyncAuthorizerParams } from \"./AsyncAuthorizerParams\";\nimport { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nfunction ensureOpenIdScope(scopes: string[]): string[] {\n return scopes.includes(\"openid\") ? scopes : [\"openid\", ...scopes];\n}\n/**\n * Requests authorization by prompting the user via an out-of-band channel from\n * the backend.\n */\nexport class AsyncAuthorizerBase<ToolExecuteArgs extends any[]> {\n private readonly auth0: AuthenticationClient;\n private readonly authResponseStore: SubStore | undefined;\n private readonly credentialsStore: SubStore<TokenSet> | undefined;\n\n private readonly params: RequireFields<\n AsyncAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: AsyncAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient(Auth0ClientSchema.parse(auth0));\n this.params = {\n credentialsContext: \"tool-call\",\n ...params,\n };\n\n this.authResponseStore = new SubStore<AsyncAuthorizationRequest>(\n params.store,\n {\n getTTL: (authResponse) =>\n authResponse.expiresIn ? authResponse.expiresIn * 1000 : undefined,\n }\n );\n\n this.credentialsStore = new SubStore<TokenSet>(params.store, {\n getTTL: (credentials) =>\n credentials.expiresIn ? credentials.expiresIn * 1000 : undefined,\n });\n }\n\n private getInstanceID(authorizeParams: any): string {\n const props = {\n auth0: this.auth0,\n params: authorizeParams,\n };\n const sh = stableHash(props);\n return crypto.createHash(\"MD5\").update(sh).digest(\"hex\");\n }\n\n private async start(authorizeParams: any): Promise<AsyncAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n\n try {\n const response = await this.auth0.backchannel.authorize(authorizeParams);\n\n return {\n id: response.auth_req_id,\n requestedAt: requestedAt,\n expiresIn: response.expires_in,\n interval: response.interval,\n };\n } catch (err: any) {\n if (err.error == \"invalid_request\") {\n throw new UserDoesNotHavePushNotificationsInterrupt(\n err.error_description\n );\n }\n throw err;\n }\n }\n\n private async getAuthorizeParams(toolContext: ToolExecuteArgs) {\n const authParams: Record<string, any> = {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n audience: this.params.audience || \"\",\n requested_expiry: (this.params.requestedExpiry ?? 300).toString(),\n binding_message:\n (await resolveParameter(this.params.bindingMessage, toolContext)) ?? \"\",\n userId: (await resolveParameter(this.params.userID, toolContext)) ?? \"\",\n };\n\n const authorizationDetails = await resolveParameter(\n this.params.authorizationDetails,\n toolContext\n );\n\n // If authorizationDetails is an array, we need to convert it to a string\n // because the auth0 library expects a valid JSON string.\n if (authorizationDetails !== undefined) {\n authParams.authorization_details = JSON.stringify(authorizationDetails);\n }\n\n // Remove undefined values from the authParams object\n return Object.fromEntries(\n Object.entries(authParams).filter(([, value]) => value !== undefined)\n );\n }\n\n private async getCredentialsInternal(\n authRequest: AsyncAuthorizationRequest\n ): Promise<TokenSet | undefined> {\n try {\n const elapsedSeconds = Date.now() / 1000 - authRequest.requestedAt;\n\n if (elapsedSeconds >= authRequest.expiresIn) {\n throw new AuthorizationRequestExpiredInterrupt(\n \"The authorization request has expired.\",\n authRequest\n );\n }\n\n const response = await this.auth0.backchannel.backchannelGrant({\n auth_req_id: authRequest.id,\n });\n\n const credentials = tokenSetFromTokenResponse(response);\n\n return credentials;\n } catch (e: any) {\n if (e.error === \"authorization_pending\") {\n throw new AuthorizationPendingInterrupt(\n e.error_description,\n authRequest\n );\n }\n\n if (e.error === \"slow_down\") {\n throw new AuthorizationPollingInterrupt(\n e.error_description,\n authRequest,\n Number(e.headers.get('retry-after'))\n );\n }\n\n if (e.error == \"invalid_grant\") {\n throw new InvalidGrantInterrupt(e.error_description, authRequest);\n }\n\n if (e.error == \"invalid_request\") {\n throw new UserDoesNotHavePushNotificationsInterrupt(\n e.error_description\n );\n }\n\n if (e.error == \"access_denied\") {\n throw new AccessDeniedInterrupt(e.error_description, authRequest);\n }\n\n throw e;\n }\n }\n\n protected async getCredentials(authRequest: AsyncAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: AsyncAuthorizationRequest\n ): Promise<TokenSet | undefined> {\n let credentials: TokenSet | undefined = undefined;\n\n do {\n try {\n credentials = await this.getCredentialsInternal(authRequest);\n } catch (err) {\n if (\n err instanceof AuthorizationPendingInterrupt ||\n err instanceof AuthorizationPollingInterrupt\n ) {\n await sleep(err.nextRetryInterval() * 1000);\n } else {\n throw err;\n }\n }\n } while (!credentials);\n\n return credentials;\n }\n\n protected deleteAuthRequest() {\n const store = asyncLocalStorage.getStore();\n if (!store) {\n throw new Error(\"This method should be called from within a tool.\");\n }\n const { authResponseNS } = store;\n return this.authResponseStore?.delete(authResponseNS, \"authResponse\");\n }\n\n /**\n *\n * Wraps the execute method of a AI tool to handle CIBA authorization.\n *\n * @param getContext - A function that returns the context of the tool execution.\n * @param execute - The tool execute method.\n * @returns The wrapped execute method.\n */\n protect(\n getContext: ContextGetter<ToolExecuteArgs>,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authResponse: AsyncAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const context = getContext(...args);\n const authorizeParams = await this.getAuthorizeParams(args);\n const instanceID = this.getInstanceID(authorizeParams);\n const authResponseNS = [\n instanceID,\n \"AuthResponses\",\n ...nsFromContext(\"tool-call\", context),\n ];\n const credentialsNS = [\n instanceID,\n \"Credentials\",\n ...nsFromContext(this.params.credentialsContext, context),\n ];\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context,\n authResponseNS,\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: TokenSet | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n credentials = await this.credentialsStore?.get(\n credentialsNS,\n \"credential\"\n );\n if (!credentials) {\n if (interruptMode) {\n authResponse = await this.authResponseStore?.get(\n authResponseNS,\n \"authResponse\"\n );\n if (!authResponse) {\n //Initial request\n authResponse = await this.start(authorizeParams);\n await this.authResponseStore?.put(\n authResponseNS,\n \"authResponse\",\n authResponse\n );\n }\n credentials = await this.getCredentials(authResponse);\n } else {\n authResponse = await this.start(authorizeParams);\n const credentialsPromise =\n this.getCredentialsPolling(authResponse);\n if (typeof this.params.onAuthorizationRequest === \"function\") {\n await this.params.onAuthorizationRequest(\n authResponse,\n credentialsPromise\n );\n }\n credentials = await credentialsPromise;\n }\n await this.deleteAuthRequest();\n if (typeof credentials !== \"undefined\") {\n this.credentialsStore?.put(\n credentialsNS,\n \"credential\",\n credentials\n );\n }\n }\n } catch (err) {\n const shouldInterrupt =\n err instanceof AuthorizationPendingInterrupt ||\n err instanceof AuthorizationPollingInterrupt;\n if (shouldInterrupt) {\n return this.handleAuthorizationInterrupts(err);\n } else {\n await this.deleteAuthRequest();\n if (typeof this.params.onUnauthorized === \"function\") {\n return this.params.onUnauthorized(err as Error, ...args);\n } else {\n return err;\n }\n }\n }\n storeValue.credentials = credentials;\n return execute(...args);\n });\n };\n }\n\n protected async handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n if (this.params.onAuthorizationInterrupt) {\n const store = asyncLocalStorage.getStore();\n if (!store) {\n throw new Error(\"This method should be called from within a tool.\");\n }\n const { context } = store;\n await this.params.onAuthorizationInterrupt(err, context);\n }\n throw err;\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { AuthorizationDetails, TokenSet } from "../../credentials";
|
|
2
|
-
import { AuthorizationPendingInterrupt, AuthorizationPollingInterrupt
|
|
2
|
+
import { AsyncAuthorizationInterrupt, AuthorizationPendingInterrupt, AuthorizationPollingInterrupt } from "../../interrupts";
|
|
3
3
|
import { AuthorizerToolParameter } from "../../parameters";
|
|
4
4
|
import { Store } from "../../stores";
|
|
5
5
|
import { AuthContext, ToolCallContext } from "../context";
|
|
6
6
|
import { OnAuthorizationRequest } from "../types";
|
|
7
|
-
import {
|
|
8
|
-
export type
|
|
7
|
+
import { AsyncAuthorizationRequest } from "./AsyncAuthorizationRequest";
|
|
8
|
+
export type AsyncAuthorizerParams<ToolExecuteArgs extends any[]> = {
|
|
9
9
|
/**
|
|
10
10
|
* The scope to request authorization for.
|
|
11
11
|
*/
|
|
@@ -42,7 +42,7 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
|
|
|
42
42
|
* Defaults to `interrupt`.
|
|
43
43
|
* Note: The block mode is only useful for development purposes and should not be used in production.
|
|
44
44
|
*/
|
|
45
|
-
onAuthorizationRequest?: OnAuthorizationRequest | ((authReq:
|
|
45
|
+
onAuthorizationRequest?: OnAuthorizationRequest | ((authReq: AsyncAuthorizationRequest, poll: Promise<TokenSet | undefined>) => Promise<void>);
|
|
46
46
|
/**
|
|
47
47
|
* AuthContext defines the scope of credential sharing:
|
|
48
48
|
* - "tool-call": Credentials are valid only for a single invocation of the tool.
|
|
@@ -62,7 +62,7 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
|
|
|
62
62
|
* @param args - The tool execution arguments.
|
|
63
63
|
* @returns The response to return when the invocation is not authorized.
|
|
64
64
|
*/
|
|
65
|
-
onUnauthorized?: (err: Error |
|
|
65
|
+
onUnauthorized?: (err: Error | AsyncAuthorizationInterrupt, ...args: ToolExecuteArgs) => any;
|
|
66
66
|
/**
|
|
67
67
|
* Callback called before the authorization interrupt is thrown.
|
|
68
68
|
* This callback is useful to setup CIBA pollers.
|
|
@@ -77,4 +77,4 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
|
|
|
77
77
|
*/
|
|
78
78
|
store: Store;
|
|
79
79
|
};
|
|
80
|
-
//# sourceMappingURL=
|
|
80
|
+
//# sourceMappingURL=AsyncAuthorizerParams.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AsyncAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/async-authorization/AsyncAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { AuthorizationDetails, TokenSet } from \"../../credentials\";\nimport {\n AsyncAuthorizationInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n} from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext, ToolCallContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { AsyncAuthorizationRequest } from \"./AsyncAuthorizationRequest\";\n\nexport type AsyncAuthorizerParams<ToolExecuteArgs extends any[]> = {\n /**\n * The scope to request authorization for.\n */\n scopes: string[];\n\n /**\n * The user ID to request authorization for.\n */\n userID: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The binding message to send to the user.\n */\n bindingMessage: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The authorization parameters for RAR request.\n */\n authorizationDetails?: AuthorizerToolParameter<\n ToolExecuteArgs,\n AuthorizationDetails[]\n >;\n\n /**\n * The audience to request authorization for.\n */\n audience?: string;\n\n /**\n * The time in seconds for the authorization request to expire.\n *\n * Defaults to 300 (5 minutes).\n */\n requestedExpiry?: number;\n\n /**\n * The behavior when the authorization request is made.\n *\n * - `block`: The tool execution is blocked until the user completes the authorization.\n * - `interrupt`: The tool execution is interrupted until the user completes the authorization.\n * - a callback: Same as \"block\" but give access to the auth request and executing logic.\n *\n * Defaults to `interrupt`.\n * Note: The block mode is only useful for development purposes and should not be used in production.\n */\n onAuthorizationRequest?:\n | OnAuthorizationRequest\n | ((\n authReq: AsyncAuthorizationRequest,\n poll: Promise<TokenSet | undefined>\n ) => Promise<void>);\n\n /**\n * AuthContext defines the scope of credential sharing:\n * - \"tool-call\": Credentials are valid only for a single invocation of the tool.\n * - \"tool\": Credentials are shared across multiple calls to the same tool within the same thread.\n * - \"thread\": Credentials are shared across all tools using the same authorizer within the current thread.\n * - \"agent\": Credentials are shared globally across all threads and tools in the agent.\n *\n * @default \"tool-call\"\n */\n credentialsContext?: AuthContext;\n\n /**\n *\n * Optional callback to generate a tool result when the invocation is not authorized.\n *\n * By default it will return the instance of the Error.\n *\n * @param args - The tool execution arguments.\n * @returns The response to return when the invocation is not authorized.\n */\n onUnauthorized?: (\n err: Error | AsyncAuthorizationInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\n\n /**\n * Callback called before the authorization interrupt is thrown.\n * This callback is useful to setup CIBA pollers.\n *\n * @param interrupt - The interrupt that is about to be thrown.\n * @param args - The tool execution arguments.\n */\n onAuthorizationInterrupt?: (\n interrupt: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt,\n context: ToolCallContext,\n ) => void | Promise<void>;\n\n /**\n * An store used to temporarly store the authorization response data\n * while the user is completing the authorization in another device.\n */\n store: Store;\n};\n"]}
|
|
@@ -16,5 +16,5 @@ export type AsyncStorageValue<TContext> = {
|
|
|
16
16
|
authResponseNS: string[];
|
|
17
17
|
};
|
|
18
18
|
export declare const asyncLocalStorage: AsyncLocalStorage<AsyncStorageValue<any>>;
|
|
19
|
-
export declare const
|
|
19
|
+
export declare const getAsyncAuthorizationCredentials: () => TokenSet | undefined;
|
|
20
20
|
//# sourceMappingURL=asyncLocalStorage.d.ts.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "async_hooks";
|
|
2
2
|
export const asyncLocalStorage = new AsyncLocalStorage();
|
|
3
|
-
export const
|
|
3
|
+
export const getAsyncAuthorizationCredentials = () => {
|
|
4
4
|
const t = asyncLocalStorage.getStore();
|
|
5
5
|
if (typeof t === "undefined") {
|
|
6
|
-
throw new Error("The tool must be wrapped with the
|
|
6
|
+
throw new Error("The tool must be wrapped with the withAsyncAuthorization function.");
|
|
7
7
|
}
|
|
8
8
|
return t.credentials;
|
|
9
9
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/async-authorization/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAuBhD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAEnD,CAAC;AAEJ,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,EAAE;IACnD,MAAM,CAAC,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IACvC,IAAI,OAAO,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC,WAAW,CAAC;AACvB,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\nimport { TokenSet } from \"../../credentials\";\n\nexport type AsyncStorageValue<TContext> = {\n credentials?: TokenSet;\n\n /**\n * The tool execution context.\n */\n context: TContext;\n\n /**\n * The tool execution arguments.\n */\n args: any[];\n\n /**\n * The namespace in the Store for the CIBA authorization response.\n */\n authResponseNS: string[];\n};\n\nexport const asyncLocalStorage = new AsyncLocalStorage<\n AsyncStorageValue<any>\n>();\n\nexport const getAsyncAuthorizationCredentials = () => {\n const t = asyncLocalStorage.getStore();\n if (typeof t === \"undefined\") {\n throw new Error(\n \"The tool must be wrapped with the withAsyncAuthorization function.\"\n );\n }\n return t.credentials;\n};\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/async-authorization/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;AAI1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["export { asyncLocalStorage, getAsyncAuthorizationCredentials } from \"./asyncLocalStorage\";\n\nexport type { AsyncAuthorizationRequest } from \"./AsyncAuthorizationRequest\";\n\nexport { AsyncAuthorizerBase } from \"./AsyncAuthorizerBase\";\n"]}
|
|
@@ -3,7 +3,7 @@ export const asyncLocalStorage = new AsyncLocalStorage();
|
|
|
3
3
|
export const getDeviceAuthorizerCredentials = () => {
|
|
4
4
|
const t = asyncLocalStorage.getStore();
|
|
5
5
|
if (typeof t === "undefined") {
|
|
6
|
-
throw new Error("The tool must be wrapped with the
|
|
6
|
+
throw new Error("The tool must be wrapped with the withAsyncAuthorization function.");
|
|
7
7
|
}
|
|
8
8
|
return t.credentials;
|
|
9
9
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/device-authorizer/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAkBhD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAEnD,CAAC;AAEJ,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,EAAE;IACjD,MAAM,CAAC,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IACvC,IAAI,OAAO,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CACb,
|
|
1
|
+
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/device-authorizer/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAkBhD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAEnD,CAAC;AAEJ,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,EAAE;IACjD,MAAM,CAAC,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IACvC,IAAI,OAAO,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC,WAAW,CAAC;AACvB,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\nimport { TokenSet } from \"../../credentials\";\n\nexport type AsyncStorageValue<TContext> = {\n credentials?: TokenSet;\n\n /**\n * The tool execution context.\n */\n context: TContext;\n\n /**\n * The tool execution arguments.\n */\n args: any[];\n};\n\nexport const asyncLocalStorage = new AsyncLocalStorage<\n AsyncStorageValue<any>\n>();\n\nexport const getDeviceAuthorizerCredentials = () => {\n const t = asyncLocalStorage.getStore();\n if (typeof t === \"undefined\") {\n throw new Error(\n \"The tool must be wrapped with the withAsyncAuthorization function.\"\n );\n }\n return t.credentials;\n};\n"]}
|
|
@@ -2,15 +2,15 @@ import { TokenResponse, TokenSet } from "../../credentials";
|
|
|
2
2
|
import { Auth0Interrupt } from "../../interrupts";
|
|
3
3
|
import { ContextGetter } from "../context";
|
|
4
4
|
import { Auth0ClientParams } from "../types";
|
|
5
|
-
import {
|
|
5
|
+
import { TokenVaultAuthorizerParams } from "./TokenVaultAuthorizerParams";
|
|
6
6
|
/**
|
|
7
|
-
* Requests authorization to a third party service via
|
|
7
|
+
* Requests authorization to a third party service via Token Vault.
|
|
8
8
|
*/
|
|
9
|
-
export declare class
|
|
9
|
+
export declare class TokenVaultAuthorizerBase<ToolExecuteArgs extends any[]> {
|
|
10
10
|
private readonly auth0;
|
|
11
11
|
private readonly params;
|
|
12
12
|
private readonly credentialsStore;
|
|
13
|
-
constructor(auth0: Partial<Auth0ClientParams>, params:
|
|
13
|
+
constructor(auth0: Partial<Auth0ClientParams>, params: TokenVaultAuthorizerParams<ToolExecuteArgs>);
|
|
14
14
|
private getInstanceID;
|
|
15
15
|
protected handleAuthorizationInterrupts(err: Auth0Interrupt): void;
|
|
16
16
|
protected validateToken(tokenResponse?: TokenResponse): void;
|
|
@@ -20,7 +20,7 @@ export declare class FederatedConnectionAuthorizerBase<ToolExecuteArgs extends a
|
|
|
20
20
|
protected getAccessTokenWithToolContext(...toolContext: ToolExecuteArgs): Promise<string | TokenResponse | undefined>;
|
|
21
21
|
/**
|
|
22
22
|
*
|
|
23
|
-
* Wraps the execute method of an AI tool to handle
|
|
23
|
+
* Wraps the execute method of an AI tool to handle Token Vaults authorization.
|
|
24
24
|
*
|
|
25
25
|
* @param getContext - A function that returns the context of the tool execution.
|
|
26
26
|
* @param execute - The tool execute method.
|
|
@@ -28,4 +28,4 @@ export declare class FederatedConnectionAuthorizerBase<ToolExecuteArgs extends a
|
|
|
28
28
|
*/
|
|
29
29
|
protect(getContext: ContextGetter<ToolExecuteArgs>, execute: (...args: ToolExecuteArgs) => any): (...args: ToolExecuteArgs) => any;
|
|
30
30
|
}
|
|
31
|
-
//# sourceMappingURL=
|
|
31
|
+
//# sourceMappingURL=TokenVaultAuthorizerBase.d.ts.map
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import crypto from "crypto";
|
|
2
2
|
import stableHash from "stable-hash";
|
|
3
|
-
import { tokenSetFromTokenResponse
|
|
4
|
-
import { Auth0Interrupt,
|
|
3
|
+
import { tokenSetFromTokenResponse } from "../../credentials";
|
|
4
|
+
import { Auth0Interrupt, TokenVaultError, TokenVaultInterrupt } from "../../interrupts";
|
|
5
5
|
import { resolveParameter } from "../../parameters";
|
|
6
6
|
import { SubStore } from "../../stores";
|
|
7
7
|
import { omit } from "../../util";
|
|
8
8
|
import { nsFromContext } from "../context";
|
|
9
9
|
import { Auth0ClientSchema } from "../types";
|
|
10
10
|
import { asyncLocalStorage } from "./asyncLocalStorage";
|
|
11
|
-
import { SUBJECT_TOKEN_TYPES
|
|
11
|
+
import { SUBJECT_TOKEN_TYPES } from "./TokenVaultAuthorizerParams";
|
|
12
12
|
/**
|
|
13
|
-
* Requests authorization to a third party service via
|
|
13
|
+
* Requests authorization to a third party service via Token Vault.
|
|
14
14
|
*/
|
|
15
|
-
export class
|
|
15
|
+
export class TokenVaultAuthorizerBase {
|
|
16
16
|
constructor(auth0, params) {
|
|
17
17
|
this.auth0 = Auth0ClientSchema.parse(auth0);
|
|
18
18
|
this.params = {
|
|
@@ -67,7 +67,7 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
67
67
|
}
|
|
68
68
|
const { scopes, connection } = store;
|
|
69
69
|
if (!tokenResponse) {
|
|
70
|
-
throw new
|
|
70
|
+
throw new TokenVaultInterrupt(`Authorization required to access the Token Vault: ${this.params.connection}`, connection, scopes, scopes);
|
|
71
71
|
}
|
|
72
72
|
const currentScopes = ((_a = tokenResponse.scope) !== null && _a !== void 0 ? _a : "")
|
|
73
73
|
.replace(/,/g, " ")
|
|
@@ -75,7 +75,7 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
75
75
|
const missingScopes = scopes.filter((s) => !currentScopes.includes(s));
|
|
76
76
|
store.currentScopes = currentScopes;
|
|
77
77
|
if (missingScopes.length > 0) {
|
|
78
|
-
throw new
|
|
78
|
+
throw new TokenVaultInterrupt(`Authorization required to access the Token Vault: ${this.params.connection}. Missing scopes: ${missingScopes.join(", ")}`, connection, scopes, [...currentScopes, ...scopes]);
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
async getAccessTokenImpl(...toolContext) {
|
|
@@ -156,7 +156,7 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
156
156
|
}
|
|
157
157
|
/**
|
|
158
158
|
*
|
|
159
|
-
* Wraps the execute method of an AI tool to handle
|
|
159
|
+
* Wraps the execute method of an AI tool to handle Token Vaults authorization.
|
|
160
160
|
*
|
|
161
161
|
* @param getContext - A function that returns the context of the tool execution.
|
|
162
162
|
* @param execute - The tool execute method.
|
|
@@ -171,7 +171,7 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
171
171
|
connection: this.params.connection,
|
|
172
172
|
};
|
|
173
173
|
if (asyncLocalStorage.getStore()) {
|
|
174
|
-
throw new Error("Cannot nest tool calls that require
|
|
174
|
+
throw new Error("Cannot nest tool calls that require Token Vault authorization.");
|
|
175
175
|
}
|
|
176
176
|
return asyncLocalStorage.run(asyncStore, async () => {
|
|
177
177
|
const credentialsNS = nsFromContext(this.params.credentialsContext, context);
|
|
@@ -185,9 +185,9 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
185
185
|
return await execute(...args);
|
|
186
186
|
}
|
|
187
187
|
catch (err) {
|
|
188
|
-
if (err instanceof
|
|
188
|
+
if (err instanceof TokenVaultError) {
|
|
189
189
|
this.credentialsStore.delete(credentialsNS, "credential");
|
|
190
|
-
const interrupt = new
|
|
190
|
+
const interrupt = new TokenVaultInterrupt(err.message, asyncStore.connection, asyncStore.scopes, asyncStore.scopes);
|
|
191
191
|
return this.handleAuthorizationInterrupts(interrupt);
|
|
192
192
|
}
|
|
193
193
|
if (err instanceof Auth0Interrupt) {
|
|
@@ -200,4 +200,4 @@ export class FederatedConnectionAuthorizerBase {
|
|
|
200
200
|
};
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
|
-
//# sourceMappingURL=
|
|
203
|
+
//# sourceMappingURL=TokenVaultAuthorizerBase.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenVaultAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/token-vault/TokenVaultAuthorizerBase.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,UAAU,MAAM,aAAa,CAAC;AAErC,OAAO,EAA2B,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACxF,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,IAAI,EAAiB,MAAM,YAAY,CAAC;AACjD,OAAO,EAAiB,aAAa,EAAE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AC,GAAG,CAAC,CAAC;oBACjD,CAAC;oBACD,MAAM,GAAG,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import crypto from \"crypto\";\nimport stableHash from \"stable-hash\";\n\nimport { TokenResponse, TokenSet, tokenSetFromTokenResponse } from \"../../credentials\";\nimport { Auth0Interrupt, TokenVaultError, TokenVaultInterrupt } from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\nimport { SubStore } from \"../../stores\";\nimport { omit, RequireFields } from \"../../util\";\nimport { ContextGetter, nsFromContext } from \"../context\";\nimport { Auth0ClientParams, Auth0ClientSchema } from \"../types\";\nimport { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { SUBJECT_TOKEN_TYPES, TokenVaultAuthorizerParams } from \"./TokenVaultAuthorizerParams\";\n\n/**\n * Requests authorization to a third party service via Token Vault.\n */\n\nexport class TokenVaultAuthorizerBase<ToolExecuteArgs extends any[]> {\n private readonly auth0: Auth0ClientParams;\n private readonly params: RequireFields<\n TokenVaultAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n private readonly credentialsStore: SubStore<TokenSet>;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: TokenVaultAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = Auth0ClientSchema.parse(auth0);\n this.params = {\n credentialsContext: \"thread\",\n ...params,\n };\n\n const instanceID = this.getInstanceID();\n\n this.credentialsStore = new SubStore<TokenSet>(params.store, {\n baseNamespace: [instanceID, \"Credentials\"],\n getTTL: (credentials) =>\n credentials.expiresIn ? credentials.expiresIn * 1000 : undefined,\n });\n\n // Validate that exactly one token source is provided\n const hasRefreshToken = typeof params.refreshToken !== \"undefined\";\n const hasAccessToken = typeof params.accessToken !== \"undefined\";\n const hasSubjectTokenType = typeof params.subjectTokenType !== \"undefined\";\n\n if (!hasRefreshToken && !hasAccessToken) {\n throw new Error(\n \"Either refreshToken or accessToken must be provided to initialize the Authorizer.\"\n );\n }\n\n if (hasRefreshToken && hasAccessToken) {\n throw new Error(\n \"Only one of refreshToken or accessToken can be provided to initialize the Authorizer.\"\n );\n }\n\n // Validate resource server client credentials when using access tokens for token exchange w/ Token Vault\n if (\n hasAccessToken &&\n hasSubjectTokenType &&\n params.subjectTokenType === SUBJECT_TOKEN_TYPES.SUBJECT_TYPE_ACCESS_TOKEN\n ) {\n if (!this.auth0.clientId || !this.auth0.clientSecret) {\n throw new Error(\n \"clientId and clientSecret must currently be provided when using accessToken for token exchange with Token Vault.\"\n );\n }\n }\n }\n\n private getInstanceID(): string {\n const props = {\n auth0: this.auth0,\n params: omit(this.params, [\n \"store\",\n \"refreshToken\",\n \"accessToken\",\n \"loginHint\",\n ]),\n };\n const sh = stableHash(props);\n return crypto.createHash(\"MD5\").update(sh).digest(\"hex\");\n }\n\n protected handleAuthorizationInterrupts(err: Auth0Interrupt) {\n throw err;\n }\n\n protected validateToken(tokenResponse?: TokenResponse) {\n const store = asyncLocalStorage.getStore();\n if (!store) {\n throw new Error(\n \"The tool must be wrapped with the FederationConnectionAuthorizer.\"\n );\n }\n\n const { scopes, connection } = store;\n\n if (!tokenResponse) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}`,\n connection,\n scopes,\n scopes\n );\n }\n\n const currentScopes = (tokenResponse.scope ?? \"\")\n .replace(/,/g, \" \")\n .split(\" \");\n const missingScopes = scopes.filter((s) => !currentScopes.includes(s));\n store.currentScopes = currentScopes;\n\n if (missingScopes.length > 0) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}. Missing scopes: ${missingScopes.join(\", \")}`,\n connection,\n scopes,\n [...currentScopes, ...scopes]\n );\n }\n }\n\n private async getAccessTokenImpl(\n ...toolContext: ToolExecuteArgs\n ): Promise<TokenResponse | undefined> {\n const store = asyncLocalStorage.getStore();\n if (!store) {\n throw new Error(\n \"The tool must be wrapped with the FederationConnectionAuthorizer.\"\n );\n }\n\n const { connection } = store;\n\n // Determine which token type to use and get the appropriate subject token\n let subjectToken: string | undefined;\n let subjectTokenType: string;\n\n if (typeof this.params.refreshToken === \"function\") {\n subjectToken = await this.getRefreshToken(...toolContext);\n subjectTokenType = \"urn:ietf:params:oauth:token-type:refresh_token\";\n } else if (typeof this.params.accessToken === \"function\") {\n subjectToken = (await this.getAccessTokenWithToolContext(\n ...toolContext\n )) as string;\n subjectTokenType = \"urn:ietf:params:oauth:token-type:access_token\";\n } else if (typeof this.params.accessToken === \"string\") {\n subjectToken = this.params.accessToken;\n subjectTokenType = \"urn:ietf:params:oauth:token-type:access_token\";\n } else {\n // This should never happen due to constructor validation, but TypeScript needs this\n throw new Error(\"Either refreshToken or accessToken must be configured\");\n }\n\n if (!subjectToken) {\n return;\n }\n\n // Get optional login hint if provided\n const loginHint =\n typeof this.params.loginHint === \"function\"\n ? await resolveParameter(this.params.loginHint, toolContext)\n : undefined;\n\n const exchangeParams = {\n grant_type:\n \"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token\",\n client_id: this.auth0.clientId,\n client_secret: this.auth0.clientSecret,\n subject_token_type: subjectTokenType,\n subject_token: subjectToken,\n login_hint: loginHint,\n connection: connection,\n requested_token_type:\n \"http://auth0.com/oauth/token-type/federated-connection-access-token\",\n };\n\n const res = await fetch(`https://${this.auth0.domain}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(exchangeParams),\n });\n\n if (!res.ok) {\n //TODO: handle all type of response errors.\n return;\n }\n\n const tokenResponse: TokenResponse = await res.json();\n return tokenResponse;\n }\n\n protected async getAccessToken(\n ...toolContext: ToolExecuteArgs\n ): Promise<TokenSet> {\n let tokenResponse: TokenResponse | undefined;\n // Use token exchange for both refresh tokens and access tokens when subjectTokenType is provided\n if (\n typeof this.params.refreshToken === \"function\" ||\n (typeof this.params.accessToken !== \"undefined\" &&\n this.params.subjectTokenType ===\n SUBJECT_TOKEN_TYPES.SUBJECT_TYPE_ACCESS_TOKEN)\n ) {\n tokenResponse = await this.getAccessTokenImpl(...toolContext);\n } else {\n // fallback to existing behavior, where third party accessToken can be provided directly\n tokenResponse = (await resolveParameter(\n this.params.accessToken!,\n toolContext\n )) as TokenResponse;\n }\n this.validateToken(tokenResponse);\n return tokenSetFromTokenResponse(tokenResponse!);\n }\n\n protected async getRefreshToken(...toolContext: ToolExecuteArgs) {\n return await resolveParameter(this.params.refreshToken, toolContext);\n }\n\n protected async getAccessTokenWithToolContext(\n ...toolContext: ToolExecuteArgs\n ) {\n return await resolveParameter(this.params.accessToken, toolContext);\n }\n\n /**\n *\n * Wraps the execute method of an AI tool to handle Token Vaults authorization.\n *\n * @param getContext - A function that returns the context of the tool execution.\n * @param execute - The tool execute method.\n * @returns The wrapped execute method.\n */\n protect(\n getContext: ContextGetter<ToolExecuteArgs>,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n const context = getContext(...args);\n const asyncStore: AsyncStorageValue = {\n context: context,\n scopes: this.params.scopes,\n connection: this.params.connection,\n };\n\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require Token Vault authorization.\"\n );\n }\n\n return asyncLocalStorage.run(asyncStore, async () => {\n const credentialsNS = nsFromContext(\n this.params.credentialsContext,\n context\n );\n try {\n let credentials: TokenSet = await this.credentialsStore.get(\n credentialsNS,\n \"credential\"\n );\n if (!credentials) {\n credentials = await this.getAccessToken(...args);\n await this.credentialsStore.put(\n credentialsNS,\n \"credential\",\n credentials\n );\n }\n asyncStore.credentials = credentials;\n return await execute(...args);\n } catch (err) {\n if (err instanceof TokenVaultError) {\n this.credentialsStore.delete(credentialsNS, \"credential\");\n const interrupt = new TokenVaultInterrupt(\n err.message,\n asyncStore.connection,\n asyncStore.scopes,\n asyncStore.scopes\n );\n return this.handleAuthorizationInterrupts(interrupt);\n }\n if (err instanceof Auth0Interrupt) {\n this.credentialsStore.delete(credentialsNS, \"credential\");\n return this.handleAuthorizationInterrupts(err);\n }\n throw err;\n }\n });\n };\n }\n}\n"]}
|
|
@@ -16,14 +16,14 @@ export declare enum SUBJECT_TOKEN_TYPES {
|
|
|
16
16
|
*/
|
|
17
17
|
SUBJECT_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token"
|
|
18
18
|
}
|
|
19
|
-
export type
|
|
19
|
+
export type TokenVaultAuthorizerParams<ToolExecuteArgs extends any[]> = {
|
|
20
20
|
/**
|
|
21
|
-
* The Auth0 refresh token to exchange for an
|
|
21
|
+
* The Auth0 refresh token to exchange for an Token Vault access token.
|
|
22
22
|
*/
|
|
23
23
|
refreshToken?: AuthorizerToolParameter<ToolExecuteArgs, string | undefined>;
|
|
24
24
|
/**
|
|
25
|
-
* The
|
|
26
|
-
* This can also be provided as a string exchange when exchanging an access token for a
|
|
25
|
+
* The Token Vault access token if available in the tool context.
|
|
26
|
+
* This can also be provided as a string exchange when exchanging an access token for a Token Vault access token.
|
|
27
27
|
*/
|
|
28
28
|
accessToken?: AuthorizerToolParameter<ToolExecuteArgs, TokenResponse | string | undefined> | string | undefined;
|
|
29
29
|
/**
|
|
@@ -31,15 +31,15 @@ export type FederatedConnectionAuthorizerParams<ToolExecuteArgs extends any[]> =
|
|
|
31
31
|
*/
|
|
32
32
|
subjectTokenType?: SUBJECT_TOKEN_TYPES | undefined;
|
|
33
33
|
/**
|
|
34
|
-
* Optional login hint to provide when exchanging an access or refresh token for a
|
|
34
|
+
* Optional login hint to provide when exchanging an access or refresh token for a Token Vault access token.
|
|
35
35
|
*/
|
|
36
36
|
loginHint?: AuthorizerToolParameter<ToolExecuteArgs, string | undefined>;
|
|
37
37
|
/**
|
|
38
|
-
* The scopes required in the access token of the
|
|
38
|
+
* The scopes required in the access token of the token vault provider.
|
|
39
39
|
*/
|
|
40
40
|
scopes: string[];
|
|
41
41
|
/**
|
|
42
|
-
* The connection name of the
|
|
42
|
+
* The connection name of the token vault provider.
|
|
43
43
|
*/
|
|
44
44
|
connection: string;
|
|
45
45
|
/**
|
|
@@ -58,4 +58,4 @@ export type FederatedConnectionAuthorizerParams<ToolExecuteArgs extends any[]> =
|
|
|
58
58
|
*/
|
|
59
59
|
store: Store;
|
|
60
60
|
};
|
|
61
|
-
//# sourceMappingURL=
|
|
61
|
+
//# sourceMappingURL=TokenVaultAuthorizerParams.d.ts.map
|
|
@@ -13,4 +13,4 @@ export var SUBJECT_TOKEN_TYPES;
|
|
|
13
13
|
*/
|
|
14
14
|
SUBJECT_TOKEN_TYPES["SUBJECT_TYPE_ACCESS_TOKEN"] = "urn:ietf:params:oauth:token-type:access_token";
|
|
15
15
|
})(SUBJECT_TOKEN_TYPES || (SUBJECT_TOKEN_TYPES = {}));
|
|
16
|
-
//# sourceMappingURL=
|
|
16
|
+
//# sourceMappingURL=TokenVaultAuthorizerParams.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenVaultAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/token-vault/TokenVaultAuthorizerParams.ts"],"names":[],"mappings":"AAKA,MAAM,CAAN,IAAY,mBAcX;AAdD,WAAY,mBAAmB;IAC7B;;;;OAIG;IACH,oGAA6E,CAAA;IAE7E;;;;OAIG;IACH,kGAA2E,CAAA;AAC7E,CAAC,EAdW,mBAAmB,KAAnB,mBAAmB,QAc9B","sourcesContent":["import { TokenResponse } from \"../../credentials\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\n\nexport enum SUBJECT_TOKEN_TYPES {\n /**\n * Indicates that the token is an OAuth 2.0 refresh token issued by the given authorization server.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-3-3.4 RFC 8693 Section 3-3.4}\n */\n SUBJECT_TYPE_REFRESH_TOKEN = \"urn:ietf:params:oauth:token-type:refresh_token\",\n\n /**\n * Indicates that the token is an OAuth 2.0 access token issued by the given authorization server.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-3-3.2 RFC 8693 Section 3-3.2}\n */\n SUBJECT_TYPE_ACCESS_TOKEN = \"urn:ietf:params:oauth:token-type:access_token\",\n}\n\nexport type TokenVaultAuthorizerParams<ToolExecuteArgs extends any[]> =\n {\n /**\n * The Auth0 refresh token to exchange for an Token Vault access token.\n */\n refreshToken?: AuthorizerToolParameter<ToolExecuteArgs, string | undefined>;\n\n /**\n * The Token Vault access token if available in the tool context.\n * This can also be provided as a string exchange when exchanging an access token for a Token Vault access token.\n */\n accessToken?:\n | AuthorizerToolParameter<\n ToolExecuteArgs,\n TokenResponse | string | undefined\n >\n | string\n | undefined;\n\n /**\n * This is used to specify the type of token being requested from Auth0 during the OAuth 2.0 token exchange request.\n */\n subjectTokenType?: SUBJECT_TOKEN_TYPES | undefined;\n\n /**\n * Optional login hint to provide when exchanging an access or refresh token for a Token Vault access token.\n */\n loginHint?: AuthorizerToolParameter<ToolExecuteArgs, string | undefined>;\n\n /**\n * The scopes required in the access token of the token vault provider.\n */\n scopes: string[];\n\n /**\n * The connection name of the token vault provider.\n */\n connection: string;\n\n /**\n * AuthContext defines the scope of credential sharing:\n * - \"tool-call\": Credentials are valid only for a single invocation of the tool.\n * - \"tool\": Credentials are shared across multiple calls to the same tool within the same thread.\n * - \"thread\": Credentials are shared across all tools using the same authorizer within the current thread.\n * - \"agent\": Credentials are shared globally across all threads and tools in the agent.\n *\n * @default \"thread\"\n */\n credentialsContext?: AuthContext;\n\n /**\n * An store used to store the authorization credentials according\n * to the `credentialsContext` scope.\n */\n store: Store;\n };\n"]}
|
|
@@ -3,7 +3,7 @@ import { TokenSet } from "../../credentials";
|
|
|
3
3
|
import { ToolCallContext } from "../context";
|
|
4
4
|
export type AsyncStorageValue = {
|
|
5
5
|
/**
|
|
6
|
-
* The
|
|
6
|
+
* The Token Vault access token.
|
|
7
7
|
*/
|
|
8
8
|
credentials?: TokenSet;
|
|
9
9
|
/**
|
|
@@ -11,11 +11,11 @@ export type AsyncStorageValue = {
|
|
|
11
11
|
*/
|
|
12
12
|
context: ToolCallContext;
|
|
13
13
|
/**
|
|
14
|
-
* The
|
|
14
|
+
* The token vault name.
|
|
15
15
|
*/
|
|
16
16
|
connection: string;
|
|
17
17
|
/**
|
|
18
|
-
* The scopes required to access the
|
|
18
|
+
* The scopes required to access the token vault.
|
|
19
19
|
*/
|
|
20
20
|
scopes: string[];
|
|
21
21
|
/**
|
|
@@ -27,16 +27,16 @@ export declare const asyncLocalStorage: AsyncLocalStorage<AsyncStorageValue>;
|
|
|
27
27
|
/**
|
|
28
28
|
* Returns the entire tokenset for the current connection.
|
|
29
29
|
*
|
|
30
|
-
* Use `
|
|
30
|
+
* Use `getAccessTokenFromTokenVault` if you only need the access token.
|
|
31
31
|
*
|
|
32
32
|
* @returns {TokenSet} The current token set.
|
|
33
33
|
*/
|
|
34
|
-
export declare const
|
|
34
|
+
export declare const getCredentialsFromTokenVault: () => TokenSet | undefined;
|
|
35
35
|
/**
|
|
36
36
|
*
|
|
37
37
|
* Get the access token for the current connection.
|
|
38
38
|
*
|
|
39
39
|
* @returns The access token for the current connection.
|
|
40
40
|
*/
|
|
41
|
-
export declare const
|
|
41
|
+
export declare const getAccessTokenFromTokenVault: () => string;
|
|
42
42
|
//# sourceMappingURL=asyncLocalStorage.d.ts.map
|