> For the complete documentation index, see [llms.txt](https://docs.sudoplatform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sudoplatform.com/guides/digital-account-protection/manage-virtual-presences.md).

# Manage Virtual Presences

A virtual presence represents a connected user identity on an external platform (e.g., an email account).

### Connecting a Virtual Presence <a href="#connecting-a-virtual-presence" id="connecting-a-virtual-presence"></a>

In order for the Privacy Interaction Service to scan a user's virtual presence, the user must grant the service access via OAuth 2.0. Your application obtains an OAuth credential from the provider and passes it to the SDK, which transmits it securely to the Privacy Interaction Service backend. The service then uses this credential to periodically access the connected account and discover data holders.

The SDK accepts credentials in one of two forms:

* **Authorization code** — A short-lived code obtained when the user completes the OAuth consent flow in your application. The Privacy Interaction Service exchanges this code server-side for an access token and refresh token, which it stores securely and uses for ongoing access.
* **Refresh token** — A long-lived credential your application has already obtained from a prior OAuth flow. Providing a refresh token directly allows the service to begin scanning without needing to perform the initial code exchange. This is useful when your application manages its own OAuth flow and already holds the user's credentials.

In both cases, the service uses the credential to obtain short-lived access tokens as needed. If the credential expires or is revoked by the user, the virtual presence transitions to the `NEEDS_REAUTH` state and your application should prompt the user to re-authenticate.

The required OAuth scopes and what data the service accesses depend on the virtual presence type. See [Supported Virtual Presence Types](#supported-virtual-presence-types) for details.

**Connect behavior**

* Provide exactly one credential: an authorization code or a refresh token. Supplying both, neither, or an empty value fails.
* Connecting an identity that is already connected for the same user reconnects the existing virtual presence rather than creating a second one. The credential is replaced, the virtual presence returns to `CONNECTED`, and no additional virtual presence entitlement is consumed. This is how a virtual presence in `NEEDS_REAUTH` is recovered.
* If `expiresAtEpochMs` is omitted when connecting with a refresh token, the service assumes the token is valid for one year.
* The returned virtual presence is in the `CONNECTED` state. The discovery scan starts asynchronously; follow its progress with a virtual presence subscription.

#### Connect with Authorization Code <a href="#connect-with-authorization-code" id="connect-with-authorization-code"></a>

Use this method when your application has completed an OAuth flow and received an authorization code from the provider. The authorization code has enough information embedded to sufficiently identify the virtual presence. If you specified a redirect uri when connecting, provide it in this call as well. Note that some OAuth connection protocols do not require the provision of a redirect uri, which is why it is optional. You may optionally specify the provider to use to connect. If not provided, the default is gmail.

{% tabs %}
{% tab title="Typescript" %}

```typescript
const input = {
    authCode = 'auth-code',
    redirectUri = 'https://provided-redirect-uri', // optional
    relationshipProvider = RelationshipProvider.GmailProvider, // optional
}
try {
  const virtualPresence = await privacyInteractionClient.connectVirtualPresenceWithAuthCode(
    input,
  )
  // The virtual presence is now connected.
  // `virtualPresence.state` will be `CONNECTED` or `SCANNING`.
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
let input = ConnectVirtualPresenceWithAuthCodeInput(
    authCode: "auth-code",
    redirectUri: "https://provided-redirect-uri", // optional
    relationshipProvider: .gmailProvider // optional
)
do {
    let virtualPresence = try await privacyInteractionClient.connectVirtualPresenceWithAuthCode(withInput: input)
    // The virtual presence is now connected.
    // `virtualPresence.state` will be `.connected` or `.scanning`.
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val input = ConnectVirtualPresenceWithAuthCodeInput(
    authCode = "auth-code",
    redirectUri = "https://provided-redirect-uri",
    relationshipProvider = RelationshipProvider.GMAIL_PROVIDER,
)
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.connectVirtualPresenceWithAuthCode(input)
        }
        // The virtual presence is now connected.
        // `virtualPresence.state` will be CONNECTED or SCANNING.
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

#### Connect with Refresh Token <a href="#connect-with-refresh-token" id="connect-with-refresh-token"></a>

Use this method when your application already holds a valid refresh token for the provider. You may optionally specify the provider to use to connect. If not provided, the default is gmail.

{% tabs %}
{% tab title="Typescript" %}

```typescript
try {
  const virtualPresence = await privacyInteractionClient.connectVirtualPresenceWithRefreshToken({
    refreshToken: 'refresh-token-value',
    providerIdentity: 'user@example.com',
    scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
    expiresAtEpochMs: 1826088953000, // optional,
    relationshipProvider = RelationshipProvider.GmailProvider, // optional
  })
  // The virtual presence is now connected.
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
let input = ConnectVirtualPresenceWithRefreshTokenInput(
    refreshToken: "refresh-token-value",
    providerIdentity: "user@example.com",
    scopes: ["https://www.googleapis.com/auth/gmail.readonly"],
    expiresAt: Date(timeIntervalSince1970: 1_700_000_000), // optional
    relationshipProvider: .gmailProvider // optional
)
do {
    let virtualPresence = try await privacyInteractionClient.connectVirtualPresenceWithRefreshToken(withInput: input)
    // The virtual presence is now connected.
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
val input = ConnectVirtualPresenceWithRefreshTokenInput(
    refreshToken = "refresh-token-value",
    providerIdentity = "user@example.com",
    scopes = listOf("https://www.googleapis.com/auth/gmail.readonly"),
    expiresAtEpochMs = 1826088953000,
    relationshipProvider = RelationshipProvider.GMAIL_PROVIDER,
)
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.connectVirtualPresenceWithRefreshToken(input)
        }
        // The virtual presence is now connected.
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

**Input Parameters:**

<table><thead><tr><th width="198.09765625">Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td><code>refreshToken</code></td><td>string</td><td>Yes</td><td>The refresh token value.</td></tr><tr><td><code>providerIdentity</code></td><td>string</td><td>Yes</td><td>The identity associated with the provider (e.g., email address).</td></tr><tr><td><code>scopes</code></td><td>string[]</td><td>No</td><td>OAuth scopes associated with the token.</td></tr><tr><td><code>expiresInEpochMs</code></td><td>number</td><td>No</td><td>Token expiration time in milliseconds since epoch.</td></tr><tr><td><code>relationshipProvider</code></td><td>enum</td><td>No</td><td>The provider to use to connect the virtual presence. Defaults to gmail if not provided.</td></tr></tbody></table>

### Disconnecting a Virtual Presence <a href="#disconnecting-a-virtual-presence" id="disconnecting-a-virtual-presence"></a>

To disconnect a virtual presence and stop it from being scanned, call `disconnectVirtualPresence` with the virtual presence's unique identifier.

When a virtual presence is disconnected, it will be removed from the system. Any tokens, existing data holders and analysis results associated with the virtual presence will be removed.

{% tabs %}
{% tab title="Typescript" %}

```typescript
try {
  const virtualPresence = await privacyInteractionClient.disconnectVirtualPresence(
    virtualPresenceId,
  )
  // The returned virtual presence is in INACTIVE state and will be disconnected and 
  // cleaned up.
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let virtualPresence = try await privacyInteractionClient.disconnectVirtualPresence(withId: virtualPresenceId)
    // The returned virtual presence is in `.inactive` state and will be
    // disconnected and cleaned up.
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.disconnectVirtualPresence(virtualPresenceId)
        }
        // The returned virtual presence is in INACTIVE state and will be
        // disconnected and cleaned up.
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

### Listing Virtual Presences <a href="#listing-virtual-presences" id="listing-virtual-presences"></a>

To retrieve all virtual presences for the signed-in user, use the `listVirtualPresences` method. Results are paginated.

A call to `listVirtualPresences` returns a `ListOutput` object containing a list of matching `items` and a `nextToken` to support pagination. If no results are found, the result will contain empty items. Always check the value of the returned `nextToken`—there are no more results to retrieve when `nextToken` is undefined.

{% tabs %}
{% tab title="Typescript" %}

```typescript
try {
  const listOutput = await privacyInteractionClient.listVirtualPresences({
    limit: 20,
    nextToken: undefined,
  })
  // `listOutput.items` contains the virtual presences.
  // Page through results if `listOutput.nextToken` is defined.
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let listOutput = try await privacyInteractionClient.listVirtualPresences(
        withInput: ListVirtualPresencesInput(limit: 20, nextToken: nil)
    )
    // `listOutput.items` contains the virtual presences.
    // Page through results while `listOutput.nextToken` is not nil.
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

<pre class="language-kt"><code class="lang-kt"><strong>launch {
</strong>    try {
        val listOutput = withContext(Dispatchers.IO) 
            privacyInteractionClient.listVirtualPresences(
                ListVirtualPresencesInput(limit = 20, nextToken = null),
            )
        }
        // `listOutput.items` contains the virtual presences.
        // Page through results while `listOutput.nextToken` is not null.
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
</code></pre>

{% endtab %}
{% endtabs %}

**Input Parameters:**

| Parameter   | Type   | Required | Description                                                      |
| ----------- | ------ | -------- | ---------------------------------------------------------------- |
| `limit`     | number | No       | Maximum number of items to return. Will be defaulted if omitted. |
| `nextToken` | string | No       | A pagination token from a previous call.                         |

### Virtual Presence States <a href="#virtual-presence-states" id="virtual-presence-states"></a>

A virtual presence transitions through the following states:

| State          | Description                                                                                                                                                                                                                        |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CONNECTED`    | The virtual presence is active and connected to the provider.                                                                                                                                                                      |
| `SCANNING`     | The virtual presence is currently being scanned for data holders.                                                                                                                                                                  |
| `NEEDS_REAUTH` | The virtual presence requires re-authentication with the provider. This will happen automatically when the refresh token expires, or when the user explicitly disconnects the Privacy Interaction application from their provider. |
| `ERROR`        | The virtual presence encountered an error and is in a failed state.                                                                                                                                                                |
| `INACTIVE`     | The virtual presence has been disconnected and is no longer active. This is a short-lived state between disconnection and deletion completing.                                                                                     |

When a virtual presence enters the `NEEDS_REAUTH` state, your application should prompt the user to re-authenticate with the provider and call `connectVirtualPresenceWithAuthCode` or `connectVirtualPresenceWithRefreshToken` again.

### Supported Virtual Presence Types <a href="#supported-virtual-presence-types" id="supported-virtual-presence-types"></a>

#### Gmail Inbox <a href="#gmail-inbox" id="gmail-inbox"></a>

| Property             | Value                                             |
| -------------------- | ------------------------------------------------- |
| Provider type        | `EMAIL`                                           |
| Required OAuth scope | `https://www.googleapis.com/auth/gmail.readonly`  |
| Provider identity    | The user's Gmail address (e.g., `user@gmail.com`) |

When connected with the `gmail.readonly` scope, the service scans email headers — sender addresses, subject lines, and metadata — to identify data holders (companies and services the user has interacted with). It does not read email body content.

The service periodically re-scans the inbox to discover new data holders as new emails arrive. Each scan updates the virtual presence's `lastScannedAt` timestamp.

**Example: Connect with auth code (Gmail)**

{% tabs %}
{% tab title="Typescript" %}

```typescript
// After the user completes Google's OAuth consent flow and you receive an auth code
// scoped to https://www.googleapis.com/auth/gmail.readonly
const virtualPresence = await privacyInteractionClient.connectVirtualPresenceWithAuthCode(
  { authCode },
)
```

{% endtab %}

{% tab title="Swift" %}

```swift
// After the user completes Google's OAuth consent flow and you receive an auth code
// scoped to https://www.googleapis.com/auth/gmail.readonly
do {
    let virtualPresence = try await privacyInteractionClient.connectVirtualPresenceWithAuthCode(
        withInput: ConnectVirtualPresenceWithAuthCodeInput(authCode: authCode)
    )
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
// After the user completes Google's OAuth consent flow and you receive an auth
// code scoped to https://www.googleapis.com/auth/gmail.readonly
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.connectVirtualPresenceWithAuthCode(
                ConnectVirtualPresenceWithAuthCodeInput(authCode = authCode)
            )
        }
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

**Example: Connect with refresh token (Gmail)**

{% tabs %}
{% tab title="Typescript" %}

```typescript
const virtualPresence = await privacyInteractionClient.connectVirtualPresenceWithRefreshToken({
  refreshToken: 'refresh-token-value',
  providerIdentity: 'user@gmail.com',
  scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
})
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let virtualPresence = try await privacyInteractionClient.connectVirtualPresenceWithRefreshToken(
        withInput: ConnectVirtualPresenceWithRefreshTokenInput(
            refreshToken: "refresh-token-value",
            providerIdentity: "user@gmail.com",
            scopes: ["https://www.googleapis.com/auth/gmail.readonly"]
        )
    )
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.connectVirtualPresenceWithRefreshToken(
                ConnectVirtualPresenceWithRefreshTokenInput(
                    refreshToken = "refresh-token-value",
                    providerIdentity = "user@gmail.com",
                    scopes = listOf("https://www.googleapis.com/auth/gmail.readonly"),
                ),
            )
        }
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

### Rescanning a Virtual Presence <a href="#subscribing-to-virtual-presence-updates" id="subscribing-to-virtual-presence-updates"></a>

Once a virtual presence is connected and the initial scan completes, you can trigger a rescan to discover new data holders that have appeared since the last scan. A rescan uses the stored credential - no new authorization from the user is required unless the credential has been revoked or expired. In this case, the virtual presence transitions to `NEEDS_REAUTH` and your application should prompt the user to re-authenticate.

Rescanning is incremental. New data holders are added to the existing set, and previously discovered data holders have their metadata updated. Existing data holders are never removed by a rescan. The virtual presence transitions to `SCANNING` while the rescan is in progress and returns to `CONNECTED` when complete.

To perform a rescan with default options, call the `rescanVirtualPresence` method with virtual presence's unique identifier. You can control the scope of a rescan by providing `ScanOptions`. This is useful for limiting how far back the scan reaches or excluding domains and categories the user is not interested in.

**Rescan behavior**

* A rescan is only started for a virtual presence in the `CONNECTED` state. For any other state (including `SCANNING` and `NEEDS_REAUTH`) the call returns the virtual presence as is, without error, and no scan starts. Check the returned `state`.
* The rescan covers items from the last scan date forward. Supply `earliestScanDate` in the scan options to override this.
* A rescan counts against the user's Gmail discovery rate entitlement (see [Privacy Interaction Entitlements](https://docs.sudoplatform.com/guides/digital-account-protection/privacy-interaction-entitlements.md)).
* The returned virtual presence reflects the state when the request was accepted. The transition to `SCANNING` and back to `CONNECTED` is delivered through a virtual presence subscription.

{% tabs %}
{% tab title="Typescript" %}

```typescript
try {
  const virtualPresence = await privacyInteractionClient.rescanVirtualPresence({
    id: virtualPresenceId,
    options: {
      earliestScanDate: '2026-01-01T00:00:00.000Z',
      maximumItemsProcessed: 200,
      excludeDomains: ['example.com', 'internal.org'],
    },
  })
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
let input = RescanVirtualPresenceInput(
    id: virtualPresenceId,
    options: ScanOptions(
        maximumItemsProcessed: 200,
        earliestScanDate: Date(timeIntervalSince1970: 1_767_225_600), // 2026-01-01
        excludeDomains: ["example.com", "internal.org"]
    )
)
do {
    let virtualPresence = try await privacyInteractionClient.rescanVirtualPresence(withInput: input)
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
val input = RescanVirtualPresenceInput(
    id = virtualPresenceId,
    options = ScanOptions(
        earliestScanDate = "2026-01-01T00:00:00.000Z",
        maximumItemsProcessed = 200,
        excludeDomains = listOf("example.com", "internal.org"),
    ),
)
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) 
            privacyInteractionClient.rescanVirtualPresence(input)
        }
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

**Input Parameters:**

| Parameter | Type          | Required | Description                                              |
| --------- | ------------- | -------- | -------------------------------------------------------- |
| `id`      | `string`      | Yes      | The unique identifier of the virtual presence to rescan. |
| `options` | `ScanOptions` | No       | Options to control the rescan behavior.                  |

**Scan Options:**

| Parameter               | Type       | Description                                                                                                        |
| ----------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------ |
| `maximumItemsProcessed` | `number`   | Maximum number of source items (e.g., emails) to process during the scan. When omitted, a service default is used. |
| `earliestScanDate`      | `string`   | Only consider items on or after this date (ISO 8601 string). Useful for narrowing the scan to recent activity.     |
| `latestScanDate`        | `string`   | Only consider items on or before this date (ISO 8601 string).                                                      |
| `excludeDomains`        | `string[]` | Domains to exclude from discovery results. Data holders matching these domains will be skipped.                    |
| `excludeCategories`     | `string[]` | Provider-specific categories or labels to exclude from processing (e.g., to skip personal emails).                 |

### Refreshing a Virtual Presence State

A user can revoke the service's access directly in their provider account (for example in their Google account settings). The provider does not notify the Privacy Interaction Service when this happens, so a virtual presence remains in the `CONNECTED` state until the next scan discovers that the grant has been revoked.

To check on demand, call `refreshVirtualPresenceState` with the virtual presence's unique identifier. The service validates the stored provider grant and returns the virtual presence with its reconciled state. Use this before gating a user flow on the virtual presence being `CONNECTED`.

* If the provider confirms the grant has been revoked, or no credential is stored, the virtual presence transitions to `NEEDS_REAUTH`, the unusable credential is removed, and the change is published to virtual presence subscribers.
* If the grant is still valid, the virtual presence is returned unchanged.
* If the check is inconclusive (for example the provider is unreachable), the virtual presence is returned unchanged. A failed check never downgrades a live connection.
* Only virtual presences in the `CONNECTED` or `SCANNING` state are validated. In any other state the current state is returned as is.

This operation does not start a scan or change `lastScannedAt`.

{% tabs %}
{% tab title="Typescript" %}

```typescript
try {
  const virtualPresence =
    await privacyInteractionClient.refreshVirtualPresenceState(virtualPresenceId)
  if (virtualPresence.state === VirtualPresenceState.NeedsReauth) {
    // Prompt the user to re-authenticate, then connect again.
  }
} catch (error) {
  // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let virtualPresence = try await privacyInteractionClient.refreshVirtualPresenceState(withId: virtualPresenceId)
    if virtualPresence.state == .needsReauth {
        // Prompt the user to re-authenticate, then connect again.
    }
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kt
launch {
    try {
        val virtualPresence = withContext(Dispatchers.IO) {
            privacyInteractionClient.refreshVirtualPresenceState(virtualPresenceId)
        }
        if (virtualPresence.state == VirtualPresenceState.NEEDS_REAUTH) {
            // Prompt the user to re-authenticate, then connect again.
        }
    } catch (e: VirtualPresenceException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

### Subscribing to Virtual Presence Updates <a href="#subscribing-to-virtual-presence-updates" id="subscribing-to-virtual-presence-updates"></a>

To receive real-time notifications when a virtual presence changes state, see [Subscriptions](https://docs.sudoplatform.com/guides/digital-account-protection/subscriptions.md).
