# Managing Password Vault Items

## Vault Item Concept

The password vaults stores vault items. Vault items have a flexible interface, allowing any type of  data to be securely stored. The client accepts an `ItemInput` and returns an `ItemOutput` which is similar to `ItemInput`, but includes metadata like `id` and encrypted secure fields. To learn more about decrypting secure fields, see [#decrypting-secure-data](#decrypting-secure-data "mention").&#x20;

Out of the box, Sudo Password Manager provides helpers to create established types with predefined fields; `BankAccount`, `Contact`, `CreditCard`, `Document`, `DriversLicense`, `Membership`, `Passport`, and `SocialSecurityNumber`. These are useful when wanting to use predefined objects and remove some of the extra work in creating a `ItemInput`. To learn more about what properties exist on the helper types, see the code documentation.&#x20;

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

```typescript
// SudoPasswordManager Defined item
const login: LoginInput = {
  label: 'Sudo Platform', 
  user: 'example@sudo.com',
  url: 'anonyome.com',
  password: 'i<3sudo_platform',
  favorite: true,
  customFields: [],
}
const loginInput: ItemInput = createLoginInput(login)
// output of helper function
{
  label: 'Sudo Platform',
  favorite: true,
  hexColor: undefined,
  type: 'login',
  fields: [
    { name: 'user', label: undefined, type: 'string', value: 'example@sudo.com' },
    { name: 'url', label: undefined, type: 'string', value: 'anonyome.com' },
    { name: 'password', label: undefined, type: 'password', unencryptedValue: 'i<3sudo_platform' },
    { name: 'otp', label: undefined, type: 'otp', unencryptedValue: undefined },
    { name: 'notes', label: undefined, type: 'secure', unencryptedValue: undefined },
  ]
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
        // Login custom type
        let login = Login(user: "me",
                               url: "anonyome.com",
                               label: "login",
                               notes: nil,
                               password: PasswordField(
                                secureValue: .token(SecureValueToken(data: Data())),
                                createdAt: Date(),
                                replacedAt: Date()
                               ),
                               oneTimePassword: nil,
                               hexColor: nil)
    
        // Transformed to item input for vault client add/update.
        let itemInput = login.transformToItemInput()
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// SudoPasswordManager Defined Item
val login: VaultLogin = VaultLogin(
	label = "Sudo Platform",
	user = "example@sudo.com",
	url = "anonyome.com",
	password = "i<3sudo_platform",
	favorite = true,
	customFields = emtpyList()
)
```

{% endtab %}
{% endtabs %}

### Vault Item Fields

An `ItemInput` contains an array of `FieldInput` where data and passwords are stored. A `FieldInput` is an object that contains some metadata about the type and how to store the property. For example, a `SecureField` will ensure that the `secureValue` is encrypted, whereas a `StringField` will not attempt to encrypt the `value`.&#x20;

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

```typescript
// Example of a field
const field = {
  name: 'url', // the key or identifier for the field
  label: 'Site URL', // optional property that is used to label the field to the user
  type: 'string', // type of field object
  value: 'sudoplatform.com', // the value to store
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
// Example of a field
let field = Field(
  name: "url", // the key or identifier for the field
  label: "Site URL", // optional property that is used to label the field to the user
  type: "string", // type of field object
  value: "sudoplatform.com", // the value to store
)
```

{% endtab %}

{% tab title="Android" %}

```kotlin
// Example of creating a string-type field.
// Android provides helper methods to create different field types.
val field = createStringFieldInput(
    name = "url", // the key or identifyier for the field
    label = "Site URL", // optional property that used to label the field to the user
    value = "sudoplatform.com" // the value to store
)
```

{% endtab %}
{% endtabs %}

## Retrieving Vault Items

To retrieve a list of vault items, use the `listItems` method. This method requires a vault identifier to retrieve the vault items. Additionally, if a user wants to get an individual item, an individual item can be fetched by using the vault id and the item id using the `getItem` method. In the JS SDK, there are functions to transform `ItemOutput` to the defined types; i.e. `transformLoginOutput`. iOS provides similar convenience by using class extensions.&#x20;

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

```typescript
try {
    const vaultId = /* vault ID from createVault or listVaults */
    const vaultItems = await client.listItems(vaultId)
} catch {
    // Handle/notify user of errors
}

try {
    const itemId = /* item ID from addItem or listItems */
    const item = await client.getItem(vaultId, itemId)
    // convience transformation if applicable
    const loginItem = transformLoginOutput(item)
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var client: PasswordManagerClient!
var vault: Vault!

client.listVaultItems(inVault: vault) { (result) in
    switch result {
    case .success(let vaultItems):
        break
    case .failure(let error):
        break
    }
}

client.getVaultItem(id: "1", in: vault) { (result) in
    switch result {
    case .success(let maybeVaultItem):
        if let vaultItem = maybeVaultItem {
            // use vault item
        }
        break
    case .failure(let error):
        break
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// val client: SudoPasswordManagerClient

launch {
    try {
        withContext(Dispatchers.IO) {
            val vault = client.getVault("1")
            val vaultItems = client.listVaultItems(vault)
            val vaultItem = client.getVaultItem("2", vault)
        }
    } catch (e: SudoPasswordManagerException) {
        // Handle any errors related to fetching vault items
    }
}
```

{% endtab %}
{% endtabs %}

## Decrypting Secure Data

Some properties such as `password` and `notes` are considered secure. Any field that has a type of `password`, `secure` , or `otp` will be considered secure and encrypted in the client and will be required to be decrypted in order to be read. These properties remain encrypted in memory even when the Password Manager is unlocked. To access the unencrypted value of these properties as a result of user interaction, use the `decryptField` method.

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

```typescript
const secureField = { name: 'cardNumber', 
                      type: 'secure' as const, 
                      secureValue: '<ENCRYPTED_VALUE>' 
                     }
const plaintextValue = await client.decryptField(secureField)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Getting Secure Data is only applicable to Web and Node.js projects. This method is not contained in the iOS and Android SDKs.
{% endhint %}

## Adding a New Vault Item <a href="#toc_5" id="toc_5"></a>

To add a new vault item, create the desired item with the required data. After an item is created, add the item to the vault using the SDK's `addItem` method. The method takes an `ItemInput` and after successfully adding the item to the vault, returns an `ItemOutput`.

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

```typescript
try {
  const login = createLoginInput({
    label: "Dev Login",
    user: "developer@company.com",
    url: 'anonyome.com',
    password: "SecretPassword",
    hexColor: "0xFF0000",
    favorite: true,
  })
  const item = await client.addItem(vaultId, login)
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var client: PasswordManagerClient!
var vault: Vault!

let login = VaultLogin(user: "developer@company.com",
                       url: "http://www.sudoplatform.com",
                       name: "Sudo Platform Login",
                       notes: VaultItemNote(value: "My login for the sudo platform service"),
                       password: VaultItemPassword(value: "SecretPassword")
                       hexColor: "0xFF0000",
                       favorite: true)

client.add(item: login, toVault: vault) { (result) in
    switch result {
    case .success(let id):
        break
    case .failure(let error):
        break
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// val client: SudoPasswordManagerClient

launch {
    try {
        withContext(Dispatchers.IO) {
            val vault = client.getVault("1")
            val login = VaultLogin(
                name = "Sudo Platform",
                user = "developer@company.com",
                url = "http://www.sudoplatform.com",
                // SecureFieldValue() is only for predefined types
                // need to use createSecureValueInput() in customFields[]
                note = SecureFieldValue("My login for the Sudo Platform"),
                password = VaultItemPassword(SecureFieldValue("SecretPassword")),
                hexcolor = "0xFF0000",
                favorite = true,
            )
            client.add(login, vault)
            client.update(vault)
        }
    } catch (e: SudoPasswordManagerException) {
        // Handle any errors
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Attempting to add an item with no properties to the vault will result in an error.
{% endhint %}

## Adding Batch Vault Items <a href="#toc_5" id="toc_5"></a>

The JS SDK provides a method to add a batch of items at one time to the vault. This is useful when importing vault data from another password manager to the Sudo Platform Vault. The method takes an array of ItemInput and after successful operation, returns an array of newly added ItemOutput.

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

```typescript
try {
  const login = createLoginInput({
    label: "Dev Login",
    user: "developer@company.com",
    url: 'anonyome.com',
    password: "SecretPassword",
    hexColor: "0xFF0000",
    favorite: true,
  })
  const items = await client.addBatchItems(vaultId, [login])
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
This feature is only available in the JS SDK.
{% endhint %}

## Updating a Vault Item <a href="#toc_6" id="toc_6"></a>

To update a vault item in the vault, first fetch the full item from the vault. Once you have the vault item (e.g. `ItemOutput)` make any changes to the properties, then save them to the vault using the `updateItem` method.

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

```javascript
try {
    const itemId = /* item ID from addItem or listItems */
    const item = await getItem(vaultId, itemId)
    const updatedItem = {
         ...item, 
         favorite: false
    }
    await client.updateItem(vaultId, itemId, updatedItem)
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var client: PasswordManagerClient!
var vault: Vault!
var login: VaultLogin!

// Make desired changes to the item
login.user = "user@sudoplatform.com"
login.password = VaultItemPassword(value: "SecurePassword101")

client.update(item: login, in: vault, completion: { result in
    switch result {
    case .success:
        break
    case .failure(let error):
        break
    }
})
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// val client: SudoPasswordManagerClient

launch {
    try {
        withContext(Dispatchers.IO) {
            val vault = client.getVault("1") ?: return@withContext
            val login = client.getVaultItem("2", vault)
            
            // Note: VaultLogin is only of type VaultItemInput for now
            // Need to use .deepCopy() or the fields list will not be copied
            val updatedLogin = login.deepCopy(
                user = "user@sudoplatform.com",
                password = VaultItemPassword(
                    createSecureFieldInput("SecurePassword101")
                )
            )
            client.update(updatedLogin, vault)
            
        }
    } catch (e: SudoPasswordManagerException) {
        // Handle any errors
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Attempting to update an item in a vault that doesn't contain the item will result in an error.
{% endhint %}

## Deleting a Vault Item <a href="#toc_7" id="toc_7"></a>

To delete a vault item, use the `removeItem` method for the JS SDK or `removeVaultItem` method for iOS and Android SDKs.

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

```typescript
try {
    const vaultId = "1" 
    const itemId = "2" /* item id can be found from addItem or listItems */
    await client.removeItem(vaultId, itemId)
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var client: PasswordManagerClient!
var vault: Vault!
var login: VaultLogin!

client.removeVaultItem(id: login.id, from: vault) { (result) in
    switch result {
    case .success:
        break
    case .failure(let error):
        break
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// val client: SudoPasswordManagerClient

launch {
    try {
        withContext(Dispatchers.IO) {
            val vault = client.getVault("1")
            vault.removeVaultItem("2", vault)
        }
    } catch (e: SudoPasswordManagerException) {
        // Handle any errors
    }
}
```

{% endtab %}
{% endtabs %}

## Deleting Batch Vault Items <a href="#toc_7" id="toc_7"></a>

To delete a batch of vault items, use the `removeBatchItems` method that accepts an array of item ids.

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

```typescript
try {
    const vaultId = "1" 
    const itemId = "2" /* item id can be found from addItem or listItems */
    await client.removeBatchItems(vaultId, [itemId])
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var client: PasswordManagerClient!
var vault: Vault!
var login: VaultLogin!

client.removeBatchItems(vaultId: vault, itemIds: [login.id]) { (result) in
    switch result {
    case .success:
        break
    case .failure(let error):
        break
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// val client: SudoPasswordManagerClient

launch {
    try {
        withContext(Dispatchers.IO) {
            val vault = client.getVault("1")
            vault.removeBatchItems(listOf("2"), vault)
        }
    } catch (e: SudoPasswordManagerException) {
        // Handle any errors
    }
}
```

{% endtab %}
{% endtabs %}
