@auth0/ai 1.0.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.
Files changed (108) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +44 -0
  3. package/dist/cjs/TokenResponse.js +3 -0
  4. package/dist/cjs/TokenResponse.js.map +1 -0
  5. package/dist/cjs/authorizers/ciba/CIBAAuthorizationRequest.js +3 -0
  6. package/dist/cjs/authorizers/ciba/CIBAAuthorizationRequest.js.map +1 -0
  7. package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js +201 -0
  8. package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -0
  9. package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js +3 -0
  10. package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -0
  11. package/dist/cjs/authorizers/ciba/asyncLocalStorage.js +14 -0
  12. package/dist/cjs/authorizers/ciba/asyncLocalStorage.js.map +1 -0
  13. package/dist/cjs/authorizers/ciba/index.js +9 -0
  14. package/dist/cjs/authorizers/ciba/index.js.map +1 -0
  15. package/dist/cjs/authorizers/device-authorizer.js +130 -0
  16. package/dist/cjs/authorizers/device-authorizer.js.map +1 -0
  17. package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js +14 -0
  18. package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js.map +1 -0
  19. package/dist/cjs/authorizers/federated-connections/index.js +129 -0
  20. package/dist/cjs/authorizers/federated-connections/index.js.map +1 -0
  21. package/dist/cjs/authorizers/fga/fga-client.js +30 -0
  22. package/dist/cjs/authorizers/fga/fga-client.js.map +1 -0
  23. package/dist/cjs/authorizers/fga/fga-filter.js +94 -0
  24. package/dist/cjs/authorizers/fga/fga-filter.js.map +1 -0
  25. package/dist/cjs/authorizers/fga/index.js +37 -0
  26. package/dist/cjs/authorizers/fga/index.js.map +1 -0
  27. package/dist/cjs/authorizers/index.js +3 -0
  28. package/dist/cjs/authorizers/index.js.map +1 -0
  29. package/dist/cjs/credentials.js +3 -0
  30. package/dist/cjs/credentials.js.map +1 -0
  31. package/dist/cjs/errors.js +46 -0
  32. package/dist/cjs/errors.js.map +1 -0
  33. package/dist/cjs/index.js +22 -0
  34. package/dist/cjs/index.js.map +1 -0
  35. package/dist/cjs/interrupts/Auth0Interrupt.js +46 -0
  36. package/dist/cjs/interrupts/Auth0Interrupt.js.map +1 -0
  37. package/dist/cjs/interrupts/CIBAInterrupts.js +89 -0
  38. package/dist/cjs/interrupts/CIBAInterrupts.js.map +1 -0
  39. package/dist/cjs/interrupts/FederatedConnectionInterrupt.js +31 -0
  40. package/dist/cjs/interrupts/FederatedConnectionInterrupt.js.map +1 -0
  41. package/dist/cjs/interrupts/index.js +17 -0
  42. package/dist/cjs/interrupts/index.js.map +1 -0
  43. package/dist/cjs/parameters.js +13 -0
  44. package/dist/cjs/parameters.js.map +1 -0
  45. package/dist/esm/TokenResponse.d.ts +15 -0
  46. package/dist/esm/TokenResponse.js +2 -0
  47. package/dist/esm/TokenResponse.js.map +1 -0
  48. package/dist/esm/authorizers/ciba/CIBAAuthorizationRequest.d.ts +20 -0
  49. package/dist/esm/authorizers/ciba/CIBAAuthorizationRequest.js +2 -0
  50. package/dist/esm/authorizers/ciba/CIBAAuthorizationRequest.js.map +1 -0
  51. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.d.ts +31 -0
  52. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js +197 -0
  53. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -0
  54. package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.d.ts +66 -0
  55. package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js +2 -0
  56. package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -0
  57. package/dist/esm/authorizers/ciba/asyncLocalStorage.d.ts +16 -0
  58. package/dist/esm/authorizers/ciba/asyncLocalStorage.js +10 -0
  59. package/dist/esm/authorizers/ciba/asyncLocalStorage.js.map +1 -0
  60. package/dist/esm/authorizers/ciba/index.d.ts +4 -0
  61. package/dist/esm/authorizers/ciba/index.js +3 -0
  62. package/dist/esm/authorizers/ciba/index.js.map +1 -0
  63. package/dist/esm/authorizers/device-authorizer.d.ts +15 -0
  64. package/dist/esm/authorizers/device-authorizer.js +90 -0
  65. package/dist/esm/authorizers/device-authorizer.js.map +1 -0
  66. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.d.ts +26 -0
  67. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js +10 -0
  68. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js.map +1 -0
  69. package/dist/esm/authorizers/federated-connections/index.d.ts +38 -0
  70. package/dist/esm/authorizers/federated-connections/index.js +123 -0
  71. package/dist/esm/authorizers/federated-connections/index.js.map +1 -0
  72. package/dist/esm/authorizers/fga/fga-client.d.ts +16 -0
  73. package/dist/esm/authorizers/fga/fga-client.js +27 -0
  74. package/dist/esm/authorizers/fga/fga-client.js.map +1 -0
  75. package/dist/esm/authorizers/fga/fga-filter.d.ts +63 -0
  76. package/dist/esm/authorizers/fga/fga-filter.js +90 -0
  77. package/dist/esm/authorizers/fga/fga-filter.js.map +1 -0
  78. package/dist/esm/authorizers/fga/index.d.ts +21 -0
  79. package/dist/esm/authorizers/fga/index.js +33 -0
  80. package/dist/esm/authorizers/fga/index.js.map +1 -0
  81. package/dist/esm/authorizers/index.d.ts +13 -0
  82. package/dist/esm/authorizers/index.js +2 -0
  83. package/dist/esm/authorizers/index.js.map +1 -0
  84. package/dist/esm/credentials.d.ts +10 -0
  85. package/dist/esm/credentials.js +2 -0
  86. package/dist/esm/credentials.js.map +1 -0
  87. package/dist/esm/errors.d.ts +19 -0
  88. package/dist/esm/errors.js +37 -0
  89. package/dist/esm/errors.js.map +1 -0
  90. package/dist/esm/index.d.ts +9 -0
  91. package/dist/esm/index.js +6 -0
  92. package/dist/esm/index.js.map +1 -0
  93. package/dist/esm/interrupts/Auth0Interrupt.d.ts +37 -0
  94. package/dist/esm/interrupts/Auth0Interrupt.js +42 -0
  95. package/dist/esm/interrupts/Auth0Interrupt.js.map +1 -0
  96. package/dist/esm/interrupts/CIBAInterrupts.d.ts +62 -0
  97. package/dist/esm/interrupts/CIBAInterrupts.js +79 -0
  98. package/dist/esm/interrupts/CIBAInterrupts.js.map +1 -0
  99. package/dist/esm/interrupts/FederatedConnectionInterrupt.d.ts +33 -0
  100. package/dist/esm/interrupts/FederatedConnectionInterrupt.js +26 -0
  101. package/dist/esm/interrupts/FederatedConnectionInterrupt.js.map +1 -0
  102. package/dist/esm/interrupts/index.d.ts +4 -0
  103. package/dist/esm/interrupts/index.js +4 -0
  104. package/dist/esm/interrupts/index.js.map +1 -0
  105. package/dist/esm/parameters.d.ts +3 -0
  106. package/dist/esm/parameters.js +9 -0
  107. package/dist/esm/parameters.js.map +1 -0
  108. package/package.json +76 -0
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # Auth0 AI SDK
2
+
3
+ `@auth0/ai` is an SDK for building secure AI-powered applications using [Auth0](https://www.auth0.ai/).
4
+
5
+ This SDK provides base abstractions for authentication and authorization in AI applications including a set of tools for implementing [asynchronous user authentication](https://demo.auth0.ai/docs/async-user-confirmation) using the [Client Initiated Backchannel Authentication (CIBA)](https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html) protocol.
6
+
7
+ ## Install
8
+
9
+ > [!WARNING]
10
+ > `@auth0/ai` is currently under development and it is not intended to be used in production, and therefore has no official support.
11
+
12
+ ```
13
+ $ npm install @auth0/ai
14
+ ```
15
+
16
+ ## Feedback
17
+
18
+ ### Contributing
19
+
20
+ We appreciate feedback and contribution to this repo! Before you get started, please see the following:
21
+
22
+ - [Auth0's general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md)
23
+ - [Auth0's code of conduct guidelines](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md)
24
+
25
+ ### Raise an issue
26
+
27
+ To provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/auth0-lab/auth0-ai-js/issues).
28
+
29
+ ### Vulnerability Reporting
30
+
31
+ Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/responsible-disclosure-policy) details the procedure for disclosing security issues.
32
+
33
+ ---
34
+
35
+ <p align="center">
36
+ <picture>
37
+ <source media="(prefers-color-scheme: light)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
38
+ <source media="(prefers-color-scheme: dark)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_dark_mode.png" width="150">
39
+ <img alt="Auth0 Logo" src="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
40
+ </picture>
41
+ </p>
42
+ <p align="center">Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout <a href="https://auth0.com/why-auth0">Why Auth0?</a></p>
43
+ <p align="center">
44
+ This project is licensed under the Apache 2.0 license. See the <a href="/LICENSE"> LICENSE</a> file for more info.</p>
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=TokenResponse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TokenResponse.js","sourceRoot":"","sources":["../../src/TokenResponse.ts"],"names":[],"mappings":"","sourcesContent":["export type TokenResponse = {\n /** Bearer token for API authorization */\n access_token: string;\n /** Refresh token (requires `offline_access` scope) */\n refresh_token?: string;\n /** JWT containing user identity claims */\n id_token: string;\n /** Typically \"Bearer\" */\n token_type?: string;\n /** Token validity in seconds (default: 86400) */\n expires_in: number;\n /** Granted permissions space */\n scope: string;\n};\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=CIBAAuthorizationRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CIBAAuthorizationRequest.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizationRequest.ts"],"names":[],"mappings":"","sourcesContent":["export type CIBAAuthorizationRequest = {\n /**\n * The authorization request ID.\n * Use this ID to check the status of the authorization request.\n */\n id: string;\n\n /**\n * The time the authorization request was made.\n */\n requestedAt: number;\n\n /**\n * The time in seconds for the authorization request to expire.\n */\n expiresIn: number;\n\n /**\n * The interval to use when polling the status.\n */\n interval: number;\n};\n"]}
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CIBAAuthorizerBase = void 0;
4
+ const auth0_1 = require("auth0");
5
+ const interrupts_1 = require("../../interrupts");
6
+ const parameters_1 = require("../../parameters");
7
+ const asyncLocalStorage_1 = require("./asyncLocalStorage");
8
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9
+ function ensureOpenIdScope(scopes) {
10
+ return scopes.includes("openid") ? scopes : ["openid", ...scopes];
11
+ }
12
+ /**
13
+ * Requests authorization by prompting the user via an out-of-band channel from
14
+ * the backend.
15
+ */
16
+ class CIBAAuthorizerBase {
17
+ constructor(auth0, params) {
18
+ this.params = params;
19
+ this.auth0 = new auth0_1.AuthenticationClient({
20
+ domain: (auth0 === null || auth0 === void 0 ? void 0 : auth0.domain) || process.env.AUTH0_DOMAIN,
21
+ clientId: (auth0 === null || auth0 === void 0 ? void 0 : auth0.clientId) || process.env.AUTH0_CLIENT_ID,
22
+ clientSecret: (auth0 === null || auth0 === void 0 ? void 0 : auth0.clientSecret) || process.env.AUTH0_CLIENT_SECRET,
23
+ clientAssertionSigningAlg: auth0 === null || auth0 === void 0 ? void 0 : auth0.clientAssertionSigningAlg,
24
+ clientAssertionSigningKey: auth0 === null || auth0 === void 0 ? void 0 : auth0.clientAssertionSigningKey,
25
+ idTokenSigningAlg: auth0 === null || auth0 === void 0 ? void 0 : auth0.idTokenSigningAlg,
26
+ clockTolerance: auth0 === null || auth0 === void 0 ? void 0 : auth0.clockTolerance,
27
+ useMTLS: auth0 === null || auth0 === void 0 ? void 0 : auth0.useMTLS,
28
+ });
29
+ }
30
+ async start(toolContext) {
31
+ var _a;
32
+ const requestedAt = Date.now() / 1000;
33
+ const authorizeParams = {
34
+ scope: ensureOpenIdScope(this.params.scopes).join(" "),
35
+ binding_message: "",
36
+ userId: "",
37
+ audience: this.params.audience || "",
38
+ request_expiry: (_a = this.params.requestExpiry) === null || _a === void 0 ? void 0 : _a.toString(),
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
+ try {
43
+ const response = await this.auth0.backchannel.authorize(authorizeParams);
44
+ return {
45
+ id: response.auth_req_id,
46
+ requestedAt: requestedAt,
47
+ expiresIn: response.expires_in,
48
+ interval: response.interval,
49
+ };
50
+ }
51
+ catch (err) {
52
+ if (err.error == "invalid_request") {
53
+ throw new interrupts_1.UserDoesNotHavePushNotificationsInterrupt(err.error_description);
54
+ }
55
+ throw err;
56
+ }
57
+ }
58
+ async getCredentialsInternal(authRequest) {
59
+ try {
60
+ const elapsedSeconds = Date.now() / 1000 - authRequest.requestedAt;
61
+ if (elapsedSeconds >= authRequest.expiresIn) {
62
+ throw new interrupts_1.AuthorizationRequestExpiredInterrupt("The authorization request has expired.", authRequest);
63
+ }
64
+ const response = await this.auth0.backchannel.backchannelGrant({
65
+ auth_req_id: authRequest.id,
66
+ });
67
+ const credentials = {
68
+ accessToken: {
69
+ type: response.token_type || "bearer",
70
+ value: response.access_token,
71
+ },
72
+ refreshToken: response.refresh_token
73
+ ? {
74
+ type: response.token_type || "bearer",
75
+ value: response.refresh_token,
76
+ }
77
+ : undefined,
78
+ idToken: response.id_token
79
+ ? {
80
+ type: response.token_type || "bearer",
81
+ value: response.id_token,
82
+ }
83
+ : undefined,
84
+ };
85
+ return credentials;
86
+ }
87
+ catch (e) {
88
+ if (e.error === "authorization_pending") {
89
+ throw new interrupts_1.AuthorizationPendingInterrupt(e.error_description, authRequest);
90
+ }
91
+ if (e.error === "slow_down") {
92
+ throw new interrupts_1.AuthorizationPollingInterrupt(e.error_description, authRequest);
93
+ }
94
+ if (e.error == "invalid_grant") {
95
+ throw new interrupts_1.InvalidGrantInterrupt(e.error_description, authRequest);
96
+ }
97
+ if (e.error == "invalid_request") {
98
+ throw new interrupts_1.UserDoesNotHavePushNotificationsInterrupt(e.error_description);
99
+ }
100
+ if (e.error == "access_denied") {
101
+ throw new interrupts_1.AccessDeniedInterrupt(e.error_description, authRequest);
102
+ }
103
+ throw e;
104
+ }
105
+ }
106
+ async getCredentials(authRequest) {
107
+ return this.getCredentialsInternal(authRequest);
108
+ }
109
+ async getCredentialsPolling(authRequest) {
110
+ let credentials = undefined;
111
+ do {
112
+ try {
113
+ credentials = await this.getCredentialsInternal(authRequest);
114
+ }
115
+ catch (err) {
116
+ if (err instanceof interrupts_1.AuthorizationPendingInterrupt ||
117
+ err instanceof interrupts_1.AuthorizationPollingInterrupt) {
118
+ await sleep(err.request.interval * 1000);
119
+ }
120
+ else {
121
+ throw err;
122
+ }
123
+ }
124
+ } while (!credentials);
125
+ return credentials;
126
+ }
127
+ deleteAuthRequest() {
128
+ const store = asyncLocalStorage_1.asyncLocalStorage.getStore();
129
+ if (!store) {
130
+ throw new Error("This method should be called from within a tool.");
131
+ }
132
+ if (!this.params.onAuthorizationRequest ||
133
+ this.params.onAuthorizationRequest === "interrupt") {
134
+ return this.params.storeAuthorizationResponse(undefined, ...store.args);
135
+ }
136
+ }
137
+ /**
138
+ *
139
+ * Wraps the execute method of a AI tool to handle CIBA authorization.
140
+ *
141
+ * @param getContext - A function that returns the context of the tool execution.
142
+ * @param execute - The tool execute method.
143
+ * @returns The wrapped execute method.
144
+ */
145
+ protect(getContext, execute) {
146
+ return async (...args) => {
147
+ let authRequest;
148
+ if (asyncLocalStorage_1.asyncLocalStorage.getStore()) {
149
+ throw new Error("Cannot nest tool calls that require CIBA authorization.");
150
+ }
151
+ const storeValue = {
152
+ args,
153
+ context: getContext(...args),
154
+ };
155
+ return asyncLocalStorage_1.asyncLocalStorage.run(storeValue, async () => {
156
+ let credentials;
157
+ const interruptMode = typeof this.params.onAuthorizationRequest === "undefined" ||
158
+ this.params.onAuthorizationRequest === "interrupt";
159
+ try {
160
+ if (interruptMode) {
161
+ authRequest = await (0, parameters_1.resolveParameter)(this.params.getAuthorizationResponse, args);
162
+ if (!authRequest) {
163
+ //Initial request
164
+ authRequest = await this.start(args);
165
+ await this.params.storeAuthorizationResponse(authRequest, ...args);
166
+ }
167
+ credentials = await this.getCredentials(authRequest);
168
+ }
169
+ else {
170
+ authRequest = await this.start(args);
171
+ credentials = await this.getCredentialsPolling(authRequest);
172
+ }
173
+ }
174
+ catch (err) {
175
+ const shouldInterrupt = err instanceof interrupts_1.AuthorizationPendingInterrupt ||
176
+ err instanceof interrupts_1.AuthorizationPollingInterrupt;
177
+ if (shouldInterrupt) {
178
+ return this.handleAuthorizationInterrupts(err);
179
+ }
180
+ else {
181
+ await this.deleteAuthRequest();
182
+ if (typeof this.params.onUnauthorized === "function") {
183
+ return this.params.onUnauthorized(err, ...args);
184
+ }
185
+ else {
186
+ return err;
187
+ }
188
+ }
189
+ }
190
+ await this.deleteAuthRequest();
191
+ storeValue.credentials = credentials;
192
+ return execute(...args);
193
+ });
194
+ };
195
+ }
196
+ handleAuthorizationInterrupts(err) {
197
+ throw err;
198
+ }
199
+ }
200
+ exports.CIBAAuthorizerBase = CIBAAuthorizerBase;
201
+ //# sourceMappingURL=CIBAAuthorizerBase.js.map
@@ -0,0 +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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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;AA3PD,gDA2PC","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"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=CIBAAuthorizerParams.js.map
@@ -0,0 +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"]}
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCIBACredentials = exports.asyncLocalStorage = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ exports.asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
6
+ const getCIBACredentials = () => {
7
+ const t = exports.asyncLocalStorage.getStore();
8
+ if (typeof t === "undefined") {
9
+ throw new Error("The tool must be wrapped with the withCIBA function.");
10
+ }
11
+ return t.credentials;
12
+ };
13
+ exports.getCIBACredentials = getCIBACredentials;
14
+ //# sourceMappingURL=asyncLocalStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/asyncLocalStorage.ts"],"names":[],"mappings":";;;AAAA,6CAAgD;AAkBnC,QAAA,iBAAiB,GAAG,IAAI,+BAAiB,EAEnD,CAAC;AAEG,MAAM,kBAAkB,GAAG,GAAG,EAAE;IACrC,MAAM,CAAC,GAAG,yBAAiB,CAAC,QAAQ,EAAE,CAAC;IACvC,IAAI,OAAO,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,CAAC,CAAC,WAAW,CAAC;AACvB,CAAC,CAAC;AANW,QAAA,kBAAkB,sBAM7B","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\nimport { Credentials } from \"../../credentials\";\n\nexport type AsyncStorageValue<TContext> = {\n credentials?: Credentials;\n\n /**\n * The tool execution context.\n */\n context: TContext;\n\n /**\n * The tool execution arguments.\n */\n args: any[];\n};\n\nexport const asyncLocalStorage = new AsyncLocalStorage<\n AsyncStorageValue<any>\n>();\n\nexport const getCIBACredentials = () => {\n const t = asyncLocalStorage.getStore();\n if (typeof t === \"undefined\") {\n throw new Error(\"The tool must be wrapped with the withCIBA function.\");\n }\n return t.credentials;\n};\n"]}
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CIBAAuthorizerBase = exports.getCIBACredentials = exports.asyncLocalStorage = void 0;
4
+ var asyncLocalStorage_1 = require("./asyncLocalStorage");
5
+ Object.defineProperty(exports, "asyncLocalStorage", { enumerable: true, get: function () { return asyncLocalStorage_1.asyncLocalStorage; } });
6
+ Object.defineProperty(exports, "getCIBACredentials", { enumerable: true, get: function () { return asyncLocalStorage_1.getCIBACredentials; } });
7
+ var CIBAAuthorizerBase_1 = require("./CIBAAuthorizerBase");
8
+ Object.defineProperty(exports, "CIBAAuthorizerBase", { enumerable: true, get: function () { return CIBAAuthorizerBase_1.CIBAAuthorizerBase; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/index.ts"],"names":[],"mappings":";;;AAAA,yDAA4E;AAAnE,sHAAA,iBAAiB,OAAA;AAAE,uHAAA,kBAAkB,OAAA;AAI9C,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA","sourcesContent":["export { asyncLocalStorage, getCIBACredentials } from \"./asyncLocalStorage\";\n\nexport type { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport { CIBAAuthorizerBase } from \"./CIBAAuthorizerBase\";\n"]}