# Embeddable View

Nected introduces a powerful framework for embedding users and providing pre-signed authentication. These features offer seamless integration and secure access control mechanisms, empowering organizations to embed Nected’s UI components and enable direct sign-ins with pre-signed URLs.

### Overview Flow of Embedded Users

Below is the overview on how to generate pre-signed urls to embed rules and workflows within another product.

<figure><img src="https://4290782554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLg716fCfV8IUwXQygkTG%2Fuploads%2FBOZjme7PUg0sMHv3NTcY%2Fembeddable_users.png?alt=media&#x26;token=b732d7df-8472-47b5-8da5-2c725a50277e" alt=""><figcaption></figcaption></figure>

To integrate **Embedded Users Flow** with the **Embedded View**, here's how you can access and manage it for these users:

### **Add Users To Enable Embeddable Flow**

1. **Navigate to Workspace Settings**:
   * Go to the **Workspace** section in the Nected platform.
   * Click on the **Embedded Users** tab under the Workspace menu.
2. **Add Embedded Users**:
   * Input the email address of the user in the **"Add user by email"** field.
   * Assign a role using the **Select Role** dropdown menu.
   * Click **Add User** to grant access.

Read more: [inviting-a-team-member-to-your-workspace](https://docs.nected.ai/nected-docs/account-settings/inviting-a-team-member-to-your-workspace "mention")

### **Generate an Embeddable Signed URL for Users**:

For each user added, you can provide access to **Embedded Views** through the pre-signed authentication URL.

1. Generate the **Pre-signed Token** using the provided API.

   **Endpoint:** `(<https://api.nected.ai/dev/signed-token?email=>)<member-email>`

   **HTTP Method:** GET

   **Authentication Parameters:**

| Parameter        | Type   | Required | Description                                  |
| ---------------- | ------ | -------- | -------------------------------------------- |
| `email`          | String | Yes      | User's email address for token generation    |
| `nected-api-key` | String | Yes      | Organization's unique API authentication key |

{% hint style="info" %}
Access the Postman workspace: [Nected Public Workspace](https://www.postman.com/tech-team-1209/nected-public-workspace/folder/bir61tc/embed-rules-wf-white-labelling). Locate the collection under "Embed Rules and Workflow White-labeling." Utilize provided APIs to fetch UI component configurations
{% endhint %}

#### Example Authentication Request

```bash
curl --location '<https://api.nected.ai/dev/signed-token?email=%3CEMAIL_ID%3E>' \\
--header 'nected-api-key: {{NECTED_API_KEY}}'
```

2\. Response Structure

When successfully executed, the API returns a comprehensive JSON response containing the pre-signed authentication token:

```json
{
  "data": {
    "signedURL": "<https://app.nected.ai/signed-url/><<PreSigned-Token>>=?redirect="
  },
  "code": "success",
  "message": "success."
}

```

3. Nected's pre-signed authentication supports targeted redirections, allowing administrators to guide users directly to specific platform sections:

| Redirect Path | Destination Resource             |
| ------------- | -------------------------------- |
| `/rules`      | Rule Management Interface        |
| `/workflow`   | Workflow Configuration Dashboard |

Example Rule Url:

```bash

<https://app.nected.ai/signed-url/><PreSigned-Token>?redirect=/rules
```

{% hint style="warning" %}
The generated pre-signed authentication URL is **valid for 5 minutes** from the time of issuance. This expiry window applies to the **entire signed URL**, including the embedded authentication token.
{% endhint %}

#### How to Regenerate the Pre-Signed URL?

To regain access after expiration, you must **generate a new pre-signed URL** by calling the same token-generation API again.

**Steps:**

1. Call the `GET /dev/signed-token` endpoint with the user’s email.
2. Pass a valid `nected-api-key` in the request header.
3. Use the newly returned `signedURL` immediately (within 5 minutes).

**Best-practice recommendations:**

* Generate the pre-signed URL **just-in-time**, right before redirecting or embedding the user.
* Do not cache or persist pre-signed URLs.
* For long-lived sessions or repeated access, always regenerate a fresh URL per session or access attempt.

This approach maintains strict security while allowing controlled, time-bound access to embedded Nected views.

### Embed Rule or Workflow listing UI inside your product via iframe

Embed Workflow Example

```html

<iframe
  src="<https://app.nected.ai/embed/><PreSigned-Token>?redirect=/workflow"
  width="100%"
  height="600"
  frameborder="0"
  allowfullscreen
></iframe>

```

{% hint style="info" %}
Embedding via iframe is currently feasible for self-hosted deployments to avoid cross-domain issues. In Saas deployments, custom domains are not present thus preventing option to embedd UI due to cross-domain issue.
{% endhint %}

### Hiding Features for Embedded Users

In on-prem deployments, admins can choose to **hide specific UI elements** from embedded users’ dashboards. The following can be disabled:

1. **Custom Attribute button**
2. **Dependency Mapping**
3. **Version Control**
4. **API Settings**

To configure this, update the following fields inside your `konark.env` file:

```
VITE_EMB_HIDE_DU_HELP_SETTINGS=true
VITE_EMB_HIDE_VC=false
VITE_EMB_HIDE_CI=true
```

***

### Embedded Logout (NEC\_EMBED\_LOGOUT)

This feature allows a parent application to programmatically sign out an embedded Nected session. It uses the browser’s `postMessage` API to communicate between the parent window and the embedded Nected iframe.

The parent application initiates the logout process. The embedded Nected application terminates the session, clears all authentication tokens, and responds with a confirmation event.

#### How does Embedded Logout work?

When Nected runs inside an iframe:

1. The parent application sends a logout request using `postMessage`.
2. The embedded Nected app receives the request and triggers its logout flow.
3. Nected invalidates the active session through the logout API.
4. The app clears stored credentials and user metadata.
5. The app sends a confirmation message back to the parent.
6. After completing the logout flow, the embedded app redirects the iframe to `/signin`.

This mechanism ensures the parent application stays in control of the embedded user’s lifecycle.

#### Parent Application Integration

Below is the standard pattern for triggering logout in the host application.

**Sending the Logout Command**

```javascript
// Reference to the Nected iframe
const nectedIframe = document.getElementById('nected-iframe');

// Trigger logout in the embedded Nected application
nectedIframe.contentWindow.postMessage(
  {
    type: 'NEC_EMBED_LOGOUT'
  },
  '*'
);
```

**Receiving Logout Confirmation**

```javascript
// Listen for confirmation from Nected
window.addEventListener('message', (event) => {
  if (event.data?.type === 'NEC_EMBED_LOGGED_OUT') {
    console.log('Nected app logout completed');
    // Add any additional cleanup logic here
  }
});
```

#### Example Implementation

```html
<!DOCTYPE html>
<html>
<head>
  <title>Parent Application</title>
</head>
<body>
  <iframe
    id="nected-iframe"
    src="https://your-nected-instance.com"
    width="100%"
    height="800px">
  </iframe>

  <button id="logout-btn">Logout from Nected</button>

  <script>
    const iframe = document.getElementById('nected-iframe');
    const logoutBtn = document.getElementById('logout-btn');

    // Trigger logout in embedded Nected app
    logoutBtn.addEventListener('click', () => {
      iframe.contentWindow.postMessage({
        type: 'NEC_EMBED_LOGOUT'
      }, '*');
    });

    // Handle logout confirmation
    window.addEventListener('message', (event) => {
      if (event.data?.type === 'NEC_EMBED_LOGGED_OUT') {
        console.log('User logged out from Nected app');
        alert('Logout successful!');
        // Redirect or show login screen in the parent app
      }
    });
  </script>
</body>
</html>
```

#### Message Events

| Direction       | Event Name             | Description                                         |
| --------------- | ---------------------- | --------------------------------------------------- |
| Parent → Nected | `NEC_EMBED_LOGOUT`     | Requests the embedded Nected application to log out |
| Nected → Parent | `NEC_EMBED_LOGGED_OUT` | Confirms that logout has completed successfully     |

#### Important Behavior

* **Iframe-Only**: Logout events apply exclusively to iframe-embedded sessions.
* **Open Origin Policy**: The parent sends messages with `'*'` as the target origin. This enables communication across any domain.
* **Automatic Redirection**: After logout, Nected redirects the iframe to `/signin`.
* **Session Termination**: All tokens are removed, and the signer state resets.

#### Security Considerations

The parent application controls when logout occurs, so it must enforce its own checks before sending the logout command.

Recommended safeguards:

* Validate the origin of confirmation messages before acting on them.
* Restrict which components in your parent app can trigger logout.
* For sensitive integrations, add an origin-verification layer around message handling.
* Review your internal session rules and align them with the embedded logout flow.

***

### Error Handling and Response Codes

#### Comprehensive Error Classification

The pre-signed authentication API implements a robust error management strategy, providing clear, actionable feedback across various potential failure scenarios:

| HTTP Status | Error Identifier           | Description                                   | Recommended Action                                                   |
| ----------- | -------------------------- | --------------------------------------------- | -------------------------------------------------------------------- |
| 401         | `UNAUTHORIZED`             | Invalid or expired API credentials            | Verify API key and regenerate if necessary                           |
| 500         | `INTERNAL_SERVER_ERROR`    | Unexpected system malfunction                 | Contact Nected technical support                                     |
| 429         | `TOO_MANY_REQUESTS`        | Authentication request quota exceeded         | Implement exponential backoff strategy                               |
| 413         | `REQUEST_ENTITY_TOO_LARGE` | Malformed authentication request              | Validate request parameters and ensure payload size is within limits |
| 400         | `BAD_REQUEST`              | Malformed authentication request              | Validate request parameters                                          |
|             | `INVALID_SIGNED_TOKEN`     | Triggered when the signed token has expired.  | Admin must regenerate a new signed token.                            |
|             | `REGENERATE_SIGNED_TOKEN`  | Triggered when the refresh token has expired. | Admin must regenerate the signed token again in this case.           |

### Best Practices and Recommendations

1. Implement strict API key rotation policies
2. Utilize HTTPS for all API interactions
3. Generate pre-signed URLs dynamically and close to the point of use
4. Establish clear access governance policies
5. Regularly audit user access and permissions

### Support and Additional Resources

For advanced implementation guidance, architectural consultations, or technical support, please get in touch with Nected's dedicated support team at <assist@nected.ai>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nected.ai/nected-docs/embedded-system/embeddable-view.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
