@asgardeo/javascript 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -55,6 +55,8 @@ export { FlowMode } from './models/flow';
55
55
  export { AsgardeoClient } from './models/client';
56
56
  export { BaseConfig, Config, Preferences, ThemePreferences, I18nPreferences, WithPreferences, SignInOptions, SignOutOptions, SignUpOptions, } from './models/config';
57
57
  export { TokenResponse, IdToken, TokenExchangeRequestConfig } from './models/token';
58
+ export { AgentConfig } from './models/agent';
59
+ export { AuthCodeResponse } from './models/auth-code-response';
58
60
  export { Crypto, JWKInterface } from './models/crypto';
59
61
  export { OAuthResponseMode } from './models/oauth-response';
60
62
  export { AuthorizeRequestUrlParams, KnownExtendedAuthorizeRequestUrlParams, ExtendedAuthorizeRequestUrlParams, } from './models/oauth-request';
@@ -63,6 +65,8 @@ export { Storage, TemporaryStore } from './models/store';
63
65
  export { User, UserProfile } from './models/user';
64
66
  export { SessionData } from './models/session';
65
67
  export { Organization } from './models/organization';
68
+ export { TranslationFn } from './models/v2/translation';
69
+ export { ResolveVarsOptions } from './models/v2/vars';
66
70
  export { BrandingPreference, BrandingPreferenceConfig, BrandingLayout, BrandingTheme, ThemeVariant, ButtonsConfig, ColorsConfig, ColorVariants, BrandingOrganizationDetails, UrlsConfig, } from './models/branding-preference';
67
71
  export { Schema, SchemaAttribute, WellKnownSchemaIds, FlattenedSchema } from './models/scim2-schema';
68
72
  export { RecursivePartial } from './models/utility-types';
@@ -92,6 +96,8 @@ export { default as get } from './utils/get';
92
96
  export { default as removeTrailingSlash } from './utils/removeTrailingSlash';
93
97
  export { default as resolveFieldType } from './utils/resolveFieldType';
94
98
  export { default as resolveFieldName } from './utils/resolveFieldName';
99
+ export { default as resolveMeta } from './utils/v2/resolveMeta';
100
+ export { default as resolveVars } from './utils/v2/resolveVars';
95
101
  export { default as processOpenIDScopes } from './utils/processOpenIDScopes';
96
102
  export { default as withVendorCSSClassPrefix } from './utils/withVendorCSSClassPrefix';
97
103
  export { default as transformBrandingPreferenceToTheme } from './utils/transformBrandingPreferenceToTheme';
package/dist/index.js CHANGED
@@ -673,8 +673,9 @@ var IsomorphicCrypto = class {
673
673
  *
674
674
  * @returns - code challenge.
675
675
  */
676
- getCodeChallenge(verifier) {
677
- return this.cryptoUtils.base64URLEncode(this.cryptoUtils.hashSha256(verifier));
676
+ async getCodeChallenge(verifier) {
677
+ const hashed = await this.cryptoUtils.hashSha256(verifier);
678
+ return this.cryptoUtils.base64URLEncode(hashed);
678
679
  }
679
680
  /**
680
681
  * Get JWK used for the id_token
@@ -894,6 +895,31 @@ var StorageManager = class _StorageManager {
894
895
  };
895
896
  var StorageManager_default = StorageManager;
896
897
 
898
+ // src/utils/deepMerge.ts
899
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && Object.prototype.toString.call(value) === "[object Object]";
900
+ var deepMerge = (target, ...sources) => {
901
+ if (!target || typeof target !== "object") {
902
+ throw new Error("Target must be an object");
903
+ }
904
+ const result = { ...target };
905
+ sources.forEach((source) => {
906
+ if (!source || typeof source !== "object") {
907
+ return;
908
+ }
909
+ Object.keys(source).forEach((key) => {
910
+ const sourceValue = source[key];
911
+ const targetValue = result[key];
912
+ if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
913
+ result[key] = deepMerge(targetValue, sourceValue);
914
+ } else if (sourceValue !== void 0) {
915
+ result[key] = sourceValue;
916
+ }
917
+ });
918
+ });
919
+ return result;
920
+ };
921
+ var deepMerge_default = deepMerge;
922
+
897
923
  // src/utils/extractPkceStorageKeyFromState.ts
898
924
  var extractPkceStorageKeyFromState = (state) => {
899
925
  const index = parseInt(state.split("request_")[1], 10);
@@ -1134,7 +1160,7 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1134
1160
  let codeChallenge;
1135
1161
  if (configData.enablePKCE) {
1136
1162
  codeVerifier = this.cryptoHelper?.getCodeVerifier();
1137
- codeChallenge = this.cryptoHelper?.getCodeChallenge(codeVerifier);
1163
+ codeChallenge = await this.cryptoHelper?.getCodeChallenge(codeVerifier);
1138
1164
  await this.storageManager.setTemporaryDataParameter(pkceKey, codeVerifier, userId);
1139
1165
  }
1140
1166
  if (authRequestConfig["client_secret"]) {
@@ -1901,7 +1927,9 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1901
1927
  * @preserve
1902
1928
  */
1903
1929
  async reInitialize(config) {
1904
- await this.storageManager.setConfigData(config);
1930
+ const currentConfig = this.storageManager.getConfigData();
1931
+ const newConfig = deepMerge_default(currentConfig, config);
1932
+ await this.storageManager.setConfigData(newConfig);
1905
1933
  await this.loadOpenIDProviderConfiguration(true);
1906
1934
  }
1907
1935
  static async clearSession(userId) {
@@ -3267,10 +3295,14 @@ var EmbeddedFlowComponentType2 = /* @__PURE__ */ ((EmbeddedFlowComponentType3) =
3267
3295
  EmbeddedFlowComponentType3["Block"] = "BLOCK";
3268
3296
  EmbeddedFlowComponentType3["Divider"] = "DIVIDER";
3269
3297
  EmbeddedFlowComponentType3["EmailInput"] = "EMAIL_INPUT";
3298
+ EmbeddedFlowComponentType3["Icon"] = "ICON";
3299
+ EmbeddedFlowComponentType3["Image"] = "IMAGE";
3270
3300
  EmbeddedFlowComponentType3["OtpInput"] = "OTP_INPUT";
3271
3301
  EmbeddedFlowComponentType3["PasswordInput"] = "PASSWORD_INPUT";
3272
3302
  EmbeddedFlowComponentType3["PhoneInput"] = "PHONE_INPUT";
3303
+ EmbeddedFlowComponentType3["RichText"] = "RICH_TEXT";
3273
3304
  EmbeddedFlowComponentType3["Select"] = "SELECT";
3305
+ EmbeddedFlowComponentType3["Stack"] = "STACK";
3274
3306
  EmbeddedFlowComponentType3["Text"] = "TEXT";
3275
3307
  EmbeddedFlowComponentType3["TextInput"] = "TEXT_INPUT";
3276
3308
  return EmbeddedFlowComponentType3;
@@ -3327,6 +3359,12 @@ var FlowMode = /* @__PURE__ */ ((FlowMode2) => {
3327
3359
  return FlowMode2;
3328
3360
  })(FlowMode || {});
3329
3361
 
3362
+ // src/models/agent.ts
3363
+ var AgentConfig;
3364
+ ((AgentConfig2) => {
3365
+ AgentConfig2.DEFAULT_AUTHENTICATOR_NAME = "Username & Password";
3366
+ })(AgentConfig || (AgentConfig = {}));
3367
+
3330
3368
  // src/models/scim2-schema.ts
3331
3369
  var WellKnownSchemaIds = /* @__PURE__ */ ((WellKnownSchemaIds2) => {
3332
3370
  WellKnownSchemaIds2["Core"] = "urn:ietf:params:scim:schemas:core:2.0";
@@ -3353,8 +3391,225 @@ var FieldType = /* @__PURE__ */ ((FieldType2) => {
3353
3391
  return FieldType2;
3354
3392
  })(FieldType || {});
3355
3393
 
3394
+ // src/DefaultCacheStore.ts
3395
+ var DefaultCacheStore = class {
3396
+ constructor() {
3397
+ __publicField(this, "cache");
3398
+ this.cache = /* @__PURE__ */ new Map();
3399
+ }
3400
+ get length() {
3401
+ return this.cache.size;
3402
+ }
3403
+ getItem(key) {
3404
+ return this.cache.get(key) ?? null;
3405
+ }
3406
+ setItem(key, value) {
3407
+ this.cache.set(key, value);
3408
+ }
3409
+ removeItem(key) {
3410
+ this.cache.delete(key);
3411
+ }
3412
+ clear() {
3413
+ this.cache.clear();
3414
+ }
3415
+ key(index) {
3416
+ const keys = Array.from(this.cache.keys());
3417
+ return keys[index] ?? null;
3418
+ }
3419
+ async setData(key, value) {
3420
+ this.cache.set(key, value);
3421
+ }
3422
+ async getData(key) {
3423
+ return this.cache.get(key) ?? "{}";
3424
+ }
3425
+ async removeData(key) {
3426
+ this.cache.delete(key);
3427
+ }
3428
+ };
3429
+
3430
+ // src/DefaultCrypto.ts
3431
+ import * as jose from "jose";
3432
+ var DefaultCrypto = class {
3433
+ // eslint-disable-next-line class-methods-use-this
3434
+ base64URLDecode(value) {
3435
+ const decodedArray = jose.base64url.decode(value);
3436
+ return new TextDecoder().decode(decodedArray);
3437
+ }
3438
+ // eslint-disable-next-line class-methods-use-this
3439
+ base64URLEncode(value) {
3440
+ return jose.base64url.encode(value);
3441
+ }
3442
+ // eslint-disable-next-line class-methods-use-this
3443
+ generateRandomBytes(length) {
3444
+ return crypto.getRandomValues(new Uint8Array(length));
3445
+ }
3446
+ // eslint-disable-next-line class-methods-use-this
3447
+ async hashSha256(data) {
3448
+ const encoder = new TextEncoder();
3449
+ const dataBuffer = encoder.encode(data);
3450
+ const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
3451
+ return new Uint8Array(hashBuffer);
3452
+ }
3453
+ // eslint-disable-next-line class-methods-use-this
3454
+ async verifyJwt(idToken, jwk, algorithms, clientId, issuer, subject, clockTolerance, validateJwtIssuer = true) {
3455
+ const key = await jose.importJWK(jwk);
3456
+ await jose.jwtVerify(idToken, key, {
3457
+ algorithms,
3458
+ audience: clientId,
3459
+ clockTolerance,
3460
+ issuer: validateJwtIssuer ? issuer : void 0,
3461
+ subject
3462
+ });
3463
+ return true;
3464
+ }
3465
+ };
3466
+
3356
3467
  // src/AsgardeoJavaScriptClient.ts
3357
3468
  var AsgardeoJavaScriptClient = class {
3469
+ constructor(config, cacheStore, cryptoUtils) {
3470
+ __publicField(this, "cacheStore");
3471
+ __publicField(this, "cryptoUtils");
3472
+ __publicField(this, "auth");
3473
+ __publicField(this, "storageManager");
3474
+ __publicField(this, "baseURL");
3475
+ this.cacheStore = cacheStore ?? new DefaultCacheStore();
3476
+ this.cryptoUtils = cryptoUtils ?? new DefaultCrypto();
3477
+ this.auth = new AsgardeoAuthClient();
3478
+ if (config) {
3479
+ this.auth.initialize(config, this.cacheStore, this.cryptoUtils);
3480
+ this.storageManager = this.auth.getStorageManager();
3481
+ }
3482
+ this.baseURL = config?.baseUrl ?? "";
3483
+ }
3484
+ /* eslint-disable class-methods-use-this, @typescript-eslint/no-unused-vars */
3485
+ switchOrganization(_organization, _sessionId) {
3486
+ throw new Error("Method not implemented.");
3487
+ }
3488
+ initialize(_config, _storage) {
3489
+ throw new Error("Method not implemented.");
3490
+ }
3491
+ reInitialize(_config) {
3492
+ throw new Error("Method not implemented.");
3493
+ }
3494
+ getUser(_options) {
3495
+ throw new Error("Method not implemented.");
3496
+ }
3497
+ getAllOrganizations(_options, _sessionId) {
3498
+ throw new Error("Method not implemented.");
3499
+ }
3500
+ getMyOrganizations(_options, _sessionId) {
3501
+ throw new Error("Method not implemented.");
3502
+ }
3503
+ getCurrentOrganization(_sessionId) {
3504
+ throw new Error("Method not implemented.");
3505
+ }
3506
+ getUserProfile(_options) {
3507
+ throw new Error("Method not implemented.");
3508
+ }
3509
+ isLoading() {
3510
+ throw new Error("Method not implemented.");
3511
+ }
3512
+ isSignedIn() {
3513
+ throw new Error("Method not implemented.");
3514
+ }
3515
+ updateUserProfile(_payload, _userId) {
3516
+ throw new Error("Method not implemented.");
3517
+ }
3518
+ getConfiguration() {
3519
+ throw new Error("Method not implemented.");
3520
+ }
3521
+ exchangeToken(_config, _sessionId) {
3522
+ throw new Error("Method not implemented.");
3523
+ }
3524
+ signInSilently(_options) {
3525
+ throw new Error("Method not implemented.");
3526
+ }
3527
+ getAccessToken(_sessionId) {
3528
+ throw new Error("Method not implemented.");
3529
+ }
3530
+ clearSession(_sessionId) {
3531
+ throw new Error("Method not implemented.");
3532
+ }
3533
+ setSession(_sessionData, _sessionId) {
3534
+ throw new Error("Method not implemented.");
3535
+ }
3536
+ decodeJwtToken(_token) {
3537
+ throw new Error("Method not implemented.");
3538
+ }
3539
+ signIn(_options) {
3540
+ throw new Error("Method not implemented.");
3541
+ }
3542
+ signOut(_options, _sessionIdOrAfterSignOut, _afterSignOut) {
3543
+ throw new Error("Method not implemented.");
3544
+ }
3545
+ signUp(_optionsOrPayload) {
3546
+ throw new Error("Method not implemented.");
3547
+ }
3548
+ /* eslint-enable class-methods-use-this, @typescript-eslint/no-unused-vars */
3549
+ async getAgentToken(agentConfig) {
3550
+ const customParam = {
3551
+ response_mode: "direct"
3552
+ };
3553
+ const authorizeURL = new URL(await this.auth.getSignInUrl(customParam));
3554
+ const authorizeResponse = await initializeEmbeddedSignInFlow_default({
3555
+ payload: Object.fromEntries(authorizeURL.searchParams.entries()),
3556
+ url: `${authorizeURL.origin}${authorizeURL.pathname}`
3557
+ });
3558
+ const authenticatorName = agentConfig.authenticatorName ?? AgentConfig.DEFAULT_AUTHENTICATOR_NAME;
3559
+ const targetAuthenticator = authorizeResponse.nextStep.authenticators.find(
3560
+ (auth) => auth.authenticator === authenticatorName
3561
+ );
3562
+ if (!targetAuthenticator) {
3563
+ throw new Error(`Authenticator '${authenticatorName}' not found among authentication steps.`);
3564
+ }
3565
+ const authnRequest = {
3566
+ baseUrl: this.baseURL,
3567
+ payload: {
3568
+ flowId: authorizeResponse.flowId,
3569
+ selectedAuthenticator: {
3570
+ authenticatorId: targetAuthenticator.authenticatorId,
3571
+ params: {
3572
+ password: agentConfig.agentSecret,
3573
+ username: agentConfig.agentID
3574
+ }
3575
+ }
3576
+ }
3577
+ };
3578
+ const authnResponse = await executeEmbeddedSignInFlow_default(authnRequest);
3579
+ if (authnResponse.flowStatus !== "SUCCESS_COMPLETED" /* SuccessCompleted */) {
3580
+ throw new Error("Agent authentication failed.");
3581
+ }
3582
+ return this.auth.requestAccessToken(
3583
+ authnResponse.authData["code"],
3584
+ authnResponse.authData["session_state"],
3585
+ authnResponse.authData["state"]
3586
+ );
3587
+ }
3588
+ async getOBOSignInURL(agentConfig) {
3589
+ const customParam = {
3590
+ requested_actor: agentConfig.agentID
3591
+ };
3592
+ const authURL = await this.auth.getSignInUrl(customParam);
3593
+ if (authURL) {
3594
+ return authURL.toString();
3595
+ }
3596
+ throw new Error("Could not build Authorize URL");
3597
+ }
3598
+ async getOBOToken(agentConfig, authCodeResponse) {
3599
+ const agentToken = await this.getAgentToken(agentConfig);
3600
+ const tokenRequestConfig = {
3601
+ params: {
3602
+ actor_token: agentToken.accessToken
3603
+ }
3604
+ };
3605
+ return this.auth.requestAccessToken(
3606
+ authCodeResponse.code,
3607
+ authCodeResponse.session_state,
3608
+ authCodeResponse.state,
3609
+ void 0,
3610
+ tokenRequestConfig
3611
+ );
3612
+ }
3358
3613
  };
3359
3614
  var AsgardeoJavaScriptClient_default = AsgardeoJavaScriptClient;
3360
3615
 
@@ -3948,9 +4203,9 @@ var arrayBufferToBase64url = (buffer) => {
3948
4203
  var arrayBufferToBase64url_default = arrayBufferToBase64url;
3949
4204
 
3950
4205
  // src/utils/base64urlToArrayBuffer.ts
3951
- var base64urlToArrayBuffer = (base64url) => {
3952
- const padding = "=".repeat((4 - base64url.length % 4) % 4);
3953
- const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/") + padding;
4206
+ var base64urlToArrayBuffer = (base64url2) => {
4207
+ const padding = "=".repeat((4 - base64url2.length % 4) % 4);
4208
+ const base64 = base64url2.replace(/-/g, "+").replace(/_/g, "/") + padding;
3954
4209
  const binaryString = atob(base64);
3955
4210
  const bytes = new Uint8Array(binaryString.length);
3956
4211
  for (let i = 0; i < binaryString.length; i += 1) {
@@ -3988,31 +4243,6 @@ var formatDate = (dateString) => {
3988
4243
  };
3989
4244
  var formatDate_default = formatDate;
3990
4245
 
3991
- // src/utils/deepMerge.ts
3992
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && Object.prototype.toString.call(value) === "[object Object]";
3993
- var deepMerge = (target, ...sources) => {
3994
- if (!target || typeof target !== "object") {
3995
- throw new Error("Target must be an object");
3996
- }
3997
- const result = { ...target };
3998
- sources.forEach((source) => {
3999
- if (!source || typeof source !== "object") {
4000
- return;
4001
- }
4002
- Object.keys(source).forEach((key) => {
4003
- const sourceValue = source[key];
4004
- const targetValue = result[key];
4005
- if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
4006
- result[key] = deepMerge(targetValue, sourceValue);
4007
- } else if (sourceValue !== void 0) {
4008
- result[key] = sourceValue;
4009
- }
4010
- });
4011
- });
4012
- return result;
4013
- };
4014
- var deepMerge_default = deepMerge;
4015
-
4016
4246
  // src/utils/logger.ts
4017
4247
  var PREFIX = "\u{1F6E1}\uFE0F Asgardeo";
4018
4248
  var DEFAULT_CONFIG = {
@@ -4644,6 +4874,48 @@ var resolveFieldName = (field) => {
4644
4874
  };
4645
4875
  var resolveFieldName_default = resolveFieldName;
4646
4876
 
4877
+ // src/utils/v2/resolveMeta.ts
4878
+ function resolveMeta(path, meta) {
4879
+ const value = path.split(".").reduce((current, part) => {
4880
+ if (current == null || typeof current !== "object") {
4881
+ return void 0;
4882
+ }
4883
+ const obj = current;
4884
+ const snakePart = part.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
4885
+ return part in obj ? obj[part] : obj[snakePart];
4886
+ }, meta);
4887
+ return value != null ? String(value) : "";
4888
+ }
4889
+
4890
+ // src/utils/v2/resolveVars.ts
4891
+ function resolveVars(text, { t, meta }) {
4892
+ if (!text) {
4893
+ return "";
4894
+ }
4895
+ return text.replace(/\{\{(.+?)\}\}/g, (match, content) => {
4896
+ const trimmed = content.trim();
4897
+ const tMatch = trimmed.match(/^t\((.+)\)$/);
4898
+ if (tMatch) {
4899
+ let key = tMatch[1].trim();
4900
+ if (key.startsWith('"') && key.endsWith('"') || key.startsWith("'") && key.endsWith("'")) {
4901
+ key = key.slice(1, -1);
4902
+ }
4903
+ return t(key.replace(/:/g, "."));
4904
+ }
4905
+ if (meta) {
4906
+ const metaMatch = trimmed.match(/^meta\((.+)\)$/);
4907
+ if (metaMatch) {
4908
+ let path = metaMatch[1].trim();
4909
+ if (path.startsWith('"') && path.endsWith('"') || path.startsWith("'") && path.endsWith("'")) {
4910
+ path = path.slice(1, -1);
4911
+ }
4912
+ return resolveMeta(path, meta);
4913
+ }
4914
+ }
4915
+ return match;
4916
+ });
4917
+ }
4918
+
4647
4919
  // src/utils/withVendorCSSClassPrefix.ts
4648
4920
  var withVendorCSSClassPrefix = (className) => `${VendorConstants_default.VENDOR_PREFIX}-${className}`;
4649
4921
  var withVendorCSSClassPrefix_default = withVendorCSSClassPrefix;
@@ -4786,6 +5058,7 @@ var transformBrandingPreferenceToTheme = (brandingPreference, forceTheme) => {
4786
5058
  };
4787
5059
  var transformBrandingPreferenceToTheme_default = transformBrandingPreferenceToTheme;
4788
5060
  export {
5061
+ AgentConfig,
4789
5062
  ApplicationNativeAuthenticationConstants_default as ApplicationNativeAuthenticationConstants,
4790
5063
  AsgardeoAPIError,
4791
5064
  AsgardeoAuthClient,
@@ -4870,6 +5143,8 @@ export {
4870
5143
  removeTrailingSlash_default as removeTrailingSlash,
4871
5144
  resolveFieldName_default as resolveFieldName,
4872
5145
  resolveFieldType_default as resolveFieldType,
5146
+ resolveMeta,
5147
+ resolveVars,
4873
5148
  set_default as set,
4874
5149
  transformBrandingPreferenceToTheme_default as transformBrandingPreferenceToTheme,
4875
5150
  updateMeProfile_default as updateMeProfile,