@asgardeo/javascript 0.22.0 → 0.23.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.
@@ -3950,12 +3950,6 @@ var FlowMode = /* @__PURE__ */ ((FlowMode2) => {
3950
3950
  return FlowMode2;
3951
3951
  })(FlowMode || {});
3952
3952
 
3953
- // src/models/agent.ts
3954
- var AgentConfig;
3955
- ((AgentConfig2) => {
3956
- AgentConfig2.DEFAULT_AUTHENTICATOR_NAME = "Username & Password";
3957
- })(AgentConfig || (AgentConfig = {}));
3958
-
3959
3953
  // src/models/scim2-schema.ts
3960
3954
  var WellKnownSchemaIds = /* @__PURE__ */ ((WellKnownSchemaIds2) => {
3961
3955
  WellKnownSchemaIds2["Core"] = "urn:ietf:params:scim:schemas:core:2.0";
@@ -4056,24 +4050,54 @@ var DefaultCrypto = class {
4056
4050
  }
4057
4051
  };
4058
4052
 
4053
+ // src/models/agent.ts
4054
+ var AgentConfig;
4055
+ ((AgentConfig2) => {
4056
+ AgentConfig2.DEFAULT_AUTHENTICATOR_NAME = "Username & Password";
4057
+ })(AgentConfig || (AgentConfig = {}));
4058
+
4059
4059
  // src/AsgardeoJavaScriptClient.ts
4060
- var AsgardeoJavaScriptClient = class {
4060
+ var RESERVED_AUTH_KEYS = /* @__PURE__ */ new Set([
4061
+ "client_id",
4062
+ "redirect_uri",
4063
+ "scope",
4064
+ "state",
4065
+ "response_type",
4066
+ "resource",
4067
+ "fidp",
4068
+ "requested_actor",
4069
+ "orgId",
4070
+ "orgHandle",
4071
+ "org",
4072
+ "login_hint",
4073
+ "orgDiscoveryType",
4074
+ "code_challenge",
4075
+ "code_challenge_method"
4076
+ ]);
4077
+ var AsgardeoJavaScriptClient = class _AsgardeoJavaScriptClient {
4061
4078
  constructor(config, cacheStore, cryptoUtils) {
4062
4079
  __publicField(this, "cacheStore");
4063
4080
  __publicField(this, "cryptoUtils");
4064
4081
  __publicField(this, "auth");
4065
4082
  __publicField(this, "storageManager");
4066
4083
  __publicField(this, "baseURL");
4084
+ __publicField(this, "initPromise");
4067
4085
  this.cacheStore = cacheStore ?? new DefaultCacheStore();
4068
4086
  this.cryptoUtils = cryptoUtils ?? new DefaultCrypto();
4069
4087
  this.auth = new AsgardeoAuthClient();
4070
4088
  if (config) {
4071
- this.auth.initialize(config, this.cacheStore, this.cryptoUtils);
4089
+ this.initPromise = this.auth.initialize(config, this.cacheStore, this.cryptoUtils);
4072
4090
  this.storageManager = this.auth.getStorageManager();
4073
4091
  }
4074
4092
  this.baseURL = config?.baseUrl ?? "";
4075
4093
  }
4094
+ async ensureInitialized() {
4095
+ if (this.initPromise) {
4096
+ await this.initPromise;
4097
+ }
4098
+ }
4076
4099
  async getDiscoveryResponse() {
4100
+ await this.ensureInitialized();
4077
4101
  if (!this.storageManager) {
4078
4102
  return null;
4079
4103
  }
@@ -4148,6 +4172,15 @@ var AsgardeoJavaScriptClient = class {
4148
4172
  }
4149
4173
  /* eslint-enable class-methods-use-this, @typescript-eslint/no-unused-vars */
4150
4174
  async getAgentToken(agentConfig) {
4175
+ await this.ensureInitialized();
4176
+ if (!agentConfig?.agentID) {
4177
+ throw new Error("agentConfig.agentID is required for getAgentToken().");
4178
+ }
4179
+ if (!agentConfig.agentSecret) {
4180
+ throw new Error(
4181
+ "agentConfig.agentSecret is required for getAgentToken(). The agent must authenticate against the token endpoint."
4182
+ );
4183
+ }
4151
4184
  const customParam = {
4152
4185
  response_mode: "direct"
4153
4186
  };
@@ -4187,6 +4220,7 @@ var AsgardeoJavaScriptClient = class {
4187
4220
  );
4188
4221
  }
4189
4222
  async getOBOSignInURL(agentConfig) {
4223
+ await this.ensureInitialized();
4190
4224
  const customParam = {
4191
4225
  requested_actor: agentConfig.agentID
4192
4226
  };
@@ -4211,6 +4245,200 @@ var AsgardeoJavaScriptClient = class {
4211
4245
  tokenRequestConfig
4212
4246
  );
4213
4247
  }
4248
+ /**
4249
+ * Builds a `/oauth2/authorize` URL targeting a specific child organization.
4250
+ *
4251
+ * The target organization can be identified by its UUID (`orgID`), handle
4252
+ * (`orgHandle`), display name (`org`) or via email-domain based discovery
4253
+ * (`emailDomain`).
4254
+ *
4255
+ * @param orgDiscoveryType - The organization discovery strategy to use.
4256
+ * @param discoveryInput - The identifier whose meaning depends on
4257
+ * `orgDiscoveryType` (UUID, handle, name or email).
4258
+ * @param options - Optional state, resource, agent delegation and
4259
+ * additional query parameters.
4260
+ * @returns The fully-built authorization URL.
4261
+ */
4262
+ async getOrgAuthorizationUrl(orgDiscoveryType, discoveryInput, options = {}) {
4263
+ await this.ensureInitialized();
4264
+ const customParam = _AsgardeoJavaScriptClient.buildOrgAuthorizationParams(
4265
+ orgDiscoveryType,
4266
+ discoveryInput,
4267
+ options
4268
+ );
4269
+ const authURL = await this.auth.getSignInUrl(customParam);
4270
+ if (!authURL) {
4271
+ throw new Error("Could not build organization authorization URL");
4272
+ }
4273
+ return authURL.toString();
4274
+ }
4275
+ /**
4276
+ * Exchanges an existing access token for one scoped to a target organization,
4277
+ * using the `organization_switch` grant type.
4278
+ *
4279
+ * Unlike {@link AsgardeoJavaScriptClient.exchangeToken} this method does
4280
+ * not require an active SDK session — the caller supplies the source
4281
+ * access token directly. This makes it safe to use from server-side agent
4282
+ * flows where there is no user session yet.
4283
+ *
4284
+ * @param token - The current access token to be switched.
4285
+ * @param switchingOrganization - The ID/UUID of the target organization.
4286
+ * @param scopes - Optional list of scopes to request for the switched token.
4287
+ * @returns A normalized {@link TokenResponse} for the switched organization.
4288
+ */
4289
+ async switchTokenToOrganization(token, switchingOrganization, scopes) {
4290
+ await this.ensureInitialized();
4291
+ if (!token) {
4292
+ throw new Error("Token is required for organization switch.");
4293
+ }
4294
+ if (!switchingOrganization) {
4295
+ throw new Error("switchingOrganization is required.");
4296
+ }
4297
+ if (!this.storageManager) {
4298
+ throw new Error("Client is not initialized. Call initialize() before switching organizations.");
4299
+ }
4300
+ const configData = await this.storageManager.getConfigData();
4301
+ if (!configData) {
4302
+ throw new Error("Client configuration is unavailable. Initialize the client before switching organizations.");
4303
+ }
4304
+ const tokenEndpoint = await this.resolveTokenEndpoint();
4305
+ const body = new URLSearchParams();
4306
+ const { clientId, clientSecret } = configData;
4307
+ if (!clientId || clientId.trim().length === 0) {
4308
+ throw new Error("clientId is required in the client configuration for organization switch.");
4309
+ }
4310
+ const hasSecret = Boolean(clientSecret && clientSecret.trim().length > 0);
4311
+ body.set("grant_type", "organization_switch");
4312
+ body.set("token", token);
4313
+ body.set("switching_organization", switchingOrganization);
4314
+ body.set("client_id", clientId);
4315
+ if (hasSecret) {
4316
+ body.set("client_secret", clientSecret);
4317
+ }
4318
+ if (scopes && scopes.length > 0) {
4319
+ body.set("scope", scopes.join(" "));
4320
+ }
4321
+ let response;
4322
+ try {
4323
+ response = await fetch(tokenEndpoint, {
4324
+ body,
4325
+ headers: {
4326
+ Accept: "application/json",
4327
+ "Content-Type": "application/x-www-form-urlencoded"
4328
+ },
4329
+ method: "POST"
4330
+ });
4331
+ } catch (error2) {
4332
+ throw new Error(`Organization switch request failed: ${error2?.message ?? String(error2)}`);
4333
+ }
4334
+ if (!response.ok) {
4335
+ let errorBody;
4336
+ try {
4337
+ errorBody = JSON.stringify(await response.json());
4338
+ } catch {
4339
+ errorBody = response.statusText;
4340
+ }
4341
+ throw new Error(`Organization switch failed (${response.status}): ${errorBody}`);
4342
+ }
4343
+ const parsed = await response.json();
4344
+ return {
4345
+ accessToken: parsed.access_token,
4346
+ createdAt: parsed.created_at ?? Date.now(),
4347
+ expiresIn: parsed.expires_in,
4348
+ idToken: parsed.id_token,
4349
+ refreshToken: parsed.refresh_token,
4350
+ scope: parsed.scope,
4351
+ tokenType: parsed.token_type
4352
+ };
4353
+ }
4354
+ /**
4355
+ * Resolves the OAuth2 token endpoint URL.
4356
+ *
4357
+ * Prefers the value advertised by the OIDC well-known document (when it
4358
+ * has already been loaded into the storage manager) and falls back to
4359
+ * `${baseURL}/oauth2/token` derived from the SDK configuration.
4360
+ */
4361
+ async resolveTokenEndpoint() {
4362
+ const discovery = this.storageManager ? await this.storageManager.loadOpenIDProviderConfiguration() : null;
4363
+ const discovered = discovery?.token_endpoint;
4364
+ if (discovered && discovered.trim().length > 0) {
4365
+ return discovered;
4366
+ }
4367
+ if (this.baseURL && this.baseURL.trim().length > 0) {
4368
+ return `${this.baseURL.replace(/\/$/, "")}/oauth2/token`;
4369
+ }
4370
+ throw new Error(
4371
+ "Unable to resolve the token endpoint. Provide a baseUrl in the client configuration or ensure OIDC discovery has been performed."
4372
+ );
4373
+ }
4374
+ /**
4375
+ * Authenticates as the agent and switches the issued agent token into a
4376
+ * target child organization in a single call.
4377
+ *
4378
+ * @param agentConfig - Agent credentials used to obtain the parent-org agent token.
4379
+ * @param switchingOrganization - The ID/UUID of the target organization.
4380
+ * @param orgScopes - Optional scopes to request for the organization-scoped token.
4381
+ * @returns A normalized {@link TokenResponse} scoped to the target organization.
4382
+ */
4383
+ async getOrganizationAgentToken(agentConfig, switchingOrganization, orgScopes) {
4384
+ if (!switchingOrganization) {
4385
+ throw new Error("switchingOrganization is required.");
4386
+ }
4387
+ const agentToken = await this.getAgentToken(agentConfig);
4388
+ return this.switchTokenToOrganization(agentToken.accessToken, switchingOrganization, orgScopes);
4389
+ }
4390
+ /**
4391
+ * Builds the custom query-parameter map for an organization-scoped authorization request.
4392
+ */
4393
+ static buildOrgAuthorizationParams(orgDiscoveryType, discoveryInput, options) {
4394
+ const trimmedValue = (discoveryInput ?? "").trim();
4395
+ if (!trimmedValue) {
4396
+ throw new Error("discoveryInput is required.");
4397
+ }
4398
+ const customParam = {};
4399
+ if (!options.isEnhancedOrgAuth) {
4400
+ customParam["fidp"] = "OrganizationSSO";
4401
+ }
4402
+ switch (orgDiscoveryType) {
4403
+ case "orgID":
4404
+ customParam["orgId"] = trimmedValue;
4405
+ break;
4406
+ case "orgHandle":
4407
+ customParam["orgHandle"] = trimmedValue;
4408
+ break;
4409
+ case "org":
4410
+ customParam["org"] = trimmedValue;
4411
+ break;
4412
+ case "emailDomain":
4413
+ customParam["login_hint"] = trimmedValue;
4414
+ customParam["orgDiscoveryType"] = "emailDomain";
4415
+ break;
4416
+ default:
4417
+ throw new Error(`Unsupported orgDiscoveryType: ${orgDiscoveryType}`);
4418
+ }
4419
+ if (options.resource) {
4420
+ customParam["resource"] = options.resource;
4421
+ }
4422
+ if (options.state) {
4423
+ customParam["state"] = options.state;
4424
+ }
4425
+ if (options.agentConfig) {
4426
+ if (!options.agentConfig.agentID || options.agentConfig.agentID.trim().length === 0) {
4427
+ throw new Error("agentConfig.agentID is required when agentConfig is provided.");
4428
+ }
4429
+ customParam["requested_actor"] = options.agentConfig.agentID;
4430
+ }
4431
+ if (options.additionalParams) {
4432
+ const conflicts = Object.keys(options.additionalParams).filter(
4433
+ (key) => RESERVED_AUTH_KEYS.has(key)
4434
+ );
4435
+ if (conflicts.length > 0) {
4436
+ throw new Error(`Reserved authorization parameters cannot be overridden: ${conflicts.sort().join(", ")}`);
4437
+ }
4438
+ Object.assign(customParam, options.additionalParams);
4439
+ }
4440
+ return customParam;
4441
+ }
4214
4442
  };
4215
4443
  var AsgardeoJavaScriptClient_default = AsgardeoJavaScriptClient;
4216
4444
 
@@ -5544,7 +5772,6 @@ var _HttpClient = class _HttpClient {
5544
5772
  __publicField(_HttpClient, "DEFAULT_HANDLER_DISABLE_TIMEOUT", 1e3);
5545
5773
  var HttpClient = _HttpClient;
5546
5774
  export {
5547
- AgentConfig,
5548
5775
  ApplicationNativeAuthenticationConstants_default as ApplicationNativeAuthenticationConstants,
5549
5776
  AsgardeoAPIError,
5550
5777
  AsgardeoAuthClient,