@auth0/ai 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js +4 -6
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js +4 -6
- package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.d.ts +2 -0
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
- package/package.json +2 -2
|
@@ -28,17 +28,15 @@ class CIBAAuthorizerBase {
|
|
|
28
28
|
});
|
|
29
29
|
}
|
|
30
30
|
async start(toolContext) {
|
|
31
|
-
var _a;
|
|
31
|
+
var _a, _b, _c;
|
|
32
32
|
const requestedAt = Date.now() / 1000;
|
|
33
33
|
const authorizeParams = {
|
|
34
34
|
scope: ensureOpenIdScope(this.params.scopes).join(" "),
|
|
35
|
-
binding_message: "",
|
|
36
|
-
userId: "",
|
|
37
35
|
audience: this.params.audience || "",
|
|
38
|
-
request_expiry: (_a = this.params.requestExpiry)
|
|
36
|
+
request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
|
|
37
|
+
binding_message: (_b = (await (0, parameters_1.resolveParameter)(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
|
|
38
|
+
userId: (_c = (await (0, parameters_1.resolveParameter)(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
|
|
39
39
|
};
|
|
40
|
-
authorizeParams.binding_message = await (0, parameters_1.resolveParameter)(this.params.bindingMessage, toolContext);
|
|
41
|
-
authorizeParams.userId = await (0, parameters_1.resolveParameter)(this.params.userID, toolContext);
|
|
42
40
|
try {
|
|
43
41
|
const response = await this.auth0.backchannel.authorize(authorizeParams);
|
|
44
42
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[],"mappings":";;;AAAA,iCAA6C;AAI7C,iDAO0B;AAC1B,iDAAoD;AACpD,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;IAG7B,YACE,KAAuB,EACN,MAA6C;QAA7C,WAAM,GAAN,MAAM,CAAuC;QAE9D,IAAI,CAAC,KAAK,GAAG,IAAI,4BAAoB,CAAC;YACpC,MAAM,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,KAAI,OAAO,CAAC,GAAG,CAAC,YAAa;YAClD,QAAQ,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,KAAI,OAAO,CAAC,GAAG,CAAC,eAAgB;YACzD,YAAY,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,YAAY,KAAI,OAAO,CAAC,GAAG,CAAC,mBAAmB;YACpE,yBAAyB,EAAE,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,yBAAyB;YAC3D,yBAAyB,EAAE,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,yBAAyB;YAC3D,iBAAiB,EAAE,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,iBAAiB;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} from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\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 auth0: AuthenticationClient;\n\n constructor(\n auth0: AuthorizerParams,\n private readonly params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient({\n domain: auth0?.domain || process.env.AUTH0_DOMAIN!,\n clientId: auth0?.clientId || process.env.AUTH0_CLIENT_ID!,\n clientSecret: auth0?.clientSecret || process.env.AUTH0_CLIENT_SECRET,\n clientAssertionSigningAlg: auth0?.clientAssertionSigningAlg,\n clientAssertionSigningKey: auth0?.clientAssertionSigningKey,\n idTokenSigningAlg: auth0?.idTokenSigningAlg,\n clockTolerance: auth0?.clockTolerance,\n useMTLS: auth0?.useMTLS,\n });\n }\n\n private async start(\n toolContext: ToolExecuteArgs\n ): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n const authorizeParams = {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n binding_message: \"\",\n userId: \"\",\n audience: this.params.audience || \"\",\n request_expiry: this.params.requestExpiry?.toString(),\n };\n\n authorizeParams.binding_message = await resolveParameter(\n this.params.bindingMessage,\n toolContext\n );\n\n authorizeParams.userId = await resolveParameter(\n this.params.userID,\n toolContext\n );\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 getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | 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 = {\n accessToken: {\n type: response.token_type || \"bearer\",\n value: response.access_token,\n },\n refreshToken: response.refresh_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.refresh_token,\n }\n : undefined,\n idToken: response.id_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.id_token,\n }\n : undefined,\n };\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<Credentials | undefined> {\n let credentials: Credentials | 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 if (\n !this.params.onAuthorizationRequest ||\n this.params.onAuthorizationRequest === \"interrupt\"\n ) {\n return this.params.storeAuthorizationResponse(\n undefined,\n ...(store.args as ToolExecuteArgs)\n );\n }\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: (...args: ToolExecuteArgs) => any,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authRequest: CIBAAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context: getContext(...args),\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: Credentials | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n if (interruptMode) {\n authRequest = await resolveParameter(\n this.params.getAuthorizationResponse,\n args\n );\n if (!authRequest) {\n //Initial request\n authRequest = await this.start(args);\n await this.params.storeAuthorizationResponse(\n authRequest,\n ...args\n );\n }\n credentials = await this.getCredentials(authRequest);\n } else {\n authRequest = await this.start(args);\n credentials = await this.getCredentialsPolling(authRequest);\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 await this.deleteAuthRequest();\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;AAI7C,iDAO0B;AAC1B,iDAAoD;AACpD,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;IAG7B,YACE,KAAuB,EACN,MAA6C;QAA7C,WAAM,GAAN,MAAM,CAAuC;QAE9D,IAAI,CAAC,KAAK,GAAG,IAAI,4BAAoB,CAAC;YACpC,MAAM,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,KAAI,OAAO,CAAC,GAAG,CAAC,YAAa;YAClD,QAAQ,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,KAAI,OAAO,CAAC,GAAG,CAAC,eAAgB;YACzD,YAAY,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,YAAY,KAAI,OAAO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AAG,IAAI,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;IAES,6BAA6B,CACrC,GAAkE;QAElE,MAAM,GAAG,CAAC;IACZ,CAAC;CACF;AAlPD,gDAkPC","sourcesContent":["import { AuthenticationClient } from \"auth0\";\n\nimport { AuthorizerParams } from \"../\";\nimport { Credentials } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\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 auth0: AuthenticationClient;\n\n constructor(\n auth0: AuthorizerParams,\n private readonly params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient({\n domain: auth0?.domain || process.env.AUTH0_DOMAIN!,\n clientId: auth0?.clientId || process.env.AUTH0_CLIENT_ID!,\n clientSecret: auth0?.clientSecret || process.env.AUTH0_CLIENT_SECRET,\n clientAssertionSigningAlg: auth0?.clientAssertionSigningAlg,\n clientAssertionSigningKey: auth0?.clientAssertionSigningKey,\n idTokenSigningAlg: auth0?.idTokenSigningAlg,\n clockTolerance: auth0?.clockTolerance,\n useMTLS: auth0?.useMTLS,\n });\n }\n\n private async start(\n toolContext: ToolExecuteArgs\n ): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n const authorizeParams = {\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 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 getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | 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 = {\n accessToken: {\n type: response.token_type || \"bearer\",\n value: response.access_token,\n },\n refreshToken: response.refresh_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.refresh_token,\n }\n : undefined,\n idToken: response.id_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.id_token,\n }\n : undefined,\n };\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<Credentials | undefined> {\n let credentials: Credentials | 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 if (\n !this.params.onAuthorizationRequest ||\n this.params.onAuthorizationRequest === \"interrupt\"\n ) {\n return this.params.storeAuthorizationResponse(\n undefined,\n ...(store.args as ToolExecuteArgs)\n );\n }\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: (...args: ToolExecuteArgs) => any,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authRequest: CIBAAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context: getContext(...args),\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: Credentials | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n if (interruptMode) {\n authRequest = await resolveParameter(\n this.params.getAuthorizationResponse,\n args\n );\n if (!authRequest) {\n //Initial request\n authRequest = await this.start(args);\n await this.params.storeAuthorizationResponse(\n authRequest,\n ...args\n );\n }\n credentials = await this.getCredentials(authRequest);\n } else {\n authRequest = await this.start(args);\n credentials = await this.getCredentialsPolling(authRequest);\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 await this.deleteAuthRequest();\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 { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\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 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 *\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?: OnAuthorizationRequest;\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 onAuthorizationRequest: \"block\";\n }\n | {\n onAuthorizationRequest?: \"interrupt\";\n\n /**\n * Retrieves the authorization response data.\n * @param args - The tool execution arguments.\n * @returns The authorization response data.\n * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.\n */\n getAuthorizationResponse: AuthorizerToolParameter<\n ToolExecuteArgs,\n CIBAAuthorizationRequest | undefined\n >;\n\n /**\n * Stores the authorization response data.\n * @param request - The authorization response data.\n * @param args - The tool execution arguments.\n * @returns A promise that resolves when the data is stored.\n * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.\n **/\n storeAuthorizationResponse: (\n request: CIBAAuthorizationRequest | undefined,\n ...args: ToolExecuteArgs\n ) => Promise<void>;\n }\n);\n"]}
|
|
1
|
+
{"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\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 *\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?: OnAuthorizationRequest;\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 onAuthorizationRequest: \"block\";\n }\n | {\n onAuthorizationRequest?: \"interrupt\";\n\n /**\n * Retrieves the authorization response data.\n * @param args - The tool execution arguments.\n * @returns The authorization response data.\n * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.\n */\n getAuthorizationResponse: AuthorizerToolParameter<\n ToolExecuteArgs,\n CIBAAuthorizationRequest | undefined\n >;\n\n /**\n * Stores the authorization response data.\n * @param request - The authorization response data.\n * @param args - The tool execution arguments.\n * @returns A promise that resolves when the data is stored.\n * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.\n **/\n storeAuthorizationResponse: (\n request: CIBAAuthorizationRequest | undefined,\n ...args: ToolExecuteArgs\n ) => Promise<void>;\n }\n);\n"]}
|
|
@@ -25,17 +25,15 @@ export class CIBAAuthorizerBase {
|
|
|
25
25
|
});
|
|
26
26
|
}
|
|
27
27
|
async start(toolContext) {
|
|
28
|
-
var _a;
|
|
28
|
+
var _a, _b, _c;
|
|
29
29
|
const requestedAt = Date.now() / 1000;
|
|
30
30
|
const authorizeParams = {
|
|
31
31
|
scope: ensureOpenIdScope(this.params.scopes).join(" "),
|
|
32
|
-
binding_message: "",
|
|
33
|
-
userId: "",
|
|
34
32
|
audience: this.params.audience || "",
|
|
35
|
-
request_expiry: (_a = this.params.requestExpiry)
|
|
33
|
+
request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
|
|
34
|
+
binding_message: (_b = (await resolveParameter(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
|
|
35
|
+
userId: (_c = (await resolveParameter(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
|
|
36
36
|
};
|
|
37
|
-
authorizeParams.binding_message = await resolveParameter(this.params.bindingMessage, toolContext);
|
|
38
|
-
authorizeParams.userId = await resolveParameter(this.params.userID, toolContext);
|
|
39
37
|
try {
|
|
40
38
|
const response = await this.auth0.backchannel.authorize(authorizeParams);
|
|
41
39
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAI7C,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,iBAAiB,EAAqB,MAAM,qBAAqB,CAAC;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,MAAM,OAAO,kBAAkB;IAG7B,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B,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,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAC/B,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\";\n\nimport { AuthorizerParams } from \"../\";\nimport { Credentials } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\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 auth0: AuthenticationClient;\n\n constructor(\n auth0: AuthorizerParams,\n private readonly params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient({\n domain: auth0?.domain || process.env.AUTH0_DOMAIN!,\n clientId: auth0?.clientId || process.env.AUTH0_CLIENT_ID!,\n clientSecret: auth0?.clientSecret || process.env.AUTH0_CLIENT_SECRET,\n clientAssertionSigningAlg: auth0?.clientAssertionSigningAlg,\n clientAssertionSigningKey: auth0?.clientAssertionSigningKey,\n idTokenSigningAlg: auth0?.idTokenSigningAlg,\n clockTolerance: auth0?.clockTolerance,\n useMTLS: auth0?.useMTLS,\n });\n }\n\n private async start(\n toolContext: ToolExecuteArgs\n ): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n const authorizeParams = {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n binding_message: \"\",\n userId: \"\",\n audience: this.params.audience || \"\",\n request_expiry: this.params.requestExpiry?.toString(),\n };\n\n authorizeParams.binding_message = await resolveParameter(\n this.params.bindingMessage,\n toolContext\n );\n\n authorizeParams.userId = await resolveParameter(\n this.params.userID,\n toolContext\n );\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 getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | 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 = {\n accessToken: {\n type: response.token_type || \"bearer\",\n value: response.access_token,\n },\n refreshToken: response.refresh_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.refresh_token,\n }\n : undefined,\n idToken: response.id_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.id_token,\n }\n : undefined,\n };\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<Credentials | undefined> {\n let credentials: Credentials | 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 if (\n !this.params.onAuthorizationRequest ||\n this.params.onAuthorizationRequest === \"interrupt\"\n ) {\n return this.params.storeAuthorizationResponse(\n undefined,\n ...(store.args as ToolExecuteArgs)\n );\n }\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: (...args: ToolExecuteArgs) => any,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authRequest: CIBAAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context: getContext(...args),\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: Credentials | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n if (interruptMode) {\n authRequest = await resolveParameter(\n this.params.getAuthorizationResponse,\n args\n );\n if (!authRequest) {\n //Initial request\n authRequest = await this.start(args);\n await this.params.storeAuthorizationResponse(\n authRequest,\n ...args\n );\n }\n credentials = await this.getCredentials(authRequest);\n } else {\n authRequest = await this.start(args);\n credentials = await this.getCredentialsPolling(authRequest);\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 await this.deleteAuthRequest();\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;AAI7C,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,O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,CAAC;wBACN,WAAW,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;wBACrC,WAAW,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;oBAC9D,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,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAC/B,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\";\n\nimport { AuthorizerParams } from \"../\";\nimport { Credentials } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\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 auth0: AuthenticationClient;\n\n constructor(\n auth0: AuthorizerParams,\n private readonly params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient({\n domain: auth0?.domain || process.env.AUTH0_DOMAIN!,\n clientId: auth0?.clientId || process.env.AUTH0_CLIENT_ID!,\n clientSecret: auth0?.clientSecret || process.env.AUTH0_CLIENT_SECRET,\n clientAssertionSigningAlg: auth0?.clientAssertionSigningAlg,\n clientAssertionSigningKey: auth0?.clientAssertionSigningKey,\n idTokenSigningAlg: auth0?.idTokenSigningAlg,\n clockTolerance: auth0?.clockTolerance,\n useMTLS: auth0?.useMTLS,\n });\n }\n\n private async start(\n toolContext: ToolExecuteArgs\n ): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n const authorizeParams = {\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 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 getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | 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 = {\n accessToken: {\n type: response.token_type || \"bearer\",\n value: response.access_token,\n },\n refreshToken: response.refresh_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.refresh_token,\n }\n : undefined,\n idToken: response.id_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.id_token,\n }\n : undefined,\n };\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<Credentials | undefined> {\n let credentials: Credentials | 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 if (\n !this.params.onAuthorizationRequest ||\n this.params.onAuthorizationRequest === \"interrupt\"\n ) {\n return this.params.storeAuthorizationResponse(\n undefined,\n ...(store.args as ToolExecuteArgs)\n );\n }\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: (...args: ToolExecuteArgs) => any,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authRequest: CIBAAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context: getContext(...args),\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: Credentials | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n if (interruptMode) {\n authRequest = await resolveParameter(\n this.params.getAuthorizationResponse,\n args\n );\n if (!authRequest) {\n //Initial request\n authRequest = await this.start(args);\n await this.params.storeAuthorizationResponse(\n authRequest,\n ...args\n );\n }\n credentials = await this.getCredentials(authRequest);\n } else {\n authRequest = await this.start(args);\n credentials = await this.getCredentialsPolling(authRequest);\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 await this.deleteAuthRequest();\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 { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\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 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 *\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?: OnAuthorizationRequest;\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 onAuthorizationRequest: \"block\";\n }\n | {\n onAuthorizationRequest?: \"interrupt\";\n\n /**\n * Retrieves the authorization response data.\n * @param args - The tool execution arguments.\n * @returns The authorization response data.\n * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.\n */\n getAuthorizationResponse: AuthorizerToolParameter<\n ToolExecuteArgs,\n CIBAAuthorizationRequest | undefined\n >;\n\n /**\n * Stores the authorization response data.\n * @param request - The authorization response data.\n * @param args - The tool execution arguments.\n * @returns A promise that resolves when the data is stored.\n * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.\n **/\n storeAuthorizationResponse: (\n request: CIBAAuthorizationRequest | undefined,\n ...args: ToolExecuteArgs\n ) => Promise<void>;\n }\n);\n"]}
|
|
1
|
+
{"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\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 *\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?: OnAuthorizationRequest;\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 onAuthorizationRequest: \"block\";\n }\n | {\n onAuthorizationRequest?: \"interrupt\";\n\n /**\n * Retrieves the authorization response data.\n * @param args - The tool execution arguments.\n * @returns The authorization response data.\n * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.\n */\n getAuthorizationResponse: AuthorizerToolParameter<\n ToolExecuteArgs,\n CIBAAuthorizationRequest | undefined\n >;\n\n /**\n * Stores the authorization response data.\n * @param request - The authorization response data.\n * @param args - The tool execution arguments.\n * @returns A promise that resolves when the data is stored.\n * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.\n **/\n storeAuthorizationResponse: (\n request: CIBAAuthorizationRequest | undefined,\n ...args: ToolExecuteArgs\n ) => Promise<void>;\n }\n);\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auth0/ai",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "Auth0AI SDK for JavaScript",
|
|
5
5
|
"types": "dist/esm/index.d.ts",
|
|
6
6
|
"main": "dist/cjs/index.js",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"typedoc": "^0.27.6",
|
|
61
61
|
"typescript": "^5.7.3",
|
|
62
62
|
"typescript-eslint": "^8.20.0",
|
|
63
|
-
"vitest": "^3.0.
|
|
63
|
+
"vitest": "^3.0.9"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@openfga/sdk": "^0.8.0",
|