@auth0/ai 2.1.1 → 3.1.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.
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js +9 -1
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
- package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
- package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js +23 -1
- package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js.map +1 -1
- package/dist/cjs/authorizers/federated-connections/index.js +3 -2
- package/dist/cjs/authorizers/federated-connections/index.js.map +1 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js +9 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.d.ts +6 -2
- package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
- package/dist/esm/authorizers/federated-connections/asyncLocalStorage.d.ts +14 -0
- package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js +21 -0
- package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js.map +1 -1
- package/dist/esm/authorizers/federated-connections/index.d.ts +1 -1
- package/dist/esm/authorizers/federated-connections/index.js +1 -1
- package/dist/esm/authorizers/federated-connections/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -64,13 +64,21 @@ class CIBAAuthorizerBase {
|
|
|
64
64
|
}
|
|
65
65
|
async getAuthorizeParams(toolContext) {
|
|
66
66
|
var _a, _b, _c;
|
|
67
|
-
|
|
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,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,4B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esContent":["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;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AE,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,0CAA6B;wBAC5C,GAAG,YAAY,0CAA6B,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;AAxSD,gDAwSC","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
|
|
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"]}
|
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getCredentialsForConnection = exports.asyncLocalStorage = void 0;
|
|
3
|
+
exports.getAccessTokenForConnection = exports.getCredentialsForConnection = exports.asyncLocalStorage = void 0;
|
|
4
4
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
5
|
+
const interrupts_1 = require("../../interrupts");
|
|
5
6
|
exports.asyncLocalStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
7
|
+
/**
|
|
8
|
+
* Returns the entire tokenset for the current connection.
|
|
9
|
+
*
|
|
10
|
+
* Use `getAccessTokenForConnection` if you only need the access token.
|
|
11
|
+
*
|
|
12
|
+
* @returns {TokenSet} The current token set.
|
|
13
|
+
*/
|
|
6
14
|
const getCredentialsForConnection = () => {
|
|
7
15
|
const store = exports.asyncLocalStorage.getStore();
|
|
8
16
|
if (typeof store === "undefined") {
|
|
@@ -11,4 +19,18 @@ const getCredentialsForConnection = () => {
|
|
|
11
19
|
return store === null || store === void 0 ? void 0 : store.credentials;
|
|
12
20
|
};
|
|
13
21
|
exports.getCredentialsForConnection = getCredentialsForConnection;
|
|
22
|
+
/**
|
|
23
|
+
*
|
|
24
|
+
* Get the access token for the current connection.
|
|
25
|
+
*
|
|
26
|
+
* @returns The access token for the current connection.
|
|
27
|
+
*/
|
|
28
|
+
const getAccessTokenForConnection = () => {
|
|
29
|
+
const credentials = (0, exports.getCredentialsForConnection)();
|
|
30
|
+
if (!credentials || !credentials.accessToken) {
|
|
31
|
+
throw new interrupts_1.FederatedConnectionError("No credentials found");
|
|
32
|
+
}
|
|
33
|
+
return credentials.accessToken;
|
|
34
|
+
};
|
|
35
|
+
exports.getAccessTokenForConnection = getAccessTokenForConnection;
|
|
14
36
|
//# sourceMappingURL=asyncLocalStorage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/asyncLocalStorage.ts"],"names":[],"mappings":";;;AAAA,uDAAqD;
|
|
1
|
+
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/asyncLocalStorage.ts"],"names":[],"mappings":";;;AAAA,uDAAqD;AAGrD,iDAA4D;AA8B/C,QAAA,iBAAiB,GAAG,IAAI,oCAAiB,EAAqB,CAAC;AAE5E;;;;;;GAMG;AACI,MAAM,2BAA2B,GAAG,GAAG,EAAE;IAC9C,MAAM,KAAK,GAAG,yBAAiB,CAAC,QAAQ,EAAE,CAAC;IAC3C,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,WAAW,CAAC;AAC5B,CAAC,CAAC;AARW,QAAA,2BAA2B,+BAQtC;AAEF;;;;;GAKG;AACI,MAAM,2BAA2B,GAAG,GAAG,EAAE;IAC9C,MAAM,WAAW,GAAG,IAAA,mCAA2B,GAAE,CAAC;IAClD,IAAI,CAAC,WAAW,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,CAAC;QAC7C,MAAM,IAAI,qCAAwB,CAAC,sBAAsB,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,WAAW,CAAC,WAAW,CAAC;AACjC,CAAC,CAAC;AANW,QAAA,2BAA2B,+BAMtC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { TokenSet } from \"../../credentials\";\nimport { FederatedConnectionError } from \"../../interrupts\";\nimport { ToolCallContext } from \"../context\";\n\nexport type AsyncStorageValue = {\n /**\n * The Federated Connection access token.\n */\n credentials?: TokenSet;\n\n /**\n * The tool execution context.\n */\n context: ToolCallContext;\n\n /**\n * The federated connection name.\n */\n connection: string;\n\n /**\n * The scopes required to access the federated connection.\n */\n scopes: string[];\n\n /**\n * The scopes that the current access token has.\n */\n currentScopes?: string[];\n};\n\nexport const asyncLocalStorage = new AsyncLocalStorage<AsyncStorageValue>();\n\n/**\n * Returns the entire tokenset for the current connection.\n *\n * Use `getAccessTokenForConnection` if you only need the access token.\n *\n * @returns {TokenSet} The current token set.\n */\nexport const getCredentialsForConnection = () => {\n const store = asyncLocalStorage.getStore();\n if (typeof store === \"undefined\") {\n throw new Error(\n \"The tool must be wrapped with the withTokenForConnections function.\"\n );\n }\n return store?.credentials;\n};\n\n/**\n *\n * Get the access token for the current connection.\n *\n * @returns The access token for the current connection.\n */\nexport const getAccessTokenForConnection = () => {\n const credentials = getCredentialsForConnection();\n if (!credentials || !credentials.accessToken) {\n throw new FederatedConnectionError(\"No credentials found\");\n }\n return credentials.accessToken;\n};\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FederatedConnectionAuthorizerBase = exports.getAccessTokenForConnection = exports.asyncLocalStorage = void 0;
|
|
3
|
+
exports.FederatedConnectionAuthorizerBase = exports.getAccessTokenForConnection = exports.getCredentialsForConnection = exports.asyncLocalStorage = void 0;
|
|
4
4
|
var asyncLocalStorage_1 = require("./asyncLocalStorage");
|
|
5
5
|
Object.defineProperty(exports, "asyncLocalStorage", { enumerable: true, get: function () { return asyncLocalStorage_1.asyncLocalStorage; } });
|
|
6
|
-
Object.defineProperty(exports, "
|
|
6
|
+
Object.defineProperty(exports, "getCredentialsForConnection", { enumerable: true, get: function () { return asyncLocalStorage_1.getCredentialsForConnection; } });
|
|
7
|
+
Object.defineProperty(exports, "getAccessTokenForConnection", { enumerable: true, get: function () { return asyncLocalStorage_1.getAccessTokenForConnection; } });
|
|
7
8
|
var FederatedConnectionAuthorizerBase_1 = require("./FederatedConnectionAuthorizerBase");
|
|
8
9
|
Object.defineProperty(exports, "FederatedConnectionAuthorizerBase", { enumerable: true, get: function () { return FederatedConnectionAuthorizerBase_1.FederatedConnectionAuthorizerBase; } });
|
|
9
10
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/index.ts"],"names":[],"mappings":";;;AAEA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/index.ts"],"names":[],"mappings":";;;AAEA,yDAI6B;AAH3B,sHAAA,iBAAiB,OAAA;AACjB,gIAAA,2BAA2B,OAAA;AAC3B,gIAAA,2BAA2B,OAAA;AAG7B,yFAAwF;AAA/E,sJAAA,iCAAiC,OAAA","sourcesContent":["export type { AsyncStorageValue } from \"./asyncLocalStorage\";\n\nexport {\n asyncLocalStorage,\n getCredentialsForConnection,\n getAccessTokenForConnection,\n} from \"./asyncLocalStorage\";\n\nexport { FederatedConnectionAuthorizerBase } from \"./FederatedConnectionAuthorizerBase\";\n\nexport type { FederatedConnectionAuthorizerParams } from \"./FederatedConnectionAuthorizerParams\";\n"]}
|
|
@@ -58,13 +58,21 @@ export class CIBAAuthorizerBase {
|
|
|
58
58
|
}
|
|
59
59
|
async getAuthorizeParams(toolContext) {
|
|
60
60
|
var _a, _b, _c;
|
|
61
|
-
|
|
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":[],"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,E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AAI,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,CAAC;AAExC,OAAO,EAAiB,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAqB,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAChE,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,CA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AAG,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
|
|
22
|
+
* The authorization parameters for RAR request.
|
|
19
23
|
*/
|
|
20
|
-
|
|
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
|
|
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"]}
|
|
@@ -24,5 +24,19 @@ export type AsyncStorageValue = {
|
|
|
24
24
|
currentScopes?: string[];
|
|
25
25
|
};
|
|
26
26
|
export declare const asyncLocalStorage: AsyncLocalStorage<AsyncStorageValue>;
|
|
27
|
+
/**
|
|
28
|
+
* Returns the entire tokenset for the current connection.
|
|
29
|
+
*
|
|
30
|
+
* Use `getAccessTokenForConnection` if you only need the access token.
|
|
31
|
+
*
|
|
32
|
+
* @returns {TokenSet} The current token set.
|
|
33
|
+
*/
|
|
27
34
|
export declare const getCredentialsForConnection: () => TokenSet | undefined;
|
|
35
|
+
/**
|
|
36
|
+
*
|
|
37
|
+
* Get the access token for the current connection.
|
|
38
|
+
*
|
|
39
|
+
* @returns The access token for the current connection.
|
|
40
|
+
*/
|
|
41
|
+
export declare const getAccessTokenForConnection: () => string;
|
|
28
42
|
//# sourceMappingURL=asyncLocalStorage.d.ts.map
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { FederatedConnectionError } from "../../interrupts";
|
|
2
3
|
export const asyncLocalStorage = new AsyncLocalStorage();
|
|
4
|
+
/**
|
|
5
|
+
* Returns the entire tokenset for the current connection.
|
|
6
|
+
*
|
|
7
|
+
* Use `getAccessTokenForConnection` if you only need the access token.
|
|
8
|
+
*
|
|
9
|
+
* @returns {TokenSet} The current token set.
|
|
10
|
+
*/
|
|
3
11
|
export const getCredentialsForConnection = () => {
|
|
4
12
|
const store = asyncLocalStorage.getStore();
|
|
5
13
|
if (typeof store === "undefined") {
|
|
@@ -7,4 +15,17 @@ export const getCredentialsForConnection = () => {
|
|
|
7
15
|
}
|
|
8
16
|
return store === null || store === void 0 ? void 0 : store.credentials;
|
|
9
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
*
|
|
20
|
+
* Get the access token for the current connection.
|
|
21
|
+
*
|
|
22
|
+
* @returns The access token for the current connection.
|
|
23
|
+
*/
|
|
24
|
+
export const getAccessTokenForConnection = () => {
|
|
25
|
+
const credentials = getCredentialsForConnection();
|
|
26
|
+
if (!credentials || !credentials.accessToken) {
|
|
27
|
+
throw new FederatedConnectionError("No credentials found");
|
|
28
|
+
}
|
|
29
|
+
return credentials.accessToken;
|
|
30
|
+
};
|
|
10
31
|
//# sourceMappingURL=asyncLocalStorage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AA8B5D,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAqB,CAAC;AAE5E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,EAAE;IAC9C,MAAM,KAAK,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IAC3C,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,WAAW,CAAC;AAC5B,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,EAAE;IAC9C,MAAM,WAAW,GAAG,2BAA2B,EAAE,CAAC;IAClD,IAAI,CAAC,WAAW,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,CAAC;QAC7C,MAAM,IAAI,wBAAwB,CAAC,sBAAsB,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,WAAW,CAAC,WAAW,CAAC;AACjC,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { TokenSet } from \"../../credentials\";\nimport { FederatedConnectionError } from \"../../interrupts\";\nimport { ToolCallContext } from \"../context\";\n\nexport type AsyncStorageValue = {\n /**\n * The Federated Connection access token.\n */\n credentials?: TokenSet;\n\n /**\n * The tool execution context.\n */\n context: ToolCallContext;\n\n /**\n * The federated connection name.\n */\n connection: string;\n\n /**\n * The scopes required to access the federated connection.\n */\n scopes: string[];\n\n /**\n * The scopes that the current access token has.\n */\n currentScopes?: string[];\n};\n\nexport const asyncLocalStorage = new AsyncLocalStorage<AsyncStorageValue>();\n\n/**\n * Returns the entire tokenset for the current connection.\n *\n * Use `getAccessTokenForConnection` if you only need the access token.\n *\n * @returns {TokenSet} The current token set.\n */\nexport const getCredentialsForConnection = () => {\n const store = asyncLocalStorage.getStore();\n if (typeof store === \"undefined\") {\n throw new Error(\n \"The tool must be wrapped with the withTokenForConnections function.\"\n );\n }\n return store?.credentials;\n};\n\n/**\n *\n * Get the access token for the current connection.\n *\n * @returns The access token for the current connection.\n */\nexport const getAccessTokenForConnection = () => {\n const credentials = getCredentialsForConnection();\n if (!credentials || !credentials.accessToken) {\n throw new FederatedConnectionError(\"No credentials found\");\n }\n return credentials.accessToken;\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { AsyncStorageValue } from "./asyncLocalStorage";
|
|
2
|
-
export { asyncLocalStorage, getCredentialsForConnection
|
|
2
|
+
export { asyncLocalStorage, getCredentialsForConnection, getAccessTokenForConnection, } from "./asyncLocalStorage";
|
|
3
3
|
export { FederatedConnectionAuthorizerBase } from "./FederatedConnectionAuthorizerBase";
|
|
4
4
|
export type { FederatedConnectionAuthorizerParams } from "./FederatedConnectionAuthorizerParams";
|
|
5
5
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { asyncLocalStorage, getCredentialsForConnection
|
|
1
|
+
export { asyncLocalStorage, getCredentialsForConnection, getAccessTokenForConnection, } from "./asyncLocalStorage";
|
|
2
2
|
export { FederatedConnectionAuthorizerBase } from "./FederatedConnectionAuthorizerBase";
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iBAAiB,EACjB,2BAA2B,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/federated-connections/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["export type { AsyncStorageValue } from \"./asyncLocalStorage\";\n\nexport {\n asyncLocalStorage,\n getCredentialsForConnection,\n getAccessTokenForConnection,\n} from \"./asyncLocalStorage\";\n\nexport { FederatedConnectionAuthorizerBase } from \"./FederatedConnectionAuthorizerBase\";\n\nexport type { FederatedConnectionAuthorizerParams } from \"./FederatedConnectionAuthorizerParams\";\n"]}
|