@crewai-ts/core 0.1.12 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +174 -0
  2. package/dist/agent.d.ts +16 -18
  3. package/dist/auth.cjs +598 -0
  4. package/dist/auth.js +40 -0
  5. package/dist/{chunk-3PVW4JKT.js → chunk-C43UEMCX.js} +6712 -7268
  6. package/dist/chunk-CCOE6MLE.js +896 -0
  7. package/dist/chunk-HFQTF332.js +4455 -0
  8. package/dist/{chunk-BE4JYKSG.js → chunk-MM4ROIFG.js} +12 -1490
  9. package/dist/chunk-RH43TNKN.js +238 -0
  10. package/dist/chunk-S477WFUT.js +565 -0
  11. package/dist/chunk-SB7ADUQA.js +110 -0
  12. package/dist/chunk-T32G6KDW.js +40 -0
  13. package/dist/crew.d.ts +24 -26
  14. package/dist/events.cjs +7513 -0
  15. package/dist/events.js +406 -0
  16. package/dist/experimental-conversational.cjs +272 -0
  17. package/dist/experimental-conversational.js +26 -0
  18. package/dist/feature-hooks.cjs +149 -0
  19. package/dist/feature-hooks.d.ts +94 -0
  20. package/dist/feature-hooks.js +36 -0
  21. package/dist/index.cjs +33923 -64381
  22. package/dist/index.d.ts +2 -15
  23. package/dist/index.js +16720 -49562
  24. package/dist/input-provider.d.ts +3 -4
  25. package/dist/lite-agent.d.ts +4 -4
  26. package/dist/llm.cjs +7467 -0
  27. package/dist/llm.d.ts +0 -4
  28. package/dist/llm.js +225 -0
  29. package/dist/optional-yaml.d.ts +8 -0
  30. package/dist/project.d.ts +1 -1
  31. package/dist/schema-utils.cjs +968 -0
  32. package/dist/schema-utils.d.ts +1 -1
  33. package/dist/schema-utils.js +102 -0
  34. package/dist/state-provider-core.js +3 -2
  35. package/dist/task.d.ts +3 -4
  36. package/dist/tools.cjs +6872 -0
  37. package/dist/tools.d.ts +0 -60
  38. package/dist/tools.js +114 -0
  39. package/dist/types.cjs +68 -0
  40. package/dist/types.js +14 -0
  41. package/package.json +52 -111
  42. package/dist/a2a.d.ts +0 -1684
  43. package/dist/a2ui-schemas.d.ts +0 -3312
  44. package/dist/a2ui.d.ts +0 -379
  45. package/dist/flow-conversation.d.ts +0 -90
  46. package/dist/flow-definition.d.ts +0 -195
  47. package/dist/flow-persistence.d.ts +0 -107
  48. package/dist/flow-visualization.d.ts +0 -77
  49. package/dist/flow.d.ts +0 -927
  50. package/dist/knowledge.d.ts +0 -353
  51. package/dist/mcp-DS7UMYAM.js +0 -62
  52. package/dist/mcp.d.ts +0 -315
  53. package/dist/memory.d.ts +0 -915
  54. package/dist/openai-completion.d.ts +0 -327
  55. package/dist/provider-completions.d.ts +0 -596
  56. package/dist/rag.d.ts +0 -1074
package/dist/auth.cjs ADDED
@@ -0,0 +1,598 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/auth.ts
21
+ var auth_exports = {};
22
+ __export(auth_exports, {
23
+ ALGORITHMS: () => ALGORITHMS,
24
+ Auth0Provider: () => Auth0Provider,
25
+ AuthError: () => AuthError,
26
+ AuthenticationCommand: () => AuthenticationCommand,
27
+ BaseProvider: () => BaseProvider,
28
+ EntraIdProvider: () => EntraIdProvider,
29
+ KeycloakProvider: () => KeycloakProvider,
30
+ Oauth2Settings: () => Oauth2Settings,
31
+ OktaProvider: () => OktaProvider,
32
+ ProviderFactory: () => ProviderFactory,
33
+ TokenManager: () => TokenManager,
34
+ WorkosProvider: () => WorkosProvider,
35
+ constantTimeEquals: () => constantTimeEquals,
36
+ createTemporaryTokenStorage: () => createTemporaryTokenStorage,
37
+ getAuthToken: () => getAuthToken,
38
+ get_auth_token: () => get_auth_token,
39
+ validateJwtToken: () => validateJwtToken,
40
+ validate_jwt_token: () => validate_jwt_token
41
+ });
42
+ module.exports = __toCommonJS(auth_exports);
43
+ var import_node_fs = require("fs");
44
+ var import_node_fs2 = require("fs");
45
+ var import_node_os = require("os");
46
+ var import_node_path = require("path");
47
+ var import_node_crypto = require("crypto");
48
+ var ALGORITHMS = ["RS256"];
49
+ var AuthError = class extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = "AuthError";
53
+ }
54
+ };
55
+ var TokenManager = class {
56
+ filePath;
57
+ file_path;
58
+ storageDir;
59
+ storage_dir;
60
+ key;
61
+ constructor(filePathOrOptions = "tokens.enc") {
62
+ const options = typeof filePathOrOptions === "string" ? { filePath: filePathOrOptions } : filePathOrOptions;
63
+ this.filePath = options.filePath ?? options.file_path ?? "tokens.enc";
64
+ this.file_path = this.filePath;
65
+ this.storageDir = options.storageDir ?? options.storage_dir ?? getSecureStoragePath();
66
+ this.storage_dir = this.storageDir;
67
+ (0, import_node_fs.mkdirSync)(this.storageDir, { recursive: true, mode: 448 });
68
+ this.key = this.getOrCreateKey();
69
+ }
70
+ saveTokens(accessToken, expiresAt) {
71
+ const data = {
72
+ access_token: accessToken,
73
+ expiration: new Date(expiresAt * 1e3).toISOString()
74
+ };
75
+ this.atomicWriteSecureFile(this.filePath, encryptJson(data, this.key));
76
+ }
77
+ save_tokens(accessToken, expiresAt) {
78
+ this.saveTokens(accessToken, expiresAt);
79
+ }
80
+ getToken() {
81
+ const encrypted = this.readSecureFile(this.filePath);
82
+ if (!encrypted) {
83
+ return null;
84
+ }
85
+ const data = decryptJson(encrypted, this.key);
86
+ const expiration = Date.parse(data.expiration);
87
+ if (!Number.isFinite(expiration) || expiration <= Date.now()) {
88
+ return null;
89
+ }
90
+ return data.access_token;
91
+ }
92
+ get_token() {
93
+ return this.getToken();
94
+ }
95
+ clearTokens() {
96
+ this.deleteSecureFile(this.filePath);
97
+ }
98
+ clear_tokens() {
99
+ this.clearTokens();
100
+ }
101
+ getOrCreateKey() {
102
+ const key = this.readSecureFile("secret.key");
103
+ if (key && key.length === 32) {
104
+ return key;
105
+ }
106
+ const newKey = (0, import_node_crypto.randomBytes)(32);
107
+ if (this.atomicCreateSecureFile("secret.key", newKey)) {
108
+ return newKey;
109
+ }
110
+ const retryKey = this.readSecureFile("secret.key");
111
+ if (retryKey && retryKey.length === 32) {
112
+ return retryKey;
113
+ }
114
+ throw new Error("Failed to create or read encryption key");
115
+ }
116
+ atomicCreateSecureFile(filename, content) {
117
+ const path = (0, import_node_path.join)(this.storageDir, filename);
118
+ try {
119
+ const fd = (0, import_node_fs.openSync)(path, "wx", 384);
120
+ (0, import_node_fs.writeFileSync)(fd, content);
121
+ return true;
122
+ } catch (error) {
123
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
124
+ return false;
125
+ }
126
+ throw error;
127
+ }
128
+ }
129
+ atomicWriteSecureFile(filename, content) {
130
+ const tempPath = (0, import_node_path.join)(this.storageDir, `.${filename}.${(0, import_node_crypto.randomBytes)(8).toString("hex")}`);
131
+ const finalPath = (0, import_node_path.join)(this.storageDir, filename);
132
+ (0, import_node_fs.writeFileSync)(tempPath, content, { mode: 384 });
133
+ (0, import_node_fs.renameSync)(tempPath, finalPath);
134
+ }
135
+ readSecureFile(filename) {
136
+ const path = (0, import_node_path.join)(this.storageDir, filename);
137
+ return (0, import_node_fs.existsSync)(path) ? (0, import_node_fs.readFileSync)(path) : null;
138
+ }
139
+ deleteSecureFile(filename) {
140
+ (0, import_node_fs.rmSync)((0, import_node_path.join)(this.storageDir, filename), { force: true });
141
+ }
142
+ };
143
+ function getAuthToken(tokenManager = new TokenManager()) {
144
+ const accessToken = tokenManager.getToken();
145
+ if (!accessToken) {
146
+ throw new AuthError("No token found, make sure you are logged in");
147
+ }
148
+ return accessToken;
149
+ }
150
+ var get_auth_token = getAuthToken;
151
+ var Oauth2Settings = class _Oauth2Settings {
152
+ provider;
153
+ clientId;
154
+ client_id;
155
+ domain;
156
+ audience;
157
+ extra;
158
+ constructor(options) {
159
+ const clientId = options.clientId ?? options.client_id;
160
+ if (!clientId) {
161
+ throw new Error("Oauth2Settings requires clientId.");
162
+ }
163
+ this.provider = options.provider;
164
+ this.clientId = clientId;
165
+ this.client_id = clientId;
166
+ this.domain = options.domain;
167
+ this.audience = options.audience ?? null;
168
+ this.extra = { ...options.extra ?? {} };
169
+ }
170
+ static fromSettings(settings) {
171
+ return new _Oauth2Settings(settings);
172
+ }
173
+ static from_settings(settings) {
174
+ return _Oauth2Settings.fromSettings(settings);
175
+ }
176
+ };
177
+ var BaseProvider = class {
178
+ settings;
179
+ constructor(settings) {
180
+ this.settings = settings;
181
+ }
182
+ get_authorize_url() {
183
+ return this.getAuthorizeUrl();
184
+ }
185
+ get_token_url() {
186
+ return this.getTokenUrl();
187
+ }
188
+ get_jwks_url() {
189
+ return this.getJwksUrl();
190
+ }
191
+ get_issuer() {
192
+ return this.getIssuer();
193
+ }
194
+ get_audience() {
195
+ return this.getAudience();
196
+ }
197
+ get_client_id() {
198
+ return this.getClientId();
199
+ }
200
+ getRequiredFields() {
201
+ return [];
202
+ }
203
+ get_required_fields() {
204
+ return this.getRequiredFields();
205
+ }
206
+ getOauthScopes() {
207
+ return ["openid", "profile", "email"];
208
+ }
209
+ get_oauth_scopes() {
210
+ return this.getOauthScopes();
211
+ }
212
+ };
213
+ var Auth0Provider = class extends BaseProvider {
214
+ getAuthorizeUrl() {
215
+ return `https://${this.domain()}/oauth/device/code`;
216
+ }
217
+ getTokenUrl() {
218
+ return `https://${this.domain()}/oauth/token`;
219
+ }
220
+ getJwksUrl() {
221
+ return `https://${this.domain()}/.well-known/jwks.json`;
222
+ }
223
+ getIssuer() {
224
+ return `https://${this.domain()}/`;
225
+ }
226
+ getAudience() {
227
+ return required(this.settings.audience, "Audience");
228
+ }
229
+ getClientId() {
230
+ return this.settings.clientId;
231
+ }
232
+ domain() {
233
+ return required(this.settings.domain, "Domain");
234
+ }
235
+ };
236
+ var WorkosProvider = class extends BaseProvider {
237
+ getAuthorizeUrl() {
238
+ return `https://${this.domain()}/oauth2/device_authorization`;
239
+ }
240
+ getTokenUrl() {
241
+ return `https://${this.domain()}/oauth2/token`;
242
+ }
243
+ getJwksUrl() {
244
+ return `https://${this.domain()}/oauth2/jwks`;
245
+ }
246
+ getIssuer() {
247
+ return `https://${this.domain()}`;
248
+ }
249
+ getAudience() {
250
+ return this.settings.audience ?? "";
251
+ }
252
+ getClientId() {
253
+ return this.settings.clientId;
254
+ }
255
+ domain() {
256
+ return required(this.settings.domain, "Domain");
257
+ }
258
+ };
259
+ var EntraIdProvider = class extends BaseProvider {
260
+ getAuthorizeUrl() {
261
+ return `${this.baseUrl()}/oauth2/v2.0/devicecode`;
262
+ }
263
+ getTokenUrl() {
264
+ return `${this.baseUrl()}/oauth2/v2.0/token`;
265
+ }
266
+ getJwksUrl() {
267
+ return `${this.baseUrl()}/discovery/v2.0/keys`;
268
+ }
269
+ getIssuer() {
270
+ return `${this.baseUrl()}/v2.0`;
271
+ }
272
+ getAudience() {
273
+ return required(this.settings.audience, "Audience");
274
+ }
275
+ getClientId() {
276
+ return this.settings.clientId;
277
+ }
278
+ getOauthScopes() {
279
+ return [...super.getOauthScopes(), ...stringFromUnknown(this.settings.extra.scope).split(/\s+/).filter(Boolean)];
280
+ }
281
+ getRequiredFields() {
282
+ return ["scope"];
283
+ }
284
+ baseUrl() {
285
+ return `https://login.microsoftonline.com/${this.settings.domain}`;
286
+ }
287
+ };
288
+ var KeycloakProvider = class extends BaseProvider {
289
+ getAuthorizeUrl() {
290
+ return `${this.baseUrl()}/realms/${String(this.settings.extra.realm)}/protocol/openid-connect/auth/device`;
291
+ }
292
+ getTokenUrl() {
293
+ return `${this.baseUrl()}/realms/${String(this.settings.extra.realm)}/protocol/openid-connect/token`;
294
+ }
295
+ getJwksUrl() {
296
+ return `${this.baseUrl()}/realms/${String(this.settings.extra.realm)}/protocol/openid-connect/certs`;
297
+ }
298
+ getIssuer() {
299
+ return `${this.baseUrl()}/realms/${String(this.settings.extra.realm)}`;
300
+ }
301
+ getAudience() {
302
+ return this.settings.audience ?? "no-audience-provided";
303
+ }
304
+ getClientId() {
305
+ return this.settings.clientId;
306
+ }
307
+ getRequiredFields() {
308
+ return ["realm"];
309
+ }
310
+ baseUrl() {
311
+ return `https://${this.settings.domain.replace(/^https?:\/\//, "")}`;
312
+ }
313
+ };
314
+ var OktaProvider = class extends BaseProvider {
315
+ getAuthorizeUrl() {
316
+ return `${this.baseUrl()}/v1/device/authorize`;
317
+ }
318
+ getTokenUrl() {
319
+ return `${this.baseUrl()}/v1/token`;
320
+ }
321
+ getJwksUrl() {
322
+ return `${this.baseUrl()}/v1/keys`;
323
+ }
324
+ getIssuer() {
325
+ return this.baseUrl().replace(/\/oauth2$/, "");
326
+ }
327
+ getAudience() {
328
+ return required(this.settings.audience, "Audience");
329
+ }
330
+ getClientId() {
331
+ return this.settings.clientId;
332
+ }
333
+ getRequiredFields() {
334
+ return ["authorization_server_name", "using_org_auth_server"];
335
+ }
336
+ baseUrl() {
337
+ return this.settings.extra.using_org_auth_server ? `https://${this.settings.domain}/oauth2` : `https://${this.settings.domain}/oauth2/${stringFromUnknown(this.settings.extra.authorization_server_name, "default")}`;
338
+ }
339
+ };
340
+ var providerRegistry = /* @__PURE__ */ new Map([
341
+ ["auth0", Auth0Provider],
342
+ ["workos", WorkosProvider],
343
+ ["entra_id", EntraIdProvider],
344
+ ["okta", OktaProvider],
345
+ ["keycloak", KeycloakProvider]
346
+ ]);
347
+ var ProviderFactory = {
348
+ register(provider, providerClass) {
349
+ providerRegistry.set(provider.toLowerCase(), providerClass);
350
+ },
351
+ fromSettings(settings) {
352
+ const providerClass = providerRegistry.get(settings.provider.toLowerCase());
353
+ if (!providerClass) {
354
+ throw new Error(`Unsupported OAuth2 provider: ${settings.provider}`);
355
+ }
356
+ return new providerClass(settings);
357
+ },
358
+ from_settings(settings) {
359
+ return ProviderFactory.fromSettings(settings);
360
+ }
361
+ };
362
+ var AuthenticationCommand = class {
363
+ tokenManager;
364
+ token_manager;
365
+ oauth2Provider;
366
+ oauth2_provider;
367
+ fetchImpl;
368
+ openBrowser;
369
+ maxAttempts;
370
+ constructor(options = {}) {
371
+ this.tokenManager = options.tokenManager ?? options.token_manager ?? new TokenManager();
372
+ this.token_manager = this.tokenManager;
373
+ this.oauth2Provider = options.oauth2Provider ?? options.oauth2_provider ?? ProviderFactory.fromSettings(defaultOauth2Settings());
374
+ this.oauth2_provider = this.oauth2Provider;
375
+ this.fetchImpl = options.fetch ?? fetch;
376
+ this.openBrowser = options.openBrowser ?? options.open_browser ?? (() => void 0);
377
+ this.maxAttempts = options.maxAttempts ?? options.max_attempts ?? 10;
378
+ }
379
+ async login() {
380
+ const deviceCodeData = await this.getDeviceCode();
381
+ this.displayAuthInstructions(deviceCodeData);
382
+ await this.pollForToken(deviceCodeData);
383
+ }
384
+ async getDeviceCode() {
385
+ const response = await this.fetchImpl(this.oauth2Provider.getAuthorizeUrl(), {
386
+ method: "POST",
387
+ body: formBody({
388
+ client_id: this.oauth2Provider.getClientId(),
389
+ scope: this.oauth2Provider.getOauthScopes().join(" "),
390
+ audience: this.oauth2Provider.getAudience()
391
+ })
392
+ });
393
+ if (!response.ok) {
394
+ throw new Error(`Failed to get device code: ${String(response.status)}`);
395
+ }
396
+ return await response.json();
397
+ }
398
+ displayAuthInstructions(deviceCodeData) {
399
+ const verificationUri = deviceCodeData.verification_uri_complete ?? deviceCodeData.verification_uri ?? "";
400
+ if (verificationUri) {
401
+ this.openBrowser(verificationUri);
402
+ }
403
+ }
404
+ async pollForToken(deviceCodeData) {
405
+ const tokenPayload = {
406
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
407
+ device_code: deviceCodeData.device_code,
408
+ client_id: this.oauth2Provider.getClientId()
409
+ };
410
+ for (let attempt = 0; attempt < this.maxAttempts; attempt += 1) {
411
+ const response = await this.fetchImpl(this.oauth2Provider.getTokenUrl(), {
412
+ method: "POST",
413
+ body: formBody(tokenPayload)
414
+ });
415
+ const tokenData = await response.json();
416
+ if (response.ok && tokenData.access_token) {
417
+ await this.validateAndSaveToken(tokenData.access_token);
418
+ return;
419
+ }
420
+ if (tokenData.error !== "authorization_pending" && tokenData.error !== "slow_down") {
421
+ throw new Error(tokenData.error_description ?? tokenData.error ?? "OAuth2 token polling failed");
422
+ }
423
+ await sleep((deviceCodeData.interval ?? 1) * 1e3);
424
+ }
425
+ throw new Error("Timeout: Failed to get the token. Please try again.");
426
+ }
427
+ async validateAndSaveToken(jwtToken) {
428
+ const decoded = await validateJwtToken({
429
+ jwtToken,
430
+ jwksUrl: this.oauth2Provider.getJwksUrl(),
431
+ issuer: this.oauth2Provider.getIssuer(),
432
+ audience: this.oauth2Provider.getAudience(),
433
+ fetch: this.fetchImpl
434
+ });
435
+ const expiresAt = Number(decoded.exp ?? 0);
436
+ this.tokenManager.saveTokens(jwtToken, expiresAt);
437
+ }
438
+ };
439
+ async function validateJwtToken(options) {
440
+ const jwtToken = options.jwtToken ?? options.jwt_token;
441
+ const jwksUrl = options.jwksUrl ?? options.jwks_url;
442
+ if (!jwtToken) {
443
+ throw new Error("jwtToken is required.");
444
+ }
445
+ if (!jwksUrl) {
446
+ throw new Error("jwksUrl is required.");
447
+ }
448
+ const [encodedHeader, encodedPayload, encodedSignature] = jwtToken.split(".");
449
+ if (!encodedHeader || !encodedPayload || !encodedSignature) {
450
+ throw new Error("Invalid token: expected a JWS compact token.");
451
+ }
452
+ const header = parseJwtPart(encodedHeader);
453
+ const payload = parseJwtPart(encodedPayload);
454
+ if (header.alg !== "RS256") {
455
+ throw new Error(`Invalid token algorithm: ${String(header.alg)}`);
456
+ }
457
+ const jwksResponse = await (options.fetch ?? fetch)(jwksUrl);
458
+ if (!jwksResponse.ok) {
459
+ throw new Error(`JWKS or key processing error: ${String(jwksResponse.status)}`);
460
+ }
461
+ const jwks = await jwksResponse.json();
462
+ const key = jwks.keys?.find((candidate) => candidate.kid === header.kid) ?? jwks.keys?.[0];
463
+ if (!key) {
464
+ throw new Error("JWKS or key processing error: no matching key found");
465
+ }
466
+ const publicKey = (0, import_node_crypto.createPublicKey)({ key, format: "jwk" });
467
+ const valid = (0, import_node_crypto.verify)(
468
+ "RSA-SHA256",
469
+ Buffer.from(`${encodedHeader}.${encodedPayload}`),
470
+ publicKey,
471
+ base64urlDecode(encodedSignature)
472
+ );
473
+ if (!valid) {
474
+ throw new Error("Invalid token: signature verification failed");
475
+ }
476
+ validateJwtClaims(payload, options.issuer, options.audience, options.leewaySeconds ?? options.leeway_seconds ?? 10);
477
+ return payload;
478
+ }
479
+ var validate_jwt_token = validateJwtToken;
480
+ function defaultOauth2Settings() {
481
+ return new Oauth2Settings({
482
+ provider: process.env.CREWAI_OAUTH2_PROVIDER ?? "workos",
483
+ clientId: process.env.CREWAI_OAUTH2_CLIENT_ID ?? "crewai-cli",
484
+ domain: process.env.CREWAI_OAUTH2_DOMAIN ?? "login.crewai.com",
485
+ audience: process.env.CREWAI_OAUTH2_AUDIENCE ?? null
486
+ });
487
+ }
488
+ function getSecureStoragePath() {
489
+ if (process.env.CREWAI_TS_CREDENTIALS_DIR) {
490
+ return process.env.CREWAI_TS_CREDENTIALS_DIR;
491
+ }
492
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
493
+ return (0, import_node_path.join)(process.env.LOCALAPPDATA, "crewai", "credentials");
494
+ }
495
+ if (process.platform === "darwin") {
496
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), "Library", "Application Support", "crewai", "credentials");
497
+ }
498
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), ".local", "share", "crewai", "credentials");
499
+ }
500
+ function createTemporaryTokenStorage() {
501
+ return (0, import_node_fs2.mkdtempSync)((0, import_node_path.join)((0, import_node_os.tmpdir)(), "crewai-ts-token-"));
502
+ }
503
+ function encryptJson(value, key) {
504
+ const iv = (0, import_node_crypto.randomBytes)(12);
505
+ const cipher = (0, import_node_crypto.createCipheriv)("aes-256-gcm", key, iv);
506
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
507
+ const tag = cipher.getAuthTag();
508
+ return Buffer.concat([Buffer.from("v1:"), iv, tag, ciphertext]);
509
+ }
510
+ function decryptJson(encrypted, key) {
511
+ const prefix = encrypted.subarray(0, 3).toString();
512
+ if (prefix !== "v1:") {
513
+ throw new Error("Unsupported token file format.");
514
+ }
515
+ const iv = encrypted.subarray(3, 15);
516
+ const tag = encrypted.subarray(15, 31);
517
+ const ciphertext = encrypted.subarray(31);
518
+ const decipher = (0, import_node_crypto.createDecipheriv)("aes-256-gcm", key, iv);
519
+ decipher.setAuthTag(tag);
520
+ return JSON.parse(Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8"));
521
+ }
522
+ function formBody(data) {
523
+ const params = new URLSearchParams();
524
+ for (const [key, value] of Object.entries(data)) {
525
+ params.set(key, value);
526
+ }
527
+ return params;
528
+ }
529
+ function sleep(ms) {
530
+ return new Promise((resolve) => {
531
+ setTimeout(resolve, ms);
532
+ });
533
+ }
534
+ function parseJwtPart(part) {
535
+ return JSON.parse(base64urlDecode(part).toString("utf8"));
536
+ }
537
+ function base64urlDecode(value) {
538
+ return Buffer.from(value.replaceAll("-", "+").replaceAll("_", "/"), "base64");
539
+ }
540
+ function validateJwtClaims(payload, issuer, audience, leewaySeconds) {
541
+ const now = Math.floor(Date.now() / 1e3);
542
+ for (const claim of ["exp", "iat", "iss", "aud", "sub"]) {
543
+ if (!(claim in payload)) {
544
+ throw new Error(`Token is missing required claims: ${claim}`);
545
+ }
546
+ }
547
+ if (Number(payload.exp) + leewaySeconds <= now) {
548
+ throw new Error("Token has expired.");
549
+ }
550
+ if (Number(payload.nbf ?? 0) - leewaySeconds > now) {
551
+ throw new Error("Invalid token: not before claim is in the future");
552
+ }
553
+ if (Number(payload.iat) - leewaySeconds > now) {
554
+ throw new Error("Invalid token: issued at claim is in the future");
555
+ }
556
+ if (payload.iss !== issuer) {
557
+ throw new Error(`Invalid token issuer. Got: '${String(payload.iss)}'. Expected: '${issuer}'`);
558
+ }
559
+ const audiences = Array.isArray(payload.aud) ? payload.aud.map(String) : [String(payload.aud)];
560
+ if (!audiences.includes(audience)) {
561
+ throw new Error(`Invalid token audience. Got: '${audiences.join(",")}'. Expected: '${audience}'`);
562
+ }
563
+ }
564
+ function required(value, name) {
565
+ if (!value) {
566
+ throw new Error(`${name} is required. Please set it in the configuration.`);
567
+ }
568
+ return value;
569
+ }
570
+ function stringFromUnknown(value, fallback = "") {
571
+ return typeof value === "string" ? value : fallback;
572
+ }
573
+ function constantTimeEquals(left, right) {
574
+ const leftHash = (0, import_node_crypto.createHash)("sha256").update(left).digest();
575
+ const rightHash = (0, import_node_crypto.createHash)("sha256").update(right).digest();
576
+ return (0, import_node_crypto.timingSafeEqual)(leftHash, rightHash);
577
+ }
578
+ // Annotate the CommonJS export names for ESM import in node:
579
+ 0 && (module.exports = {
580
+ ALGORITHMS,
581
+ Auth0Provider,
582
+ AuthError,
583
+ AuthenticationCommand,
584
+ BaseProvider,
585
+ EntraIdProvider,
586
+ KeycloakProvider,
587
+ Oauth2Settings,
588
+ OktaProvider,
589
+ ProviderFactory,
590
+ TokenManager,
591
+ WorkosProvider,
592
+ constantTimeEquals,
593
+ createTemporaryTokenStorage,
594
+ getAuthToken,
595
+ get_auth_token,
596
+ validateJwtToken,
597
+ validate_jwt_token
598
+ });
package/dist/auth.js ADDED
@@ -0,0 +1,40 @@
1
+ import {
2
+ ALGORITHMS,
3
+ Auth0Provider,
4
+ AuthError,
5
+ AuthenticationCommand,
6
+ BaseProvider,
7
+ EntraIdProvider,
8
+ KeycloakProvider,
9
+ Oauth2Settings,
10
+ OktaProvider,
11
+ ProviderFactory,
12
+ TokenManager,
13
+ WorkosProvider,
14
+ constantTimeEquals,
15
+ createTemporaryTokenStorage,
16
+ getAuthToken,
17
+ get_auth_token,
18
+ validateJwtToken,
19
+ validate_jwt_token
20
+ } from "./chunk-S477WFUT.js";
21
+ export {
22
+ ALGORITHMS,
23
+ Auth0Provider,
24
+ AuthError,
25
+ AuthenticationCommand,
26
+ BaseProvider,
27
+ EntraIdProvider,
28
+ KeycloakProvider,
29
+ Oauth2Settings,
30
+ OktaProvider,
31
+ ProviderFactory,
32
+ TokenManager,
33
+ WorkosProvider,
34
+ constantTimeEquals,
35
+ createTemporaryTokenStorage,
36
+ getAuthToken,
37
+ get_auth_token,
38
+ validateJwtToken,
39
+ validate_jwt_token
40
+ };