@auth0/ai 5.1.0 → 5.1.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.
@@ -89,7 +89,7 @@ class TokenVaultAuthorizerBase {
89
89
  throw new interrupts_1.TokenVaultInterrupt(`Authorization required to access the Token Vault: ${this.params.connection}. Authorized scopes: ${currentScopes.join(", ")}. Missing scopes: ${missingScopes.join(", ")}`, {
90
90
  connection,
91
91
  scopes,
92
- requiredScopes: [...currentScopes, ...scopes],
92
+ requiredScopes: [...currentScopes, ...missingScopes],
93
93
  authorizationParams,
94
94
  });
95
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"TokenVaultAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/token-vault/TokenVaultAuthorizerBase.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAC5B,8DAAqC;AAErC,mDAI2B;AAC3B,iDAI0B;AAC1B,iDAAoD;AACpD,yCAAwC;AACxC,qCAAiD;AACjD,wCAA0D;AAC1D,oCAAgE;AAChE,2DAA2E;AAC3E,6EAGsC;AAEtC;;GAEG;AAEH,MAAa,wBAAwB;IAQnC,YACE,KAAiC,EACjC,MAAmD;QAEnD,IAAI,CAAC,KAAK,GAAG,yBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM,GAAG;YACZ,kBAAkB,EAAE,QAAQ;YAC5B,GAAG,MAAM;SACV,CAAC;QAEF,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAExC,IAAI,CAAC,gBAAgB,GAAG,IAAI,iBAAQ,CAAW,MAAM,CAAC,KAAK,EAAE;YAC3D,aAAa,EAAE,CAAC,UAAU,EAAE,aAAa,CAAC;YAC1C,MAAM,EAAE,CAAC,WAAW,EAAE,EAAE,CACtB,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS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AC;wBACjD,MAAM,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAC7B,aAAa,EACb,YAAY,EACZ,WAAW,CACZ,CAAC;oBACJ,CAAC;oBACD,UAAU,CAAC,WAAW,GAAG,WAAW,CAAC;oBACrC,OAAO,MAAM,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;gBAChC,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,GAAG,YAAY,4BAAe,EAAE,CAAC;wBACnC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,MAAM,SAAS,GAAG,IAAI,gCAAmB,CAAC,GAAG,CAAC,OAAO,EAAE;4BACrD,UAAU,EAAE,UAAU,CAAC,UAAU;4BACjC,MAAM,EAAE,UAAU,CAAC,MAAM;4BACzB,cAAc,EAAE,UAAU,CAAC,MAAM;4BACjC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;yBACpD,CAAC,CAAC;wBACH,OAAO,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,CAAC;oBACvD,CAAC;oBACD,IAAI,GAAG,YAAY,2BAAc,EAAE,CAAC;wBAClC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;oBACD,MAAM,GAAG,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;CACF;AA9RD,4DA8RC","sourcesContent":["import crypto from \"crypto\";\nimport stableHash from \"stable-hash\";\n\nimport {\n TokenResponse,\n TokenSet,\n tokenSetFromTokenResponse,\n} from \"../../credentials\";\nimport {\n Auth0Interrupt,\n TokenVaultError,\n TokenVaultInterrupt,\n} 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 {\n SUBJECT_TOKEN_TYPES,\n TokenVaultAuthorizerParams,\n} 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, authorizationParams } = store;\n\n if (!tokenResponse) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}`,\n {\n connection,\n scopes,\n requiredScopes: scopes,\n authorizationParams,\n },\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}. Authorized scopes: ${currentScopes.join(\", \")}. Missing scopes: ${missingScopes.join(\", \")}`,\n {\n connection,\n scopes,\n requiredScopes: [...currentScopes, ...scopes],\n authorizationParams,\n },\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 authorizationParams: this.params.authorizationParams,\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(err.message, {\n connection: asyncStore.connection,\n scopes: asyncStore.scopes,\n requiredScopes: asyncStore.scopes,\n authorizationParams: asyncStore.authorizationParams,\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"]}
1
+ {"version":3,"file":"TokenVaultAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/token-vault/TokenVa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BACjC,MAAM,EAAE,UAAU,CAAC,MAAM;4BACzB,cAAc,EAAE,UAAU,CAAC,MAAM;4BACjC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;yBACpD,CAAC,CAAC;wBACH,OAAO,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,CAAC;oBACvD,CAAC;oBACD,IAAI,GAAG,YAAY,2BAAc,EAAE,CAAC;wBAClC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;oBACD,MAAM,GAAG,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;CACF;AA9RD,4DA8RC","sourcesContent":["import crypto from \"crypto\";\nimport stableHash from \"stable-hash\";\n\nimport {\n TokenResponse,\n TokenSet,\n tokenSetFromTokenResponse,\n} from \"../../credentials\";\nimport {\n Auth0Interrupt,\n TokenVaultError,\n TokenVaultInterrupt,\n} 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 {\n SUBJECT_TOKEN_TYPES,\n TokenVaultAuthorizerParams,\n} 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, authorizationParams } = store;\n\n if (!tokenResponse) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}`,\n {\n connection,\n scopes,\n requiredScopes: scopes,\n authorizationParams,\n },\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}. Authorized scopes: ${currentScopes.join(\", \")}. Missing scopes: ${missingScopes.join(\", \")}`,\n {\n connection,\n scopes,\n requiredScopes: [...currentScopes, ...missingScopes],\n authorizationParams,\n },\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 authorizationParams: this.params.authorizationParams,\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(err.message, {\n connection: asyncStore.connection,\n scopes: asyncStore.scopes,\n requiredScopes: asyncStore.scopes,\n authorizationParams: asyncStore.authorizationParams,\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"]}
@@ -83,7 +83,7 @@ export class TokenVaultAuthorizerBase {
83
83
  throw new TokenVaultInterrupt(`Authorization required to access the Token Vault: ${this.params.connection}. Authorized scopes: ${currentScopes.join(", ")}. Missing scopes: ${missingScopes.join(", ")}`, {
84
84
  connection,
85
85
  scopes,
86
- requiredScopes: [...currentScopes, ...scopes],
86
+ requiredScopes: [...currentScopes, ...missingScopes],
87
87
  authorizationParams,
88
88
  });
89
89
  }
@@ -1 +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,EAGL,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,cAAc,EACd,eAAe,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AC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,MAAM,SAAS,GAAG,IAAI,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE;4BACrD,UAAU,EAAE,UAAU,CAAC,UAAU;4BACjC,MAAM,EAAE,UAAU,CAAC,MAAM;4BACzB,cAAc,EAAE,UAAU,CAAC,MAAM;4BACjC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;yBACpD,CAAC,CAAC;wBACH,OAAO,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,CAAC;oBACvD,CAAC;oBACD,IAAI,GAAG,YAAY,cAAc,EAAE,CAAC;wBAClC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,OAAO,IAAI,CAAC,6BAA6B,CAAC,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 {\n TokenResponse,\n TokenSet,\n tokenSetFromTokenResponse,\n} from \"../../credentials\";\nimport {\n Auth0Interrupt,\n TokenVaultError,\n TokenVaultInterrupt,\n} 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 {\n SUBJECT_TOKEN_TYPES,\n TokenVaultAuthorizerParams,\n} 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, authorizationParams } = store;\n\n if (!tokenResponse) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}`,\n {\n connection,\n scopes,\n requiredScopes: scopes,\n authorizationParams,\n },\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}. Authorized scopes: ${currentScopes.join(\", \")}. Missing scopes: ${missingScopes.join(\", \")}`,\n {\n connection,\n scopes,\n requiredScopes: [...currentScopes, ...scopes],\n authorizationParams,\n },\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 authorizationParams: this.params.authorizationParams,\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(err.message, {\n connection: asyncStore.connection,\n scopes: asyncStore.scopes,\n requiredScopes: asyncStore.scopes,\n authorizationParams: asyncStore.authorizationParams,\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"]}
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,EAGL,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,cAAc,EACd,eAAe,EACf,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,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AU;4BACjC,MAAM,EAAE,UAAU,CAAC,MAAM;4BACzB,cAAc,EAAE,UAAU,CAAC,MAAM;4BACjC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;yBACpD,CAAC,CAAC;wBACH,OAAO,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,CAAC;oBACvD,CAAC;oBACD,IAAI,GAAG,YAAY,cAAc,EAAE,CAAC;wBAClC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;wBAC1D,OAAO,IAAI,CAAC,6BAA6B,CAAC,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 {\n TokenResponse,\n TokenSet,\n tokenSetFromTokenResponse,\n} from \"../../credentials\";\nimport {\n Auth0Interrupt,\n TokenVaultError,\n TokenVaultInterrupt,\n} 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 {\n SUBJECT_TOKEN_TYPES,\n TokenVaultAuthorizerParams,\n} 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, authorizationParams } = store;\n\n if (!tokenResponse) {\n throw new TokenVaultInterrupt(\n `Authorization required to access the Token Vault: ${this.params.connection}`,\n {\n connection,\n scopes,\n requiredScopes: scopes,\n authorizationParams,\n },\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}. Authorized scopes: ${currentScopes.join(\", \")}. Missing scopes: ${missingScopes.join(\", \")}`,\n {\n connection,\n scopes,\n requiredScopes: [...currentScopes, ...missingScopes],\n authorizationParams,\n },\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 authorizationParams: this.params.authorizationParams,\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(err.message, {\n connection: asyncStore.connection,\n scopes: asyncStore.scopes,\n requiredScopes: asyncStore.scopes,\n authorizationParams: asyncStore.authorizationParams,\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auth0/ai",
3
- "version": "5.1.0",
3
+ "version": "5.1.1",
4
4
  "description": "Auth0AI SDK for JavaScript",
5
5
  "types": "dist/esm/index.d.ts",
6
6
  "main": "dist/cjs/index.js",