npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cobo/cobo-ui-toolkit

v1.0.9

Published

## Components Demo and Documentation

Downloads

143

Readme

@cobo/cobo-ui-toolkit

Components Demo and Documentation

You can explore the live demo and documentation for @cobo/cobo-ui-toolkit at:

https://cobo-ui-toolkit.demo.apps.sandbox.cobo.com/index.html

Installation

To use @cobo/cobo-ui-toolkit in your project, you first need to install it via npm. You can do this by running the following command:

npm install @cobo/cobo-ui-toolkit

MFA Integration Documentation for @cobo/cobo-ui-toolkit

This document provides a guide on how to integrate Multi-Factor Authentication (MFA) into your application using the @cobo/cobo-ui-toolkit.

The useMFA hook is designed to manage Multi-Factor Authentication (MFA) methods in your application. It allows you to send MFA methods and retrieve a unique request ID upon successful processing.

API

const { sendMfaMethods } = useMFA();

sendMfaMethods(mfaMethods: MfaListItem[])

  • Parameters

    • mfaMethods: An array of objects, each representing an MFA method. Each object should have the following structure:
      {
        mfaMethod: string; // e.g., "google_auth", "cobo_guard", "security_key"
        mfaStatus: string; // e.g., "Active", "Inactive"
      }
  • Returns: A Promise that resolves with a unique request ID when the MFA methods have been successfully sent.

Usage Example

import React, { useEffect } from 'react';
import { useMFA } from './path/to/useMFA';

const MyComponent = () => {
  const sendMfaMethods = useMFA();

  const testMFA = async () => {
    const mfaMethods = [
      {
        mfaMethod: "google_auth",
        mfaStatus: "Active",
      },
      {
        mfaMethod: "cobo_guard",
        mfaStatus: "Active",
      },
      {
        mfaMethod: "security_key",
        mfaStatus: "Active",
      },
    ];
    try {
      const requestId = await sendMfaMethods(mfaMethods);
      console.log('Request ID:', requestId);
      // You can now send the requestId to your server or handle it as needed
    } catch (error) {
      console.error('Error sending MFA methods:', error);
    }
  };

  useEffect(() => {
    testMFA();
  }, []);

  return <div>Check console for request ID.</div>;
};

export default MyComponent;

Explanation of the Example

  1. Import the Hook: The useMFA hook is imported into the component.

  2. Define MFA Methods: An array of MFA methods is defined. Each method includes a type and its status.

  3. Send MFA Methods: The sendMfaMethods function is called with the defined methods. The function is awaited to handle the asynchronous nature of sending data.

  4. Handling Response: Upon successful sending, the request ID is logged to the console. In case of an error, it's caught and logged.

  5. Use Effect Hook: The testMFA function is invoked when the component mounts, triggering the process to send MFA methods.

This example provides a clear way to implement and test the useMFA hook within a React component. Adjust the path for the import statement as needed for your project structure.

2.Tracking Script Hooks

2.1 useTrackingScript

This hook dynamically loads a tracking script based on the environment and product line. It uses useEffect to inject a script into the DOM and cleans it up when the component unmounts.

参数

Tracking Script Hooks

useTrackingScript

This hook dynamically loads a tracking script based on the environment and product line. It uses useEffect to inject a script into the DOM and cleans it up when the component unmounts.

Parameters

  • env: ('sandbox' | 'production')

    • Defines the environment for the script.
    • sandbox: Load the script in a sandbox environment.
    • production: Load the script in the production environment.
  • productLine: ('app' | 'portal') (default: 'app')

    • Specifies the product line for the script.
    • app: Default product line.
    • portal: Portal product line.

Usage Example

import React from 'react';
import { useTrackingScript } from '@cobo/cobo-ui-toolkit';

const MyApp = () => {
  useTrackingScript('sandbox', 'app');
  return <h1>Hello world</h1>;
};

export default MyApp;

2.2 useAddUidToBody

This hook converts the specified uid to Base64 format and adds it as a uid attribute to the <body> tag of the HTML document. Whenever the uid changes, the uid attribute in the <body> tag will be updated.

Parameters

  • uid: string
    • The user ID to be added to the <body> tag, must be a string.
    • If uid is empty, the hook will not perform any action.

Behavior

  • When the uid changes, useEffect encodes the uid into Base64 format and adds it as a uid attribute to the <body> tag.
  • If the uid is an empty string or invalid value, the hook skips any operations.

Base64 Encoding Example

  • If the provided uid is 'user123', the hook will generate dXNlcjEyMw== and add it as a uid attribute to the <body>.

Use Case

This hook is suitable for scenarios where a user ID or other unique identifier needs to be applied to the document structure or globally tracked.


import React from 'react';
import { useAddUidToBody } from '@cobo/cobo-ui-toolkit';

const UserProfile = () => {
  const userId = 'user123';

  // 将用户 ID 添加到 body 标签
  useAddUidToBody(userId);

  return (
    <div>
      <h1>Hello,user {userId}</h1>
    </div>
  );
};

export default UserProfile;

3 getAuthInfo

This is an asynchronous function used to retrieve user authentication information from the Portal. It sends a request to get authentication details using the postMessage method, returning an object that includes the user's token, orgID, and optionally userID.

Type Definition

AuthInfo

type AuthInfo = {
  token: string; // User authentication token
  orgID: string; // Organization ID
  userID?: string; // Optional user ID
};

Return Value

The function returns an object of type AuthInfo, which includes:

  • token: User authentication token.
  • orgID: User's organization ID.
  • userID: Optional user ID.
  • May also include an optional action property, indicating the current operation type.

Error Handling

  • If the authentication information is unavailable or the request fails, the function returns undefined.

Behavior Description

  • getAuthInfo sends a request to the Portal using the _appPostActionToPortal function to retrieve the user's authentication information.
  • The request includes the action type getAuthInfo and is executed only once (once: true).
  • If the request is successful, the returned authInfo object will contain the authentication data and be assigned to event.data.
import React, { useEffect, useState } from 'react';
import { getAuthInfo } from '@cobo/cobo-ui-toolkit';

const UserProfile = () => {
  const [authInfo, setAuthInfo] = useState<AuthInfo | undefined>(undefined);

  useEffect(() => {
    const fetchAuthInfo = async () => {
      const info = await getAuthInfo();
      setAuthInfo(info);
    };

    fetchAuthInfo();
  }, []);

  if (!authInfo) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>User Information</h1>
      <p>Token: {authInfo.token}</p>
      <p>Organization ID: {authInfo.orgID}</p>
      {authInfo.userID && <p>User ID: {authInfo.userID}</p>}
    </div>
  );
};

export default UserProfile;

4 JWT-Related Functions

4.1 parseJwtToken

This function is used to parse a JWT (JSON Web Token) and return the payload as a JSON object. If the token format is invalid or parsing fails, the function throws an error.

Parameters

  • token: string
    The JWT string to be parsed. JWT typically consists of three parts in the format: header.payload.signature.

Return Value

If the token is a valid JWT, the function returns the payload (the second part) as a JSON object.

Error Handling

If the token format is incorrect or cannot be parsed, the function throws an error with messages such as:

  • Invalid Base64 encoding: This error is thrown when the payload part of the token is not properly Base64 encoded.
  • Invalid token format: This error is thrown when there is an issue parsing the token (e.g., incorrect structure or failure to decode).

Behavior Description

  1. The function first extracts the second part of the JWT (payload) using token.split('.')[1].
  2. It checks if the extracted Base64 string is empty or contains invalid characters. If so, it throws an Invalid Base64 encoding error.
  3. The Base64 URL encoding is converted to standard Base64 encoding (replacing - with + and _ with /).
  4. The atob function is used to decode the Base64 string, then each character is converted to its corresponding percent-encoded value.
  5. The percent-encoded string is then decoded using decodeURIComponent, and the result is parsed into a JSON object using JSON.parse.
  6. If any step fails, the function throws an Invalid token format error.

Use Cases

  • This function is used to parse JWT tokens obtained from a server in order to extract user information, permissions, or other related data.
  • In authentication and authorization scenarios, it can be used to effectively decode and verify JWT tokens.

Example Usage

import { parseJwtToken } from '@cobo/cobo-ui-toolkit';

const token =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

try {
  const payload = parseJwtToken(token);
  console.log(payload);
  // Output: { sub: "1234567890", name: "John Doe", iat: 1516239022 }
} catch (error) {
  console.error(error.message);
}

4.2 verifyJwtToken

This function is used to verify a JWT (JSON Web Token), ensuring the validity of the token using a given set of public keys. It decodes the JWT and uses cryptographic APIs to verify the token's signature.

Parameters

  • token: string
    The JWT to be verified, in the format header.payload.signature.
  • publicKeySet: any
    A set of public keys used to verify the JWT signature. Each public key should have a kid attribute, which matches the kid in the JWT header.

Return Value

  • true: If the JWT verification is successful, the function returns true, indicating that the token is valid.

Error Handling

  • JWT token format is incorrect: This error is thrown when the token does not contain the three parts: header, payload, or signature.
  • Cannot find a suitable public key: This error is thrown when the corresponding public key cannot be found based on the kid in the JWT header.
  • Unable to parse JWT Token: This error is thrown when the token cannot be decoded or parsed.
  • JWT Token verification failed: This error is thrown when the token's signature verification fails.
  • Error occurred while parsing or verifying JWT Token: {error.message}: Any other errors are caught and formatted in this manner, and the error message is thrown.

Use Cases

  • JWT Verification: Use this function in scenarios where JWT signatures need to be verified, ensuring that the token has not been tampered with and is valid.
  • Authentication: This function can be used in user login processes, API calls, or sensitive operations to validate the legitimacy and security of the request.

Example Usage

import { parseJwtToken, verifyJwtToken } from '@cobo/cobo-ui-toolkit';

get('https://api.sandbox.cobo.com/web/v2/oauth/authorize/jwks.json').then(async (res) => {
  const verified = await verifyJwtToken(token, res);
  if (!verified) return;
  const jwtInfo = parseJwtToken(token);
  setUserInfo({
    email: jwtInfo.email,
    roleNames: jwtInfo.role_names,
    roles: jwtInfo.roles,
    sub: jwtInfo.sub,
  });
});

5 getPortalLocale

The getPortalLocale function retrieves the current locale from the portal and executes a callback with the locale data. It uses a post action to communicate with the portal.

API

getPortalLocale(callback: (data: Locale) => void): void

  • Parameters

    • callback: A function that takes a Locale object as an argument. This function will be executed with the locale data received from the portal.
  • Returns: This function does not return a value.

removeGetLocaleListener

  • Functionality: Removes the listener for the locale retrieval action.

Locale Type

The Locale type defines the structure of the locale data:

  • locale: A string that can be either 'en-US' or 'zh-CN'.

Usage Example

To use the getPortalLocale function within a React component, you can do the following:

  1. Import the function into your component.
  2. Call getPortalLocale inside a useEffect hook to fetch the locale when the component mounts.

Example:

useEffect(() => {
  getPortalLocale((locale) => {
    console.log("locale", locale);
  });
}, []);

Error Handling

If the locale data is undefined, an error message will be logged to the console: "Failed to get locale: data is undefined".

Notes

  • Ensure that the portal is set up to respond to the GET_LOCALE action.
  • Use removeGetLocaleListener to clean up the listener when it's no longer needed, especially in components that may unmount.

This documentation provides a clear guide on how to implement and use the getPortalLocale function in your application.