@auth0/ai 1.0.1 → 2.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 (141) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js +81 -55
  3. package/dist/cjs/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
  4. package/dist/cjs/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
  5. package/dist/cjs/authorizers/ciba/asyncLocalStorage.js +1 -1
  6. package/dist/cjs/authorizers/ciba/asyncLocalStorage.js.map +1 -1
  7. package/dist/cjs/authorizers/context.js +20 -0
  8. package/dist/cjs/authorizers/context.js.map +1 -0
  9. package/dist/cjs/authorizers/device-authorizer/DeviceAuthResponse.js +18 -0
  10. package/dist/cjs/authorizers/device-authorizer/DeviceAuthResponse.js.map +1 -0
  11. package/dist/cjs/authorizers/device-authorizer/DeviceAuthorizerBase.js +231 -0
  12. package/dist/cjs/authorizers/device-authorizer/DeviceAuthorizerBase.js.map +1 -0
  13. package/dist/cjs/{TokenResponse.js → authorizers/device-authorizer/DeviceAuthorizerParams.js} +1 -1
  14. package/dist/cjs/authorizers/device-authorizer/DeviceAuthorizerParams.js.map +1 -0
  15. package/dist/cjs/authorizers/device-authorizer/asyncLocalStorage.js +14 -0
  16. package/dist/cjs/authorizers/device-authorizer/asyncLocalStorage.js.map +1 -0
  17. package/dist/cjs/authorizers/device-authorizer/index.js +9 -0
  18. package/dist/cjs/authorizers/device-authorizer/index.js.map +1 -0
  19. package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js +158 -0
  20. package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js.map +1 -0
  21. package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js +3 -0
  22. package/dist/cjs/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js.map +1 -0
  23. package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js +5 -5
  24. package/dist/cjs/authorizers/federated-connections/asyncLocalStorage.js.map +1 -1
  25. package/dist/cjs/authorizers/federated-connections/index.js +5 -125
  26. package/dist/cjs/authorizers/federated-connections/index.js.map +1 -1
  27. package/dist/cjs/authorizers/index.js.map +1 -1
  28. package/dist/cjs/authorizers/types.js +14 -0
  29. package/dist/cjs/authorizers/types.js.map +1 -0
  30. package/dist/cjs/credentials.js +13 -0
  31. package/dist/cjs/credentials.js.map +1 -1
  32. package/dist/cjs/index.js +0 -1
  33. package/dist/cjs/index.js.map +1 -1
  34. package/dist/cjs/interrupts/Auth0Interrupt.js +2 -1
  35. package/dist/cjs/interrupts/Auth0Interrupt.js.map +1 -1
  36. package/dist/cjs/interrupts/DeviceInterrupts.js +79 -0
  37. package/dist/cjs/interrupts/DeviceInterrupts.js.map +1 -0
  38. package/dist/cjs/interrupts/index.js +37 -1
  39. package/dist/cjs/interrupts/index.js.map +1 -1
  40. package/dist/cjs/stores/Store.js +12 -0
  41. package/dist/cjs/stores/Store.js.map +1 -0
  42. package/dist/cjs/stores/SubStore.js +52 -0
  43. package/dist/cjs/stores/SubStore.js.map +1 -0
  44. package/dist/cjs/stores/impl/FSStore.js +80 -0
  45. package/dist/cjs/stores/impl/FSStore.js.map +1 -0
  46. package/dist/cjs/stores/impl/MemoryStore.js +15 -0
  47. package/dist/cjs/stores/impl/MemoryStore.js.map +1 -0
  48. package/dist/cjs/stores/impl/TempBoxStore.js +22 -0
  49. package/dist/cjs/stores/impl/TempBoxStore.js.map +1 -0
  50. package/dist/cjs/stores/index.js +10 -0
  51. package/dist/cjs/stores/index.js.map +1 -0
  52. package/dist/cjs/util/index.js +12 -0
  53. package/dist/cjs/util/index.js.map +1 -0
  54. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.d.ts +12 -8
  55. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js +78 -55
  56. package/dist/esm/authorizers/ciba/CIBAAuthorizerBase.js.map +1 -1
  57. package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.d.ts +20 -20
  58. package/dist/esm/authorizers/ciba/CIBAAuthorizerParams.js.map +1 -1
  59. package/dist/esm/authorizers/ciba/asyncLocalStorage.d.ts +7 -3
  60. package/dist/esm/authorizers/ciba/asyncLocalStorage.js +1 -1
  61. package/dist/esm/authorizers/ciba/asyncLocalStorage.js.map +1 -1
  62. package/dist/esm/authorizers/context.d.ts +16 -0
  63. package/dist/esm/authorizers/context.js +16 -0
  64. package/dist/esm/authorizers/context.js.map +1 -0
  65. package/dist/esm/authorizers/device-authorizer/DeviceAuthResponse.d.ts +38 -0
  66. package/dist/esm/authorizers/device-authorizer/DeviceAuthResponse.js +15 -0
  67. package/dist/esm/authorizers/device-authorizer/DeviceAuthResponse.js.map +1 -0
  68. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerBase.d.ts +49 -0
  69. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerBase.js +224 -0
  70. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerBase.js.map +1 -0
  71. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerParams.d.ts +58 -0
  72. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerParams.js +2 -0
  73. package/dist/esm/authorizers/device-authorizer/DeviceAuthorizerParams.js.map +1 -0
  74. package/dist/esm/authorizers/device-authorizer/asyncLocalStorage.d.ts +16 -0
  75. package/dist/esm/authorizers/device-authorizer/asyncLocalStorage.js +10 -0
  76. package/dist/esm/authorizers/device-authorizer/asyncLocalStorage.js.map +1 -0
  77. package/dist/esm/authorizers/device-authorizer/index.d.ts +4 -0
  78. package/dist/esm/authorizers/device-authorizer/index.js +3 -0
  79. package/dist/esm/authorizers/device-authorizer/index.js.map +1 -0
  80. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerBase.d.ts +30 -0
  81. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js +151 -0
  82. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerBase.js.map +1 -0
  83. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerParams.d.ts +38 -0
  84. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js +2 -0
  85. package/dist/esm/authorizers/federated-connections/FederatedConnectionAuthorizerParams.js.map +1 -0
  86. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.d.ts +7 -5
  87. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js +3 -3
  88. package/dist/esm/authorizers/federated-connections/asyncLocalStorage.js.map +1 -1
  89. package/dist/esm/authorizers/federated-connections/index.d.ts +3 -36
  90. package/dist/esm/authorizers/federated-connections/index.js +2 -122
  91. package/dist/esm/authorizers/federated-connections/index.js.map +1 -1
  92. package/dist/esm/authorizers/index.d.ts +1 -12
  93. package/dist/esm/authorizers/index.js.map +1 -1
  94. package/dist/esm/authorizers/types.d.ts +37 -0
  95. package/dist/esm/authorizers/types.js +11 -0
  96. package/dist/esm/authorizers/types.js.map +1 -0
  97. package/dist/esm/credentials.d.ts +33 -8
  98. package/dist/esm/credentials.js +11 -1
  99. package/dist/esm/credentials.js.map +1 -1
  100. package/dist/esm/index.d.ts +1 -3
  101. package/dist/esm/index.js +0 -1
  102. package/dist/esm/index.js.map +1 -1
  103. package/dist/esm/interrupts/Auth0Interrupt.js +2 -1
  104. package/dist/esm/interrupts/Auth0Interrupt.js.map +1 -1
  105. package/dist/esm/interrupts/DeviceInterrupts.d.ts +55 -0
  106. package/dist/esm/interrupts/DeviceInterrupts.js +70 -0
  107. package/dist/esm/interrupts/DeviceInterrupts.js.map +1 -0
  108. package/dist/esm/interrupts/index.d.ts +2 -0
  109. package/dist/esm/interrupts/index.js +2 -0
  110. package/dist/esm/interrupts/index.js.map +1 -1
  111. package/dist/esm/stores/Store.d.ts +40 -0
  112. package/dist/esm/stores/Store.js +11 -0
  113. package/dist/esm/stores/Store.js.map +1 -0
  114. package/dist/esm/stores/SubStore.d.ts +31 -0
  115. package/dist/esm/stores/SubStore.js +48 -0
  116. package/dist/esm/stores/SubStore.js.map +1 -0
  117. package/dist/esm/stores/impl/FSStore.d.ts +19 -0
  118. package/dist/esm/stores/impl/FSStore.js +72 -0
  119. package/dist/esm/stores/impl/FSStore.js.map +1 -0
  120. package/dist/esm/stores/impl/MemoryStore.d.ts +8 -0
  121. package/dist/esm/stores/impl/MemoryStore.js +11 -0
  122. package/dist/esm/stores/impl/MemoryStore.js.map +1 -0
  123. package/dist/esm/stores/impl/TempBoxStore.d.ts +13 -0
  124. package/dist/esm/stores/impl/TempBoxStore.js +18 -0
  125. package/dist/esm/stores/impl/TempBoxStore.js.map +1 -0
  126. package/dist/esm/stores/index.d.ts +5 -0
  127. package/dist/esm/stores/index.js +4 -0
  128. package/dist/esm/stores/index.js.map +1 -0
  129. package/dist/esm/util/index.d.ts +3 -0
  130. package/dist/esm/util/index.js +8 -0
  131. package/dist/esm/util/index.js.map +1 -0
  132. package/package.json +20 -4
  133. package/dist/cjs/TokenResponse.js.map +0 -1
  134. package/dist/cjs/authorizers/device-authorizer.js +0 -130
  135. package/dist/cjs/authorizers/device-authorizer.js.map +0 -1
  136. package/dist/esm/TokenResponse.d.ts +0 -15
  137. package/dist/esm/TokenResponse.js +0 -2
  138. package/dist/esm/TokenResponse.js.map +0 -1
  139. package/dist/esm/authorizers/device-authorizer.d.ts +0 -15
  140. package/dist/esm/authorizers/device-authorizer.js +0 -90
  141. package/dist/esm/authorizers/device-authorizer.js.map +0 -1
@@ -1,6 +1,12 @@
1
1
  import { AuthenticationClient } from "auth0";
2
+ import crypto from "crypto";
3
+ import stableHash from "stable-hash";
4
+ import { tokenSetFromTokenResponse } from "../../credentials";
2
5
  import { AccessDeniedInterrupt, AuthorizationPendingInterrupt, AuthorizationPollingInterrupt, AuthorizationRequestExpiredInterrupt, InvalidGrantInterrupt, UserDoesNotHavePushNotificationsInterrupt, } from "../../interrupts";
3
6
  import { resolveParameter } from "../../parameters";
7
+ import { SubStore } from "../../stores";
8
+ import { nsFromContext } from "../context";
9
+ import { Auth0ClientSchema } from "../types";
4
10
  import { asyncLocalStorage } from "./asyncLocalStorage";
5
11
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6
12
  function ensureOpenIdScope(scopes) {
@@ -12,28 +18,28 @@ function ensureOpenIdScope(scopes) {
12
18
  */
13
19
  export class CIBAAuthorizerBase {
14
20
  constructor(auth0, params) {
15
- this.params = params;
16
- this.auth0 = new AuthenticationClient({
17
- domain: (auth0 === null || auth0 === void 0 ? void 0 : auth0.domain) || process.env.AUTH0_DOMAIN,
18
- clientId: (auth0 === null || auth0 === void 0 ? void 0 : auth0.clientId) || process.env.AUTH0_CLIENT_ID,
19
- clientSecret: (auth0 === null || auth0 === void 0 ? void 0 : auth0.clientSecret) || process.env.AUTH0_CLIENT_SECRET,
20
- clientAssertionSigningAlg: auth0 === null || auth0 === void 0 ? void 0 : auth0.clientAssertionSigningAlg,
21
- clientAssertionSigningKey: auth0 === null || auth0 === void 0 ? void 0 : auth0.clientAssertionSigningKey,
22
- idTokenSigningAlg: auth0 === null || auth0 === void 0 ? void 0 : auth0.idTokenSigningAlg,
23
- clockTolerance: auth0 === null || auth0 === void 0 ? void 0 : auth0.clockTolerance,
24
- useMTLS: auth0 === null || auth0 === void 0 ? void 0 : auth0.useMTLS,
21
+ this.auth0 = new AuthenticationClient(Auth0ClientSchema.parse(auth0));
22
+ this.params = {
23
+ credentialsContext: "tool-call",
24
+ ...params,
25
+ };
26
+ this.authResponseStore = new SubStore(params.store, {
27
+ getTTL: (authResponse) => authResponse.expiresIn ? authResponse.expiresIn * 1000 : undefined,
28
+ });
29
+ this.credentialsStore = new SubStore(params.store, {
30
+ getTTL: (credentials) => credentials.expiresIn ? credentials.expiresIn * 1000 : undefined,
25
31
  });
26
32
  }
27
- async start(toolContext) {
28
- var _a, _b, _c;
29
- const requestedAt = Date.now() / 1000;
30
- const authorizeParams = {
31
- scope: ensureOpenIdScope(this.params.scopes).join(" "),
32
- audience: this.params.audience || "",
33
- request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
34
- binding_message: (_b = (await resolveParameter(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
35
- userId: (_c = (await resolveParameter(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
33
+ getInstanceID(authorizeParams) {
34
+ const props = {
35
+ auth0: this.auth0,
36
+ params: authorizeParams,
36
37
  };
38
+ const sh = stableHash(props);
39
+ return crypto.createHash("MD5").update(sh).digest("hex");
40
+ }
41
+ async start(authorizeParams) {
42
+ const requestedAt = Date.now() / 1000;
37
43
  try {
38
44
  const response = await this.auth0.backchannel.authorize(authorizeParams);
39
45
  return {
@@ -50,6 +56,16 @@ export class CIBAAuthorizerBase {
50
56
  throw err;
51
57
  }
52
58
  }
59
+ async getAuthorizeParams(toolContext) {
60
+ var _a, _b, _c;
61
+ return {
62
+ scope: ensureOpenIdScope(this.params.scopes).join(" "),
63
+ audience: this.params.audience || "",
64
+ request_expiry: ((_a = this.params.requestExpiry) !== null && _a !== void 0 ? _a : 300).toString(),
65
+ binding_message: (_b = (await resolveParameter(this.params.bindingMessage, toolContext))) !== null && _b !== void 0 ? _b : "",
66
+ userId: (_c = (await resolveParameter(this.params.userID, toolContext))) !== null && _c !== void 0 ? _c : "",
67
+ };
68
+ }
53
69
  async getCredentialsInternal(authRequest) {
54
70
  try {
55
71
  const elapsedSeconds = Date.now() / 1000 - authRequest.requestedAt;
@@ -59,24 +75,7 @@ export class CIBAAuthorizerBase {
59
75
  const response = await this.auth0.backchannel.backchannelGrant({
60
76
  auth_req_id: authRequest.id,
61
77
  });
62
- const credentials = {
63
- accessToken: {
64
- type: response.token_type || "bearer",
65
- value: response.access_token,
66
- },
67
- refreshToken: response.refresh_token
68
- ? {
69
- type: response.token_type || "bearer",
70
- value: response.refresh_token,
71
- }
72
- : undefined,
73
- idToken: response.id_token
74
- ? {
75
- type: response.token_type || "bearer",
76
- value: response.id_token,
77
- }
78
- : undefined,
79
- };
78
+ const credentials = tokenSetFromTokenResponse(response);
80
79
  return credentials;
81
80
  }
82
81
  catch (e) {
@@ -120,14 +119,13 @@ export class CIBAAuthorizerBase {
120
119
  return credentials;
121
120
  }
122
121
  deleteAuthRequest() {
122
+ var _a;
123
123
  const store = asyncLocalStorage.getStore();
124
124
  if (!store) {
125
125
  throw new Error("This method should be called from within a tool.");
126
126
  }
127
- if (!this.params.onAuthorizationRequest ||
128
- this.params.onAuthorizationRequest === "interrupt") {
129
- return this.params.storeAuthorizationResponse(undefined, ...store.args);
130
- }
127
+ const { authResponseNS } = store;
128
+ return (_a = this.authResponseStore) === null || _a === void 0 ? void 0 : _a.delete(authResponseNS, "authResponse");
131
129
  }
132
130
  /**
133
131
  *
@@ -139,31 +137,57 @@ export class CIBAAuthorizerBase {
139
137
  */
140
138
  protect(getContext, execute) {
141
139
  return async (...args) => {
142
- let authRequest;
140
+ let authResponse;
143
141
  if (asyncLocalStorage.getStore()) {
144
142
  throw new Error("Cannot nest tool calls that require CIBA authorization.");
145
143
  }
144
+ const context = getContext(...args);
145
+ const authorizeParams = await this.getAuthorizeParams(args);
146
+ const instanceID = this.getInstanceID(authorizeParams);
147
+ const authResponseNS = [
148
+ instanceID,
149
+ "AuthResponses",
150
+ ...nsFromContext("tool-call", context),
151
+ ];
152
+ const credentialsNS = [
153
+ instanceID,
154
+ "Credentials",
155
+ ...nsFromContext(this.params.credentialsContext, context),
156
+ ];
146
157
  const storeValue = {
147
158
  args,
148
- context: getContext(...args),
159
+ context,
160
+ authResponseNS,
149
161
  };
150
162
  return asyncLocalStorage.run(storeValue, async () => {
163
+ var _a, _b, _c, _d;
151
164
  let credentials;
152
165
  const interruptMode = typeof this.params.onAuthorizationRequest === "undefined" ||
153
166
  this.params.onAuthorizationRequest === "interrupt";
154
167
  try {
155
- if (interruptMode) {
156
- authRequest = await resolveParameter(this.params.getAuthorizationResponse, args);
157
- if (!authRequest) {
158
- //Initial request
159
- authRequest = await this.start(args);
160
- await this.params.storeAuthorizationResponse(authRequest, ...args);
168
+ credentials = await ((_a = this.credentialsStore) === null || _a === void 0 ? void 0 : _a.get(credentialsNS, "credential"));
169
+ if (!credentials) {
170
+ if (interruptMode) {
171
+ authResponse = await ((_b = this.authResponseStore) === null || _b === void 0 ? void 0 : _b.get(authResponseNS, "authResponse"));
172
+ if (!authResponse) {
173
+ //Initial request
174
+ authResponse = await this.start(authorizeParams);
175
+ await ((_c = this.authResponseStore) === null || _c === void 0 ? void 0 : _c.put(authResponseNS, "authResponse", authResponse));
176
+ }
177
+ credentials = await this.getCredentials(authResponse);
178
+ }
179
+ else {
180
+ authResponse = await this.start(authorizeParams);
181
+ const credentialsPromise = this.getCredentialsPolling(authResponse);
182
+ if (typeof this.params.onAuthorizationRequest === "function") {
183
+ await this.params.onAuthorizationRequest(authResponse, credentialsPromise);
184
+ }
185
+ credentials = await credentialsPromise;
186
+ }
187
+ await this.deleteAuthRequest();
188
+ if (typeof credentials !== "undefined") {
189
+ (_d = this.credentialsStore) === null || _d === void 0 ? void 0 : _d.put(credentialsNS, "credential", credentials);
161
190
  }
162
- credentials = await this.getCredentials(authRequest);
163
- }
164
- else {
165
- authRequest = await this.start(args);
166
- credentials = await this.getCredentialsPolling(authRequest);
167
191
  }
168
192
  }
169
193
  catch (err) {
@@ -182,7 +206,6 @@ export class CIBAAuthorizerBase {
182
206
  }
183
207
  }
184
208
  }
185
- await this.deleteAuthRequest();
186
209
  storeValue.credentials = credentials;
187
210
  return execute(...args);
188
211
  });
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerBase.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerBase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAI7C,OAAO,EACL,qBAAqB,EACrB,6BAA6B,EAC7B,6BAA6B,EAC7B,oCAAoC,EACpC,qBAAqB,EACrB,yCAAyC,GAC1C,MAAM,kBAAkB,CAAC;AAC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I,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;oBACvD,CAAC;yBAAM,CAAC;wBACN,WAAW,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;wBACrC,WAAW,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;oBAC9D,CAAC;gBACH,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,eAAe,GACnB,GAAG,YAAY,6BAA6B;wBAC5C,GAAG,YAAY,6BAA6B,CAAC;oBAC/C,IAAI,eAAe,EAAE,CAAC;wBACpB,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;wBAC/B,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,KAAK,UAAU,EAAE,CAAC;4BACrD,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,GAAY,EAAE,GAAG,IAAI,CAAC,CAAC;wBAC3D,CAAC;6BAAM,CAAC;4BACN,OAAO,GAAG,CAAC;wBACb,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAC/B,UAAU,CAAC,WAAW,GAAG,WAAW,CAAC;gBACrC,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;IAES,6BAA6B,CACrC,GAAkE;QAElE,MAAM,GAAG,CAAC;IACZ,CAAC;CACF","sourcesContent":["import { AuthenticationClient } from \"auth0\";\n\nimport { AuthorizerParams } from \"../\";\nimport { Credentials } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\nimport { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nfunction ensureOpenIdScope(scopes: string[]): string[] {\n return scopes.includes(\"openid\") ? scopes : [\"openid\", ...scopes];\n}\n/**\n * Requests authorization by prompting the user via an out-of-band channel from\n * the backend.\n */\nexport class CIBAAuthorizerBase<ToolExecuteArgs extends any[]> {\n auth0: AuthenticationClient;\n\n constructor(\n auth0: AuthorizerParams,\n private readonly params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient({\n domain: auth0?.domain || process.env.AUTH0_DOMAIN!,\n clientId: auth0?.clientId || process.env.AUTH0_CLIENT_ID!,\n clientSecret: auth0?.clientSecret || process.env.AUTH0_CLIENT_SECRET,\n clientAssertionSigningAlg: auth0?.clientAssertionSigningAlg,\n clientAssertionSigningKey: auth0?.clientAssertionSigningKey,\n idTokenSigningAlg: auth0?.idTokenSigningAlg,\n clockTolerance: auth0?.clockTolerance,\n useMTLS: auth0?.useMTLS,\n });\n }\n\n private async start(\n toolContext: ToolExecuteArgs\n ): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n const authorizeParams = {\n scope: ensureOpenIdScope(this.params.scopes).join(\" \"),\n audience: this.params.audience || \"\",\n request_expiry: (this.params.requestExpiry ?? 300).toString(),\n binding_message:\n (await resolveParameter(this.params.bindingMessage, toolContext)) ?? \"\",\n userId: (await resolveParameter(this.params.userID, toolContext)) ?? \"\",\n };\n\n try {\n const response = await this.auth0.backchannel.authorize(authorizeParams);\n\n return {\n id: response.auth_req_id,\n requestedAt: requestedAt,\n expiresIn: response.expires_in,\n interval: response.interval,\n };\n } catch (err: any) {\n if (err.error == \"invalid_request\") {\n throw new UserDoesNotHavePushNotificationsInterrupt(\n err.error_description\n );\n }\n throw err;\n }\n }\n\n private async getCredentialsInternal(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | undefined> {\n try {\n const elapsedSeconds = Date.now() / 1000 - authRequest.requestedAt;\n\n if (elapsedSeconds >= authRequest.expiresIn) {\n throw new AuthorizationRequestExpiredInterrupt(\n \"The authorization request has expired.\",\n authRequest\n );\n }\n\n const response = await this.auth0.backchannel.backchannelGrant({\n auth_req_id: authRequest.id,\n });\n\n const credentials = {\n accessToken: {\n type: response.token_type || \"bearer\",\n value: response.access_token,\n },\n refreshToken: response.refresh_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.refresh_token,\n }\n : undefined,\n idToken: response.id_token\n ? {\n type: response.token_type || \"bearer\",\n value: response.id_token,\n }\n : undefined,\n };\n\n return credentials;\n } catch (e: any) {\n if (e.error === \"authorization_pending\") {\n throw new AuthorizationPendingInterrupt(\n e.error_description,\n authRequest\n );\n }\n\n if (e.error === \"slow_down\") {\n throw new AuthorizationPollingInterrupt(\n e.error_description,\n authRequest\n );\n }\n\n if (e.error == \"invalid_grant\") {\n throw new InvalidGrantInterrupt(e.error_description, authRequest);\n }\n\n if (e.error == \"invalid_request\") {\n throw new UserDoesNotHavePushNotificationsInterrupt(\n e.error_description\n );\n }\n\n if (e.error == \"access_denied\") {\n throw new AccessDeniedInterrupt(e.error_description, authRequest);\n }\n\n throw e;\n }\n }\n\n protected async getCredentials(authRequest: CIBAAuthorizationRequest) {\n return this.getCredentialsInternal(authRequest);\n }\n\n protected async getCredentialsPolling(\n authRequest: CIBAAuthorizationRequest\n ): Promise<Credentials | undefined> {\n let credentials: Credentials | undefined = undefined;\n\n do {\n try {\n credentials = await this.getCredentialsInternal(authRequest);\n } catch (err) {\n if (\n err instanceof AuthorizationPendingInterrupt ||\n err instanceof AuthorizationPollingInterrupt\n ) {\n await sleep(err.request.interval * 1000);\n } else {\n throw err;\n }\n }\n } while (!credentials);\n\n return credentials;\n }\n\n protected deleteAuthRequest() {\n const store = asyncLocalStorage.getStore();\n if (!store) {\n throw new Error(\"This method should be called from within a tool.\");\n }\n if (\n !this.params.onAuthorizationRequest ||\n this.params.onAuthorizationRequest === \"interrupt\"\n ) {\n return this.params.storeAuthorizationResponse(\n undefined,\n ...(store.args as ToolExecuteArgs)\n );\n }\n }\n\n /**\n *\n * Wraps the execute method of a AI tool to handle CIBA authorization.\n *\n * @param getContext - A function that returns the context of the tool execution.\n * @param execute - The tool execute method.\n * @returns The wrapped execute method.\n */\n protect(\n getContext: (...args: ToolExecuteArgs) => any,\n execute: (...args: ToolExecuteArgs) => any\n ): (...args: ToolExecuteArgs) => any {\n return async (...args: ToolExecuteArgs) => {\n let authRequest: CIBAAuthorizationRequest | undefined;\n if (asyncLocalStorage.getStore()) {\n throw new Error(\n \"Cannot nest tool calls that require CIBA authorization.\"\n );\n }\n\n const storeValue: AsyncStorageValue<any> = {\n args,\n context: getContext(...args),\n };\n\n return asyncLocalStorage.run(storeValue, async () => {\n let credentials: Credentials | undefined;\n\n const interruptMode =\n typeof this.params.onAuthorizationRequest === \"undefined\" ||\n this.params.onAuthorizationRequest === \"interrupt\";\n\n try {\n if (interruptMode) {\n authRequest = await resolveParameter(\n this.params.getAuthorizationResponse,\n args\n );\n if (!authRequest) {\n //Initial request\n authRequest = await this.start(args);\n await this.params.storeAuthorizationResponse(\n authRequest,\n ...args\n );\n }\n credentials = await this.getCredentials(authRequest);\n } else {\n authRequest = await this.start(args);\n credentials = await this.getCredentialsPolling(authRequest);\n }\n } catch (err) {\n const shouldInterrupt =\n err instanceof AuthorizationPendingInterrupt ||\n err instanceof AuthorizationPollingInterrupt;\n if (shouldInterrupt) {\n return this.handleAuthorizationInterrupts(err);\n } else {\n await this.deleteAuthRequest();\n if (typeof this.params.onUnauthorized === \"function\") {\n return this.params.onUnauthorized(err as Error, ...args);\n } else {\n return err;\n }\n }\n }\n await this.deleteAuthRequest();\n storeValue.credentials = credentials;\n return execute(...args);\n });\n };\n }\n\n protected handleAuthorizationInterrupts(\n err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt\n ) {\n throw err;\n }\n}\n"]}
1
+ {"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,CAAC,MAAgB;IACzC,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,CAAC;AACpE,CAAC;AACD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAU7B,YACE,KAAiC,EACjC,MAA6C;QAE7C,IAAI,CAAC,KAAK,GAAG,IAAI,oBAAoB,CAAC,iB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,MAAM,CAAC,sBAAsB,KAAK,UAAU,EAAE,CAAC;gCAC7D,MAAM,IAAI,CAAC,MAAM,CAAC,sBAAsB,CACtC,YAAY,EACZ,kBAAkB,CACnB,CAAC;4BACJ,CAAC;4BACD,WAAW,GAAG,MAAM,kBAAkB,CAAC;wBACzC,CAAC;wBACD,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;wBAC/B,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;4BACvC,MAAA,IAAI,CAAC,gBAAgB,0CAAE,GAAG,CACxB,aAAa,EACb,YAAY,EACZ,WAAW,CACZ,CAAC;wBACJ,CAAC;oBACH,CAAC;gBACH,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,eAAe,GACnB,GAAG,YAAY,6BAA6B;wBAC5C,GAAG,YAAY,6BAA6B,CAAC;oBAC/C,IAAI,eAAe,EAAE,CAAC;wBACpB,OAAO,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjD,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;wBAC/B,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,KAAK,UAAU,EAAE,CAAC;4BACrD,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,GAAY,EAAE,GAAG,IAAI,CAAC,CAAC;wBAC3D,CAAC;6BAAM,CAAC;4BACN,OAAO,GAAG,CAAC;wBACb,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,UAAU,CAAC,WAAW,GAAG,WAAW,CAAC;gBACrC,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;IACJ,CAAC;IAES,6BAA6B,CACrC,GAAkE;QAElE,MAAM,GAAG,CAAC;IACZ,CAAC;CACF","sourcesContent":["import { AuthenticationClient } from \"auth0\";\nimport crypto from \"crypto\";\nimport stableHash from \"stable-hash\";\n\nimport { TokenSet, tokenSetFromTokenResponse } from \"../../credentials\";\nimport {\n AccessDeniedInterrupt,\n AuthorizationPendingInterrupt,\n AuthorizationPollingInterrupt,\n AuthorizationRequestExpiredInterrupt,\n InvalidGrantInterrupt,\n UserDoesNotHavePushNotificationsInterrupt,\n} from \"../../interrupts\";\nimport { resolveParameter } from \"../../parameters\";\nimport { SubStore } from \"../../stores\";\nimport { RequireFields } from \"../../util\";\nimport { ContextGetter, nsFromContext } from \"../context\";\nimport { Auth0ClientParams, Auth0ClientSchema } from \"../types\";\nimport { asyncLocalStorage, AsyncStorageValue } from \"./asyncLocalStorage\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\nimport { CIBAAuthorizerParams } from \"./CIBAAuthorizerParams\";\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nfunction ensureOpenIdScope(scopes: string[]): string[] {\n return scopes.includes(\"openid\") ? scopes : [\"openid\", ...scopes];\n}\n/**\n * Requests authorization by prompting the user via an out-of-band channel from\n * the backend.\n */\nexport class CIBAAuthorizerBase<ToolExecuteArgs extends any[]> {\n private readonly auth0: AuthenticationClient;\n private readonly authResponseStore: SubStore | undefined;\n private readonly credentialsStore: SubStore<TokenSet> | undefined;\n\n private readonly params: RequireFields<\n CIBAAuthorizerParams<ToolExecuteArgs>,\n \"credentialsContext\"\n >;\n\n constructor(\n auth0: Partial<Auth0ClientParams>,\n params: CIBAAuthorizerParams<ToolExecuteArgs>\n ) {\n this.auth0 = new AuthenticationClient(Auth0ClientSchema.parse(auth0));\n this.params = {\n credentialsContext: \"tool-call\",\n ...params,\n };\n\n this.authResponseStore = new SubStore<CIBAAuthorizationRequest>(\n params.store,\n {\n getTTL: (authResponse) =>\n authResponse.expiresIn ? authResponse.expiresIn * 1000 : undefined,\n }\n );\n\n this.credentialsStore = new SubStore<TokenSet>(params.store, {\n getTTL: (credentials) =>\n credentials.expiresIn ? credentials.expiresIn * 1000 : undefined,\n });\n }\n\n private getInstanceID(authorizeParams: any): string {\n const props = {\n auth0: this.auth0,\n params: authorizeParams,\n };\n const sh = stableHash(props);\n return crypto.createHash(\"MD5\").update(sh).digest(\"hex\");\n }\n\n private async start(authorizeParams: any): Promise<CIBAAuthorizationRequest> {\n const requestedAt = Date.now() / 1000;\n\n try {\n const response = await this.auth0.backchannel.authorize(authorizeParams);\n\n return {\n id: response.auth_req_id,\n requestedAt: requestedAt,\n expiresIn: response.expires_in,\n interval: response.interval,\n };\n } catch (err: any) {\n if (err.error == \"invalid_request\") {\n throw new UserDoesNotHavePushNotificationsInterrupt(\n err.error_description\n );\n }\n throw err;\n }\n }\n\n private async getAuthorizeParams(toolContext: ToolExecuteArgs) {\n 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,7 +1,10 @@
1
+ import { TokenSet } from "../../credentials";
1
2
  import { CIBAInterrupt } from "../../interrupts";
2
3
  import { AuthorizerToolParameter } from "../../parameters";
4
+ import { Store } from "../../stores";
5
+ import { AuthContext } from "../context";
6
+ import { OnAuthorizationRequest } from "../types";
3
7
  import { CIBAAuthorizationRequest } from "./CIBAAuthorizationRequest";
4
- export type OnAuthorizationRequest = "block" | "interrupt";
5
8
  export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
6
9
  /**
7
10
  * The user ID to request authorization for.
@@ -30,11 +33,22 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
30
33
  *
31
34
  * - `block`: The tool execution is blocked until the user completes the authorization.
32
35
  * - `interrupt`: The tool execution is interrupted until the user completes the authorization.
36
+ * - a callback: Same as "block" but give access to the auth request and executing logic.
33
37
  *
34
38
  * Defaults to `interrupt`.
35
39
  * Note: The block mode is only useful for development purposes and should not be used in production.
36
40
  */
37
- onAuthorizationRequest?: OnAuthorizationRequest;
41
+ onAuthorizationRequest?: OnAuthorizationRequest | ((authReq: CIBAAuthorizationRequest, poll: Promise<TokenSet | undefined>) => Promise<void>);
42
+ /**
43
+ * AuthContext defines the scope of credential sharing:
44
+ * - "tool-call": Credentials are valid only for a single invocation of the tool.
45
+ * - "tool": Credentials are shared across multiple calls to the same tool within the same thread.
46
+ * - "thread": Credentials are shared across all tools using the same authorizer within the current thread.
47
+ * - "agent": Credentials are shared globally across all threads and tools in the agent.
48
+ *
49
+ * @default "tool-call"
50
+ */
51
+ credentialsContext?: AuthContext;
38
52
  /**
39
53
  *
40
54
  * Optional callback to generate a tool result when the invocation is not authorized.
@@ -45,24 +59,10 @@ export type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {
45
59
  * @returns The response to return when the invocation is not authorized.
46
60
  */
47
61
  onUnauthorized?: (err: Error | CIBAInterrupt, ...args: ToolExecuteArgs) => any;
48
- } & ({
49
- onAuthorizationRequest: "block";
50
- } | {
51
- onAuthorizationRequest?: "interrupt";
52
62
  /**
53
- * Retrieves the authorization response data.
54
- * @param args - The tool execution arguments.
55
- * @returns The authorization response data.
56
- * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.
63
+ * An store used to temporarly store the authorization response data
64
+ * while the user is completing the authorization in another device.
57
65
  */
58
- getAuthorizationResponse: AuthorizerToolParameter<ToolExecuteArgs, CIBAAuthorizationRequest | undefined>;
59
- /**
60
- * Stores the authorization response data.
61
- * @param request - The authorization response data.
62
- * @param args - The tool execution arguments.
63
- * @returns A promise that resolves when the data is stored.
64
- * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.
65
- **/
66
- storeAuthorizationResponse: (request: CIBAAuthorizationRequest | undefined, ...args: ToolExecuteArgs) => Promise<void>;
67
- });
66
+ store: Store;
67
+ };
68
68
  //# sourceMappingURL=CIBAAuthorizerParams.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type OnAuthorizationRequest = \"block\" | \"interrupt\";\n\nexport type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {\n /**\n * The user ID to request authorization for.\n */\n userID: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The binding message to send to the user.\n */\n bindingMessage: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The scope to request authorization for.\n */\n scopes: string[];\n\n /**\n * The audience to request authorization for.\n */\n audience?: string;\n\n /**\n * The time in seconds for the authorization request to expire.\n *\n * Defaults to 5m.\n */\n requestExpiry?: number;\n\n /**\n * The behavior when the authorization request is made.\n *\n * - `block`: The tool execution is blocked until the user completes the authorization.\n * - `interrupt`: The tool execution is interrupted until the user completes the authorization.\n *\n * Defaults to `interrupt`.\n * Note: The block mode is only useful for development purposes and should not be used in production.\n */\n onAuthorizationRequest?: OnAuthorizationRequest;\n\n /**\n *\n * Optional callback to generate a tool result when the invocation is not authorized.\n *\n * By default it will return the instance of the Error.\n *\n * @param args - The tool execution arguments.\n * @returns The response to return when the invocation is not authorized.\n */\n onUnauthorized?: (\n err: Error | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\n} & (\n | {\n onAuthorizationRequest: \"block\";\n }\n | {\n onAuthorizationRequest?: \"interrupt\";\n\n /**\n * Retrieves the authorization response data.\n * @param args - The tool execution arguments.\n * @returns The authorization response data.\n * @remarks The data should be stored in a way that it can be retrieved later by the `storeAuthorizationResponse` parameter.\n */\n getAuthorizationResponse: AuthorizerToolParameter<\n ToolExecuteArgs,\n CIBAAuthorizationRequest | undefined\n >;\n\n /**\n * Stores the authorization response data.\n * @param request - The authorization response data.\n * @param args - The tool execution arguments.\n * @returns A promise that resolves when the data is stored.\n * @remarks The data should be stored in a way that it can be retrieved later by the `getAuthorizationResponse` parameter.\n **/\n storeAuthorizationResponse: (\n request: CIBAAuthorizationRequest | undefined,\n ...args: ToolExecuteArgs\n ) => Promise<void>;\n }\n);\n"]}
1
+ {"version":3,"file":"CIBAAuthorizerParams.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/CIBAAuthorizerParams.ts"],"names":[],"mappings":"","sourcesContent":["import { TokenSet } from \"../../credentials\";\nimport { CIBAInterrupt } from \"../../interrupts\";\nimport { AuthorizerToolParameter } from \"../../parameters\";\nimport { Store } from \"../../stores\";\nimport { AuthContext } from \"../context\";\nimport { OnAuthorizationRequest } from \"../types\";\nimport { CIBAAuthorizationRequest } from \"./CIBAAuthorizationRequest\";\n\nexport type CIBAAuthorizerParams<ToolExecuteArgs extends any[]> = {\n /**\n * The user ID to request authorization for.\n */\n userID: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The binding message to send to the user.\n */\n bindingMessage: AuthorizerToolParameter<ToolExecuteArgs>;\n\n /**\n * The scope to request authorization for.\n */\n scopes: string[];\n\n /**\n * The audience to request authorization for.\n */\n audience?: string;\n\n /**\n * The time in seconds for the authorization request to expire.\n *\n * Defaults to 5m.\n */\n requestExpiry?: number;\n\n /**\n * The behavior when the authorization request is made.\n *\n * - `block`: The tool execution is blocked until the user completes the authorization.\n * - `interrupt`: The tool execution is interrupted until the user completes the authorization.\n * - a callback: Same as \"block\" but give access to the auth request and executing logic.\n *\n * Defaults to `interrupt`.\n * Note: The block mode is only useful for development purposes and should not be used in production.\n */\n onAuthorizationRequest?:\n | OnAuthorizationRequest\n | ((\n authReq: CIBAAuthorizationRequest,\n poll: Promise<TokenSet | undefined>\n ) => Promise<void>);\n\n /**\n * AuthContext defines the scope of credential sharing:\n * - \"tool-call\": Credentials are valid only for a single invocation of the tool.\n * - \"tool\": Credentials are shared across multiple calls to the same tool within the same thread.\n * - \"thread\": Credentials are shared across all tools using the same authorizer within the current thread.\n * - \"agent\": Credentials are shared globally across all threads and tools in the agent.\n *\n * @default \"tool-call\"\n */\n credentialsContext?: AuthContext;\n\n /**\n *\n * Optional callback to generate a tool result when the invocation is not authorized.\n *\n * By default it will return the instance of the Error.\n *\n * @param args - The tool execution arguments.\n * @returns The response to return when the invocation is not authorized.\n */\n onUnauthorized?: (\n err: Error | CIBAInterrupt,\n ...args: ToolExecuteArgs\n ) => any;\n\n /**\n * An store used to temporarly store the authorization response data\n * while the user is completing the authorization in another device.\n */\n store: Store;\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  import { AsyncLocalStorage } from "async_hooks";
2
- import { Credentials } from "../../credentials";
2
+ import { TokenSet } from "../../credentials";
3
3
  export type AsyncStorageValue<TContext> = {
4
- credentials?: Credentials;
4
+ credentials?: TokenSet;
5
5
  /**
6
6
  * The tool execution context.
7
7
  */
@@ -10,7 +10,11 @@ export type AsyncStorageValue<TContext> = {
10
10
  * The tool execution arguments.
11
11
  */
12
12
  args: any[];
13
+ /**
14
+ * The namespace in the Store for the CIBA authorization response.
15
+ */
16
+ authResponseNS: string[];
13
17
  };
14
18
  export declare const asyncLocalStorage: AsyncLocalStorage<AsyncStorageValue<any>>;
15
- export declare const getCIBACredentials: () => Credentials | undefined;
19
+ export declare const getCIBACredentials: () => TokenSet | undefined;
16
20
  //# sourceMappingURL=asyncLocalStorage.d.ts.map
@@ -3,7 +3,7 @@ export const asyncLocalStorage = new AsyncLocalStorage();
3
3
  export const getCIBACredentials = () => {
4
4
  const t = asyncLocalStorage.getStore();
5
5
  if (typeof t === "undefined") {
6
- throw new Error("The tool must be wrapped with the withCIBA function.");
6
+ throw new Error("The tool must be wrapped with the withAsyncUserConfirmation function.");
7
7
  }
8
8
  return t.credentials;
9
9
  };
@@ -1 +1 @@
1
- {"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAkBhD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAEnD,CAAC;AAEJ,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,EAAE;IACrC,MAAM,CAAC,GAAG,iBAAiB,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","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"]}
1
+ {"version":3,"file":"asyncLocalStorage.js","sourceRoot":"","sources":["../../../../src/authorizers/ciba/asyncLocalStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAuBhD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAEnD,CAAC;AAEJ,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,EAAE;IACrC,MAAM,CAAC,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IACvC,IAAI,OAAO,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC,WAAW,CAAC;AACvB,CAAC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\nimport { TokenSet } from \"../../credentials\";\n\nexport type AsyncStorageValue<TContext> = {\n credentials?: TokenSet;\n\n /**\n * The tool execution context.\n */\n context: TContext;\n\n /**\n * The tool execution arguments.\n */\n args: any[];\n\n /**\n * The namespace in the Store for the CIBA authorization response.\n */\n authResponseNS: string[];\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(\n \"The tool must be wrapped with the withAsyncUserConfirmation function.\"\n );\n }\n return t.credentials;\n};\n"]}
@@ -0,0 +1,16 @@
1
+ export type ToolCallContext = {
2
+ threadID: string;
3
+ toolCallID: string;
4
+ toolName: string;
5
+ };
6
+ export type ContextGetter<ToolExecuteArgs extends any[]> = (...args: ToolExecuteArgs) => ToolCallContext;
7
+ /**
8
+ * AuthContext defines the scope of credential sharing:
9
+ * - "tool-call": Credentials are valid only for a single invocation of the tool.
10
+ * - "tool": Credentials are shared across multiple calls to the same tool within the same thread.
11
+ * - "thread": Credentials are shared across all tools using the same authorizer within the current thread.
12
+ * - "agent": Credentials are shared globally across all threads and tools in the agent.
13
+ */
14
+ export type AuthContext = "tool-call" | "tool" | "thread" | "agent";
15
+ export declare const nsFromContext: (authContext: AuthContext, callContext: ToolCallContext) => string[];
16
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1,16 @@
1
+ export const nsFromContext = (authContext, callContext) => {
2
+ const threadNS = ["Threads", callContext.threadID];
3
+ const toolNS = ["Tools", callContext.toolName];
4
+ const toolCallNS = ["ToolCalls", callContext.toolCallID];
5
+ switch (authContext) {
6
+ case "tool-call":
7
+ return [...threadNS, ...toolNS, ...toolCallNS];
8
+ case "tool":
9
+ return [...threadNS, ...toolNS];
10
+ case "thread":
11
+ return threadNS;
12
+ case "agent":
13
+ return [];
14
+ }
15
+ };
16
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/authorizers/context.ts"],"names":[],"mappings":"AAmBA,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,WAAwB,EACxB,WAA4B,EAC5B,EAAE;IACF,MAAM,QAAQ,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IACnD,MAAM,MAAM,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;IAEzD,QAAQ,WAAW,EAAE,CAAC;QACpB,KAAK,WAAW;YACd,OAAO,CAAC,GAAG,QAAQ,EAAE,GAAG,MAAM,EAAE,GAAG,UAAU,CAAC,CAAC;QACjD,KAAK,MAAM;YACT,OAAO,CAAC,GAAG,QAAQ,EAAE,GAAG,MAAM,CAAC,CAAC;QAClC,KAAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB,KAAK,OAAO;YACV,OAAO,EAAE,CAAC;IACd,CAAC;AACH,CAAC,CAAC","sourcesContent":["export type ToolCallContext = {\n threadID: string;\n toolCallID: string;\n toolName: string;\n};\n\nexport type ContextGetter<ToolExecuteArgs extends any[]> = (\n ...args: ToolExecuteArgs\n) => ToolCallContext;\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 */\nexport type AuthContext = \"tool-call\" | \"tool\" | \"thread\" | \"agent\";\n\nexport const nsFromContext = (\n authContext: AuthContext,\n callContext: ToolCallContext\n) => {\n const threadNS = [\"Threads\", callContext.threadID];\n const toolNS = [\"Tools\", callContext.toolName];\n const toolCallNS = [\"ToolCalls\", callContext.toolCallID];\n\n switch (authContext) {\n case \"tool-call\":\n return [...threadNS, ...toolNS, ...toolCallNS];\n case \"tool\":\n return [...threadNS, ...toolNS];\n case \"thread\":\n return threadNS;\n case \"agent\":\n return [];\n }\n};\n"]}
@@ -0,0 +1,38 @@
1
+ import { DeviceAuthorizationResponse as DeviceAuthorizationResponseOIDC } from "openid-client";
2
+ export interface DeviceAuthorizationResponse {
3
+ /**
4
+ * The device verification code
5
+ */
6
+ readonly deviceCode: string;
7
+ /**
8
+ * The end-user verification code
9
+ */
10
+ readonly userCode: string;
11
+ /**
12
+ * The end-user verification URI on the authorization server. The URI should be short and easy to
13
+ * remember as end users will be asked to manually type it into their user agent.
14
+ */
15
+ readonly verificationUri: string;
16
+ /**
17
+ * The lifetime in seconds of the "device_code" and "user_code".
18
+ */
19
+ readonly expiresIn: number;
20
+ /**
21
+ * A verification URI that includes the "user_code" (or other information with the same function
22
+ * as the "user_code"), which is designed for non-textual transmission
23
+ */
24
+ readonly verificationUriComplete?: string;
25
+ /**
26
+ * The minimum amount of time in seconds that the client
27
+ * should wait between polling requests to the token endpoint.
28
+ */
29
+ readonly interval?: number;
30
+ /**
31
+ * The time at which the request was made
32
+ * (in secs since the Unix epoch)
33
+ */
34
+ readonly requestedAt: number;
35
+ readonly [parameter: string]: any | undefined;
36
+ }
37
+ export declare function parseDeviceAuthResponse(oidcResponse: DeviceAuthorizationResponseOIDC, requestedAt: number): DeviceAuthorizationResponse;
38
+ //# sourceMappingURL=DeviceAuthResponse.d.ts.map
@@ -0,0 +1,15 @@
1
+ // Function to map from DeviceAuthorizationResponseOIDC to DeviceAuthorizationResponse
2
+ export function parseDeviceAuthResponse(oidcResponse, requestedAt) {
3
+ const { device_code, user_code, verification_uri, expires_in, verification_uri_complete, interval, ...rest } = oidcResponse;
4
+ return {
5
+ deviceCode: device_code,
6
+ userCode: user_code,
7
+ verificationUri: verification_uri,
8
+ expiresIn: expires_in,
9
+ verificationUriComplete: verification_uri_complete,
10
+ interval: interval,
11
+ requestedAt,
12
+ ...rest,
13
+ };
14
+ }
15
+ //# sourceMappingURL=DeviceAuthResponse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeviceAuthResponse.js","sourceRoot":"","sources":["../../../../src/authorizers/device-authorizer/DeviceAuthResponse.ts"],"names":[],"mappings":"AA0CA,sFAAsF;AACtF,MAAM,UAAU,uBAAuB,CACrC,YAA6C,EAC7C,WAAmB;IAEnB,MAAM,EACJ,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,UAAU,EACV,yBAAyB,EACzB,QAAQ,EACR,GAAG,IAAI,EACR,GAAG,YAAY,CAAC;IACjB,OAAO;QACL,UAAU,EAAE,WAAW;QACvB,QAAQ,EAAE,SAAS;QACnB,eAAe,EAAE,gBAAgB;QACjC,SAAS,EAAE,UAAU;QACrB,uBAAuB,EAAE,yBAAyB;QAClD,QAAQ,EAAE,QAAQ;QAClB,WAAW;QACX,GAAG,IAAI;KACR,CAAC;AACJ,CAAC","sourcesContent":["import { DeviceAuthorizationResponse as DeviceAuthorizationResponseOIDC } from \"openid-client\";\n\nexport interface DeviceAuthorizationResponse {\n /**\n * The device verification code\n */\n readonly deviceCode: string;\n /**\n * The end-user verification code\n */\n readonly userCode: string;\n /**\n * The end-user verification URI on the authorization server. The URI should be short and easy to\n * remember as end users will be asked to manually type it into their user agent.\n */\n readonly verificationUri: string;\n\n /**\n * The lifetime in seconds of the \"device_code\" and \"user_code\".\n */\n readonly expiresIn: number;\n\n /**\n * A verification URI that includes the \"user_code\" (or other information with the same function\n * as the \"user_code\"), which is designed for non-textual transmission\n */\n readonly verificationUriComplete?: string;\n /**\n * The minimum amount of time in seconds that the client\n * should wait between polling requests to the token endpoint.\n */\n readonly interval?: number;\n\n /**\n * The time at which the request was made\n * (in secs since the Unix epoch)\n */\n readonly requestedAt: number;\n\n readonly [parameter: string]: any | undefined;\n}\n\n// Function to map from DeviceAuthorizationResponseOIDC to DeviceAuthorizationResponse\nexport function parseDeviceAuthResponse(\n oidcResponse: DeviceAuthorizationResponseOIDC,\n requestedAt: number\n): DeviceAuthorizationResponse {\n const {\n device_code,\n user_code,\n verification_uri,\n expires_in,\n verification_uri_complete,\n interval,\n ...rest\n } = oidcResponse;\n return {\n deviceCode: device_code,\n userCode: user_code,\n verificationUri: verification_uri,\n expiresIn: expires_in,\n verificationUriComplete: verification_uri_complete,\n interval: interval,\n requestedAt,\n ...rest,\n };\n}\n"]}
@@ -0,0 +1,49 @@
1
+ import { TokenSet } from "../../credentials";
2
+ import { AuthorizationPendingInterrupt, AuthorizationPollingInterrupt } from "../../interrupts/DeviceInterrupts";
3
+ import { ContextGetter } from "../context";
4
+ import { Auth0PublicClientParams } from "../types";
5
+ import { DeviceAuthorizerParams } from "./DeviceAuthorizerParams";
6
+ import { DeviceAuthorizationResponse } from "./DeviceAuthResponse";
7
+ /**
8
+ * The DeviceAuthorizerBase class acts as a guard and wrapper around tools or agent
9
+ * capabilities that require authenticated access. It encapsulates the
10
+ * OpenID Connect Device Authorization Flow, allowing tools to interrupt execution
11
+ * to request user authorization and resume seamlessly once authorization is granted.
12
+ *
13
+ * Enable agentic tools to be wrapped with secure, lazy-triggered device authorization,
14
+ * with a clean interrupt/resume model for user-in-the-loop authentication.
15
+ *
16
+ * Core Concepts
17
+ *
18
+ * - Interrupt-driven flow: If no valid token is present, the tool throws a DeviceAuthInterrupt,
19
+ * which contains the verification_uri, user_code, and other relevant metadata.
20
+ *
21
+ * - Polling/resumption: The Agent client can poll the agent to resume execution.
22
+ *
23
+ * - Token management: Tokens (and refresh tokens, if applicable) are stored and reused
24
+ * transparently.
25
+ *
26
+ */
27
+ export declare class DeviceAuthorizerBase<ToolExecuteArgs extends any[]> {
28
+ private auth0;
29
+ private params;
30
+ private credentialsStore;
31
+ private authResponseStore;
32
+ constructor(auth0: Partial<Auth0PublicClientParams>, params: DeviceAuthorizerParams<ToolExecuteArgs>);
33
+ private start;
34
+ /**
35
+ *
36
+ * Wraps the execute method of a AI tool to handle CIBA authorization.
37
+ *
38
+ * @param getContext - A function that returns the context of the tool execution.
39
+ * @param execute - The tool execute method.
40
+ * @returns The wrapped execute method.
41
+ */
42
+ protect(getContext: ContextGetter<ToolExecuteArgs>, execute: (...args: ToolExecuteArgs) => any): (...args: ToolExecuteArgs) => any;
43
+ private getCredentials;
44
+ protected getCredentialsPolling(authResponse: DeviceAuthorizationResponse): Promise<TokenSet | undefined>;
45
+ private getInstanceID;
46
+ protected deleteAuthRequest(): Promise<void>;
47
+ protected handleAuthorizationInterrupts(err: AuthorizationPendingInterrupt | AuthorizationPollingInterrupt): void;
48
+ }
49
+ //# sourceMappingURL=DeviceAuthorizerBase.d.ts.map