npm.io
4.5.1 • Published 37m ago

@descope/web-component

Licence
MIT
Version
4.5.1
Deps
6
Size
1.4 MB
Vulns
0
Weekly
0
Stars
72

@descope/web-component

Create your login pages on our console-app, once done, you can use this library to inject those pages to your app
it registers- a web component and update the web-component content based on the relevant page, See usage example below

Usage

Install the package

npm install @descope/web-component
As a library
import '@descope/web-component' // This import will define `descope-wc` custom element
import { DescopeWc } // In case you need types definition or you want to use the class directly

// Render Descope Web Component, for example:
render(){
  return (
    <descope-wc project-id="myProjectId"/>
  )
}
In HTML file
  • Copy the file @descope/web-component/dist/index.js rename it to descope-wc.js and place it where your HTML file is located

  • Add the following script tag to your HTML file

<head>
  <script src="./descope-wc.js"></script>
</head>
  • Now you can add the custom element to your HTML
<descope-wc project-id="<project-id>" flow-id="<flow-id>" form='{ "email": "predefinedname@domain.com", "myCustomInput": "12" }' client='{ "browserVersion": window.navigator.appVersion }'></descope-wc>
  • Note: the form and client are optional parameters to add additional information that can be used in the flow. For more information click here.
Run Example

To run the example:

  1. Install dependencies pnpm i
  2. Create a .env file and the following variables:
// .env
# Descope Project ID
DESCOPE_PROJECT_ID=<project-id>
# Flow ID to run, e.g. sign-up-or-in
DESCOPE_FLOW_ID=<flow-id>
# Optional - Descope base URL
DESCOPE_BASE_URL
# Optional - Descope locale (according to the target locales configured in the flow)
DESCOPE_LOCALE=<locale>

# Telemetry fallback config (AWS CloudWatch RUM).
# Optional — used by the SDK only when the backend's config.json doesn't
# ship a `telemetry` block. Once it does, these are ignored.
# Leave DESCOPE_TELEMETRY_ENABLED unset or set to anything other than
# "true" to keep the fallback off.
DESCOPE_TELEMETRY_ENABLED=<true|false>
DESCOPE_TELEMETRY_APPLICATION_ID=<cloudwatch-rum-app-monitor-id>
DESCOPE_TELEMETRY_IDENTITY_POOL_ID=<aws-cognito-identity-pool-id>
DESCOPE_TELEMETRY_REGION=<aws-region>
# Optional — only required for the classic Cognito flow.
DESCOPE_TELEMETRY_GUEST_ROLE_ARN=<iam-guest-role-arn>
# Optional — 0..1, defaults to 1 (capture every session).
DESCOPE_TELEMETRY_SESSION_SAMPLE_RATE=1
  1. Run the sample pnpm run start / pnpm run start-web-sample

NOTE: This package is a part of a monorepo. so if you make changes in a dependency, you will have to rerun npm run start / pnpm run start-web-sample (this is a temporary solution until we improve the process to fit to monorepo).

Security Features

Subresource Integrity (SRI)

The web component automatically applies Subresource Integrity (SRI) checks to the web-components-ui loader when the SRI hash is available in the project configuration. This provides cryptographic verification that the loaded script has not been tampered with.

How it works:

  1. The Descope orchestration service generates SRI hashes for each version of the web-components-ui library
  2. The hash is included in the config.json as componentsVersionSri
  3. The web component automatically adds integrity and crossorigin attributes to the script tag
  4. The browser verifies the script integrity before executing it

Example generated script tag:

<script src="https://descopecdn.com/npm/@descope/web-components-ui@1.0.0/dist/umd/index.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K..." crossorigin="anonymous"></script>

Content Security Policy (CSP) compatibility:

SRI works seamlessly with CSP. For strict CSP configurations, combine SRI with the nonce attribute:

<descope-wc project-id="myProjectId" flow-id="sign-up-or-in" nonce="random-nonce-value"></descope-wc>

CSP header example:

Content-Security-Policy:
  script-src 'self'
    https://descopecdn.com
    https://static.descope.com
    https://cdn.jsdelivr.net
    'nonce-random-nonce-value';

Backward compatibility:

If the SRI hash is not available in the configuration (older projects), the component will load normally without integrity checks. No breaking changes required.

Optional Attributes

Attribute Available options Default value
base-url Custom Descope base URL ""
theme "light" - Light theme
"dark" - Dark theme
"os" - Auto select a theme based on the OS theme settings
"light"
debug "true" - Enable debugger
"false" - Disable debugger
"false"
preview "true" - Run flow in a preview mode
"false" - Do run flow in a preview mode
"false"
auto-focus "true" - Automatically focus on the first input of each screen
"false" - Do not automatically focus on screen's inputs
"skipFirstScreen" - Automatically focus on the first input of each screen, except first screen
"true"
validate-on-blur "true" - Triggers the input validation upon blur in addition to the validation on submit
"false" - Do not triggers validation upon blur
"false"
restart-on-error "true" - In case of flow version mismatch, will restart the flow if the components version was not changed
"false" - Do not restart the flow automatically
"false"
send-session-token "true" - Send the current session JWT on flow start/next requests, exposing its validated claims to the flow via the sessionJwtClaims context key
"false" - Do not send the session JWT
"false"
storage-prefix String - A prefix to add to the key of the local storage when persisting tokens ""
store-last-authenticated-user "true" - Stores last-authenticated user details in local storage when flow is completed
"false" - Do not store last-auth user details. Disabling this flag may cause last-authenticated user features to not function properly
"true"
keep-last-authenticated-user-after-logout "true" - Do not clear the last authenticated user details from the browser storage after logout
"false" - Clear the last authenticated user details from the browser storage after logout
"false"
style-id "String" - Set a specific style to load rather then the default style ""
nonce "String" - Set a CSP nonce that will be used for style and script tags. Works with SRI for enhanced security ""
popup-origin "String" - Sets the expected origin for OAuth popup communication when redirect URL is on different origin than the main application. Required for cross-origin OAuth popup flows ""
dismiss-screen-error-on-input "true" - Clear screen error message on user input
"false" - Do not clear screen error message on user input
"false"
outbound-app-id "String" - Outbound application ID to use for connecting to external services ""
outbound-app-scopes "String[]" - JSON array of scopes to request from the outbound application (e.g., '["email", "profile"]') null

Optional Properties

errorTransformer - A function that receives an error object and returns a string. The returned string will be displayed to the user.

The function can be used to translate error messages to the user's language or to change the error message.

Usage example:

function translateError(error) {
  const translationMap = {
    SAMLStartFailed: 'No es posible iniciar sesión en este momento, por favor intenta nuevamente más tarde',
  };
  return translationMap[error.type] || error.text;
}

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];

descopeWcEle.errorTransformer = translateError;
logger - An object that defines how to log error, warning and info. Defaults to console.error, console.warn and console.info respectively

Usage example:

const logger = {
  info: (message: string, description: string, state: any) => {
    console.log(message, description);
  },
  warn: (title: string, description: string) => {
    console.warn(`WARN: ${title}`, description);
  },
  error: (title: string, description: string) => {
    console.error(`ERROR: ${title}`, description);
  },
};

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];

descopeWcEle.logger = logger;
onScreenUpdate

A function that is called whenever there is a new screen state and after every next call. It receives the following parameters:

  • screenName: The name of the screen that is about to be rendered
  • context: An object containing the upcoming screen state
  • next: A function that, when called, continues the flow execution
  • ref: A reference to the descope-wc node

The function can be sync or async, and should return a boolean indicating whether a custom screen should be rendered:

  • true: Render a custom screen
  • false: Render the default flow screen

Breaking change (v4.0.0): server-produced screen data that used to sit directly on context now lives under context.data — e.g. context.totp → context.data.totp, context.inboundAppApproveScopes → context.data.inboundAppApproveScopes. Status, form, and identity fields (user / project / lastAuth) stay at the top level. See The context object below for the full list of context.data fields.

This function allows rendering custom screens instead of the default flow screens. It can be useful for highly customized UIs or specific logic not covered by the default screens

To render a custom screen, its elements should be appended as children of the descope-wc component

Usage example:

function onScreenUpdate(screenName, context, next, ref) {
  if (screenName === 'My Custom Screen') {
    ref.innerHTML = `
          <form>
            <input type="text" name="email" placeholder="Email" />
            <button type="submit">Submit</button>
          </form>
        `;

    ref.closest('form').addEventListener('submit', (e) => {
      e.preventDefault();
      const formData = new FormData(e.target);
      const data = Object.fromEntries(formData.entries());

      // replace with the button interaction id
      next('interactionId', data);
    });

    return true;
  }

  return false;
}

const descopeWcEle = document.querySelector('descope-wc');

descopeWcEle.onScreenUpdate = onScreenUpdate;
The context object

context carries the upcoming screen's state:

  • Top level — error, action, form (the input/output channel), and the acting user's context: user, project, lastAuth.
  • context.data — all server-produced screen data, in one clean, stable place, so you don't have to read internal, deeply-nested paths.

For example, a screen that generates MFA recovery codes exposes them as a plain array:

function onScreenUpdate(screenName, context, next, ref) {
  if (screenName === 'Display recovery codes') {
    const codes = context.data.recoveryCodes; // string[]
    // render the codes in your custom UI…
    return true;
  }
  return false;
}

context.data may include (each present only when the screen produces it):

  • recoveryCodes — generated MFA recovery codes (string[])
  • totp / notp — MFA setup (image, provisioning/redirect URL)
  • sentTo — where an OTP/code was sent (masked email/phone)
  • inboundAppApproveScopes — scopes an inbound app is asking the user to approve
  • passwordPolicy — password rules to show/enforce
  • securityQuestionsSetup / securityQuestionsVerify — security questions
  • userTenants, userRoles, ssoApplications, ssoConfigurations — selection options
  • samlAttributeMappings, oidcAttributeMappings, samlGroupMappings — SSO mappings
  • sso — SSO service-provider config
  • selfProvisionDomains — tenant self-provision domains
  • outboundApp — outbound OAuth app button info

context.data is a supported, stable field owned by the SDK — prefer it over reading raw screen-state internals. It exposes only the documented fields above; any other internal screen-state data is intentionally omitted. New fields are added in SDK releases.

Every key on context.data is an SDK-owned, documented name. The SDK never puts arbitrary, flow-defined keys directly on context.data, so new fields are always added without breaking existing ones.

Not exposed yet: dynamic-select options (a select component whose options are computed by the flow). Their keys are the flow's own field names, so they don't fit the fixed shape above; they are omitted for now and reserved for a future context.data.selects map. This data was not available to custom screens before, so nothing changes for existing code.

Breaking change (v4.0.0): screen-data fields that used to sit directly on context now live under context.data. Migrate reads accordingly, e.g. context.inboundAppApproveScopes → context.data.inboundAppApproveScopes, context.totp → context.data.totp. Status, form, and identity fields (user/project/lastAuth) stay at the top level.

Events

error - Fired when an error occurs. The event detail contains the error object.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('error', (e) => alert(`Error! - ${e.detail.errorMessage}`));
success - Fired when the flow is completed successfully. The event detail contains the flow result.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('success', (e) => alert(`Success! - ${JSON.stringify(e.detail)}`));
ready - Fired when the page is ready.

This event is useful for showing/hiding a loading indication before the page is loading. Note: in cases where the flow involves redirection to a non-initial stage of the process, such as with Magic Link or OAuth, this event is also dispatched.

Usage example:

const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.addEventListener('ready', () => {
  // Remove/hide the loading indication
});