@auth0/ai 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,13 +64,21 @@ class CIBAAuthorizerBase {
64
64
  }
65
65
  async getAuthorizeParams(toolContext) {
66
66
  var _a, _b, _c;
67
- return {
67
+ const authParams = {
68
68
  scope: ensureOpenIdScope(this.params.scopes).join(" "),
69
69
  audience: this.params.audience || "",
70
70
  request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
71
71
  binding_message: (_b = (await (0, parameters_1.resolveParameter)(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
72
72
  userId: (_c = (await (0, parameters_1.resolveParameter)(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
73
73
  };
74
+ const authorizationDetails = await (0, parameters_1.resolveParameter)(this.params.authorizationDetails, toolContext);
75
+ // If authorizationDetails is an array, we need to convert it to a string
76
+ // because the auth0 library expects a valid JSON string.
77
+ if (authorizationDetails !== undefined) {
78
+ authParams.authorization_details = JSON.stringify(authorizationDetails);
79
+ }
80
+ // Remove undefined values from the authParams object
81
+ return Object.fromEntries(Object.entries(authParams).filter(([, value]) => value !== undefined));
74
82
  }
75
83
  async getCredentialsInternal(authRequest) {
76
84
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[],"mappings":";;;;;;AAAA,iCAA6C;AAC7C,oDAA4B;AAC5B,8DAAqC;AAErC,mDAAwE;AACxE,iDAO0B;AAC1B,iDAAoD;AACpD,yCAAwC;AAExC,wCAA0D;AAC1D,oCAAgE;AAChE,2DAA2E;AAI3E,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC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,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,6BAA6B,CACrC,GAAkE;QAElE,MAAM,GAAG,CAAC;IACZ,CAAC;CACF;AAxRD,gDAwRC","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 { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\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 CIBAAuthorizerBase<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 CIBAAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: CIBAAuthorizerParams<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<CIBAAuthorizationRequest>(\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<CIBAAuthorizationRequest> {\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 return {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n audience: this.params.audience || \"\",\n request_expiry: (this.params.requestExpiry ?? 300).toString(),\n binding_message:\n (await resolveParameter(this.params.bindingMessage, toolContext)) ?? \"\",\n userId: (await resolveParameter(this.params.userID, toolContext)) ?? \"\",\n };\n }\n\n private async getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\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 );\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: CIBAAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: CIBAAuthorizationRequest\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.request.interval * 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: CIBAAuthorizationRequest | 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 handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n throw err;\n }\n}\n"]}
1
+ {"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[],"mappings":";;;;;;AAAA,iCAA6C;AAC7C,oDAA4B;AAC5B,8DAAqC;AAErC,mDAAwE;AACxE,iDAO0B;AAC1B,iDAAoD;AACpD,yCAAwC;AAExC,wCAA0D;AAC1D,oCAAgE;AAChE,2DAA2E;AAI3E,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,MAAa,kBAAkB;IAU7B,YACE,KAAiC,EACjC,MAA6C;QAE7C,IAAI,CAAC,KAAK,GAAG,IAAI,4BAAoB,CAAC,yBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;QACtE,IAAI,CAAC,MAAM,GAAG;YACZ,kBAAkB,EAAE,WAAW;YAC/B,GAAG,MAAM;SACV,CAAC;QAEF,IAAI,CAAC,iBAAiB,GAAG,IAAI,iBAAQ,CACnC,MAAM,CAAC,KAAK,EACZ;YACE,MAAM,EAAE,CAAC,YAAY,EAAE,EAAE,CACvB,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS;SACrE,CACF,CAAC;QAEF,IAAI,CAAC,gBAAgB,GAAG,IAAI,iBAAQ,CAAW,MAAM,CAAC,KAAK,EAAE;YAC3D,MAAM,E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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 { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\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 CIBAAuthorizerBase<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 CIBAAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: CIBAAuthorizerParams<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<CIBAAuthorizationRequest>(\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<CIBAAuthorizationRequest> {\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 request_expiry: (this.params.requestExpiry ?? 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: CIBAAuthorizationRequest\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 );\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: CIBAAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: CIBAAuthorizationRequest\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.request.interval * 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: CIBAAuthorizationRequest | 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 handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n throw err;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { TokenSet } from \"../../credentials\";\nimport { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {\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 scope to request authorization for.\n */\n scopes: string[];\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 5m.\n */\n requestExpiry?: 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: CIBAAuthorizationRequest,\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 | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\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"]}
1
+ {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { TokenSet } from \"../../credentials\";\nimport { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type CIBAAuthorizerParams<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 Record<string, any>[]\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 5m.\n */\n requestExpiry?: 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: CIBAAuthorizationRequest,\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 | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\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"]}
@@ -6,6 +6,13 @@ exports.Auth0ClientSchema = zod_1.z.object({
6
6
  domain: zod_1.z.string().default(() => process.env.AUTH0_DOMAIN),
7
7
  clientId: zod_1.z.string().default(() => process.env.AUTH0_CLIENT_ID),
8
8
  clientSecret: zod_1.z.string().default(() => process.env.AUTH0_CLIENT_SECRET),
9
+ telemetry: zod_1.z.boolean().optional(),
10
+ clientInfo: zod_1.z
11
+ .object({
12
+ name: zod_1.z.string(),
13
+ })
14
+ .passthrough()
15
+ .optional(),
9
16
  });
10
17
  exports.Auth0PublicClientSchema = zod_1.z.object({
11
18
  domain: zod_1.z.string().default(() => process.env.AUTH0_DOMAIN),
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/authorizers/types.ts"],"names":[],"mappings":";;;AAEA,6BAAwB;AAcX,QAAA,iBAAiB,GAAG,OAAC,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;IAChE,YAAY,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAoB,CAAC;CACzE,CAAC,CAAC;AAEU,QAAA,uBAAuB,GAAG,OAAC,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;CACjE,CAAC,CAAC","sourcesContent":["import { AuthenticationClientOptions } from \"auth0\";\nimport * as jose from \"jose\";\nimport { z } from \"zod\";\n\nexport type AuthParams = {\n allowed?: boolean;\n accessToken?: string;\n claims?: jose.JWTPayload;\n};\n\nexport type ToolWithAuthHandler<I, O, C> = (\n authParams: AuthParams,\n input: I,\n config?: C\n) => Promise<O>;\n\nexport const Auth0ClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n clientSecret: z.string().default(() => process.env.AUTH0_CLIENT_SECRET!),\n});\n\nexport const Auth0PublicClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n});\n\nexport type Auth0ClientParams = z.infer<typeof Auth0ClientSchema>;\nexport type Auth0PublicClientParams = z.infer<typeof Auth0PublicClientSchema>;\n\nexport type AuthorizerParams = Pick<\n AuthenticationClientOptions,\n \"domain\" | \"clientId\" | \"clientSecret\"\n>;\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/authorizers/types.ts"],"names":[],"mappings":";;;AAEA,6BAAwB;AAcX,QAAA,iBAAiB,GAAG,OAAC,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;IAChE,YAAY,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAoB,CAAC;IACxE,SAAS,EAAE,OAAC,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;IACjC,UAAU,EAAE,OAAC;SACV,MAAM,CAAC;QACN,IAAI,EAAE,OAAC,CAAC,MAAM,EAAE;KACjB,CAAC;SACD,WAAW,EAAE;SACb,QAAQ,EAAE;CACd,CAAC,CAAC;AAEU,QAAA,uBAAuB,GAAG,OAAC,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;CACjE,CAAC,CAAC","sourcesContent":["import { AuthenticationClientOptions } from \"auth0\";\nimport * as jose from \"jose\";\nimport { z } from \"zod\";\n\nexport type AuthParams = {\n allowed?: boolean;\n accessToken?: string;\n claims?: jose.JWTPayload;\n};\n\nexport type ToolWithAuthHandler<I, O, C> = (\n authParams: AuthParams,\n input: I,\n config?: C\n) => Promise<O>;\n\nexport const Auth0ClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n clientSecret: z.string().default(() => process.env.AUTH0_CLIENT_SECRET!),\n telemetry: z.boolean().optional(),\n clientInfo: z\n .object({\n name: z.string(),\n })\n .passthrough()\n .optional(),\n});\n\nexport const Auth0PublicClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n});\n\nexport type Auth0ClientParams = z.infer<typeof Auth0ClientSchema>;\nexport type Auth0PublicClientParams = z.infer<typeof Auth0PublicClientSchema>;\n\nexport type AuthorizerParams = Pick<\n AuthenticationClientOptions,\n \"domain\" | \"clientId\" | \"clientSecret\"\n>;\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\n"]}
@@ -58,13 +58,21 @@ export class CIBAAuthorizerBase {
58
58
  }
59
59
  async getAuthorizeParams(toolContext) {
60
60
  var _a, _b, _c;
61
- return {
61
+ const authParams = {
62
62
  scope: ensureOpenIdScope(this.params.scopes).join(" "),
63
63
  audience: this.params.audience || "",
64
64
  request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
65
65
  binding_message: (_b = (await resolveParameter(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
66
66
  userId: (_c = (await resolveParameter(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
67
67
  };
68
+ const authorizationDetails = await resolveParameter(this.params.authorizationDetails, toolContext);
69
+ // If authorizationDetails is an array, we need to convert it to a string
70
+ // because the auth0 library expects a valid JSON string.
71
+ if (authorizationDetails !== undefined) {
72
+ authParams.authorization_details = JSON.stringify(authorizationDetails);
73
+ }
74
+ // Remove undefined values from the authParams object
75
+ return Object.fromEntries(Object.entries(authParams).filter(([, value]) => value !== undefined));
68
76
  }
69
77
  async getCredentialsInternal(authRequest) {
70
78
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[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ACD,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;wBAC/B,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;4BACvC,MAAA,IAAI,CAAC,gBAAgB,0CAAE,GAAG,CACxB,aAAa,EACb,YAAY,EACZ,WAAW,CACZ,CAAC;wBACJ,CAAC;oBACH,CAAC;gBACH,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,eAAe,GACnB,GAAG,YAAY,6BAA6B;wBAC5C,GAAG,YAAY,6BAA6B,CAAC;oBAC/C,IAAI,eAAe,EAAE,CAAC;wBACpB,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,CAAC,iBAAiB,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,6BAA6B,CACrC,GAAkE;QAElE,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 { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\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 CIBAAuthorizerBase<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 CIBAAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: CIBAAuthorizerParams<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<CIBAAuthorizationRequest>(\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<CIBAAuthorizationRequest> {\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 return {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n audience: this.params.audience || \"\",\n request_expiry: (this.params.requestExpiry ?? 300).toString(),\n binding_message:\n (await resolveParameter(this.params.bindingMessage, toolContext)) ?? \"\",\n userId: (await resolveParameter(this.params.userID, toolContext)) ?? \"\",\n };\n }\n\n private async getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\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 );\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: CIBAAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: CIBAAuthorizationRequest\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.request.interval * 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: CIBAAuthorizationRequest | 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 handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n throw err;\n }\n}\n"]}
1
+ {"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.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,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C;4BACD,WAAW,GAAG,MAAM,kBAAkB,CAAC;wBACzC,CAAC;wBACD,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;wBAC/B,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;4BACvC,MAAA,IAAI,CAAC,gBAAgB,0CAAE,GAAG,CACxB,aAAa,EACb,YAAY,EACZ,WAAW,CACZ,CAAC;wBACJ,CAAC;oBACH,CAAC;gBACH,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,eAAe,GACnB,GAAG,YAAY,6BAA6B;wBAC5C,GAAG,YAAY,6BAA6B,CAAC;oBAC/C,IAAI,eAAe,EAAE,CAAC;wBACpB,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,CAAC,iBAAiB,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,6BAA6B,CACrC,GAAkE;QAElE,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 { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\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 CIBAAuthorizerBase<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 CIBAAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: CIBAAuthorizerParams<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<CIBAAuthorizationRequest>(\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<CIBAAuthorizationRequest> {\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 request_expiry: (this.params.requestExpiry ?? 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: CIBAAuthorizationRequest\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 );\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: CIBAAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: CIBAAuthorizationRequest\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.request.interval * 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: CIBAAuthorizationRequest | 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 handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n throw err;\n }\n}\n"]}
@@ -6,6 +6,10 @@ import { AuthContext } from "../context";
6
6
  import { OnAuthorizationRequest } from "../types";
7
7
  import { CIBAAuthorizationRequest } from "./CIBAAuthorizationRequest";
8
8
  export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
9
+ /**
10
+ * The scope to request authorization for.
11
+ */
12
+ scopes: string[];
9
13
  /**
10
14
  * The user ID to request authorization for.
11
15
  */
@@ -15,9 +19,9 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
15
19
  */
16
20
  bindingMessage: AuthorizerToolParameter<ToolExecuteArgs>;
17
21
  /**
18
- * The scope to request authorization for.
22
+ * The authorization parameters for RAR request.
19
23
  */
20
- scopes: string[];
24
+ authorizationDetails?: AuthorizerToolParameter<ToolExecuteArgs, Record<string, any>[]>;
21
25
  /**
22
26
  * The audience to request authorization for.
23
27
  */
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { TokenSet } from \"../../credentials\";\nimport { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {\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 scope to request authorization for.\n */\n scopes: string[];\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 5m.\n */\n requestExpiry?: 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: CIBAAuthorizationRequest,\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 | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\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"]}
1
+ {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { TokenSet } from \"../../credentials\";\nimport { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type CIBAAuthorizerParams<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 Record<string, any>[]\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 5m.\n */\n requestExpiry?: 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: CIBAAuthorizationRequest,\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 | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\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"]}
@@ -11,14 +11,30 @@ export declare const Auth0ClientSchema: z.ZodObject<{
11
11
  domain: z.ZodDefault<z.ZodString>;
12
12
  clientId: z.ZodDefault<z.ZodString>;
13
13
  clientSecret: z.ZodDefault<z.ZodString>;
14
+ telemetry: z.ZodOptional<z.ZodBoolean>;
15
+ clientInfo: z.ZodOptional<z.ZodObject<{
16
+ name: z.ZodString;
17
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
18
+ name: z.ZodString;
19
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
20
+ name: z.ZodString;
21
+ }, z.ZodTypeAny, "passthrough">>>;
14
22
  }, "strip", z.ZodTypeAny, {
15
23
  domain: string;
16
24
  clientId: string;
17
25
  clientSecret: string;
26
+ telemetry?: boolean | undefined;
27
+ clientInfo?: z.objectOutputType<{
28
+ name: z.ZodString;
29
+ }, z.ZodTypeAny, "passthrough"> | undefined;
18
30
  }, {
19
31
  domain?: string | undefined;
20
32
  clientId?: string | undefined;
21
33
  clientSecret?: string | undefined;
34
+ telemetry?: boolean | undefined;
35
+ clientInfo?: z.objectInputType<{
36
+ name: z.ZodString;
37
+ }, z.ZodTypeAny, "passthrough"> | undefined;
22
38
  }>;
23
39
  export declare const Auth0PublicClientSchema: z.ZodObject<{
24
40
  domain: z.ZodDefault<z.ZodString>;
@@ -3,6 +3,13 @@ export const Auth0ClientSchema = z.object({
3
3
  domain: z.string().default(() => process.env.AUTH0_DOMAIN),
4
4
  clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID),
5
5
  clientSecret: z.string().default(() => process.env.AUTH0_CLIENT_SECRET),
6
+ telemetry: z.boolean().optional(),
7
+ clientInfo: z
8
+ .object({
9
+ name: z.string(),
10
+ })
11
+ .passthrough()
12
+ .optional(),
6
13
  });
7
14
  export const Auth0PublicClientSchema = z.object({
8
15
  domain: z.string().default(() => process.env.AUTH0_DOMAIN),
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/authorizers/types.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAcxB,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;IAChE,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAoB,CAAC;CACzE,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;CACjE,CAAC,CAAC","sourcesContent":["import { AuthenticationClientOptions } from \"auth0\";\nimport * as jose from \"jose\";\nimport { z } from \"zod\";\n\nexport type AuthParams = {\n allowed?: boolean;\n accessToken?: string;\n claims?: jose.JWTPayload;\n};\n\nexport type ToolWithAuthHandler<I, O, C> = (\n authParams: AuthParams,\n input: I,\n config?: C\n) => Promise<O>;\n\nexport const Auth0ClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n clientSecret: z.string().default(() => process.env.AUTH0_CLIENT_SECRET!),\n});\n\nexport const Auth0PublicClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n});\n\nexport type Auth0ClientParams = z.infer<typeof Auth0ClientSchema>;\nexport type Auth0PublicClientParams = z.infer<typeof Auth0PublicClientSchema>;\n\nexport type AuthorizerParams = Pick<\n AuthenticationClientOptions,\n \"domain\" | \"clientId\" | \"clientSecret\"\n>;\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/authorizers/types.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAcxB,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;IAChE,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAoB,CAAC;IACxE,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;IACjC,UAAU,EAAE,CAAC;SACV,MAAM,CAAC;QACN,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;KACjB,CAAC;SACD,WAAW,EAAE;SACb,QAAQ,EAAE;CACd,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,YAAa,CAAC;IAC3D,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC;CACjE,CAAC,CAAC","sourcesContent":["import { AuthenticationClientOptions } from \"auth0\";\nimport * as jose from \"jose\";\nimport { z } from \"zod\";\n\nexport type AuthParams = {\n allowed?: boolean;\n accessToken?: string;\n claims?: jose.JWTPayload;\n};\n\nexport type ToolWithAuthHandler<I, O, C> = (\n authParams: AuthParams,\n input: I,\n config?: C\n) => Promise<O>;\n\nexport const Auth0ClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n clientSecret: z.string().default(() => process.env.AUTH0_CLIENT_SECRET!),\n telemetry: z.boolean().optional(),\n clientInfo: z\n .object({\n name: z.string(),\n })\n .passthrough()\n .optional(),\n});\n\nexport const Auth0PublicClientSchema = z.object({\n domain: z.string().default(() => process.env.AUTH0_DOMAIN!),\n clientId: z.string().default(() => process.env.AUTH0_CLIENT_ID!),\n});\n\nexport type Auth0ClientParams = z.infer<typeof Auth0ClientSchema>;\nexport type Auth0PublicClientParams = z.infer<typeof Auth0PublicClientSchema>;\n\nexport type AuthorizerParams = Pick<\n AuthenticationClientOptions,\n \"domain\" | \"clientId\" | \"clientSecret\"\n>;\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auth0/ai",
3
- "version": "3.0.0",
3
+ "version": "3.2.0",
4
4
  "description": "Auth0AI SDK for JavaScript",
5
5
  "types": "dist/esm/index.d.ts",
6
6
  "main": "dist/cjs/index.js",