Sign In

@metamask/toprf-secure-backup

Package Overview
Dependencies
Maintainers
7
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@metamask/toprf-secure-backup - npm Package Compare versions

Comparing version
1.0.0
to
1.1.0
+8
-1
CHANGELOG.md

@@ -10,2 +10,8 @@ # Changelog

## [1.1.0]
### Changed
- `changeEncKey` accepts an optional `transformDataItems` callback (`(items: FetchedSecretDataItem[]) => SecretDataItemInput[]`); the SDK fetches inside the metadata lock and passes items to the callback for sorting before re-insertion, preventing data loss from concurrent writes ([#160](https://github.com/MetaMask/toprf-secure-backup/pull/160))
## [1.0.0]

@@ -160,3 +166,4 @@

[Unreleased]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/toprf-secure-backup@1.0.0...HEAD
[Unreleased]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/toprf-secure-backup@1.1.0...HEAD
[1.1.0]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/toprf-secure-backup@1.0.0...@metamask/toprf-secure-backup@1.1.0
[1.0.0]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/toprf-secure-backup@0.11.0...@metamask/toprf-secure-backup@1.0.0

@@ -163,0 +170,0 @@ [0.11.0]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/toprf-secure-backup@0.10.1...@metamask/toprf-secure-backup@0.11.0

+1
-1

@@ -1,1 +0,1 @@

{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AACA,0DAAoC;AAEpC,uCAAsD;AAA7C,oGAAA,UAAU,OAAA;AAAE,wGAAA,cAAc,OAAA;AACnC,8CAAwB;AACxB,6CAAiD;AAAxC,+GAAA,kBAAkB,OAAA","sourcesContent":["export type * from './interfaces';\nexport * from './toprfSecureBackup';\nexport type { RateLimitErrorData } from './errors';\nexport { TOPRFError, TOPRFErrorCode } from './errors';\nexport * from './utils';\nexport { EncAccountDataType } from './constants';\nexport type {\n SecretDataItem,\n SecretDataItemInput,\n SecretDataItemOutput,\n UpdateSecretDataItem,\n MetadataUpdateSecretDataItemParams,\n MetadataBatchUpdateSecretDataItemParams,\n} from './metadata';\n"]}
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AACA,0DAAoC;AAEpC,uCAAsD;AAA7C,oGAAA,UAAU,OAAA;AAAE,wGAAA,cAAc,OAAA;AACnC,8CAAwB;AACxB,6CAAiD;AAAxC,+GAAA,kBAAkB,OAAA","sourcesContent":["export type * from './interfaces';\nexport * from './toprfSecureBackup';\nexport type { RateLimitErrorData } from './errors';\nexport { TOPRFError, TOPRFErrorCode } from './errors';\nexport * from './utils';\nexport { EncAccountDataType } from './constants';\nexport type {\n UpdateSecretDataItem,\n MetadataUpdateSecretDataItemParams,\n MetadataBatchUpdateSecretDataItemParams,\n} from './metadata';\n"]}

@@ -7,3 +7,3 @@ export type * from "./interfaces.cjs";

export { EncAccountDataType } from "./constants.cjs";
export type { SecretDataItem, SecretDataItemInput, SecretDataItemOutput, UpdateSecretDataItem, MetadataUpdateSecretDataItemParams, MetadataBatchUpdateSecretDataItemParams, } from "./metadata.cjs";
export type { UpdateSecretDataItem, MetadataUpdateSecretDataItemParams, MetadataBatchUpdateSecretDataItemParams, } from "./metadata.cjs";
//# sourceMappingURL=index.d.cts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAkC;AAClC,wCAAoC;AACpC,YAAY,EAAE,kBAAkB,EAAE,qBAAiB;AACnD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB;AACjD,YAAY,EACV,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACpB,oBAAoB,EACpB,kCAAkC,EAClC,uCAAuC,GACxC,uBAAmB"}
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAkC;AAClC,wCAAoC;AACpC,YAAY,EAAE,kBAAkB,EAAE,qBAAiB;AACnD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB;AACjD,YAAY,EACV,oBAAoB,EACpB,kCAAkC,EAClC,uCAAuC,GACxC,uBAAmB"}

@@ -7,3 +7,3 @@ export type * from "./interfaces.mjs";

export { EncAccountDataType } from "./constants.mjs";
export type { SecretDataItem, SecretDataItemInput, SecretDataItemOutput, UpdateSecretDataItem, MetadataUpdateSecretDataItemParams, MetadataBatchUpdateSecretDataItemParams, } from "./metadata.mjs";
export type { UpdateSecretDataItem, MetadataUpdateSecretDataItemParams, MetadataBatchUpdateSecretDataItemParams, } from "./metadata.mjs";
//# sourceMappingURL=index.d.mts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAkC;AAClC,wCAAoC;AACpC,YAAY,EAAE,kBAAkB,EAAE,qBAAiB;AACnD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB;AACjD,YAAY,EACV,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACpB,oBAAoB,EACpB,kCAAkC,EAClC,uCAAuC,GACxC,uBAAmB"}
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAkC;AAClC,wCAAoC;AACpC,YAAY,EAAE,kBAAkB,EAAE,qBAAiB;AACnD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB;AACjD,YAAY,EACV,oBAAoB,EACpB,kCAAkC,EAClC,uCAAuC,GACxC,uBAAmB"}

@@ -1,1 +0,1 @@

{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,wCAAoC;AAEpC,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB","sourcesContent":["export type * from './interfaces';\nexport * from './toprfSecureBackup';\nexport type { RateLimitErrorData } from './errors';\nexport { TOPRFError, TOPRFErrorCode } from './errors';\nexport * from './utils';\nexport { EncAccountDataType } from './constants';\nexport type {\n SecretDataItem,\n SecretDataItemInput,\n SecretDataItemOutput,\n UpdateSecretDataItem,\n MetadataUpdateSecretDataItemParams,\n MetadataBatchUpdateSecretDataItemParams,\n} from './metadata';\n"]}
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,wCAAoC;AAEpC,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAiB;AACtD,4BAAwB;AACxB,OAAO,EAAE,kBAAkB,EAAE,wBAAoB","sourcesContent":["export type * from './interfaces';\nexport * from './toprfSecureBackup';\nexport type { RateLimitErrorData } from './errors';\nexport { TOPRFError, TOPRFErrorCode } from './errors';\nexport * from './utils';\nexport { EncAccountDataType } from './constants';\nexport type {\n UpdateSecretDataItem,\n MetadataUpdateSecretDataItemParams,\n MetadataBatchUpdateSecretDataItemParams,\n} from './metadata';\n"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"interfaces.cjs","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type { INodePub } from '@toruslabs/constants';\n\nimport type { EncAccountDataType } from './constants';\n\n/**\n * SEC1 encoded public key\n */\nexport type SEC1EncodedPublicKey = Uint8Array;\n\n/**\n * KeyPair - The encryption/decryption private and public key pair.\n *\n * sk - The decryption private key in bigint format.\n *\n * pk - The encryption public key in SEC1 encoded format.\n */\nexport type KeyPair = {\n sk: bigint;\n pk: SEC1EncodedPublicKey;\n};\n\n/**\n * Optional override for node details.\n */\nexport type NodeDetailsOverride = {\n /**\n * Endpoint configuration. This allows for overriding the default SSS node endpoints.\n *\n * - **To use FND-resolved node URLs with a custom path:** Provide a single `string`\n * representing the path to be appended to each FND-resolved node URL.\n * For example, `'/sss-toprf'` will transform FND URLs like `https://node1.example.com`\n * into `https://node1.example.com/sss-toprf`.\n *\n * - **To use a completely custom set of node URLs (bypassing FND resolution):**\n * Provide an array of `string[]` where each string is a complete endpoint URL.\n * For example, `['https://custom-node1.com/custom-path', 'https://custom-node2.com/custom-path']`.\n *\n * If left `undefined`, the SDK will use the default FND-resolved SSS endpoints directly.\n */\n endpoints?: string | string[];\n /**\n * Array of node indexes. Must match network node count if provided.\n */\n indexes?: number[];\n /**\n * Array of node public keys. Must match network node count if provided.\n */\n pubKeys?: INodePub[];\n};\n\n/**\n * AuthenticateParams - The parameters for the authenticate request.\n *\n * idTokens - The idTokens to be used for the authenticate request.\n *\n * authConnectionId - The auth connection name to be used for the authenticate request.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user to be used for the authenticate request.\n *\n * groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n */\nexport type AuthenticateParams = {\n // for now we only support one idToken, in future we will support multiple to remove commitment call\n // so leaving it as an array for future use\n idTokens: string[];\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * NodeAuthToken - An authentication token and the node details.\n *\n * authToken - The authentication token.\n *\n * nodeIndex - The index of the node that issued the token.\n *\n * nodePubKey - The public key of the node that issued the token.\n */\nexport type NodeAuthToken = {\n authToken: string;\n nodeIndex: number;\n nodePubKey: string;\n};\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n */\nexport type NodeAuthTokens = NodeAuthToken[];\n\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n *\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n */\nexport type AuthenticateResult = {\n nodeAuthTokens: NodeAuthTokens;\n isNewUser: boolean;\n};\n\n/**\n * CreateLocalKeyParams - The parameters for creating an OPRF encryption key locally.\n *\n * password - The password of the user.\n *\n * oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n */\nexport type CreateLocalKeyParams = {\n password: string;\n oprfKey?: bigint;\n};\n\n/**\n * CreateLocalKeyResult - The result of creating an encryption key.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * seed - The seed which is used to derive the authentication and encryption keys.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n */\nexport type CreateLocalKeyResult = {\n oprfKey: bigint;\n seed: Uint8Array;\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * PersistLocalKeyParams - The parameters for persisting an OPRF key's shares to the servers.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * authPubKey - The authentication public key which is used to authenticate the write request to the metadata store.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * keyShareIndex - Optional key share index to be persisted.\n *\n * oldAuthKeyPair - Optional authentication key pair to be used for key change flow.\n */\nexport type PersistLocalKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n oprfKey: bigint;\n authPubKey: SEC1EncodedPublicKey;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n keyShareIndex?: number;\n oldAuthKeyPair?: KeyPair;\n};\n\n/**\n * CreateEncryptionKeyParams - The parameters for creating an encryption key.\n *\n * authConnectionId - The auth connection name of the user.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * nodeAuthTokens - The tokens issued by the nodes on verifying the idTokens.\n *\n * password - The password of the user.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type CreateEncryptionKeyParams = {\n authConnectionId: string;\n userId: string;\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * CreateEncryptionKeyResult - The result of creating an encryption key.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n *\n * pwEncKey - The password encryption key which is used to encrypt the password.\n */\nexport type CreateEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\nexport type BaseAddSecretDataItemParams<\n SecretDataType,\n EncKeyType = Uint8Array,\n> = {\n /**\n * The secret data to be stored.\n */\n secretData: SecretDataType;\n\n /**\n * The encryption key to be used to encrypt the secret data.\n */\n encKey: EncKeyType;\n\n /**\n * The authentication key to be used to provide valid signature for storing the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * AddSecretDataItemParams - Parameters for adding a secret data item.\n *\n * secretData - The secret data to be stored.\n *\n * encKey - The encryption key to be used to encrypt the secret data before storing it.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * itemId - Optional item ID for the data item.\n *\n * version - Optional version string for the data item.\n *\n * dataType - Optional data type for categorizing the secret data.\n */\nexport type AddSecretDataItemParams =\n BaseAddSecretDataItemParams<Uint8Array> & {\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n };\n\n/**\n * BatchAddSecretDataItem - A single item in a batch add operation.\n */\nexport type BatchAddSecretDataItem = {\n data: Uint8Array;\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n};\n\n/**\n * BatchAddSecretDataItemParams - Parameters for batch adding secret data items.\n *\n * secretData - Array of items to store, each with data and optional itemId/dataType.\n *\n * encKey - The encryption key(s) to be used to encrypt the secret data.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\nexport type BatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n BatchAddSecretDataItem[],\n Uint8Array | Uint8Array[]\n>;\n\n/**\n * FetchedSecretDataItem - A secret data item returned from fetch operations.\n */\nexport type FetchedSecretDataItem = {\n data: Uint8Array;\n itemId: string;\n version: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\n/**\n * UpdateSecretDataItemParams - Parameters for updating a secret data item's fields.\n *\n * itemId - The ID of the item to update.\n *\n * dataType - The data type to set for the item.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type UpdateSecretDataItemParams = {\n itemId: string;\n dataType: EncAccountDataType;\n authKeyPair: KeyPair;\n};\n\n/**\n * BatchUpdateSecretDataItemParams - Parameters for batch updating secret data items' fields.\n *\n * updateItems - Array of items to update, each with itemId and fields to update.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type BatchUpdateSecretDataItemParams = {\n updateItems: { itemId: string; dataType: EncAccountDataType }[];\n authKeyPair: KeyPair;\n};\n\n/**\n * RecoverEncryptionKeyParams - The parameters for recovering the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * password - The password of the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type RecoverEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n * encKey - The encryption key which is used to encrypt the secret data.\n * keyShareIndex - The index of the key shares on the nodes, used for key change operations.\n * rateLimitResetResult - A promise that resolves when the rate limit is reset.\n */\nexport type RecoverEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n keyShareIndex: number;\n rateLimitResetResult: Promise<void>;\n};\n\n/**\n * Parameters for changing the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * oldEncKey - The old encryption key of the user.\n *\n * oldAuthKeyPair - The old authentication key pair of the user.\n *\n * newKeyShareIndex - The key share index to be used for the new key.\n *\n * newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n */\nexport type ChangeEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n userId: string;\n oldEncKey: Uint8Array;\n oldPwEncKey: Uint8Array;\n oldAuthKeyPair: KeyPair;\n newKeyShareIndex: number;\n newPassword?: string;\n groupedAuthConnectionId?: string;\n pregeneratedOprfKey?: CreateLocalKeyResult;\n};\n\n/**\n * authKeyPair - The new authentication key pair which is used to authenticate the user.\n * encKey - The new encryption key which is used to encrypt the secret data.\n */\nexport type ChangeEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * keyPair - The encryption/decryption key pair which is used to decrypt the secret data.\n */\nexport type FetchAllSecretDataParams = {\n /**\n * The decryption key to be used to decrypt the secret data.\n */\n decKey: Uint8Array;\n\n /**\n * The authentication key to be used to provide valid signature for fetching the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * Proof that the user owns the old key when changing to a new password/key\n * Contains a signature created with the old private key on a timestamp and new key share data.\n */\nexport type KeyChangeProof = {\n oldKeySignature: string;\n signatureTimestamp: number;\n};\n\n/**\n * FetchAuthPubKeyParams - The parameters for fetching the authentication public key.\n *\n * nodeAuthTokens - Auth tokens issued by nodes.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user issued by authentication service.\n */\nexport type FetchAuthPubKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n groupedAuthConnectionId?: string;\n userId: string;\n};\n\nexport type FetchAuthPubKeyResult = {\n authPubKey: SEC1EncodedPublicKey;\n keyIndex: number;\n};\n\nexport type RecoverPwEncKeyParams = {\n targetAuthPubKey: SEC1EncodedPublicKey;\n curPwEncKey: Uint8Array;\n curAuthKeyPair: KeyPair;\n maxPwChainLength?: number;\n};\n\nexport type RecoverPwEncKeyResult = {\n pwEncKey: Uint8Array;\n};\n\nexport type IToprfSecureBackup = {\n authenticate: (params: AuthenticateParams) => Promise<AuthenticateResult>;\n\n /**\n * This function locally creates an OPRF and encryption key without storing it at the key\n * management service. It returns the OPRF key, derives the corresponding key\n * seed, authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns A promise that resolves with the encryption key.\n */\n createLocalKey: (\n params: CreateLocalKeyParams,\n ) => Promise<CreateLocalKeyResult>;\n\n /**\n * This function persists an locally created OPRF key's shares to the servers.\n *\n * @param params - The parameters for persisting an OPRF key's shares.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the write request to the metadata store.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n * @returns A promise that resolves when the OPRF key's shares are persisted.\n */\n persistLocalKey: (params: PersistLocalKeyParams) => Promise<void>;\n\n createAndPersistEncKey: (\n params: CreateEncryptionKeyParams,\n ) => Promise<CreateEncryptionKeyResult>;\n\n recoverEncKey: (\n params: RecoverEncryptionKeyParams,\n ) => Promise<RecoverEncryptionKeyResult>;\n\n /**\n * This function replaces the existing encryption key with a new one and copies the secret data of existing encryption key to the new one.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.newPassword - The new password of the user.\n * @param params.keyPair - The current encryption key of the user.\n *\n * @returns A promise that resolves with the new encryption key.\n */\n changeEncKey: (\n params: ChangeEncryptionKeyParams,\n ) => Promise<ChangeEncryptionKeyResult>;\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n * @param params.secretData - The secret data to be registered.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.dataType - Optional data type for categorizing the secret data.\n *\n * @returns A promise that resolves when the secret data is registered.\n */\n addSecretDataItem: (params: AddSecretDataItemParams) => Promise<void>;\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores it in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * @returns A promise that resolves when the secret data is stored.\n */\n batchAddSecretDataItems: (\n params: BatchAddSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when the update is complete.\n */\n updateSecretDataItem: (params: UpdateSecretDataItemParams) => Promise<void>;\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when all updates are complete.\n */\n batchUpdateSecretDataItems: (\n params: BatchUpdateSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns A promise that resolves with the array of decrypted secret data items.\n */\n fetchAllSecretDataItems: (\n params: FetchAllSecretDataParams,\n ) => Promise<FetchedSecretDataItem[]>;\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for fetching the authentication public key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n *\n * @returns A promise that resolves with the authentication public key.\n */\n fetchAuthPubKey: (\n params: FetchAuthPubKeyParams,\n ) => Promise<FetchAuthPubKeyResult>;\n\n /**\n * This function recovers the password encryption key of the user.\n *\n * @param params - The parameters for recovering the password encryption key.\n * @param params.targetAuthPubKey - The public key of the target encryption key.\n * @param params.curPwEncKey - The current password encryption key of the user.\n * @param params.curAuthKeyPair - The current authentication key pair of the user.\n *\n * @returns A promise that resolves to the password encryption key of the user.\n */\n recoverPwEncKey: (\n params: RecoverPwEncKeyParams,\n ) => Promise<RecoverPwEncKeyResult>;\n\n /**\n * This function gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * This function is useful when you want to pre-fetch the node details before any TOPRF operations\n * so that the subsequent calls to the TOPRF operations are faster without waiting for the node details to be fetched.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n getNodeDetails: () => Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }>;\n};\n\n/**\n * Base payload structure for metadata request\n */\nexport type IBaseMetadataRequestBody = {\n /**\n * The feature name related to the secret data\n */\n feature: string;\n /**\n * The public key of the user\n */\n pubKey: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n timestamp: string;\n};\n\n/**\n * The array of secret data to be stored in batch request\n */\nexport type IBatchAddData = {\n /**\n * The base64-encoded string of the secret data\n */\n data: string;\n /**\n * The version of the Metadata Store\n */\n version?: string;\n /**\n * Optional item id for the data item\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n}[];\n\n/**\n * Payload structure for storing secret data\n */\nexport type IBaseAddSecretDataRequestBody<DataType> =\n IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n * this token is also known as `metadataAccessToken`.\n */\n authToken?: string;\n /**\n * The secret data to be stored.\n *\n * For storing the single secret data, the data should be base64-encoded string.\n *\n * @example\n * ```ts\n * const data = Buffer.from('SECRET_DATA').toString('base64');\n * ```\n *\n * For storing the batch of secret data, the data should be an array of `IBatchAddData`.\n *\n * @example\n * ```ts\n * const data = [\n * { data: Buffer.from('SECRET_DATA_1').toString('base64') },\n * { data: Buffer.from('SECRET_DATA_2').toString('base64') },\n * ];\n * ```\n */\n data: DataType;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(data, feature, authToken, timestamp))\n */\n signature: string;\n };\n\n/**\n * Payload structure for storing secret data for single secret data\n */\nexport type IAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<string> & {\n /**\n * The version of the secret data\n */\n version?: string;\n /**\n * The item id to be used for storing the secret data.\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n };\n\n/**\n * Payload structure for storing secret data in batch request\n */\nexport type IBatchAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<IBatchAddData>;\n\n/**\n * Fields that can be updated for an existing secret data item.\n */\nexport type UpdateSecretDataItemFields = {\n /**\n * The data type to set for the item\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n};\n\n/**\n * Payload structure for updating secret data fields by itemId\n */\nexport type IUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The item id of the record to update\n */\n itemId: string;\n /**\n * The data type for categorizing the secret data\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for batch updating secret data fields by itemId\n */\nexport type IBatchUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The array of items to update\n */\n items: {\n itemId: string;\n dataType: EncAccountDataType;\n version?: 'v1' | 'v2';\n }[];\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for fetching secret data\n */\nexport type IGetSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by the SSS services\n */\n authToken?: string;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The item id to be used for fetching the secret data.\n */\n itemId?: string;\n};\n\n/**\n * Payload structure for acquiring/releasing a lock on the metadata\n */\nexport type IMetadataLockRequestBody = {\n /**\n * The public key of the user\n */\n key: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n data: {\n timestamp: number;\n };\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The lock id to be released.\n */\n id?: string | undefined;\n};\n\n/**\n * FetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n *\n * @returns The metadata access credentials.\n */\nexport type FetchMetadataAccessCreds = () => Promise<{\n metadataAccessToken: string;\n}>;\n"]}
{"version":3,"file":"interfaces.cjs","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type { INodePub } from '@toruslabs/constants';\n\nimport type { EncAccountDataType } from './constants';\n\nexport type SecretDataItem = {\n itemId?: string;\n data: Uint8Array;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\nexport type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;\n\nexport type SecretDataItemOutput = SecretDataItem & {\n itemId: string;\n version: 'v1' | 'v2';\n};\n\n/**\n * SEC1 encoded public key\n */\nexport type SEC1EncodedPublicKey = Uint8Array;\n\n/**\n * KeyPair - The encryption/decryption private and public key pair.\n *\n * sk - The decryption private key in bigint format.\n *\n * pk - The encryption public key in SEC1 encoded format.\n */\nexport type KeyPair = {\n sk: bigint;\n pk: SEC1EncodedPublicKey;\n};\n\n/**\n * Optional override for node details.\n */\nexport type NodeDetailsOverride = {\n /**\n * Endpoint configuration. This allows for overriding the default SSS node endpoints.\n *\n * - **To use FND-resolved node URLs with a custom path:** Provide a single `string`\n * representing the path to be appended to each FND-resolved node URL.\n * For example, `'/sss-toprf'` will transform FND URLs like `https://node1.example.com`\n * into `https://node1.example.com/sss-toprf`.\n *\n * - **To use a completely custom set of node URLs (bypassing FND resolution):**\n * Provide an array of `string[]` where each string is a complete endpoint URL.\n * For example, `['https://custom-node1.com/custom-path', 'https://custom-node2.com/custom-path']`.\n *\n * If left `undefined`, the SDK will use the default FND-resolved SSS endpoints directly.\n */\n endpoints?: string | string[];\n /**\n * Array of node indexes. Must match network node count if provided.\n */\n indexes?: number[];\n /**\n * Array of node public keys. Must match network node count if provided.\n */\n pubKeys?: INodePub[];\n};\n\n/**\n * AuthenticateParams - The parameters for the authenticate request.\n *\n * idTokens - The idTokens to be used for the authenticate request.\n *\n * authConnectionId - The auth connection name to be used for the authenticate request.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user to be used for the authenticate request.\n *\n * groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n */\nexport type AuthenticateParams = {\n // for now we only support one idToken, in future we will support multiple to remove commitment call\n // so leaving it as an array for future use\n idTokens: string[];\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * NodeAuthToken - An authentication token and the node details.\n *\n * authToken - The authentication token.\n *\n * nodeIndex - The index of the node that issued the token.\n *\n * nodePubKey - The public key of the node that issued the token.\n */\nexport type NodeAuthToken = {\n authToken: string;\n nodeIndex: number;\n nodePubKey: string;\n};\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n */\nexport type NodeAuthTokens = NodeAuthToken[];\n\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n *\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n */\nexport type AuthenticateResult = {\n nodeAuthTokens: NodeAuthTokens;\n isNewUser: boolean;\n};\n\n/**\n * CreateLocalKeyParams - The parameters for creating an OPRF encryption key locally.\n *\n * password - The password of the user.\n *\n * oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n */\nexport type CreateLocalKeyParams = {\n password: string;\n oprfKey?: bigint;\n};\n\n/**\n * CreateLocalKeyResult - The result of creating an encryption key.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * seed - The seed which is used to derive the authentication and encryption keys.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n */\nexport type CreateLocalKeyResult = {\n oprfKey: bigint;\n seed: Uint8Array;\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * PersistLocalKeyParams - The parameters for persisting an OPRF key's shares to the servers.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * authPubKey - The authentication public key which is used to authenticate the write request to the metadata store.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * keyShareIndex - Optional key share index to be persisted.\n *\n * oldAuthKeyPair - Optional authentication key pair to be used for key change flow.\n */\nexport type PersistLocalKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n oprfKey: bigint;\n authPubKey: SEC1EncodedPublicKey;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n keyShareIndex?: number;\n oldAuthKeyPair?: KeyPair;\n};\n\n/**\n * CreateEncryptionKeyParams - The parameters for creating an encryption key.\n *\n * authConnectionId - The auth connection name of the user.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * nodeAuthTokens - The tokens issued by the nodes on verifying the idTokens.\n *\n * password - The password of the user.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type CreateEncryptionKeyParams = {\n authConnectionId: string;\n userId: string;\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * CreateEncryptionKeyResult - The result of creating an encryption key.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n *\n * pwEncKey - The password encryption key which is used to encrypt the password.\n */\nexport type CreateEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\nexport type BaseAddSecretDataItemParams<\n SecretDataType,\n EncKeyType = Uint8Array,\n> = {\n /**\n * The secret data to be stored.\n */\n secretData: SecretDataType;\n\n /**\n * The encryption key to be used to encrypt the secret data.\n */\n encKey: EncKeyType;\n\n /**\n * The authentication key to be used to provide valid signature for storing the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * AddSecretDataItemParams - Parameters for adding a secret data item.\n *\n * secretData - The secret data to be stored.\n *\n * encKey - The encryption key to be used to encrypt the secret data before storing it.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * itemId - Optional item ID for the data item.\n *\n * version - Optional version string for the data item.\n *\n * dataType - Optional data type for categorizing the secret data.\n */\nexport type AddSecretDataItemParams =\n BaseAddSecretDataItemParams<Uint8Array> & {\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n };\n\n/**\n * BatchAddSecretDataItem - A single item in a batch add operation.\n */\nexport type BatchAddSecretDataItem = {\n data: Uint8Array;\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n};\n\n/**\n * BatchAddSecretDataItemParams - Parameters for batch adding secret data items.\n *\n * secretData - Array of items to store, each with data and optional itemId/dataType.\n *\n * encKey - The encryption key(s) to be used to encrypt the secret data.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\nexport type BatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n BatchAddSecretDataItem[],\n Uint8Array | Uint8Array[]\n>;\n\n/**\n * FetchedSecretDataItem - A secret data item returned from fetch operations.\n */\nexport type FetchedSecretDataItem = {\n data: Uint8Array;\n itemId: string;\n version: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\n/**\n * UpdateSecretDataItemParams - Parameters for updating a secret data item's fields.\n *\n * itemId - The ID of the item to update.\n *\n * dataType - The data type to set for the item.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type UpdateSecretDataItemParams = {\n itemId: string;\n dataType: EncAccountDataType;\n authKeyPair: KeyPair;\n};\n\n/**\n * BatchUpdateSecretDataItemParams - Parameters for batch updating secret data items' fields.\n *\n * updateItems - Array of items to update, each with itemId and fields to update.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type BatchUpdateSecretDataItemParams = {\n updateItems: { itemId: string; dataType: EncAccountDataType }[];\n authKeyPair: KeyPair;\n};\n\n/**\n * RecoverEncryptionKeyParams - The parameters for recovering the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * password - The password of the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type RecoverEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n * encKey - The encryption key which is used to encrypt the secret data.\n * keyShareIndex - The index of the key shares on the nodes, used for key change operations.\n * rateLimitResetResult - A promise that resolves when the rate limit is reset.\n */\nexport type RecoverEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n keyShareIndex: number;\n rateLimitResetResult: Promise<void>;\n};\n\n/**\n * Parameters for changing the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * oldEncKey - The old encryption key of the user.\n *\n * oldAuthKeyPair - The old authentication key pair of the user.\n *\n * newKeyShareIndex - The key share index to be used for the new key.\n *\n * newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n */\nexport type ChangeEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n userId: string;\n oldEncKey: Uint8Array;\n oldPwEncKey: Uint8Array;\n oldAuthKeyPair: KeyPair;\n newKeyShareIndex: number;\n newPassword?: string;\n groupedAuthConnectionId?: string;\n pregeneratedOprfKey?: CreateLocalKeyResult;\n /** Optional callback to sort/transform items after fetching, inside the lock. If omitted, items are re-inserted as-is. */\n transformDataItems?: (\n items: FetchedSecretDataItem[],\n ) => SecretDataItemInput[];\n};\n\n/**\n * authKeyPair - The new authentication key pair which is used to authenticate the user.\n * encKey - The new encryption key which is used to encrypt the secret data.\n */\nexport type ChangeEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * keyPair - The encryption/decryption key pair which is used to decrypt the secret data.\n */\nexport type FetchAllSecretDataParams = {\n /**\n * The decryption key to be used to decrypt the secret data.\n */\n decKey: Uint8Array;\n\n /**\n * The authentication key to be used to provide valid signature for fetching the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * Proof that the user owns the old key when changing to a new password/key\n * Contains a signature created with the old private key on a timestamp and new key share data.\n */\nexport type KeyChangeProof = {\n oldKeySignature: string;\n signatureTimestamp: number;\n};\n\n/**\n * FetchAuthPubKeyParams - The parameters for fetching the authentication public key.\n *\n * nodeAuthTokens - Auth tokens issued by nodes.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user issued by authentication service.\n */\nexport type FetchAuthPubKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n groupedAuthConnectionId?: string;\n userId: string;\n};\n\nexport type FetchAuthPubKeyResult = {\n authPubKey: SEC1EncodedPublicKey;\n keyIndex: number;\n};\n\nexport type RecoverPwEncKeyParams = {\n targetAuthPubKey: SEC1EncodedPublicKey;\n curPwEncKey: Uint8Array;\n curAuthKeyPair: KeyPair;\n maxPwChainLength?: number;\n};\n\nexport type RecoverPwEncKeyResult = {\n pwEncKey: Uint8Array;\n};\n\nexport type IToprfSecureBackup = {\n authenticate: (params: AuthenticateParams) => Promise<AuthenticateResult>;\n\n /**\n * This function locally creates an OPRF and encryption key without storing it at the key\n * management service. It returns the OPRF key, derives the corresponding key\n * seed, authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns A promise that resolves with the encryption key.\n */\n createLocalKey: (\n params: CreateLocalKeyParams,\n ) => Promise<CreateLocalKeyResult>;\n\n /**\n * This function persists an locally created OPRF key's shares to the servers.\n *\n * @param params - The parameters for persisting an OPRF key's shares.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the write request to the metadata store.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n * @returns A promise that resolves when the OPRF key's shares are persisted.\n */\n persistLocalKey: (params: PersistLocalKeyParams) => Promise<void>;\n\n createAndPersistEncKey: (\n params: CreateEncryptionKeyParams,\n ) => Promise<CreateEncryptionKeyResult>;\n\n recoverEncKey: (\n params: RecoverEncryptionKeyParams,\n ) => Promise<RecoverEncryptionKeyResult>;\n\n /**\n * This function replaces the existing encryption key with a new one and copies the secret data of existing encryption key to the new one.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.newPassword - The new password of the user.\n * @param params.keyPair - The current encryption key of the user.\n *\n * @returns A promise that resolves with the new encryption key.\n */\n changeEncKey: (\n params: ChangeEncryptionKeyParams,\n ) => Promise<ChangeEncryptionKeyResult>;\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n * @param params.secretData - The secret data to be registered.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.dataType - Optional data type for categorizing the secret data.\n *\n * @returns A promise that resolves when the secret data is registered.\n */\n addSecretDataItem: (params: AddSecretDataItemParams) => Promise<void>;\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores it in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * @returns A promise that resolves when the secret data is stored.\n */\n batchAddSecretDataItems: (\n params: BatchAddSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when the update is complete.\n */\n updateSecretDataItem: (params: UpdateSecretDataItemParams) => Promise<void>;\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when all updates are complete.\n */\n batchUpdateSecretDataItems: (\n params: BatchUpdateSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns A promise that resolves with the array of decrypted secret data items.\n */\n fetchAllSecretDataItems: (\n params: FetchAllSecretDataParams,\n ) => Promise<FetchedSecretDataItem[]>;\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for fetching the authentication public key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n *\n * @returns A promise that resolves with the authentication public key.\n */\n fetchAuthPubKey: (\n params: FetchAuthPubKeyParams,\n ) => Promise<FetchAuthPubKeyResult>;\n\n /**\n * This function recovers the password encryption key of the user.\n *\n * @param params - The parameters for recovering the password encryption key.\n * @param params.targetAuthPubKey - The public key of the target encryption key.\n * @param params.curPwEncKey - The current password encryption key of the user.\n * @param params.curAuthKeyPair - The current authentication key pair of the user.\n *\n * @returns A promise that resolves to the password encryption key of the user.\n */\n recoverPwEncKey: (\n params: RecoverPwEncKeyParams,\n ) => Promise<RecoverPwEncKeyResult>;\n\n /**\n * This function gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * This function is useful when you want to pre-fetch the node details before any TOPRF operations\n * so that the subsequent calls to the TOPRF operations are faster without waiting for the node details to be fetched.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n getNodeDetails: () => Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }>;\n};\n\n/**\n * Base payload structure for metadata request\n */\nexport type IBaseMetadataRequestBody = {\n /**\n * The feature name related to the secret data\n */\n feature: string;\n /**\n * The public key of the user\n */\n pubKey: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n timestamp: string;\n};\n\n/**\n * The array of secret data to be stored in batch request\n */\nexport type IBatchAddData = {\n /**\n * The base64-encoded string of the secret data\n */\n data: string;\n /**\n * The version of the Metadata Store\n */\n version?: string;\n /**\n * Optional item id for the data item\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n}[];\n\n/**\n * Payload structure for storing secret data\n */\nexport type IBaseAddSecretDataRequestBody<DataType> =\n IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n * this token is also known as `metadataAccessToken`.\n */\n authToken?: string;\n /**\n * The secret data to be stored.\n *\n * For storing the single secret data, the data should be base64-encoded string.\n *\n * @example\n * ```ts\n * const data = Buffer.from('SECRET_DATA').toString('base64');\n * ```\n *\n * For storing the batch of secret data, the data should be an array of `IBatchAddData`.\n *\n * @example\n * ```ts\n * const data = [\n * { data: Buffer.from('SECRET_DATA_1').toString('base64') },\n * { data: Buffer.from('SECRET_DATA_2').toString('base64') },\n * ];\n * ```\n */\n data: DataType;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(data, feature, authToken, timestamp))\n */\n signature: string;\n };\n\n/**\n * Payload structure for storing secret data for single secret data\n */\nexport type IAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<string> & {\n /**\n * The version of the secret data\n */\n version?: string;\n /**\n * The item id to be used for storing the secret data.\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n };\n\n/**\n * Payload structure for storing secret data in batch request\n */\nexport type IBatchAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<IBatchAddData>;\n\n/**\n * Fields that can be updated for an existing secret data item.\n */\nexport type UpdateSecretDataItemFields = {\n /**\n * The data type to set for the item\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n};\n\n/**\n * Payload structure for updating secret data fields by itemId\n */\nexport type IUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The item id of the record to update\n */\n itemId: string;\n /**\n * The data type for categorizing the secret data\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for batch updating secret data fields by itemId\n */\nexport type IBatchUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The array of items to update\n */\n items: {\n itemId: string;\n dataType: EncAccountDataType;\n version?: 'v1' | 'v2';\n }[];\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for fetching secret data\n */\nexport type IGetSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by the SSS services\n */\n authToken?: string;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The item id to be used for fetching the secret data.\n */\n itemId?: string;\n};\n\n/**\n * Payload structure for acquiring/releasing a lock on the metadata\n */\nexport type IMetadataLockRequestBody = {\n /**\n * The public key of the user\n */\n key: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n data: {\n timestamp: number;\n };\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The lock id to be released.\n */\n id?: string | undefined;\n};\n\n/**\n * FetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n *\n * @returns The metadata access credentials.\n */\nexport type FetchMetadataAccessCreds = () => Promise<{\n metadataAccessToken: string;\n}>;\n"]}
import type { INodePub } from "@toruslabs/constants";
import type { EncAccountDataType } from "./constants.cjs";
export type SecretDataItem = {
itemId?: string;
data: Uint8Array;
version?: 'v1' | 'v2';
dataType?: EncAccountDataType;
createdAt?: string;
};
export type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;
export type SecretDataItemOutput = SecretDataItem & {
itemId: string;
version: 'v1' | 'v2';
};
/**

@@ -343,2 +355,4 @@ * SEC1 encoded public key

pregeneratedOprfKey?: CreateLocalKeyResult;
/** Optional callback to sort/transform items after fetching, inside the lock. If omitted, items are re-inserted as-is. */
transformDataItems?: (items: FetchedSecretDataItem[]) => SecretDataItemInput[];
};

@@ -345,0 +359,0 @@ /**

@@ -1,1 +0,1 @@

{"version":3,"file":"interfaces.d.cts","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,6BAA6B;AAErD,OAAO,KAAK,EAAE,kBAAkB,EAAE,wBAAoB;AAEtD;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,oBAAoB,CAAC;CAC1B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;OAEG;IACH,OAAO,CAAC,EAAE,QAAQ,EAAE,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAG/B,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,uBAAuB,CAAC,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE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ruslabs/constants";
import type { EncAccountDataType } from "./constants.mjs";
export type SecretDataItem = {
itemId?: string;
data: Uint8Array;
version?: 'v1' | 'v2';
dataType?: EncAccountDataType;
createdAt?: string;
};
export type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;
export type SecretDataItemOutput = SecretDataItem & {
itemId: string;
version: 'v1' | 'v2';
};
/**

@@ -343,2 +355,4 @@ * SEC1 encoded public key

pregeneratedOprfKey?: CreateLocalKeyResult;
/** Optional callback to sort/transform items after fetching, inside the lock. If omitted, items are re-inserted as-is. */
transformDataItems?: (items: FetchedSecretDataItem[]) => SecretDataItemInput[];
};

@@ -345,0 +359,0 @@ /**

@@ -1,1 +0,1 @@

{"version":3,"file":"interfaces.d.mts","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,6BAA6B;AAErD,OAAO,KAAK,EAAE,kBAAkB,EAAE,wBAAoB;AAEtD;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,oBAAoB,CAAC;CAC1B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;OAEG;IACH,OAAO,CAAC,EAAE,QAAQ,EAAE,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAG/B,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,uBAAuB,CAAC,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF;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AAG,MAAM,OAAO,CAAC;IACnD,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC,CAAC"}

@@ -1,1 +0,1 @@

{"version":3,"file":"interfaces.mjs","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type { INodePub } from '@toruslabs/constants';\n\nimport type { EncAccountDataType } from './constants';\n\n/**\n * SEC1 encoded public key\n */\nexport type SEC1EncodedPublicKey = Uint8Array;\n\n/**\n * KeyPair - The encryption/decryption private and public key pair.\n *\n * sk - The decryption private key in bigint format.\n *\n * pk - The encryption public key in SEC1 encoded format.\n */\nexport type KeyPair = {\n sk: bigint;\n pk: SEC1EncodedPublicKey;\n};\n\n/**\n * Optional override for node details.\n */\nexport type NodeDetailsOverride = {\n /**\n * Endpoint configuration. This allows for overriding the default SSS node endpoints.\n *\n * - **To use FND-resolved node URLs with a custom path:** Provide a single `string`\n * representing the path to be appended to each FND-resolved node URL.\n * For example, `'/sss-toprf'` will transform FND URLs like `https://node1.example.com`\n * into `https://node1.example.com/sss-toprf`.\n *\n * - **To use a completely custom set of node URLs (bypassing FND resolution):**\n * Provide an array of `string[]` where each string is a complete endpoint URL.\n * For example, `['https://custom-node1.com/custom-path', 'https://custom-node2.com/custom-path']`.\n *\n * If left `undefined`, the SDK will use the default FND-resolved SSS endpoints directly.\n */\n endpoints?: string | string[];\n /**\n * Array of node indexes. Must match network node count if provided.\n */\n indexes?: number[];\n /**\n * Array of node public keys. Must match network node count if provided.\n */\n pubKeys?: INodePub[];\n};\n\n/**\n * AuthenticateParams - The parameters for the authenticate request.\n *\n * idTokens - The idTokens to be used for the authenticate request.\n *\n * authConnectionId - The auth connection name to be used for the authenticate request.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user to be used for the authenticate request.\n *\n * groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n */\nexport type AuthenticateParams = {\n // for now we only support one idToken, in future we will support multiple to remove commitment call\n // so leaving it as an array for future use\n idTokens: string[];\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * NodeAuthToken - An authentication token and the node details.\n *\n * authToken - The authentication token.\n *\n * nodeIndex - The index of the node that issued the token.\n *\n * nodePubKey - The public key of the node that issued the token.\n */\nexport type NodeAuthToken = {\n authToken: string;\n nodeIndex: number;\n nodePubKey: string;\n};\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n */\nexport type NodeAuthTokens = NodeAuthToken[];\n\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n *\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n */\nexport type AuthenticateResult = {\n nodeAuthTokens: NodeAuthTokens;\n isNewUser: boolean;\n};\n\n/**\n * CreateLocalKeyParams - The parameters for creating an OPRF encryption key locally.\n *\n * password - The password of the user.\n *\n * oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n */\nexport type CreateLocalKeyParams = {\n password: string;\n oprfKey?: bigint;\n};\n\n/**\n * CreateLocalKeyResult - The result of creating an encryption key.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * seed - The seed which is used to derive the authentication and encryption keys.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n */\nexport type CreateLocalKeyResult = {\n oprfKey: bigint;\n seed: Uint8Array;\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * PersistLocalKeyParams - The parameters for persisting an OPRF key's shares to the servers.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * authPubKey - The authentication public key which is used to authenticate the write request to the metadata store.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * keyShareIndex - Optional key share index to be persisted.\n *\n * oldAuthKeyPair - Optional authentication key pair to be used for key change flow.\n */\nexport type PersistLocalKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n oprfKey: bigint;\n authPubKey: SEC1EncodedPublicKey;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n keyShareIndex?: number;\n oldAuthKeyPair?: KeyPair;\n};\n\n/**\n * CreateEncryptionKeyParams - The parameters for creating an encryption key.\n *\n * authConnectionId - The auth connection name of the user.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * nodeAuthTokens - The tokens issued by the nodes on verifying the idTokens.\n *\n * password - The password of the user.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type CreateEncryptionKeyParams = {\n authConnectionId: string;\n userId: string;\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * CreateEncryptionKeyResult - The result of creating an encryption key.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n *\n * pwEncKey - The password encryption key which is used to encrypt the password.\n */\nexport type CreateEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\nexport type BaseAddSecretDataItemParams<\n SecretDataType,\n EncKeyType = Uint8Array,\n> = {\n /**\n * The secret data to be stored.\n */\n secretData: SecretDataType;\n\n /**\n * The encryption key to be used to encrypt the secret data.\n */\n encKey: EncKeyType;\n\n /**\n * The authentication key to be used to provide valid signature for storing the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * AddSecretDataItemParams - Parameters for adding a secret data item.\n *\n * secretData - The secret data to be stored.\n *\n * encKey - The encryption key to be used to encrypt the secret data before storing it.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * itemId - Optional item ID for the data item.\n *\n * version - Optional version string for the data item.\n *\n * dataType - Optional data type for categorizing the secret data.\n */\nexport type AddSecretDataItemParams =\n BaseAddSecretDataItemParams<Uint8Array> & {\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n };\n\n/**\n * BatchAddSecretDataItem - A single item in a batch add operation.\n */\nexport type BatchAddSecretDataItem = {\n data: Uint8Array;\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n};\n\n/**\n * BatchAddSecretDataItemParams - Parameters for batch adding secret data items.\n *\n * secretData - Array of items to store, each with data and optional itemId/dataType.\n *\n * encKey - The encryption key(s) to be used to encrypt the secret data.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\nexport type BatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n BatchAddSecretDataItem[],\n Uint8Array | Uint8Array[]\n>;\n\n/**\n * FetchedSecretDataItem - A secret data item returned from fetch operations.\n */\nexport type FetchedSecretDataItem = {\n data: Uint8Array;\n itemId: string;\n version: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\n/**\n * UpdateSecretDataItemParams - Parameters for updating a secret data item's fields.\n *\n * itemId - The ID of the item to update.\n *\n * dataType - The data type to set for the item.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type UpdateSecretDataItemParams = {\n itemId: string;\n dataType: EncAccountDataType;\n authKeyPair: KeyPair;\n};\n\n/**\n * BatchUpdateSecretDataItemParams - Parameters for batch updating secret data items' fields.\n *\n * updateItems - Array of items to update, each with itemId and fields to update.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type BatchUpdateSecretDataItemParams = {\n updateItems: { itemId: string; dataType: EncAccountDataType }[];\n authKeyPair: KeyPair;\n};\n\n/**\n * RecoverEncryptionKeyParams - The parameters for recovering the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * password - The password of the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type RecoverEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n * encKey - The encryption key which is used to encrypt the secret data.\n * keyShareIndex - The index of the key shares on the nodes, used for key change operations.\n * rateLimitResetResult - A promise that resolves when the rate limit is reset.\n */\nexport type RecoverEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n keyShareIndex: number;\n rateLimitResetResult: Promise<void>;\n};\n\n/**\n * Parameters for changing the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * oldEncKey - The old encryption key of the user.\n *\n * oldAuthKeyPair - The old authentication key pair of the user.\n *\n * newKeyShareIndex - The key share index to be used for the new key.\n *\n * newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n */\nexport type ChangeEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n userId: string;\n oldEncKey: Uint8Array;\n oldPwEncKey: Uint8Array;\n oldAuthKeyPair: KeyPair;\n newKeyShareIndex: number;\n newPassword?: string;\n groupedAuthConnectionId?: string;\n pregeneratedOprfKey?: CreateLocalKeyResult;\n};\n\n/**\n * authKeyPair - The new authentication key pair which is used to authenticate the user.\n * encKey - The new encryption key which is used to encrypt the secret data.\n */\nexport type ChangeEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * keyPair - The encryption/decryption key pair which is used to decrypt the secret data.\n */\nexport type FetchAllSecretDataParams = {\n /**\n * The decryption key to be used to decrypt the secret data.\n */\n decKey: Uint8Array;\n\n /**\n * The authentication key to be used to provide valid signature for fetching the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * Proof that the user owns the old key when changing to a new password/key\n * Contains a signature created with the old private key on a timestamp and new key share data.\n */\nexport type KeyChangeProof = {\n oldKeySignature: string;\n signatureTimestamp: number;\n};\n\n/**\n * FetchAuthPubKeyParams - The parameters for fetching the authentication public key.\n *\n * nodeAuthTokens - Auth tokens issued by nodes.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user issued by authentication service.\n */\nexport type FetchAuthPubKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n groupedAuthConnectionId?: string;\n userId: string;\n};\n\nexport type FetchAuthPubKeyResult = {\n authPubKey: SEC1EncodedPublicKey;\n keyIndex: number;\n};\n\nexport type RecoverPwEncKeyParams = {\n targetAuthPubKey: SEC1EncodedPublicKey;\n curPwEncKey: Uint8Array;\n curAuthKeyPair: KeyPair;\n maxPwChainLength?: number;\n};\n\nexport type RecoverPwEncKeyResult = {\n pwEncKey: Uint8Array;\n};\n\nexport type IToprfSecureBackup = {\n authenticate: (params: AuthenticateParams) => Promise<AuthenticateResult>;\n\n /**\n * This function locally creates an OPRF and encryption key without storing it at the key\n * management service. It returns the OPRF key, derives the corresponding key\n * seed, authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns A promise that resolves with the encryption key.\n */\n createLocalKey: (\n params: CreateLocalKeyParams,\n ) => Promise<CreateLocalKeyResult>;\n\n /**\n * This function persists an locally created OPRF key's shares to the servers.\n *\n * @param params - The parameters for persisting an OPRF key's shares.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the write request to the metadata store.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n * @returns A promise that resolves when the OPRF key's shares are persisted.\n */\n persistLocalKey: (params: PersistLocalKeyParams) => Promise<void>;\n\n createAndPersistEncKey: (\n params: CreateEncryptionKeyParams,\n ) => Promise<CreateEncryptionKeyResult>;\n\n recoverEncKey: (\n params: RecoverEncryptionKeyParams,\n ) => Promise<RecoverEncryptionKeyResult>;\n\n /**\n * This function replaces the existing encryption key with a new one and copies the secret data of existing encryption key to the new one.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.newPassword - The new password of the user.\n * @param params.keyPair - The current encryption key of the user.\n *\n * @returns A promise that resolves with the new encryption key.\n */\n changeEncKey: (\n params: ChangeEncryptionKeyParams,\n ) => Promise<ChangeEncryptionKeyResult>;\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n * @param params.secretData - The secret data to be registered.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.dataType - Optional data type for categorizing the secret data.\n *\n * @returns A promise that resolves when the secret data is registered.\n */\n addSecretDataItem: (params: AddSecretDataItemParams) => Promise<void>;\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores it in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * @returns A promise that resolves when the secret data is stored.\n */\n batchAddSecretDataItems: (\n params: BatchAddSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when the update is complete.\n */\n updateSecretDataItem: (params: UpdateSecretDataItemParams) => Promise<void>;\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when all updates are complete.\n */\n batchUpdateSecretDataItems: (\n params: BatchUpdateSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns A promise that resolves with the array of decrypted secret data items.\n */\n fetchAllSecretDataItems: (\n params: FetchAllSecretDataParams,\n ) => Promise<FetchedSecretDataItem[]>;\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for fetching the authentication public key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n *\n * @returns A promise that resolves with the authentication public key.\n */\n fetchAuthPubKey: (\n params: FetchAuthPubKeyParams,\n ) => Promise<FetchAuthPubKeyResult>;\n\n /**\n * This function recovers the password encryption key of the user.\n *\n * @param params - The parameters for recovering the password encryption key.\n * @param params.targetAuthPubKey - The public key of the target encryption key.\n * @param params.curPwEncKey - The current password encryption key of the user.\n * @param params.curAuthKeyPair - The current authentication key pair of the user.\n *\n * @returns A promise that resolves to the password encryption key of the user.\n */\n recoverPwEncKey: (\n params: RecoverPwEncKeyParams,\n ) => Promise<RecoverPwEncKeyResult>;\n\n /**\n * This function gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * This function is useful when you want to pre-fetch the node details before any TOPRF operations\n * so that the subsequent calls to the TOPRF operations are faster without waiting for the node details to be fetched.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n getNodeDetails: () => Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }>;\n};\n\n/**\n * Base payload structure for metadata request\n */\nexport type IBaseMetadataRequestBody = {\n /**\n * The feature name related to the secret data\n */\n feature: string;\n /**\n * The public key of the user\n */\n pubKey: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n timestamp: string;\n};\n\n/**\n * The array of secret data to be stored in batch request\n */\nexport type IBatchAddData = {\n /**\n * The base64-encoded string of the secret data\n */\n data: string;\n /**\n * The version of the Metadata Store\n */\n version?: string;\n /**\n * Optional item id for the data item\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n}[];\n\n/**\n * Payload structure for storing secret data\n */\nexport type IBaseAddSecretDataRequestBody<DataType> =\n IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n * this token is also known as `metadataAccessToken`.\n */\n authToken?: string;\n /**\n * The secret data to be stored.\n *\n * For storing the single secret data, the data should be base64-encoded string.\n *\n * @example\n * ```ts\n * const data = Buffer.from('SECRET_DATA').toString('base64');\n * ```\n *\n * For storing the batch of secret data, the data should be an array of `IBatchAddData`.\n *\n * @example\n * ```ts\n * const data = [\n * { data: Buffer.from('SECRET_DATA_1').toString('base64') },\n * { data: Buffer.from('SECRET_DATA_2').toString('base64') },\n * ];\n * ```\n */\n data: DataType;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(data, feature, authToken, timestamp))\n */\n signature: string;\n };\n\n/**\n * Payload structure for storing secret data for single secret data\n */\nexport type IAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<string> & {\n /**\n * The version of the secret data\n */\n version?: string;\n /**\n * The item id to be used for storing the secret data.\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n };\n\n/**\n * Payload structure for storing secret data in batch request\n */\nexport type IBatchAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<IBatchAddData>;\n\n/**\n * Fields that can be updated for an existing secret data item.\n */\nexport type UpdateSecretDataItemFields = {\n /**\n * The data type to set for the item\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n};\n\n/**\n * Payload structure for updating secret data fields by itemId\n */\nexport type IUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The item id of the record to update\n */\n itemId: string;\n /**\n * The data type for categorizing the secret data\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for batch updating secret data fields by itemId\n */\nexport type IBatchUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The array of items to update\n */\n items: {\n itemId: string;\n dataType: EncAccountDataType;\n version?: 'v1' | 'v2';\n }[];\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for fetching secret data\n */\nexport type IGetSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by the SSS services\n */\n authToken?: string;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The item id to be used for fetching the secret data.\n */\n itemId?: string;\n};\n\n/**\n * Payload structure for acquiring/releasing a lock on the metadata\n */\nexport type IMetadataLockRequestBody = {\n /**\n * The public key of the user\n */\n key: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n data: {\n timestamp: number;\n };\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The lock id to be released.\n */\n id?: string | undefined;\n};\n\n/**\n * FetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n *\n * @returns The metadata access credentials.\n */\nexport type FetchMetadataAccessCreds = () => Promise<{\n metadataAccessToken: string;\n}>;\n"]}
{"version":3,"file":"interfaces.mjs","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type { INodePub } from '@toruslabs/constants';\n\nimport type { EncAccountDataType } from './constants';\n\nexport type SecretDataItem = {\n itemId?: string;\n data: Uint8Array;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\nexport type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;\n\nexport type SecretDataItemOutput = SecretDataItem & {\n itemId: string;\n version: 'v1' | 'v2';\n};\n\n/**\n * SEC1 encoded public key\n */\nexport type SEC1EncodedPublicKey = Uint8Array;\n\n/**\n * KeyPair - The encryption/decryption private and public key pair.\n *\n * sk - The decryption private key in bigint format.\n *\n * pk - The encryption public key in SEC1 encoded format.\n */\nexport type KeyPair = {\n sk: bigint;\n pk: SEC1EncodedPublicKey;\n};\n\n/**\n * Optional override for node details.\n */\nexport type NodeDetailsOverride = {\n /**\n * Endpoint configuration. This allows for overriding the default SSS node endpoints.\n *\n * - **To use FND-resolved node URLs with a custom path:** Provide a single `string`\n * representing the path to be appended to each FND-resolved node URL.\n * For example, `'/sss-toprf'` will transform FND URLs like `https://node1.example.com`\n * into `https://node1.example.com/sss-toprf`.\n *\n * - **To use a completely custom set of node URLs (bypassing FND resolution):**\n * Provide an array of `string[]` where each string is a complete endpoint URL.\n * For example, `['https://custom-node1.com/custom-path', 'https://custom-node2.com/custom-path']`.\n *\n * If left `undefined`, the SDK will use the default FND-resolved SSS endpoints directly.\n */\n endpoints?: string | string[];\n /**\n * Array of node indexes. Must match network node count if provided.\n */\n indexes?: number[];\n /**\n * Array of node public keys. Must match network node count if provided.\n */\n pubKeys?: INodePub[];\n};\n\n/**\n * AuthenticateParams - The parameters for the authenticate request.\n *\n * idTokens - The idTokens to be used for the authenticate request.\n *\n * authConnectionId - The auth connection name to be used for the authenticate request.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user to be used for the authenticate request.\n *\n * groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n */\nexport type AuthenticateParams = {\n // for now we only support one idToken, in future we will support multiple to remove commitment call\n // so leaving it as an array for future use\n idTokens: string[];\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * NodeAuthToken - An authentication token and the node details.\n *\n * authToken - The authentication token.\n *\n * nodeIndex - The index of the node that issued the token.\n *\n * nodePubKey - The public key of the node that issued the token.\n */\nexport type NodeAuthToken = {\n authToken: string;\n nodeIndex: number;\n nodePubKey: string;\n};\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n */\nexport type NodeAuthTokens = NodeAuthToken[];\n\n/**\n * nodeAuthTokens - An array of authentication tokens issued by the nodes.\n *\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n */\nexport type AuthenticateResult = {\n nodeAuthTokens: NodeAuthTokens;\n isNewUser: boolean;\n};\n\n/**\n * CreateLocalKeyParams - The parameters for creating an OPRF encryption key locally.\n *\n * password - The password of the user.\n *\n * oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n */\nexport type CreateLocalKeyParams = {\n password: string;\n oprfKey?: bigint;\n};\n\n/**\n * CreateLocalKeyResult - The result of creating an encryption key.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * seed - The seed which is used to derive the authentication and encryption keys.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n */\nexport type CreateLocalKeyResult = {\n oprfKey: bigint;\n seed: Uint8Array;\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * PersistLocalKeyParams - The parameters for persisting an OPRF key's shares to the servers.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * oprfKey - The OPRF key which is used to for local OPRF evaluation.\n *\n * authPubKey - The authentication public key which is used to authenticate the write request to the metadata store.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * keyShareIndex - Optional key share index to be persisted.\n *\n * oldAuthKeyPair - Optional authentication key pair to be used for key change flow.\n */\nexport type PersistLocalKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n oprfKey: bigint;\n authPubKey: SEC1EncodedPublicKey;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n keyShareIndex?: number;\n oldAuthKeyPair?: KeyPair;\n};\n\n/**\n * CreateEncryptionKeyParams - The parameters for creating an encryption key.\n *\n * authConnectionId - The auth connection name of the user.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * nodeAuthTokens - The tokens issued by the nodes on verifying the idTokens.\n *\n * password - The password of the user.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type CreateEncryptionKeyParams = {\n authConnectionId: string;\n userId: string;\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * CreateEncryptionKeyResult - The result of creating an encryption key.\n *\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n *\n * encKey - The encryption key which is used to encrypt the secret data.\n *\n * pwEncKey - The password encryption key which is used to encrypt the password.\n */\nexport type CreateEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\nexport type BaseAddSecretDataItemParams<\n SecretDataType,\n EncKeyType = Uint8Array,\n> = {\n /**\n * The secret data to be stored.\n */\n secretData: SecretDataType;\n\n /**\n * The encryption key to be used to encrypt the secret data.\n */\n encKey: EncKeyType;\n\n /**\n * The authentication key to be used to provide valid signature for storing the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * AddSecretDataItemParams - Parameters for adding a secret data item.\n *\n * secretData - The secret data to be stored.\n *\n * encKey - The encryption key to be used to encrypt the secret data before storing it.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * itemId - Optional item ID for the data item.\n *\n * version - Optional version string for the data item.\n *\n * dataType - Optional data type for categorizing the secret data.\n */\nexport type AddSecretDataItemParams =\n BaseAddSecretDataItemParams<Uint8Array> & {\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n };\n\n/**\n * BatchAddSecretDataItem - A single item in a batch add operation.\n */\nexport type BatchAddSecretDataItem = {\n data: Uint8Array;\n itemId?: string;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n};\n\n/**\n * BatchAddSecretDataItemParams - Parameters for batch adding secret data items.\n *\n * secretData - Array of items to store, each with data and optional itemId/dataType.\n *\n * encKey - The encryption key(s) to be used to encrypt the secret data.\n *\n * authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\nexport type BatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n BatchAddSecretDataItem[],\n Uint8Array | Uint8Array[]\n>;\n\n/**\n * FetchedSecretDataItem - A secret data item returned from fetch operations.\n */\nexport type FetchedSecretDataItem = {\n data: Uint8Array;\n itemId: string;\n version: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\n/**\n * UpdateSecretDataItemParams - Parameters for updating a secret data item's fields.\n *\n * itemId - The ID of the item to update.\n *\n * dataType - The data type to set for the item.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type UpdateSecretDataItemParams = {\n itemId: string;\n dataType: EncAccountDataType;\n authKeyPair: KeyPair;\n};\n\n/**\n * BatchUpdateSecretDataItemParams - Parameters for batch updating secret data items' fields.\n *\n * updateItems - Array of items to update, each with itemId and fields to update.\n *\n * authKeyPair - The authentication key pair for signing the request.\n */\nexport type BatchUpdateSecretDataItemParams = {\n updateItems: { itemId: string; dataType: EncAccountDataType }[];\n authKeyPair: KeyPair;\n};\n\n/**\n * RecoverEncryptionKeyParams - The parameters for recovering the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * password - The password of the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n */\nexport type RecoverEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n password: string;\n authConnectionId: string;\n userId: string;\n groupedAuthConnectionId?: string;\n};\n\n/**\n * authKeyPair - The authentication key pair which is used to authenticate the user.\n * encKey - The encryption key which is used to encrypt the secret data.\n * keyShareIndex - The index of the key shares on the nodes, used for key change operations.\n * rateLimitResetResult - A promise that resolves when the rate limit is reset.\n */\nexport type RecoverEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n keyShareIndex: number;\n rateLimitResetResult: Promise<void>;\n};\n\n/**\n * Parameters for changing the encryption key.\n *\n * nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * userId - The user id of the user issued by authentication service.\n *\n * oldEncKey - The old encryption key of the user.\n *\n * oldAuthKeyPair - The old authentication key pair of the user.\n *\n * newKeyShareIndex - The key share index to be used for the new key.\n *\n * newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n */\nexport type ChangeEncryptionKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n userId: string;\n oldEncKey: Uint8Array;\n oldPwEncKey: Uint8Array;\n oldAuthKeyPair: KeyPair;\n newKeyShareIndex: number;\n newPassword?: string;\n groupedAuthConnectionId?: string;\n pregeneratedOprfKey?: CreateLocalKeyResult;\n /** Optional callback to sort/transform items after fetching, inside the lock. If omitted, items are re-inserted as-is. */\n transformDataItems?: (\n items: FetchedSecretDataItem[],\n ) => SecretDataItemInput[];\n};\n\n/**\n * authKeyPair - The new authentication key pair which is used to authenticate the user.\n * encKey - The new encryption key which is used to encrypt the secret data.\n */\nexport type ChangeEncryptionKeyResult = {\n authKeyPair: KeyPair;\n encKey: Uint8Array;\n pwEncKey: Uint8Array;\n};\n\n/**\n * keyPair - The encryption/decryption key pair which is used to decrypt the secret data.\n */\nexport type FetchAllSecretDataParams = {\n /**\n * The decryption key to be used to decrypt the secret data.\n */\n decKey: Uint8Array;\n\n /**\n * The authentication key to be used to provide valid signature for fetching the secret data.\n */\n authKeyPair: KeyPair;\n};\n\n/**\n * Proof that the user owns the old key when changing to a new password/key\n * Contains a signature created with the old private key on a timestamp and new key share data.\n */\nexport type KeyChangeProof = {\n oldKeySignature: string;\n signatureTimestamp: number;\n};\n\n/**\n * FetchAuthPubKeyParams - The parameters for fetching the authentication public key.\n *\n * nodeAuthTokens - Auth tokens issued by nodes.\n *\n * authConnectionId - The auth connection name used for authentication.\n *\n * groupedAuthConnectionId - Optional grouped auth connection id to be used for the authenticate request with aggregate (single id) verifier.\n *\n * userId - The user id of the user issued by authentication service.\n */\nexport type FetchAuthPubKeyParams = {\n nodeAuthTokens: NodeAuthTokens;\n authConnectionId: string;\n groupedAuthConnectionId?: string;\n userId: string;\n};\n\nexport type FetchAuthPubKeyResult = {\n authPubKey: SEC1EncodedPublicKey;\n keyIndex: number;\n};\n\nexport type RecoverPwEncKeyParams = {\n targetAuthPubKey: SEC1EncodedPublicKey;\n curPwEncKey: Uint8Array;\n curAuthKeyPair: KeyPair;\n maxPwChainLength?: number;\n};\n\nexport type RecoverPwEncKeyResult = {\n pwEncKey: Uint8Array;\n};\n\nexport type IToprfSecureBackup = {\n authenticate: (params: AuthenticateParams) => Promise<AuthenticateResult>;\n\n /**\n * This function locally creates an OPRF and encryption key without storing it at the key\n * management service. It returns the OPRF key, derives the corresponding key\n * seed, authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns A promise that resolves with the encryption key.\n */\n createLocalKey: (\n params: CreateLocalKeyParams,\n ) => Promise<CreateLocalKeyResult>;\n\n /**\n * This function persists an locally created OPRF key's shares to the servers.\n *\n * @param params - The parameters for persisting an OPRF key's shares.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the write request to the metadata store.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n * @returns A promise that resolves when the OPRF key's shares are persisted.\n */\n persistLocalKey: (params: PersistLocalKeyParams) => Promise<void>;\n\n createAndPersistEncKey: (\n params: CreateEncryptionKeyParams,\n ) => Promise<CreateEncryptionKeyResult>;\n\n recoverEncKey: (\n params: RecoverEncryptionKeyParams,\n ) => Promise<RecoverEncryptionKeyResult>;\n\n /**\n * This function replaces the existing encryption key with a new one and copies the secret data of existing encryption key to the new one.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.newPassword - The new password of the user.\n * @param params.keyPair - The current encryption key of the user.\n *\n * @returns A promise that resolves with the new encryption key.\n */\n changeEncKey: (\n params: ChangeEncryptionKeyParams,\n ) => Promise<ChangeEncryptionKeyResult>;\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n * @param params.secretData - The secret data to be registered.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.dataType - Optional data type for categorizing the secret data.\n *\n * @returns A promise that resolves when the secret data is registered.\n */\n addSecretDataItem: (params: AddSecretDataItemParams) => Promise<void>;\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores it in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n *\n * @returns A promise that resolves when the secret data is stored.\n */\n batchAddSecretDataItems: (\n params: BatchAddSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when the update is complete.\n */\n updateSecretDataItem: (params: UpdateSecretDataItemParams) => Promise<void>;\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n *\n * @returns A promise that resolves when all updates are complete.\n */\n batchUpdateSecretDataItems: (\n params: BatchUpdateSecretDataItemParams,\n ) => Promise<void>;\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns A promise that resolves with the array of decrypted secret data items.\n */\n fetchAllSecretDataItems: (\n params: FetchAllSecretDataParams,\n ) => Promise<FetchedSecretDataItem[]>;\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for fetching the authentication public key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.userId - The user id of the user issued by authentication service.\n *\n * @returns A promise that resolves with the authentication public key.\n */\n fetchAuthPubKey: (\n params: FetchAuthPubKeyParams,\n ) => Promise<FetchAuthPubKeyResult>;\n\n /**\n * This function recovers the password encryption key of the user.\n *\n * @param params - The parameters for recovering the password encryption key.\n * @param params.targetAuthPubKey - The public key of the target encryption key.\n * @param params.curPwEncKey - The current password encryption key of the user.\n * @param params.curAuthKeyPair - The current authentication key pair of the user.\n *\n * @returns A promise that resolves to the password encryption key of the user.\n */\n recoverPwEncKey: (\n params: RecoverPwEncKeyParams,\n ) => Promise<RecoverPwEncKeyResult>;\n\n /**\n * This function gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * This function is useful when you want to pre-fetch the node details before any TOPRF operations\n * so that the subsequent calls to the TOPRF operations are faster without waiting for the node details to be fetched.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n getNodeDetails: () => Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }>;\n};\n\n/**\n * Base payload structure for metadata request\n */\nexport type IBaseMetadataRequestBody = {\n /**\n * The feature name related to the secret data\n */\n feature: string;\n /**\n * The public key of the user\n */\n pubKey: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n timestamp: string;\n};\n\n/**\n * The array of secret data to be stored in batch request\n */\nexport type IBatchAddData = {\n /**\n * The base64-encoded string of the secret data\n */\n data: string;\n /**\n * The version of the Metadata Store\n */\n version?: string;\n /**\n * Optional item id for the data item\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n}[];\n\n/**\n * Payload structure for storing secret data\n */\nexport type IBaseAddSecretDataRequestBody<DataType> =\n IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n * this token is also known as `metadataAccessToken`.\n */\n authToken?: string;\n /**\n * The secret data to be stored.\n *\n * For storing the single secret data, the data should be base64-encoded string.\n *\n * @example\n * ```ts\n * const data = Buffer.from('SECRET_DATA').toString('base64');\n * ```\n *\n * For storing the batch of secret data, the data should be an array of `IBatchAddData`.\n *\n * @example\n * ```ts\n * const data = [\n * { data: Buffer.from('SECRET_DATA_1').toString('base64') },\n * { data: Buffer.from('SECRET_DATA_2').toString('base64') },\n * ];\n * ```\n */\n data: DataType;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(data, feature, authToken, timestamp))\n */\n signature: string;\n };\n\n/**\n * Payload structure for storing secret data for single secret data\n */\nexport type IAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<string> & {\n /**\n * The version of the secret data\n */\n version?: string;\n /**\n * The item id to be used for storing the secret data.\n */\n itemId?: string;\n /**\n * Optional data type for categorizing the secret data\n */\n dataType?: EncAccountDataType;\n };\n\n/**\n * Payload structure for storing secret data in batch request\n */\nexport type IBatchAddSecretDataRequestBody =\n IBaseAddSecretDataRequestBody<IBatchAddData>;\n\n/**\n * Fields that can be updated for an existing secret data item.\n */\nexport type UpdateSecretDataItemFields = {\n /**\n * The data type to set for the item\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n};\n\n/**\n * Payload structure for updating secret data fields by itemId\n */\nexport type IUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The item id of the record to update\n */\n itemId: string;\n /**\n * The data type for categorizing the secret data\n */\n dataType: EncAccountDataType;\n /**\n * The version to set for the item. Defaults to 'v2' on server if not provided.\n */\n version?: 'v1' | 'v2';\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for batch updating secret data fields by itemId\n */\nexport type IBatchUpdateSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by authentication service.\n */\n authToken?: string;\n /**\n * The array of items to update\n */\n items: {\n itemId: string;\n dataType: EncAccountDataType;\n version?: 'v1' | 'v2';\n }[];\n /**\n * The signature produced by signing the payload using the user's private key.\n */\n signature: string;\n};\n\n/**\n * Payload structure for fetching secret data\n */\nexport type IGetSecretDataRequestBody = IBaseMetadataRequestBody & {\n /**\n * The authentication token of the user issued by the SSS services\n */\n authToken?: string;\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The item id to be used for fetching the secret data.\n */\n itemId?: string;\n};\n\n/**\n * Payload structure for acquiring/releasing a lock on the metadata\n */\nexport type IMetadataLockRequestBody = {\n /**\n * The public key of the user\n */\n key: string;\n /**\n * The Unix timestamp when the request payload is created along with the signature.\n *\n */\n data: {\n timestamp: number;\n };\n /**\n * The signature produced by signing the payload (without pubKey field) using the user's private key.\n *\n * Sample signature: sign(keccak256(feature, authToken, timestamp))\n */\n signature: string;\n /**\n * The lock id to be released.\n */\n id?: string | undefined;\n};\n\n/**\n * FetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n *\n * @returns The metadata access credentials.\n */\nexport type FetchMetadataAccessCreds = () => Promise<{\n metadataAccessToken: string;\n}>;\n"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"metadata.cjs","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAA6D;AAC7D,4CAAyC;AACzC,wDAAwD;AACxD,uDAAoD;AACpD,6CAA6D;AAC7D,+CAAiD;AAEjD,+CAAyE;AAyBzE,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,+DAAU,CAAA;IACV,iEAAW,CAAA;AACb,CAAC,EAHW,kBAAkB,kCAAlB,kBAAkB,QAG7B;AA8CD;;GAEG;AACH,MAAa,kBAAmB,SAAQ,KAAK;IAC3C;;;;OAIG;IACH,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACF;AAXD,gDAWC;AAED;;;;;GAKG;AACH,MAAa,aAAa;IAOxB;;;;;;OAMG;IACH,YAAY,OAA6B;;QAbhC,iCAAW,YAAY,EAAC;QAExB,kDAA0B;QAE1B,0DAAoD;QAU3D,uBAAA,IAAI,mCAAqB,OAAO,CAAC,gBAAgB,MAAA,CAAC;QAClD,uBAAA,IAAI,2CAA6B,OAAO,CAAC,wBAAwB,MAAA,CAAC;IACpE,CAAC;IAED;;;;;;;;;;OAUG;IACH,KAAK,CAAC,iBAAiB,CACrB,MAAuC;QAEvC,IAAI;YACF,MAAM,EAAE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AE,EACF,gBAAgB,CACjB,CAAC;IACF,MAAM,GAAG,GAAG,IAAA,kBAAU,EAAC,EAAE,CAAC,CAAC;IAE3B,MAAM,qBAAqB,GAA6B;QACtD,IAAI;QACJ,SAAS;QACT,GAAG;QACH,EAAE,EAAE,MAAM;KACX,CAAC;IAEF,OAAO,qBAAqB,CAAC;AAC/B,CAAC,6FAWC,OAAgC,EAChC,OAAe,EACf,gBAAgB,GAAG,KAAK;IAExB,MAAM,aAAa,GAAG,IAAA,kCAAa,EAAC,OAAO,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,IAAA,iBAAS,EAAC,aAAa,CAAC,CAAC;IACtC,MAAM,SAAS,GAAG,qBAAS,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAEhD,IAAI,gBAAgB,EAAE;QACpB,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;KAC7B;IAED,OAAO,SAAS,CAAC,YAAY,EAAE,CAAC;AAClC,CAAC,mEASY,IAAgB,EAAE,aAAyB;IACtD,MAAM,MAAM,GAAG,IAAA,wBAAY,EAAC,SAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC,mEASY,UAAsB,EAAE,aAAyB;IAC5D,MAAM,MAAM,GAAG,IAAA,wBAAY,EAAC,SAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAEjD,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { safeStringify } from '@metamask/auth-network-utils';\nimport { gcm } from '@noble/ciphers/aes';\nimport { managedNonce } from '@noble/ciphers/webcrypto';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nimport { PW_BACKUP_ITEM_ID, type EncAccountDataType } from './constants';\nimport type {\n IGetSecretDataRequestBody,\n KeyPair,\n IAddSecretDataRequestBody,\n IBatchAddSecretDataRequestBody,\n IMetadataLockRequestBody,\n NodeAuthToken,\n BaseAddSecretDataItemParams,\n FetchMetadataAccessCreds,\n IUpdateSecretDataRequestBody,\n IBatchUpdateSecretDataRequestBody,\n UpdateSecretDataItemFields,\n} from './interfaces';\n\ntype MetadataStoreOptions = {\n metadataEndpoint: string;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n};\n\nexport type MetadataLock = {\n id: string;\n nodeIndex: number;\n}[];\n\nexport enum MetadataLockStatus {\n FAILED = 0,\n SUCCESS = 1,\n}\n\nexport type AuthTokenToMetadataEndpointsMap = {\n [endpoint: string]: NodeAuthToken;\n};\n\nexport type LockAcquiredResponse = { status: MetadataLockStatus; id?: string };\n\nexport type SecretDataItem = {\n itemId?: string;\n data: Uint8Array;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\nexport type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;\n\nexport type SecretDataItemOutput = SecretDataItem & {\n itemId: string;\n version: 'v1' | 'v2';\n};\n\nexport type UpdateSecretDataItem = {\n itemId: string;\n fields: UpdateSecretDataItemFields;\n};\n\nexport type MetadataAddSecretDataItemParams =\n BaseAddSecretDataItemParams<SecretDataItemInput>;\n\nexport type MetadataBatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n SecretDataItemInput[],\n Uint8Array | Uint8Array[]\n>;\n\nexport type MetadataUpdateSecretDataItemParams = {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n};\n\nexport type MetadataBatchUpdateSecretDataItemParams = {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n};\n\n/**\n * Error class for metadata store.\n */\nexport class MetadataStoreError extends Error {\n /**\n * Constructor for MetadataStoreError.\n *\n * @param message - The error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'MetadataStoreError';\n Object.setPrototypeOf(this, MetadataStoreError.prototype);\n }\n}\n\n/**\n * MetadataStore class.\n *\n * This class is used to store and retrieve encrypted account metadata for the\n * given feature.\n */\nexport class MetadataStore {\n readonly #feature = 'srp-backup';\n\n readonly #metadataEndpoint: string;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n /**\n *\n * @param options - The initialization options for the metadata store.\n * @param options.nodeEndpointsMap - The map of node endpoints which includes node index as key and node endpoint as value.\n * @param options.storageLocation - The storage location of the metadata.\n * @param options.fetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n */\n constructor(options: MetadataStoreOptions) {\n this.#metadataEndpoint = options.metadataEndpoint;\n this.#fetchMetadataAccessCreds = options.fetchMetadataAccessCreds;\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored, including optional version and dataType.\n * @param params.secretData.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.secretData.dataType - Optional data type for categorizing the secret data. Required for v2.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the secret data is stored.\n */\n async addSecretDataItem(\n params: MetadataAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#addData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async batchAddSecretData(\n params: MetadataBatchAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#batchAddData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add batch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Fetches the secret data from the metadata store and decrypts it.\n *\n * @param encKey - The encryption key to be used for decrypting the secret data.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async fetchAllSecretDataItems(\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<SecretDataItemOutput[]> {\n try {\n const result = await this.#getAllDataItems({\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n itemId,\n });\n return result;\n } catch (error) {\n throw new MetadataStoreError(\n `failed to fetch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the update is complete.\n */\n async updateSecretDataItem(\n params: MetadataUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItem, authKeyPair } = params;\n await this.#updateData({\n updateItem,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data items.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when all updates are complete.\n */\n async batchUpdateSecretData(\n params: MetadataBatchUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItems, authKeyPair } = params;\n await this.#batchUpdateData({\n updateItems,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to batch update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves with the lock id.\n */\n async acquireMetadataLock(authKeyPair: KeyPair): Promise<string> {\n const { status: lockStatus, id: lockId } = await this.#acquireLock(\n this.#metadataEndpoint,\n authKeyPair,\n );\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError('Failed to acquire metadata lock');\n }\n if (!lockId) {\n throw new MetadataStoreError(\n 'Failed to acquire metadata lock. Missing lock id',\n );\n }\n\n return lockId;\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async releaseMetadataLock(\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n const lockStatus = await this.#releaseLock(\n this.#metadataEndpoint,\n authKeyPair,\n lockId,\n );\n\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError(\n `Failed to release metadata lock with id ${lockId}`,\n );\n }\n\n return lockStatus;\n }\n\n /**\n * Encrypts the secret data and inserts or appends it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #addData(params: {\n secretData: SecretDataItemInput;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (\n params.secretData.itemId === PW_BACKUP_ITEM_ID &&\n params.secretData.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n params.secretData.itemId !== PW_BACKUP_ITEM_ID &&\n params.secretData.version !== 'v1' &&\n params.secretData.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/set`;\n const encryptedData = this.#encryptData(\n params.secretData.data,\n params.encKey,\n );\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n {\n itemId: params.secretData.itemId,\n data: encryptedData,\n version: params.secretData.version ?? 'v2',\n dataType: params.secretData.dataType,\n },\n params.authKeyPair,\n );\n const requestBody = JSON.stringify(payload);\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: requestBody,\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Encrypts the array of secret data and inserts them in the metadata store.\n *\n * @param params - The parameters for serializing and making batch set secret\n * data request.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key or keys to be used for encrypting\n * the secret data. If an array is provided, it must have the same length as\n * the secret data array.\n * @param params.authKeyPair - The authentication key pair to be used for\n * authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used\n * for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #batchAddData(params: {\n secretData: SecretDataItemInput[];\n encKey: Uint8Array | Uint8Array[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n const encKeys = (\n Array.isArray(params.encKey)\n ? params.encKey\n : params.secretData.map(() => params.encKey)\n ) as Uint8Array[];\n\n if (encKeys.length !== params.secretData.length) {\n throw new MetadataStoreError(\n 'encKey must be of same length as secretData',\n );\n }\n\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/batch_set`;\n const encryptedDataArray = params.secretData.map((secret, index) => {\n if (\n secret.itemId === PW_BACKUP_ITEM_ID &&\n secret.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n secret.itemId !== PW_BACKUP_ITEM_ID &&\n secret.version !== 'v1' &&\n secret.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n return {\n data: this.#encryptData(secret.data, encKeys[index]),\n itemId: secret.itemId,\n version: secret.version ?? 'v2',\n dataType: secret.dataType,\n };\n });\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n encryptedDataArray,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId (without modifying encrypted data).\n *\n * @param params - The parameters for updating the secret data.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when the update is complete.\n */\n async #updateData(params: {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (params.updateItem.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItem,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when all updates are complete.\n */\n async #batchUpdateData(params: {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n for (const item of params.updateItems) {\n if (item.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/batch_update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItems,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to batch update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Fetches all the secret data from the metadata store by provided public key and decrypts it.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for fetching the secret data.\n * @param params.itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async #getAllDataItems(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n itemId?: string;\n }): Promise<SecretDataItemOutput[]> {\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/get`;\n const payload = await this.#generatePayloadForGetSecretDataRequest(\n params.authKeyPair,\n params.itemId,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = (await response.json()) as {\n data: string[];\n ids: string[];\n versions: string[];\n dataTypes: (number | null)[];\n createdAt: (string | null)[];\n };\n if (!jsonData.data) {\n throw new MetadataStoreError('Failed to fetch metadata');\n }\n\n const secretData: SecretDataItemOutput[] = [];\n\n // Server filters by itemId when provided, so no client-side filtering needed\n for (let i = 0; i < jsonData.data.length; i++) {\n const id = jsonData.ids[i];\n\n // Skip PW_BACKUP unless specifically requested\n if (!params.itemId && id === PW_BACKUP_ITEM_ID) {\n continue;\n }\n\n const rawData = new Uint8Array(Buffer.from(jsonData.data[i], 'base64'));\n const decryptedData = this.#decryptData(rawData, params.encKey);\n const dataType = jsonData.dataTypes?.[i];\n const createdAt = jsonData.createdAt?.[i];\n secretData.push({\n itemId: id,\n data: decryptedData,\n version: jsonData.versions[i] as 'v1' | 'v2',\n dataType: typeof dataType === 'number' ? dataType : undefined,\n createdAt: typeof createdAt === 'string' ? createdAt : undefined,\n });\n }\n\n return secretData;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(`failed to fetch metadata: ${errorMessage}`);\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for acquiring the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the lock is acquired.\n */\n async #acquireLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n ): Promise<LockAcquiredResponse> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair);\n const url = `${metadataEndpoint}/acquireLock`;\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return {\n status: jsonData.status,\n id: jsonData.id,\n };\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to acquire metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for releasing the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async #releaseLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair, lockId);\n\n const url = `${metadataEndpoint}/releaseLock`;\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return jsonData.status;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to release metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Generate the payload for the set or batch set secret data request and get payload signature.\n *\n * @param inputData - The raw encrypted secret data or batch of encrypted secret data to be stored.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns The payload for the batch set secret data request.\n */\n async #generatePayloadForSetOrBatchSetSecretDataRequest(\n inputData: SecretDataItemInput | SecretDataItemInput[],\n authKeyPair: KeyPair,\n ): Promise<IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.data = inputData.map((item) => ({\n data: Buffer.from(item.data).toString('base64'),\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n }));\n } else {\n sigPayload.data = Buffer.from(inputData.data).toString('base64');\n sigPayload.itemId = inputData.itemId;\n sigPayload.version = inputData.version;\n sigPayload.dataType = inputData.dataType;\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n const payload = {\n ...sigPayload,\n signature,\n pubKey,\n } as IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody;\n\n return payload;\n }\n\n /**\n * Generate the payload for the get secret data request and get payload signature.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns The payload for the get secret data request.\n */\n async #generatePayloadForGetSecretDataRequest(\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<IGetSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { pk, sk } = authKeyPair;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n const sigPayload = {\n feature,\n timestamp,\n itemId,\n authToken: metadataAccessToken,\n };\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n pubKey,\n signature,\n };\n }\n\n /**\n * Generate the payload for updating secret data items by itemId.\n *\n * @param inputData - Single update item or array of update items.\n * @param authKeyPair - The authentication key pair for signing the request.\n * @returns The payload for the update request.\n */\n async #generatePayloadForUpdateSecretDataRequest(\n inputData: UpdateSecretDataItem | UpdateSecretDataItem[],\n authKeyPair: KeyPair,\n ): Promise<IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.items = inputData.map((item) => ({\n itemId: item.itemId,\n dataType: item.fields.dataType,\n version: item.fields.version ?? 'v2',\n }));\n } else {\n sigPayload.itemId = inputData.itemId;\n sigPayload.dataType = inputData.fields.dataType;\n sigPayload.version = inputData.fields.version ?? 'v2';\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n signature,\n pubKey,\n } as IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody;\n }\n\n /**\n * Generate the payload for the lock requests.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns The payload for the lock requests.\n */\n #generatePayloadForLockRequests(\n authKeyPair: KeyPair,\n lockId?: string,\n ): IMetadataLockRequestBody {\n const { pk, sk } = authKeyPair;\n const data = { timestamp: Date.now() };\n // metadata server expects der encoded signature for lock requests\n const shouldDerEncoded = true;\n const signature = this.#generatePayloadSignature(\n data,\n sk,\n shouldDerEncoded,\n );\n const key = bytesToHex(pk);\n\n const payloadForLockRequest: IMetadataLockRequestBody = {\n data,\n signature,\n key,\n id: lockId,\n };\n\n return payloadForLockRequest;\n }\n\n /**\n * Generate the signature for the payload.\n *\n * @param payload - The payload to be signed.\n * @param privKey - The private key to sign the payload.\n * @param shouldDerEncoded - Whether the signature should be der encoded.\n * @returns The signature hex string.\n */\n #generatePayloadSignature(\n payload: Record<string, unknown>,\n privKey: bigint,\n shouldDerEncoded = false,\n ): string {\n const payloadString = safeStringify(payload);\n const hash = keccak256(payloadString);\n const signature = secp256k1.sign(hash, privKey);\n\n if (shouldDerEncoded) {\n return signature.toDERHex();\n }\n\n return signature.toCompactHex();\n }\n\n /**\n * Encrypt the data using the key with AES-256-GCM.\n *\n * @param data - The secret data to be encrypted.\n * @param encryptionKey - The encryption key to encrypt the data.\n * @returns The encrypted data.\n */\n #encryptData(data: Uint8Array, encryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(encryptionKey);\n const ciphertext = aesGcm.encrypt(data);\n return ciphertext;\n }\n\n /**\n * Decrypt the data using the encryption key.\n *\n * @param cipherText - The cipher text, encrypted with AES-256-GCM.\n * @param decryptionKey - The encryption key to decrypt the data.\n * @returns The decrypted data.\n */\n #decryptData(cipherText: Uint8Array, decryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(decryptionKey);\n const decryptedData = aesGcm.decrypt(cipherText);\n\n return decryptedData;\n }\n}\n"]}
{"version":3,"file":"metadata.cjs","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAA6D;AAC7D,4CAAyC;AACzC,wDAAwD;AACxD,uDAAoD;AACpD,6CAA6D;AAC7D,+CAAiD;AAEjD,+CAAgD;AA2BhD,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,+DAAU,CAAA;IACV,iEAAW,CAAA;AACb,CAAC,EAHW,kBAAkB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AE,CAAC;AAClC,CAAC,mEASY,IAAgB,EAAE,aAAyB;IACtD,MAAM,MAAM,GAAG,IAAA,wBAAY,EAAC,SAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC,mEASY,UAAsB,EAAE,aAAyB;IAC5D,MAAM,MAAM,GAAG,IAAA,wBAAY,EAAC,SAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAEjD,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { safeStringify } from '@metamask/auth-network-utils';\nimport { gcm } from '@noble/ciphers/aes';\nimport { managedNonce } from '@noble/ciphers/webcrypto';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nimport { PW_BACKUP_ITEM_ID } from './constants';\nimport type {\n IGetSecretDataRequestBody,\n KeyPair,\n IAddSecretDataRequestBody,\n IBatchAddSecretDataRequestBody,\n IMetadataLockRequestBody,\n NodeAuthToken,\n BaseAddSecretDataItemParams,\n FetchMetadataAccessCreds,\n IUpdateSecretDataRequestBody,\n IBatchUpdateSecretDataRequestBody,\n UpdateSecretDataItemFields,\n SecretDataItemInput,\n SecretDataItemOutput,\n} from './interfaces';\n\ntype MetadataStoreOptions = {\n metadataEndpoint: string;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n};\n\nexport type MetadataLock = {\n id: string;\n nodeIndex: number;\n}[];\n\nexport enum MetadataLockStatus {\n FAILED = 0,\n SUCCESS = 1,\n}\n\nexport type AuthTokenToMetadataEndpointsMap = {\n [endpoint: string]: NodeAuthToken;\n};\n\nexport type LockAcquiredResponse = { status: MetadataLockStatus; id?: string };\n\nexport type UpdateSecretDataItem = {\n itemId: string;\n fields: UpdateSecretDataItemFields;\n};\n\nexport type MetadataAddSecretDataItemParams =\n BaseAddSecretDataItemParams<SecretDataItemInput>;\n\nexport type MetadataBatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n SecretDataItemInput[],\n Uint8Array | Uint8Array[]\n>;\n\nexport type MetadataUpdateSecretDataItemParams = {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n};\n\nexport type MetadataBatchUpdateSecretDataItemParams = {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n};\n\n/**\n * Error class for metadata store.\n */\nexport class MetadataStoreError extends Error {\n /**\n * Constructor for MetadataStoreError.\n *\n * @param message - The error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'MetadataStoreError';\n Object.setPrototypeOf(this, MetadataStoreError.prototype);\n }\n}\n\n/**\n * MetadataStore class.\n *\n * This class is used to store and retrieve encrypted account metadata for the\n * given feature.\n */\nexport class MetadataStore {\n readonly #feature = 'srp-backup';\n\n readonly #metadataEndpoint: string;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n /**\n *\n * @param options - The initialization options for the metadata store.\n * @param options.nodeEndpointsMap - The map of node endpoints which includes node index as key and node endpoint as value.\n * @param options.storageLocation - The storage location of the metadata.\n * @param options.fetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n */\n constructor(options: MetadataStoreOptions) {\n this.#metadataEndpoint = options.metadataEndpoint;\n this.#fetchMetadataAccessCreds = options.fetchMetadataAccessCreds;\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored, including optional version and dataType.\n * @param params.secretData.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.secretData.dataType - Optional data type for categorizing the secret data. Required for v2.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the secret data is stored.\n */\n async addSecretDataItem(\n params: MetadataAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#addData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async batchAddSecretData(\n params: MetadataBatchAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#batchAddData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add batch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Fetches the secret data from the metadata store and decrypts it.\n *\n * @param encKey - The encryption key to be used for decrypting the secret data.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async fetchAllSecretDataItems(\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<SecretDataItemOutput[]> {\n try {\n const result = await this.#getAllDataItems({\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n itemId,\n });\n return result;\n } catch (error) {\n throw new MetadataStoreError(\n `failed to fetch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the update is complete.\n */\n async updateSecretDataItem(\n params: MetadataUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItem, authKeyPair } = params;\n await this.#updateData({\n updateItem,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data items.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when all updates are complete.\n */\n async batchUpdateSecretData(\n params: MetadataBatchUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItems, authKeyPair } = params;\n await this.#batchUpdateData({\n updateItems,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to batch update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves with the lock id.\n */\n async acquireMetadataLock(authKeyPair: KeyPair): Promise<string> {\n const { status: lockStatus, id: lockId } = await this.#acquireLock(\n this.#metadataEndpoint,\n authKeyPair,\n );\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError('Failed to acquire metadata lock');\n }\n if (!lockId) {\n throw new MetadataStoreError(\n 'Failed to acquire metadata lock. Missing lock id',\n );\n }\n\n return lockId;\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async releaseMetadataLock(\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n const lockStatus = await this.#releaseLock(\n this.#metadataEndpoint,\n authKeyPair,\n lockId,\n );\n\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError(\n `Failed to release metadata lock with id ${lockId}`,\n );\n }\n\n return lockStatus;\n }\n\n /**\n * Encrypts the secret data and inserts or appends it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #addData(params: {\n secretData: SecretDataItemInput;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (\n params.secretData.itemId === PW_BACKUP_ITEM_ID &&\n params.secretData.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n params.secretData.itemId !== PW_BACKUP_ITEM_ID &&\n params.secretData.version !== 'v1' &&\n params.secretData.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/set`;\n const encryptedData = this.#encryptData(\n params.secretData.data,\n params.encKey,\n );\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n {\n itemId: params.secretData.itemId,\n data: encryptedData,\n version: params.secretData.version ?? 'v2',\n dataType: params.secretData.dataType,\n },\n params.authKeyPair,\n );\n const requestBody = JSON.stringify(payload);\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: requestBody,\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Encrypts the array of secret data and inserts them in the metadata store.\n *\n * @param params - The parameters for serializing and making batch set secret\n * data request.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key or keys to be used for encrypting\n * the secret data. If an array is provided, it must have the same length as\n * the secret data array.\n * @param params.authKeyPair - The authentication key pair to be used for\n * authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used\n * for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #batchAddData(params: {\n secretData: SecretDataItemInput[];\n encKey: Uint8Array | Uint8Array[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n const encKeys = (\n Array.isArray(params.encKey)\n ? params.encKey\n : params.secretData.map(() => params.encKey)\n ) as Uint8Array[];\n\n if (encKeys.length !== params.secretData.length) {\n throw new MetadataStoreError(\n 'encKey must be of same length as secretData',\n );\n }\n\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/batch_set`;\n const encryptedDataArray = params.secretData.map((secret, index) => {\n if (\n secret.itemId === PW_BACKUP_ITEM_ID &&\n secret.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n secret.itemId !== PW_BACKUP_ITEM_ID &&\n secret.version !== 'v1' &&\n secret.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n return {\n data: this.#encryptData(secret.data, encKeys[index]),\n itemId: secret.itemId,\n version: secret.version ?? 'v2',\n dataType: secret.dataType,\n };\n });\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n encryptedDataArray,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId (without modifying encrypted data).\n *\n * @param params - The parameters for updating the secret data.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when the update is complete.\n */\n async #updateData(params: {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (params.updateItem.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItem,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when all updates are complete.\n */\n async #batchUpdateData(params: {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n for (const item of params.updateItems) {\n if (item.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/batch_update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItems,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to batch update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Fetches all the secret data from the metadata store by provided public key and decrypts it.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for fetching the secret data.\n * @param params.itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async #getAllDataItems(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n itemId?: string;\n }): Promise<SecretDataItemOutput[]> {\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/get`;\n const payload = await this.#generatePayloadForGetSecretDataRequest(\n params.authKeyPair,\n params.itemId,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = (await response.json()) as {\n data: string[];\n ids: string[];\n versions: string[];\n dataTypes: (number | null)[];\n createdAt: (string | null)[];\n };\n if (!jsonData.data) {\n throw new MetadataStoreError('Failed to fetch metadata');\n }\n\n const secretData: SecretDataItemOutput[] = [];\n\n // Server filters by itemId when provided, so no client-side filtering needed\n for (let i = 0; i < jsonData.data.length; i++) {\n const id = jsonData.ids[i];\n\n // Skip PW_BACKUP unless specifically requested\n if (!params.itemId && id === PW_BACKUP_ITEM_ID) {\n continue;\n }\n\n const rawData = new Uint8Array(Buffer.from(jsonData.data[i], 'base64'));\n const decryptedData = this.#decryptData(rawData, params.encKey);\n const dataType = jsonData.dataTypes?.[i];\n const createdAt = jsonData.createdAt?.[i];\n secretData.push({\n itemId: id,\n data: decryptedData,\n version: jsonData.versions[i] as 'v1' | 'v2',\n dataType: typeof dataType === 'number' ? dataType : undefined,\n createdAt: typeof createdAt === 'string' ? createdAt : undefined,\n });\n }\n\n return secretData;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(`failed to fetch metadata: ${errorMessage}`);\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for acquiring the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the lock is acquired.\n */\n async #acquireLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n ): Promise<LockAcquiredResponse> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair);\n const url = `${metadataEndpoint}/acquireLock`;\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return {\n status: jsonData.status,\n id: jsonData.id,\n };\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to acquire metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for releasing the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async #releaseLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair, lockId);\n\n const url = `${metadataEndpoint}/releaseLock`;\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return jsonData.status;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to release metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Generate the payload for the set or batch set secret data request and get payload signature.\n *\n * @param inputData - The raw encrypted secret data or batch of encrypted secret data to be stored.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns The payload for the batch set secret data request.\n */\n async #generatePayloadForSetOrBatchSetSecretDataRequest(\n inputData: SecretDataItemInput | SecretDataItemInput[],\n authKeyPair: KeyPair,\n ): Promise<IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.data = inputData.map((item) => ({\n data: Buffer.from(item.data).toString('base64'),\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n }));\n } else {\n sigPayload.data = Buffer.from(inputData.data).toString('base64');\n sigPayload.itemId = inputData.itemId;\n sigPayload.version = inputData.version;\n sigPayload.dataType = inputData.dataType;\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n const payload = {\n ...sigPayload,\n signature,\n pubKey,\n } as IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody;\n\n return payload;\n }\n\n /**\n * Generate the payload for the get secret data request and get payload signature.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns The payload for the get secret data request.\n */\n async #generatePayloadForGetSecretDataRequest(\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<IGetSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { pk, sk } = authKeyPair;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n const sigPayload = {\n feature,\n timestamp,\n itemId,\n authToken: metadataAccessToken,\n };\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n pubKey,\n signature,\n };\n }\n\n /**\n * Generate the payload for updating secret data items by itemId.\n *\n * @param inputData - Single update item or array of update items.\n * @param authKeyPair - The authentication key pair for signing the request.\n * @returns The payload for the update request.\n */\n async #generatePayloadForUpdateSecretDataRequest(\n inputData: UpdateSecretDataItem | UpdateSecretDataItem[],\n authKeyPair: KeyPair,\n ): Promise<IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.items = inputData.map((item) => ({\n itemId: item.itemId,\n dataType: item.fields.dataType,\n version: item.fields.version ?? 'v2',\n }));\n } else {\n sigPayload.itemId = inputData.itemId;\n sigPayload.dataType = inputData.fields.dataType;\n sigPayload.version = inputData.fields.version ?? 'v2';\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n signature,\n pubKey,\n } as IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody;\n }\n\n /**\n * Generate the payload for the lock requests.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns The payload for the lock requests.\n */\n #generatePayloadForLockRequests(\n authKeyPair: KeyPair,\n lockId?: string,\n ): IMetadataLockRequestBody {\n const { pk, sk } = authKeyPair;\n const data = { timestamp: Date.now() };\n // metadata server expects der encoded signature for lock requests\n const shouldDerEncoded = true;\n const signature = this.#generatePayloadSignature(\n data,\n sk,\n shouldDerEncoded,\n );\n const key = bytesToHex(pk);\n\n const payloadForLockRequest: IMetadataLockRequestBody = {\n data,\n signature,\n key,\n id: lockId,\n };\n\n return payloadForLockRequest;\n }\n\n /**\n * Generate the signature for the payload.\n *\n * @param payload - The payload to be signed.\n * @param privKey - The private key to sign the payload.\n * @param shouldDerEncoded - Whether the signature should be der encoded.\n * @returns The signature hex string.\n */\n #generatePayloadSignature(\n payload: Record<string, unknown>,\n privKey: bigint,\n shouldDerEncoded = false,\n ): string {\n const payloadString = safeStringify(payload);\n const hash = keccak256(payloadString);\n const signature = secp256k1.sign(hash, privKey);\n\n if (shouldDerEncoded) {\n return signature.toDERHex();\n }\n\n return signature.toCompactHex();\n }\n\n /**\n * Encrypt the data using the key with AES-256-GCM.\n *\n * @param data - The secret data to be encrypted.\n * @param encryptionKey - The encryption key to encrypt the data.\n * @returns The encrypted data.\n */\n #encryptData(data: Uint8Array, encryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(encryptionKey);\n const ciphertext = aesGcm.encrypt(data);\n return ciphertext;\n }\n\n /**\n * Decrypt the data using the encryption key.\n *\n * @param cipherText - The cipher text, encrypted with AES-256-GCM.\n * @param decryptionKey - The encryption key to decrypt the data.\n * @returns The decrypted data.\n */\n #decryptData(cipherText: Uint8Array, decryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(decryptionKey);\n const decryptedData = aesGcm.decrypt(cipherText);\n\n return decryptedData;\n }\n}\n"]}

@@ -1,3 +0,2 @@

import { type EncAccountDataType } from "./constants.cjs";
import type { KeyPair, NodeAuthToken, BaseAddSecretDataItemParams, FetchMetadataAccessCreds, UpdateSecretDataItemFields } from "./interfaces.cjs";
import type { KeyPair, NodeAuthToken, BaseAddSecretDataItemParams, FetchMetadataAccessCreds, UpdateSecretDataItemFields, SecretDataItemInput, SecretDataItemOutput } from "./interfaces.cjs";
type MetadataStoreOptions = {

@@ -22,14 +21,2 @@ metadataEndpoint: string;

};
export type SecretDataItem = {
itemId?: string;
data: Uint8Array;
version?: 'v1' | 'v2';
dataType?: EncAccountDataType;
createdAt?: string;
};
export type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;
export type SecretDataItemOutput = SecretDataItem & {
itemId: string;
version: 'v1' | 'v2';
};
export type UpdateSecretDataItem = {

@@ -36,0 +23,0 @@ itemId: string;

@@ -1,1 +0,1 @@

{"version":3,"file":"metadata.d.cts","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAOA,OAAO,EAAqB,KAAK,kBAAkB,EAAE,wBAAoB;AACzE,OAAO,KAAK,EAEV,OAAO,EAIP,aAAa,EACb,2BAA2B,EAC3B,wBAAwB,EAGxB,0BAA0B,EAC3B,yBAAqB;AAEtB,KAAK,oBAAoB,GAAG;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,wBAAwB,EAAE,wBAAwB,CAAC;CACpD,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;CACnB,EAAE,CAAC;AAEJ,oBAAY,kBAAkB;IAC5B,MAAM,IAAI;IACV,OAAO,IAAI;CACZ;AAED,MAAM,MAAM,+BAA+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,GACd,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAgBlC;;;;;;;;OAQG;IACG,oBAAoB,CACxB,MAAM,EAAE,kCAAkC,GACzC,OAAO,CAAC,IAAI,CAAC;IAehB;;;;;;;;OAQG;IACG,qBAAqB,CACzB,MAAM,EAAE,uCAAuC,GAC9C,OAAO,CAAC,IAAI,CAAC;IAehB;;;;;OAKG;IACG,mBAAmB,CAAC,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAiBhE;;;;;;OAMG;IACG,mBAAmB,CACvB,WAAW,EAAE,OAAO,EACpB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,kBAAkB,CAAC;CAwoB/B"}

@@ -1,3 +0,2 @@

import { type EncAccountDataType } from "./constants.mjs";
import type { KeyPair, NodeAuthToken, BaseAddSecretDataItemParams, FetchMetadataAccessCreds, UpdateSecretDataItemFields } from "./interfaces.mjs";
import type { KeyPair, NodeAuthToken, BaseAddSecretDataItemParams, FetchMetadataAccessCreds, UpdateSecretDataItemFields, SecretDataItemInput, SecretDataItemOutput } from "./interfaces.mjs";
type MetadataStoreOptions = {

@@ -22,14 +21,2 @@ metadataEndpoint: string;

};
export type SecretDataItem = {
itemId?: string;
data: Uint8Array;
version?: 'v1' | 'v2';
dataType?: EncAccountDataType;
createdAt?: string;
};
export type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;
export type SecretDataItemOutput = SecretDataItem & {
itemId: string;
version: 'v1' | 'v2';
};
export type UpdateSecretDataItem = {

@@ -36,0 +23,0 @@ itemId: string;

@@ -1,1 +0,1 @@

{"version":3,"file":"metadata.d.mts","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAOA,OAAO,EAAqB,KAAK,kBAAkB,EAAE,wBAAoB;AACzE,OAAO,KAAK,EAEV,OAAO,EAIP,aAAa,EACb,2BAA2B,EAC3B,wBAAwB,EAGxB,0BAA0B,EAC3B,yBAAqB;AAEtB,KAAK,oBAAoB,GAAG;IAC1B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C,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC,mEASY,UAAsB,EAAE,aAAyB;IAC5D,MAAM,MAAM,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAEjD,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { safeStringify } from '@metamask/auth-network-utils';\nimport { gcm } from '@noble/ciphers/aes';\nimport { managedNonce } from '@noble/ciphers/webcrypto';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nimport { PW_BACKUP_ITEM_ID, type EncAccountDataType } from './constants';\nimport type {\n IGetSecretDataRequestBody,\n KeyPair,\n IAddSecretDataRequestBody,\n IBatchAddSecretDataRequestBody,\n IMetadataLockRequestBody,\n NodeAuthToken,\n BaseAddSecretDataItemParams,\n FetchMetadataAccessCreds,\n IUpdateSecretDataRequestBody,\n IBatchUpdateSecretDataRequestBody,\n UpdateSecretDataItemFields,\n} from './interfaces';\n\ntype MetadataStoreOptions = {\n metadataEndpoint: string;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n};\n\nexport type MetadataLock = {\n id: string;\n nodeIndex: number;\n}[];\n\nexport enum MetadataLockStatus {\n FAILED = 0,\n SUCCESS = 1,\n}\n\nexport type AuthTokenToMetadataEndpointsMap = {\n [endpoint: string]: NodeAuthToken;\n};\n\nexport type LockAcquiredResponse = { status: MetadataLockStatus; id?: string };\n\nexport type SecretDataItem = {\n itemId?: string;\n data: Uint8Array;\n version?: 'v1' | 'v2';\n dataType?: EncAccountDataType;\n createdAt?: string;\n};\n\nexport type SecretDataItemInput = Omit<SecretDataItem, 'createdAt'>;\n\nexport type SecretDataItemOutput = SecretDataItem & {\n itemId: string;\n version: 'v1' | 'v2';\n};\n\nexport type UpdateSecretDataItem = {\n itemId: string;\n fields: UpdateSecretDataItemFields;\n};\n\nexport type MetadataAddSecretDataItemParams =\n BaseAddSecretDataItemParams<SecretDataItemInput>;\n\nexport type MetadataBatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n SecretDataItemInput[],\n Uint8Array | Uint8Array[]\n>;\n\nexport type MetadataUpdateSecretDataItemParams = {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n};\n\nexport type MetadataBatchUpdateSecretDataItemParams = {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n};\n\n/**\n * Error class for metadata store.\n */\nexport class MetadataStoreError extends Error {\n /**\n * Constructor for MetadataStoreError.\n *\n * @param message - The error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'MetadataStoreError';\n Object.setPrototypeOf(this, MetadataStoreError.prototype);\n }\n}\n\n/**\n * MetadataStore class.\n *\n * This class is used to store and retrieve encrypted account metadata for the\n * given feature.\n */\nexport class MetadataStore {\n readonly #feature = 'srp-backup';\n\n readonly #metadataEndpoint: string;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n /**\n *\n * @param options - The initialization options for the metadata store.\n * @param options.nodeEndpointsMap - The map of node endpoints which includes node index as key and node endpoint as value.\n * @param options.storageLocation - The storage location of the metadata.\n * @param options.fetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n */\n constructor(options: MetadataStoreOptions) {\n this.#metadataEndpoint = options.metadataEndpoint;\n this.#fetchMetadataAccessCreds = options.fetchMetadataAccessCreds;\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored, including optional version and dataType.\n * @param params.secretData.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.secretData.dataType - Optional data type for categorizing the secret data. Required for v2.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the secret data is stored.\n */\n async addSecretDataItem(\n params: MetadataAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#addData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async batchAddSecretData(\n params: MetadataBatchAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#batchAddData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add batch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Fetches the secret data from the metadata store and decrypts it.\n *\n * @param encKey - The encryption key to be used for decrypting the secret data.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async fetchAllSecretDataItems(\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<SecretDataItemOutput[]> {\n try {\n const result = await this.#getAllDataItems({\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n itemId,\n });\n return result;\n } catch (error) {\n throw new MetadataStoreError(\n `failed to fetch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the update is complete.\n */\n async updateSecretDataItem(\n params: MetadataUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItem, authKeyPair } = params;\n await this.#updateData({\n updateItem,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data items.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when all updates are complete.\n */\n async batchUpdateSecretData(\n params: MetadataBatchUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItems, authKeyPair } = params;\n await this.#batchUpdateData({\n updateItems,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to batch update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves with the lock id.\n */\n async acquireMetadataLock(authKeyPair: KeyPair): Promise<string> {\n const { status: lockStatus, id: lockId } = await this.#acquireLock(\n this.#metadataEndpoint,\n authKeyPair,\n );\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError('Failed to acquire metadata lock');\n }\n if (!lockId) {\n throw new MetadataStoreError(\n 'Failed to acquire metadata lock. Missing lock id',\n );\n }\n\n return lockId;\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async releaseMetadataLock(\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n const lockStatus = await this.#releaseLock(\n this.#metadataEndpoint,\n authKeyPair,\n lockId,\n );\n\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError(\n `Failed to release metadata lock with id ${lockId}`,\n );\n }\n\n return lockStatus;\n }\n\n /**\n * Encrypts the secret data and inserts or appends it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #addData(params: {\n secretData: SecretDataItemInput;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (\n params.secretData.itemId === PW_BACKUP_ITEM_ID &&\n params.secretData.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n params.secretData.itemId !== PW_BACKUP_ITEM_ID &&\n params.secretData.version !== 'v1' &&\n params.secretData.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/set`;\n const encryptedData = this.#encryptData(\n params.secretData.data,\n params.encKey,\n );\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n {\n itemId: params.secretData.itemId,\n data: encryptedData,\n version: params.secretData.version ?? 'v2',\n dataType: params.secretData.dataType,\n },\n params.authKeyPair,\n );\n const requestBody = JSON.stringify(payload);\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: requestBody,\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Encrypts the array of secret data and inserts them in the metadata store.\n *\n * @param params - The parameters for serializing and making batch set secret\n * data request.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key or keys to be used for encrypting\n * the secret data. If an array is provided, it must have the same length as\n * the secret data array.\n * @param params.authKeyPair - The authentication key pair to be used for\n * authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used\n * for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #batchAddData(params: {\n secretData: SecretDataItemInput[];\n encKey: Uint8Array | Uint8Array[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n const encKeys = (\n Array.isArray(params.encKey)\n ? params.encKey\n : params.secretData.map(() => params.encKey)\n ) as Uint8Array[];\n\n if (encKeys.length !== params.secretData.length) {\n throw new MetadataStoreError(\n 'encKey must be of same length as secretData',\n );\n }\n\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/batch_set`;\n const encryptedDataArray = params.secretData.map((secret, index) => {\n if (\n secret.itemId === PW_BACKUP_ITEM_ID &&\n secret.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n secret.itemId !== PW_BACKUP_ITEM_ID &&\n secret.version !== 'v1' &&\n secret.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n return {\n data: this.#encryptData(secret.data, encKeys[index]),\n itemId: secret.itemId,\n version: secret.version ?? 'v2',\n dataType: secret.dataType,\n };\n });\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n encryptedDataArray,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId (without modifying encrypted data).\n *\n * @param params - The parameters for updating the secret data.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when the update is complete.\n */\n async #updateData(params: {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (params.updateItem.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItem,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when all updates are complete.\n */\n async #batchUpdateData(params: {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n for (const item of params.updateItems) {\n if (item.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/batch_update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItems,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to batch update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Fetches all the secret data from the metadata store by provided public key and decrypts it.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for fetching the secret data.\n * @param params.itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async #getAllDataItems(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n itemId?: string;\n }): Promise<SecretDataItemOutput[]> {\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/get`;\n const payload = await this.#generatePayloadForGetSecretDataRequest(\n params.authKeyPair,\n params.itemId,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = (await response.json()) as {\n data: string[];\n ids: string[];\n versions: string[];\n dataTypes: (number | null)[];\n createdAt: (string | null)[];\n };\n if (!jsonData.data) {\n throw new MetadataStoreError('Failed to fetch metadata');\n }\n\n const secretData: SecretDataItemOutput[] = [];\n\n // Server filters by itemId when provided, so no client-side filtering needed\n for (let i = 0; i < jsonData.data.length; i++) {\n const id = jsonData.ids[i];\n\n // Skip PW_BACKUP unless specifically requested\n if (!params.itemId && id === PW_BACKUP_ITEM_ID) {\n continue;\n }\n\n const rawData = new Uint8Array(Buffer.from(jsonData.data[i], 'base64'));\n const decryptedData = this.#decryptData(rawData, params.encKey);\n const dataType = jsonData.dataTypes?.[i];\n const createdAt = jsonData.createdAt?.[i];\n secretData.push({\n itemId: id,\n data: decryptedData,\n version: jsonData.versions[i] as 'v1' | 'v2',\n dataType: typeof dataType === 'number' ? dataType : undefined,\n createdAt: typeof createdAt === 'string' ? createdAt : undefined,\n });\n }\n\n return secretData;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(`failed to fetch metadata: ${errorMessage}`);\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for acquiring the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the lock is acquired.\n */\n async #acquireLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n ): Promise<LockAcquiredResponse> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair);\n const url = `${metadataEndpoint}/acquireLock`;\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return {\n status: jsonData.status,\n id: jsonData.id,\n };\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to acquire metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for releasing the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async #releaseLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair, lockId);\n\n const url = `${metadataEndpoint}/releaseLock`;\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return jsonData.status;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to release metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Generate the payload for the set or batch set secret data request and get payload signature.\n *\n * @param inputData - The raw encrypted secret data or batch of encrypted secret data to be stored.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns The payload for the batch set secret data request.\n */\n async #generatePayloadForSetOrBatchSetSecretDataRequest(\n inputData: SecretDataItemInput | SecretDataItemInput[],\n authKeyPair: KeyPair,\n ): Promise<IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.data = inputData.map((item) => ({\n data: Buffer.from(item.data).toString('base64'),\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n }));\n } else {\n sigPayload.data = Buffer.from(inputData.data).toString('base64');\n sigPayload.itemId = inputData.itemId;\n sigPayload.version = inputData.version;\n sigPayload.dataType = inputData.dataType;\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n const payload = {\n ...sigPayload,\n signature,\n pubKey,\n } as IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody;\n\n return payload;\n }\n\n /**\n * Generate the payload for the get secret data request and get payload signature.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns The payload for the get secret data request.\n */\n async #generatePayloadForGetSecretDataRequest(\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<IGetSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { pk, sk } = authKeyPair;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n const sigPayload = {\n feature,\n timestamp,\n itemId,\n authToken: metadataAccessToken,\n };\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n pubKey,\n signature,\n };\n }\n\n /**\n * Generate the payload for updating secret data items by itemId.\n *\n * @param inputData - Single update item or array of update items.\n * @param authKeyPair - The authentication key pair for signing the request.\n * @returns The payload for the update request.\n */\n async #generatePayloadForUpdateSecretDataRequest(\n inputData: UpdateSecretDataItem | UpdateSecretDataItem[],\n authKeyPair: KeyPair,\n ): Promise<IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.items = inputData.map((item) => ({\n itemId: item.itemId,\n dataType: item.fields.dataType,\n version: item.fields.version ?? 'v2',\n }));\n } else {\n sigPayload.itemId = inputData.itemId;\n sigPayload.dataType = inputData.fields.dataType;\n sigPayload.version = inputData.fields.version ?? 'v2';\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n signature,\n pubKey,\n } as IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody;\n }\n\n /**\n * Generate the payload for the lock requests.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns The payload for the lock requests.\n */\n #generatePayloadForLockRequests(\n authKeyPair: KeyPair,\n lockId?: string,\n ): IMetadataLockRequestBody {\n const { pk, sk } = authKeyPair;\n const data = { timestamp: Date.now() };\n // metadata server expects der encoded signature for lock requests\n const shouldDerEncoded = true;\n const signature = this.#generatePayloadSignature(\n data,\n sk,\n shouldDerEncoded,\n );\n const key = bytesToHex(pk);\n\n const payloadForLockRequest: IMetadataLockRequestBody = {\n data,\n signature,\n key,\n id: lockId,\n };\n\n return payloadForLockRequest;\n }\n\n /**\n * Generate the signature for the payload.\n *\n * @param payload - The payload to be signed.\n * @param privKey - The private key to sign the payload.\n * @param shouldDerEncoded - Whether the signature should be der encoded.\n * @returns The signature hex string.\n */\n #generatePayloadSignature(\n payload: Record<string, unknown>,\n privKey: bigint,\n shouldDerEncoded = false,\n ): string {\n const payloadString = safeStringify(payload);\n const hash = keccak256(payloadString);\n const signature = secp256k1.sign(hash, privKey);\n\n if (shouldDerEncoded) {\n return signature.toDERHex();\n }\n\n return signature.toCompactHex();\n }\n\n /**\n * Encrypt the data using the key with AES-256-GCM.\n *\n * @param data - The secret data to be encrypted.\n * @param encryptionKey - The encryption key to encrypt the data.\n * @returns The encrypted data.\n */\n #encryptData(data: Uint8Array, encryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(encryptionKey);\n const ciphertext = aesGcm.encrypt(data);\n return ciphertext;\n }\n\n /**\n * Decrypt the data using the encryption key.\n *\n * @param cipherText - The cipher text, encrypted with AES-256-GCM.\n * @param decryptionKey - The encryption key to decrypt the data.\n * @returns The decrypted data.\n */\n #decryptData(cipherText: Uint8Array, decryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(decryptionKey);\n const decryptedData = aesGcm.decrypt(cipherText);\n\n return decryptedData;\n }\n}\n"]}
{"version":3,"file":"metadata.mjs","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,qCAAqC;AAC7D,OAAO,EAAE,GAAG,EAAE,2BAA2B;AACzC,OAAO,EAAE,YAAY,EAAE,iCAAiC;AACxD,OAAO,EAAE,SAAS,EAAE,gCAAgC;AACpD,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,2BAA2B;AAC7D,OAAO,EAAE,UAAU,EAAE,4BAA4B;AAEjD,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AA2BhD,MAAM,CAAN,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,+DAAU,CAAA;IACV,iEAAW,CAAA;AACb,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,QAG7B;AA+BD;;GAEG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC3C;;;;OAIG;IACH,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,OAAO,aAAa;IAOxB;;;;;;OAMG;IACH,YAAY,OAA6B;;QAbhC,iCAAW,YAAY,EAAC;QAExB,kDAA0B;QAE1B,0DAAoD;QAU3D,uBAAA,IAAI,mCAAqB,OAAO,CAAC,gBAAgB,MAAA,CAAC;QAClD,uBAAA,IAAI,2CAA6B,OA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AAI,CAAC;IAC9B,MAAM,SAAS,GAAG,uBAAA,IAAI,yEAA0B,MAA9B,IAAI,EACpB,IAAI,EACJ,EAAE,EACF,gBAAgB,CACjB,CAAC;IACF,MAAM,GAAG,GAAG,UAAU,CAAC,EAAE,CAAC,CAAC;IAE3B,MAAM,qBAAqB,GAA6B;QACtD,IAAI;QACJ,SAAS;QACT,GAAG;QACH,EAAE,EAAE,MAAM;KACX,CAAC;IAEF,OAAO,qBAAqB,CAAC;AAC/B,CAAC,6FAWC,OAAgC,EAChC,OAAe,EACf,gBAAgB,GAAG,KAAK;IAExB,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,SAAS,CAAC,aAAa,CAAC,CAAC;IACtC,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAEhD,IAAI,gBAAgB,EAAE;QACpB,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;KAC7B;IAED,OAAO,SAAS,CAAC,YAAY,EAAE,CAAC;AAClC,CAAC,mEASY,IAAgB,EAAE,aAAyB;IACtD,MAAM,MAAM,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC,mEASY,UAAsB,EAAE,aAAyB;IAC5D,MAAM,MAAM,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAEjD,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { safeStringify } from '@metamask/auth-network-utils';\nimport { gcm } from '@noble/ciphers/aes';\nimport { managedNonce } from '@noble/ciphers/webcrypto';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nimport { PW_BACKUP_ITEM_ID } from './constants';\nimport type {\n IGetSecretDataRequestBody,\n KeyPair,\n IAddSecretDataRequestBody,\n IBatchAddSecretDataRequestBody,\n IMetadataLockRequestBody,\n NodeAuthToken,\n BaseAddSecretDataItemParams,\n FetchMetadataAccessCreds,\n IUpdateSecretDataRequestBody,\n IBatchUpdateSecretDataRequestBody,\n UpdateSecretDataItemFields,\n SecretDataItemInput,\n SecretDataItemOutput,\n} from './interfaces';\n\ntype MetadataStoreOptions = {\n metadataEndpoint: string;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n};\n\nexport type MetadataLock = {\n id: string;\n nodeIndex: number;\n}[];\n\nexport enum MetadataLockStatus {\n FAILED = 0,\n SUCCESS = 1,\n}\n\nexport type AuthTokenToMetadataEndpointsMap = {\n [endpoint: string]: NodeAuthToken;\n};\n\nexport type LockAcquiredResponse = { status: MetadataLockStatus; id?: string };\n\nexport type UpdateSecretDataItem = {\n itemId: string;\n fields: UpdateSecretDataItemFields;\n};\n\nexport type MetadataAddSecretDataItemParams =\n BaseAddSecretDataItemParams<SecretDataItemInput>;\n\nexport type MetadataBatchAddSecretDataItemParams = BaseAddSecretDataItemParams<\n SecretDataItemInput[],\n Uint8Array | Uint8Array[]\n>;\n\nexport type MetadataUpdateSecretDataItemParams = {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n};\n\nexport type MetadataBatchUpdateSecretDataItemParams = {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n};\n\n/**\n * Error class for metadata store.\n */\nexport class MetadataStoreError extends Error {\n /**\n * Constructor for MetadataStoreError.\n *\n * @param message - The error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'MetadataStoreError';\n Object.setPrototypeOf(this, MetadataStoreError.prototype);\n }\n}\n\n/**\n * MetadataStore class.\n *\n * This class is used to store and retrieve encrypted account metadata for the\n * given feature.\n */\nexport class MetadataStore {\n readonly #feature = 'srp-backup';\n\n readonly #metadataEndpoint: string;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n /**\n *\n * @param options - The initialization options for the metadata store.\n * @param options.nodeEndpointsMap - The map of node endpoints which includes node index as key and node endpoint as value.\n * @param options.storageLocation - The storage location of the metadata.\n * @param options.fetchMetadataAccessCreds - The function to fetch the metadata access credentials.\n */\n constructor(options: MetadataStoreOptions) {\n this.#metadataEndpoint = options.metadataEndpoint;\n this.#fetchMetadataAccessCreds = options.fetchMetadataAccessCreds;\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored, including optional version and dataType.\n * @param params.secretData.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.secretData.dataType - Optional data type for categorizing the secret data. Required for v2.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the secret data is stored.\n */\n async addSecretDataItem(\n params: MetadataAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#addData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Encrypts the secret data and stores it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async batchAddSecretData(\n params: MetadataBatchAddSecretDataItemParams,\n ): Promise<void> {\n try {\n const { secretData, encKey, authKeyPair } = params;\n\n await this.#batchAddData({\n secretData,\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to add batch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Fetches the secret data from the metadata store and decrypts it.\n *\n * @param encKey - The encryption key to be used for decrypting the secret data.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async fetchAllSecretDataItems(\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<SecretDataItemOutput[]> {\n try {\n const result = await this.#getAllDataItems({\n encKey,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n itemId,\n });\n return result;\n } catch (error) {\n throw new MetadataStoreError(\n `failed to fetch metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when the update is complete.\n */\n async updateSecretDataItem(\n params: MetadataUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItem, authKeyPair } = params;\n await this.#updateData({\n updateItem,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n * This does not modify the encrypted data itself, only metadata fields like dataType.\n *\n * @param params - The parameters for updating the secret data items.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @returns A promise that resolves when all updates are complete.\n */\n async batchUpdateSecretData(\n params: MetadataBatchUpdateSecretDataItemParams,\n ): Promise<void> {\n try {\n const { updateItems, authKeyPair } = params;\n await this.#batchUpdateData({\n updateItems,\n authKeyPair,\n metadataEndpoint: this.#metadataEndpoint,\n });\n } catch (error) {\n throw new MetadataStoreError(\n `failed to batch update metadata: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves with the lock id.\n */\n async acquireMetadataLock(authKeyPair: KeyPair): Promise<string> {\n const { status: lockStatus, id: lockId } = await this.#acquireLock(\n this.#metadataEndpoint,\n authKeyPair,\n );\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError('Failed to acquire metadata lock');\n }\n if (!lockId) {\n throw new MetadataStoreError(\n 'Failed to acquire metadata lock. Missing lock id',\n );\n }\n\n return lockId;\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async releaseMetadataLock(\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n const lockStatus = await this.#releaseLock(\n this.#metadataEndpoint,\n authKeyPair,\n lockId,\n );\n\n if (lockStatus !== MetadataLockStatus.SUCCESS) {\n throw new MetadataStoreError(\n `Failed to release metadata lock with id ${lockId}`,\n );\n }\n\n return lockStatus;\n }\n\n /**\n * Encrypts the secret data and inserts or appends it in the metadata store.\n *\n * @param params - The parameters for storing the secret data.\n * @param params.secretData - The secret data to be stored.\n * @param params.encKey - The encryption key to be used for encrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #addData(params: {\n secretData: SecretDataItemInput;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (\n params.secretData.itemId === PW_BACKUP_ITEM_ID &&\n params.secretData.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n params.secretData.itemId !== PW_BACKUP_ITEM_ID &&\n params.secretData.version !== 'v1' &&\n params.secretData.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/set`;\n const encryptedData = this.#encryptData(\n params.secretData.data,\n params.encKey,\n );\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n {\n itemId: params.secretData.itemId,\n data: encryptedData,\n version: params.secretData.version ?? 'v2',\n dataType: params.secretData.dataType,\n },\n params.authKeyPair,\n );\n const requestBody = JSON.stringify(payload);\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: requestBody,\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Encrypts the array of secret data and inserts them in the metadata store.\n *\n * @param params - The parameters for serializing and making batch set secret\n * data request.\n * @param params.secretData - The array of secret data to be stored.\n * @param params.encKey - The encryption key or keys to be used for encrypting\n * the secret data. If an array is provided, it must have the same length as\n * the secret data array.\n * @param params.authKeyPair - The authentication key pair to be used for\n * authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used\n * for storing the secret data.\n * @returns A promise that resolves when the secret data is stored.\n */\n async #batchAddData(params: {\n secretData: SecretDataItemInput[];\n encKey: Uint8Array | Uint8Array[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n const encKeys = (\n Array.isArray(params.encKey)\n ? params.encKey\n : params.secretData.map(() => params.encKey)\n ) as Uint8Array[];\n\n if (encKeys.length !== params.secretData.length) {\n throw new MetadataStoreError(\n 'encKey must be of same length as secretData',\n );\n }\n\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/batch_set`;\n const encryptedDataArray = params.secretData.map((secret, index) => {\n if (\n secret.itemId === PW_BACKUP_ITEM_ID &&\n secret.dataType !== undefined\n ) {\n throw new MetadataStoreError(\n 'dataType cannot be set for PW_BACKUP item',\n );\n }\n // For v2 (or default), dataType is required for non-PW_BACKUP items\n if (\n secret.itemId !== PW_BACKUP_ITEM_ID &&\n secret.version !== 'v1' &&\n secret.dataType === undefined\n ) {\n throw new MetadataStoreError(\n 'dataType is required for v2 secret data items',\n );\n }\n return {\n data: this.#encryptData(secret.data, encKeys[index]),\n itemId: secret.itemId,\n version: secret.version ?? 'v2',\n dataType: secret.dataType,\n };\n });\n const payload =\n await this.#generatePayloadForSetOrBatchSetSecretDataRequest(\n encryptedDataArray,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to upsert metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId (without modifying encrypted data).\n *\n * @param params - The parameters for updating the secret data.\n * @param params.updateItem - The item ID and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when the update is complete.\n */\n async #updateData(params: {\n updateItem: UpdateSecretDataItem;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n if (params.updateItem.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItem,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating.\n * @param params.updateItems - Array of items with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n * @param params.metadataEndpoint - The metadata server endpoint.\n * @returns A promise that resolves when all updates are complete.\n */\n async #batchUpdateData(params: {\n updateItems: UpdateSecretDataItem[];\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n }): Promise<boolean> {\n try {\n for (const item of params.updateItems) {\n if (item.itemId === PW_BACKUP_ITEM_ID) {\n throw new MetadataStoreError('PW_BACKUP cannot be updated');\n }\n }\n\n const url = `${params.metadataEndpoint}/enc_account_data/batch_update`;\n const payload = await this.#generatePayloadForUpdateSecretDataRequest(\n params.updateItems,\n params.authKeyPair,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n const jsonData = await response.json();\n return jsonData.success;\n } catch (error: unknown) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to batch update metadata: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Fetches all the secret data from the metadata store by provided public key and decrypts it.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param params.metadataEndpoint - The metadata server endpoint to be used for fetching the secret data.\n * @param params.itemId - The item id to be used for fetching the secret data.\n * @returns A promise that resolves with the decrypted secret data.\n */\n async #getAllDataItems(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n metadataEndpoint: string;\n itemId?: string;\n }): Promise<SecretDataItemOutput[]> {\n try {\n const url = `${params.metadataEndpoint}/enc_account_data/get`;\n const payload = await this.#generatePayloadForGetSecretDataRequest(\n params.authKeyPair,\n params.itemId,\n );\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = (await response.json()) as {\n data: string[];\n ids: string[];\n versions: string[];\n dataTypes: (number | null)[];\n createdAt: (string | null)[];\n };\n if (!jsonData.data) {\n throw new MetadataStoreError('Failed to fetch metadata');\n }\n\n const secretData: SecretDataItemOutput[] = [];\n\n // Server filters by itemId when provided, so no client-side filtering needed\n for (let i = 0; i < jsonData.data.length; i++) {\n const id = jsonData.ids[i];\n\n // Skip PW_BACKUP unless specifically requested\n if (!params.itemId && id === PW_BACKUP_ITEM_ID) {\n continue;\n }\n\n const rawData = new Uint8Array(Buffer.from(jsonData.data[i], 'base64'));\n const decryptedData = this.#decryptData(rawData, params.encKey);\n const dataType = jsonData.dataTypes?.[i];\n const createdAt = jsonData.createdAt?.[i];\n secretData.push({\n itemId: id,\n data: decryptedData,\n version: jsonData.versions[i] as 'v1' | 'v2',\n dataType: typeof dataType === 'number' ? dataType : undefined,\n createdAt: typeof createdAt === 'string' ? createdAt : undefined,\n });\n }\n\n return secretData;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(`failed to fetch metadata: ${errorMessage}`);\n }\n }\n\n /**\n * Acquires a lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for acquiring the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns A promise that resolves when the lock is acquired.\n */\n async #acquireLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n ): Promise<LockAcquiredResponse> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair);\n const url = `${metadataEndpoint}/acquireLock`;\n\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return {\n status: jsonData.status,\n id: jsonData.id,\n };\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to acquire metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Releases the lock on the metadata store.\n *\n * @param metadataEndpoint - The metadata server endpoint to be used for releasing the lock.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns A promise that resolves with the lock status.\n */\n async #releaseLock(\n metadataEndpoint: string,\n authKeyPair: KeyPair,\n lockId: string,\n ): Promise<MetadataLockStatus> {\n try {\n const payload = this.#generatePayloadForLockRequests(authKeyPair, lockId);\n\n const url = `${metadataEndpoint}/releaseLock`;\n const response = await fetch(url, {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const responseBody = await response.json();\n throw new Error(`HTTP error message: ${responseBody.error}`);\n }\n\n const jsonData = await response.json();\n return jsonData.status;\n } catch (error) {\n const errorMessage = (error as Error).message || 'Unknown error';\n throw new MetadataStoreError(\n `failed to release metadata lock: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Generate the payload for the set or batch set secret data request and get payload signature.\n *\n * @param inputData - The raw encrypted secret data or batch of encrypted secret data to be stored.\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @returns The payload for the batch set secret data request.\n */\n async #generatePayloadForSetOrBatchSetSecretDataRequest(\n inputData: SecretDataItemInput | SecretDataItemInput[],\n authKeyPair: KeyPair,\n ): Promise<IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.data = inputData.map((item) => ({\n data: Buffer.from(item.data).toString('base64'),\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n }));\n } else {\n sigPayload.data = Buffer.from(inputData.data).toString('base64');\n sigPayload.itemId = inputData.itemId;\n sigPayload.version = inputData.version;\n sigPayload.dataType = inputData.dataType;\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n const payload = {\n ...sigPayload,\n signature,\n pubKey,\n } as IAddSecretDataRequestBody | IBatchAddSecretDataRequestBody;\n\n return payload;\n }\n\n /**\n * Generate the payload for the get secret data request and get payload signature.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param itemId - The item id to be used for fetching the secret data.\n * @returns The payload for the get secret data request.\n */\n async #generatePayloadForGetSecretDataRequest(\n authKeyPair: KeyPair,\n itemId?: string,\n ): Promise<IGetSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { pk, sk } = authKeyPair;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n const sigPayload = {\n feature,\n timestamp,\n itemId,\n authToken: metadataAccessToken,\n };\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n pubKey,\n signature,\n };\n }\n\n /**\n * Generate the payload for updating secret data items by itemId.\n *\n * @param inputData - Single update item or array of update items.\n * @param authKeyPair - The authentication key pair for signing the request.\n * @returns The payload for the update request.\n */\n async #generatePayloadForUpdateSecretDataRequest(\n inputData: UpdateSecretDataItem | UpdateSecretDataItem[],\n authKeyPair: KeyPair,\n ): Promise<IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody> {\n const timestamp = Date.now().toString();\n const feature = this.#feature;\n const { metadataAccessToken } = await this.#fetchMetadataAccessCreds();\n\n const sigPayload: Record<string, unknown> = {\n timestamp,\n feature,\n authToken: metadataAccessToken,\n };\n\n if (Array.isArray(inputData)) {\n sigPayload.items = inputData.map((item) => ({\n itemId: item.itemId,\n dataType: item.fields.dataType,\n version: item.fields.version ?? 'v2',\n }));\n } else {\n sigPayload.itemId = inputData.itemId;\n sigPayload.dataType = inputData.fields.dataType;\n sigPayload.version = inputData.fields.version ?? 'v2';\n }\n\n const { pk, sk } = authKeyPair;\n const signature = this.#generatePayloadSignature(sigPayload, sk);\n\n const pubKey = bytesToHex(pk);\n return {\n ...sigPayload,\n signature,\n pubKey,\n } as IUpdateSecretDataRequestBody | IBatchUpdateSecretDataRequestBody;\n }\n\n /**\n * Generate the payload for the lock requests.\n *\n * @param authKeyPair - The authentication key pair to be used for authenticating the secret data.\n * @param lockId - The lock id to be released.\n * @returns The payload for the lock requests.\n */\n #generatePayloadForLockRequests(\n authKeyPair: KeyPair,\n lockId?: string,\n ): IMetadataLockRequestBody {\n const { pk, sk } = authKeyPair;\n const data = { timestamp: Date.now() };\n // metadata server expects der encoded signature for lock requests\n const shouldDerEncoded = true;\n const signature = this.#generatePayloadSignature(\n data,\n sk,\n shouldDerEncoded,\n );\n const key = bytesToHex(pk);\n\n const payloadForLockRequest: IMetadataLockRequestBody = {\n data,\n signature,\n key,\n id: lockId,\n };\n\n return payloadForLockRequest;\n }\n\n /**\n * Generate the signature for the payload.\n *\n * @param payload - The payload to be signed.\n * @param privKey - The private key to sign the payload.\n * @param shouldDerEncoded - Whether the signature should be der encoded.\n * @returns The signature hex string.\n */\n #generatePayloadSignature(\n payload: Record<string, unknown>,\n privKey: bigint,\n shouldDerEncoded = false,\n ): string {\n const payloadString = safeStringify(payload);\n const hash = keccak256(payloadString);\n const signature = secp256k1.sign(hash, privKey);\n\n if (shouldDerEncoded) {\n return signature.toDERHex();\n }\n\n return signature.toCompactHex();\n }\n\n /**\n * Encrypt the data using the key with AES-256-GCM.\n *\n * @param data - The secret data to be encrypted.\n * @param encryptionKey - The encryption key to encrypt the data.\n * @returns The encrypted data.\n */\n #encryptData(data: Uint8Array, encryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(encryptionKey);\n const ciphertext = aesGcm.encrypt(data);\n return ciphertext;\n }\n\n /**\n * Decrypt the data using the encryption key.\n *\n * @param cipherText - The cipher text, encrypted with AES-256-GCM.\n * @param decryptionKey - The encryption key to decrypt the data.\n * @returns The decrypted data.\n */\n #decryptData(cipherText: Uint8Array, decryptionKey: Uint8Array): Uint8Array {\n const aesGcm = managedNonce(gcm)(decryptionKey);\n const decryptedData = aesGcm.decrypt(cipherText);\n\n return decryptedData;\n }\n}\n"]}

@@ -339,3 +339,3 @@ "use strict";

async changeEncKey(params) {
const { nodeAuthTokens, authConnectionId, groupedAuthConnectionId, userId, oldEncKey, oldPwEncKey, oldAuthKeyPair, newPassword, newKeyShareIndex, pregeneratedOprfKey, } = params;
const { nodeAuthTokens, authConnectionId, groupedAuthConnectionId, userId, oldEncKey, oldPwEncKey, oldAuthKeyPair, newPassword, newKeyShareIndex, pregeneratedOprfKey, transformDataItems, } = params;
if (!pregeneratedOprfKey && !newPassword) {

@@ -361,8 +361,10 @@ throw new Error('Either newPassword or pregeneratedOprfKey is required');

]);
const existingData = (await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair)).map((dataItem) => ({
data: dataItem.data,
dataType: dataItem.dataType,
// Use v1 to bypass dataType validation for legacy data without dataType
version: dataItem.dataType === undefined ? 'v1' : dataItem.version,
}));
const fetched = await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair);
const existingData = transformDataItems
? transformDataItems(fetched)
: fetched.map(({ data, dataType, version }) => ({
data,
dataType,
version: dataType === undefined ? 'v1' : version,
}));
// Validate that this is actually a key change scenario

@@ -369,0 +371,0 @@ if (!existingData || existingData.length === 0) {

@@ -1,1 +0,1 @@

{"version":3,"file":"toprfSecureBackup.cjs","sourceRoot":"","sources":["../src/toprfSecureBackup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAA4E;AAC5E,gDAA+D;AAC/D,wDAA2D;AAC3D,uDAAoD;AACpD,+CAA6D;AAK7D,sEAAkE;AAElE,mEAAyD;AACzD,uDAAgD;AAChD,+CAIqB;AACrB,yCAAsC;AACtC,6DAA+C;AA4B/C,uDAIyB;AAEzB,6CAA2C;AAE3C,qCAAoD;AACpD,2DAAoD;AACpD,iEAAuE;AACvE,6DAAsD;AACtD,uCAAiD;AAEjD;;;GAGG;AACH,MAAa,iBAAiB;IAW5B;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,MAKX;;QAhCQ,uDAAsC;QAEtC,yDAA2C;QAE3C,gDAAyB;QAEzB,8DAAoD;QAE7D,wDAA+C;QAyB7C,uBAAA,IAAI,wCAAsB,IAAI,sCAAiB,CAAC;YAC9C,OAAO,EAAE,MAAM,CAAC,OAAO;SACxB,CAAC,MAAA,CAAC;QACH,uBAAA,IAAI,0CAAwB,MAAM,CAAC,mBAAmB,MAAA,CAAC;QACvD,uBAAA,IAAI,iCAAe,MAAM,CAAC,UAAU,MAAA,CAAC;QACrC,uBAAA,IAAI,+CAA6B,MAAM,CAAC,wBAAwB,MAAA,CAAC;IACnE,CAAC;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,KAAK,CAAC,YAAY,CAAC,MAA0B;QAC3C,MAAM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,CAAC,WAAW;KAC1C,CAAC;AACJ,CAAC,yGAWC,OAAkB,EAClB,OAAkB,EAClB,SAAoB;IAEpB,IACE,OAAO,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QACjC,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EACnC;QACA,MAAM,OAAO,GACX,2EAA2E,CAAC;QAC9E,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;KAC1B;AACH,CAAC;AAGH;;;;;;;GAOG;AACH,SAAS,iBAAiB,CACxB,EAAU,EACV,MAAkB,EAClB,WAAoB;IAEpB,OAAO,IAAA,mBAAW,EAChB,IAAI,CAAC,SAAS,CAAC;QACb,EAAE;QACF,MAAM,EAAE,IAAA,kBAAU,EAAC,MAAM,CAAC;QAC1B,WAAW,EAAE;YACX,EAAE,EAAE,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE;YAC7B,EAAE,EAAE,IAAA,kBAAU,EAAC,WAAW,CAAC,EAAE,CAAC;SAC/B;KACF,CAAC,CACH,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,IAAgB;IAK3C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAA,mBAAW,EAAC,IAAI,CAAC,CAAC,CAAC;IAC3C,OAAO;QACL,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,MAAM,EAAE,IAAA,kBAAU,EAAC,IAAI,CAAC,MAAM,CAAC;QAC/B,WAAW,EAAE;YACX,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YAC/B,EAAE,EAAE,IAAA,kBAAU,EAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { keccak256AndHexify, remove0x } from '@metamask/auth-network-utils';\nimport { bytesToUtf8, equalBytes } from '@noble/ciphers/utils';\nimport { utf8ToBytes } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\nimport type {\n INodePub,\n TORUS_SAPPHIRE_NETWORK_TYPE,\n} from '@toruslabs/constants';\nimport { NodeDetailManager } from '@toruslabs/fetch-node-details';\n\nimport { authenticateUser } from './authenticateRequest';\nimport { commitIdToken } from './commitRequest';\nimport {\n FIRST_KEY_INDEX,\n MAX_PASSWORD_CHAIN_LENGTH,\n PW_BACKUP_ITEM_ID,\n} from './constants';\nimport { TOPRFError } from './errors';\nimport { getPubKey } from './getPubKeyRequest';\nimport type {\n AuthenticateParams,\n AuthenticateResult,\n CreateEncryptionKeyParams,\n CreateEncryptionKeyResult,\n FetchAllSecretDataParams,\n IToprfSecureBackup,\n RecoverEncryptionKeyParams,\n RecoverEncryptionKeyResult,\n AddSecretDataItemParams,\n ChangeEncryptionKeyParams,\n ChangeEncryptionKeyResult,\n FetchAuthPubKeyParams,\n FetchAuthPubKeyResult,\n PersistLocalKeyParams,\n CreateLocalKeyParams,\n CreateLocalKeyResult,\n BatchAddSecretDataItemParams,\n RecoverPwEncKeyParams,\n KeyPair,\n RecoverPwEncKeyResult,\n NodeDetailsOverride,\n FetchMetadataAccessCreds,\n UpdateSecretDataItemParams,\n BatchUpdateSecretDataItemParams,\n FetchedSecretDataItem,\n} from './interfaces';\nimport {\n deriveAuthenticationKeyPair,\n deriveEncryptionKey,\n derivePwEncKey,\n} from './keyDerivation';\nimport type { SecretDataItem } from './metadata';\nimport { MetadataStore } from './metadata';\nimport type { KeyDeriver } from './oprf';\nimport { OPRF, generateRandomScalar } from './oprf';\nimport { resetRateLimits } from './resetRateLimits';\nimport { storeKeyShares, changeKeyShares } from './storeSharesRequest';\nimport { recoverTOPRFSeed } from './toprfEvalRequest';\nimport { createNodeEndpointsMap } from './utils';\n\n/**\n * ToprfSecureBackup - The main class for the tOPRF Secure Backup service.\n *\n */\nexport class ToprfSecureBackup implements IToprfSecureBackup {\n readonly #nodeDetailManager: NodeDetailManager;\n\n readonly #nodeDetailsOverride?: NodeDetailsOverride;\n\n readonly #keyDeriver?: KeyDeriver;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n #metadataStoreCache: MetadataStore | undefined;\n\n /**\n * The constructor for the ToprfSecureBackup class.\n *\n * If `keyDeriver` is provided, it will be used as an additional step during\n * key derivation. This can be used, for example, to inject a slow key\n * derivation step to protect against local brute force attacks on the\n * password.\n *\n * @param params - The parameters for the constructor.\n * @param params.network - The web3auth network to be used for key management\n * and authentication.\n * @param params.nodeDetailsOverride - Optional overrides for node details\n * like SSS endpoints, indexes, and public keys.\n * @param params.keyDeriver - Optional key deriver to be used for an\n * additional layer of security.\n * @param params.fetchMetadataAccessCreds - Function to fetch metadata access credentials.\n */\n constructor(params: {\n network: TORUS_SAPPHIRE_NETWORK_TYPE;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n nodeDetailsOverride?: NodeDetailsOverride;\n keyDeriver?: KeyDeriver;\n }) {\n this.#nodeDetailManager = new NodeDetailManager({\n network: params.network,\n });\n this.#nodeDetailsOverride = params.nodeDetailsOverride;\n this.#keyDeriver = params.keyDeriver;\n this.#fetchMetadataAccessCreds = params.fetchMetadataAccessCreds;\n }\n\n /**\n * This function is used to authenticate the user by sending the oauth idToken to the nodes and\n * getting the authentication tokens from the nodes in return.\n *\n * @param params - The authentication parameters.\n * @param params.idTokens - An array of id tokens for authentication.\n * @param params.authConnectionId - The auth connection name to be used for the authenticate request\n * @param params.userId - The user id of the user issued by authentication service\n * @param params.groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n *\n * @returns - The authentication result containing the authentication tokens and a boolean indicating if the user is new or not.\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n * @throws {Error} If idToken is older than 6 minutes.\n */\n async authenticate(params: AuthenticateParams): Promise<AuthenticateResult> {\n const { nodeEndpoints, nodeEndpointsMap } = await this.#getNodeDetails();\n let sessionPrivKey: Uint8Array | null = secp256k1.utils.randomPrivateKey();\n\n try {\n const sessionPubKey =\n secp256k1.ProjectivePoint.fromPrivateKey(sessionPrivKey);\n const sessionPubKeyX = sessionPubKey.x.toString(16);\n const sessionPubKeyY = sessionPubKey.y.toString(16);\n\n let hashedIdToken: string | undefined;\n if (params.groupedAuthConnectionId) {\n // if groupedAuthConnectionId is provided, we'll compute the hashedIdToken for the aggregate (single id) verifier login\n hashedIdToken = remove0x(\n keccak256AndHexify(Buffer.from(params.idTokens[0], 'utf8')),\n );\n }\n\n // commit idToken to nodes\n const commitmentResults = await commitIdToken({\n idToken: hashedIdToken ?? params.idTokens[0],\n authConnectionId:\n params.groupedAuthConnectionId ?? params.authConnectionId,\n sessionPubKeyX,\n sessionPubKeyY,\n endpoints: nodeEndpoints,\n });\n\n // use only the node indexes that returned valid commitment responses\n const selectedEndpointsMap = commitmentResults.reduce<\n Record<number, string>\n >((acc, result) => {\n acc[result.nodeIndex] = nodeEndpointsMap[result.nodeIndex];\n return acc;\n }, {});\n\n // get auth tokens from nodes\n const { authTokensData, isNewUser } = await authenticateUser({\n idToken: params.idTokens[0],\n authConnectionId: params.authConnectionId,\n userId: params.userId,\n sessionPrivateKey: sessionPrivKey,\n nodeEndpointsMap: selectedEndpointsMap,\n commitmentSignatures: commitmentResults,\n groupedAuthConnectionId: params.groupedAuthConnectionId,\n hashedIdToken,\n });\n\n return {\n nodeAuthTokens: authTokensData.map((tokenData) => ({\n authToken: tokenData.authToken,\n nodeIndex: tokenData.nodeIndex,\n nodePubKey: tokenData.nodePubKey,\n })),\n isNewUser,\n };\n } finally {\n // Clean up session private key\n sessionPrivKey.fill(0);\n sessionPrivKey = null;\n }\n }\n\n /**\n * This function locally creates an OPRF and encryption keys without storing them at the\n * key management service. It returns the OPRF key, derives the corresponding key seed,\n * authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns The OPRF key, seed, and derived keys.\n */\n async createLocalKey(\n params: CreateLocalKeyParams,\n ): Promise<CreateLocalKeyResult> {\n const { password, oprfKey = generateRandomScalar() } = params;\n let pwBytes: Uint8Array | null = null;\n\n try {\n pwBytes = utf8ToBytes(password);\n const seed = await OPRF.localEval(oprfKey, pwBytes, this.#keyDeriver);\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n return {\n oprfKey,\n seed,\n authKeyPair,\n encKey,\n pwEncKey,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n }\n }\n\n /**\n * This function persists the OPRF key's shares at the servers.\n *\n * @param params - The parameters for persisting the OPRF key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authPubKey - The authentication public key.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n */\n async persistLocalKey(params: PersistLocalKeyParams): Promise<void> {\n const {\n nodeAuthTokens,\n oprfKey,\n authPubKey,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex = FIRST_KEY_INDEX,\n oldAuthKeyPair,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n\n const selectedEndpointsMap = nodeAuthTokens.reduce<Record<number, string>>(\n (acc, tokenData) => {\n acc[tokenData.nodeIndex] = nodeEndpointsMap[tokenData.nodeIndex];\n return acc;\n },\n {},\n );\n\n if (oldAuthKeyPair) {\n await changeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n newOprfKey: oprfKey,\n newAuthPubKey: authPubKey,\n oldAuthPrivKey: oldAuthKeyPair.sk,\n });\n } else {\n await storeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n oprfKey,\n authPubKey,\n });\n }\n }\n\n /**\n * This function creates the encryption key which is used to encrypt/decrypt the secret data.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - New password of the user.\n *\n * @returns The encryption key.\n */\n async createAndPersistEncKey(\n params: CreateEncryptionKeyParams,\n ): Promise<CreateEncryptionKeyResult> {\n const { nodeAuthTokens, password, authConnectionId, userId } = params;\n const { oprfKey, authKeyPair, encKey, pwEncKey } =\n await this.createLocalKey({\n password,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n userId,\n });\n\n return {\n authKeyPair: {\n sk: authKeyPair.sk,\n pk: authKeyPair.pk,\n },\n encKey,\n pwEncKey,\n };\n }\n\n /**\n * This function recovers the encryption key which is used to decrypt the secret data.\n *\n * @param params - The parameters for recovering the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - The password of the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The encryption key result with auth key pair, encryption key and key share index.\n */\n async recoverEncKey(\n params: RecoverEncryptionKeyParams,\n ): Promise<RecoverEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n password,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n } = params;\n\n let pwBytes: Uint8Array | null = null;\n let seed: Uint8Array | null = null;\n\n try {\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n pwBytes = utf8ToBytes(password);\n\n const { seed: seedValue, keyShareIndex } = await recoverTOPRFSeed({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n userInput: pwBytes,\n keyDeriver: this.#keyDeriver,\n });\n\n seed = seedValue;\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n const rateLimitResetResult = new Promise<void>((resolve, reject) => {\n resetRateLimits({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authPrivKey: authKeyPair.sk,\n })\n .then(() => {\n return resolve();\n })\n .catch((error) => {\n reject(error as Error);\n });\n });\n\n return {\n authKeyPair,\n encKey,\n pwEncKey,\n keyShareIndex,\n rateLimitResetResult,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n\n if (seed) {\n seed.fill(0);\n seed = null;\n }\n }\n }\n\n /**\n * This function replaces the existing encryption key with a new one by generating a new key from\n * the new password, copying all existing secret data encrypted with the old key to be encrypted\n * with the new key, and updating the key shares on the nodes.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n * @param params.oldEncKey - The old encryption key of the user.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user.\n * @param params.newKeyShareIndex - The key share index to be used for the new key.\n * @param params.newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n * @param params.pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n *\n * @returns The new key pair and encryption key.\n * @throws {Error} If both newPassword and pregeneratedOprfKey are provided.\n * @throws {Error} If neither newPassword nor pregeneratedOprfKey is provided.\n */\n async changeEncKey(\n params: ChangeEncryptionKeyParams,\n ): Promise<ChangeEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n oldEncKey,\n oldPwEncKey,\n oldAuthKeyPair,\n newPassword,\n newKeyShareIndex,\n pregeneratedOprfKey,\n } = params;\n\n if (!pregeneratedOprfKey && !newPassword) {\n throw new Error('Either newPassword or pregeneratedOprfKey is required');\n }\n\n if (pregeneratedOprfKey && newPassword) {\n throw new Error(\n 'Only one of newPassword or pregeneratedOprfKey is allowed',\n );\n }\n\n // if newPassword is provided, create a new key from the password\n // else use the pregeneratedOprfKey, both can't be undefined as per check above.\n const { oprfKey, authKeyPair, encKey, pwEncKey } = newPassword\n ? await this.createLocalKey({ password: newPassword })\n : (pregeneratedOprfKey as CreateLocalKeyResult);\n\n let metadataStore: MetadataStore | undefined;\n let oldMetadataLockId: string | undefined;\n let newMetadataLockId: string | undefined;\n\n try {\n metadataStore = await this.#createMetadataStore();\n\n [oldMetadataLockId, newMetadataLockId] = await Promise.all([\n metadataStore.acquireMetadataLock(oldAuthKeyPair),\n metadataStore.acquireMetadataLock(authKeyPair),\n ]);\n\n const existingData = (\n await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair)\n ).map((dataItem) => ({\n data: dataItem.data,\n dataType: dataItem.dataType,\n // Use v1 to bypass dataType validation for legacy data without dataType\n version:\n dataItem.dataType === undefined ? ('v1' as const) : dataItem.version,\n }));\n\n // Validate that this is actually a key change scenario\n if (!existingData || existingData.length === 0) {\n throw new Error('No existing data found to change key');\n }\n\n const pwBackup: SecretDataItem = {\n data: serializePwBackup('', oldPwEncKey, oldAuthKeyPair),\n itemId: PW_BACKUP_ITEM_ID,\n };\n\n const secretDataItems = [pwBackup, ...existingData];\n const encKeys = [pwEncKey, ...existingData.map(() => encKey)];\n await metadataStore.batchAddSecretData({\n secretData: secretDataItems,\n encKey: encKeys,\n authKeyPair,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex: newKeyShareIndex,\n oldAuthKeyPair,\n });\n\n return { authKeyPair, encKey, pwEncKey };\n } finally {\n if (metadataStore && oldMetadataLockId && newMetadataLockId) {\n try {\n await Promise.all([\n metadataStore.releaseMetadataLock(\n oldAuthKeyPair,\n oldMetadataLockId,\n ),\n metadataStore.releaseMetadataLock(authKeyPair, newMetadataLockId),\n ]);\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key which is used to encrypt the secret data before storing it.\n * @param params.secretData - The secret data to be registered.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the user to the storage service.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.dataType - Optional data type for categorizing the secret data. Required for v2.\n */\n async addSecretDataItem(params: AddSecretDataItemParams): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.addSecretDataItem({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: {\n data: params.secretData,\n itemId: params.itemId,\n version: params.version,\n dataType: params.dataType,\n },\n });\n }\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\n async batchAddSecretDataItems(\n params: BatchAddSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchAddSecretData({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: params.secretData.map((item) => ({\n data: item.data,\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n })),\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async updateSecretDataItem(\n params: UpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.updateSecretDataItem({\n updateItem: {\n itemId: params.itemId,\n fields: { dataType: params.dataType },\n },\n authKeyPair: params.authKeyPair,\n });\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async batchUpdateSecretDataItems(\n params: BatchUpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchUpdateSecretData({\n updateItems: params.updateItems.map((item) => ({\n itemId: item.itemId,\n fields: { dataType: item.dataType },\n })),\n authKeyPair: params.authKeyPair,\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns The decrypted secret data. Returns an empty array if no secret data is found.\n */\n async fetchAllSecretDataItems(\n params: FetchAllSecretDataParams,\n ): Promise<FetchedSecretDataItem[]> {\n const metadataStore = await this.#createMetadataStore();\n const dataItems = await metadataStore.fetchAllSecretDataItems(\n params.decKey,\n params.authKeyPair,\n );\n return dataItems;\n }\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for getting the authentication public key.\n * @param params.authTokens - The auth tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The authentication public key.\n */\n async fetchAuthPubKey(\n params: FetchAuthPubKeyParams,\n ): Promise<FetchAuthPubKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n return getPubKey({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n });\n }\n\n /**\n * This function looks up a password encryption key from the password\n * encryption key history.\n *\n * @param params - The parameters for getting the password encryption key.\n * @param params.targetPwPubKey - The target password public key.\n * @param params.curPwEncKey - The current password encryption key.\n * @param params.curAuthKeyPair - The current authentication key pair.\n * @param params.maxPwChainLength - Optional maximum password chain length\n * allowed to be traversed.\n *\n * @returns The password encryption key.\n */\n async recoverPwEncKey(\n params: RecoverPwEncKeyParams,\n ): Promise<RecoverPwEncKeyResult> {\n const {\n targetAuthPubKey: targetPwPubKey,\n curPwEncKey,\n curAuthKeyPair,\n maxPwChainLength = MAX_PASSWORD_CHAIN_LENGTH,\n } = params;\n\n let pwAndKeys = {\n password: '',\n encKey: curPwEncKey,\n authKeyPair: curAuthKeyPair,\n };\n\n for (let i = 0; i < maxPwChainLength; i++) {\n try {\n pwAndKeys = await this.#getPrevPasswordAndKeys({\n encKey: pwAndKeys.encKey,\n authKeyPair: pwAndKeys.authKeyPair,\n });\n if (equalBytes(pwAndKeys.authKeyPair.pk, targetPwPubKey)) {\n return { pwEncKey: pwAndKeys.encKey };\n }\n } catch (error) {\n throw TOPRFError.couldNotFetchPassword((error as Error).message);\n }\n }\n\n throw TOPRFError.maxKeyChainLengthExceeded();\n }\n\n /**\n * Gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n return this.#getNodeDetails();\n }\n\n /**\n * Gets the node details.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async #getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n let finalIndexes = this.#nodeDetailsOverride?.indexes;\n let finalPubKeys = this.#nodeDetailsOverride?.pubKeys;\n let finalEndpoints = this.#nodeDetailsOverride?.endpoints;\n\n if (finalIndexes && finalPubKeys && Array.isArray(finalEndpoints)) {\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n // NodeDetailManager has internal caching after first call to getNodeDetails\n // so we don't need internal caching here.\n // reference: {@link https://github.com/torusresearch/fetch-node-details/blob/master/packages/fetch-node-details/src/nodeDetailManager.ts#L88}\n const { torusNodeSSSEndpoints, torusIndexes, torusNodePub } =\n await this.#nodeDetailManager.getNodeDetails({\n verifier: 'auth-connection-id',\n verifierId: 'user-id',\n });\n\n finalIndexes ??= torusIndexes;\n finalPubKeys ??= torusNodePub;\n\n if (!Array.isArray(finalEndpoints)) {\n if (!torusNodeSSSEndpoints) {\n const message = 'Failed to get node details';\n throw new Error(message);\n }\n\n finalEndpoints = finalEndpoints\n ? torusNodeSSSEndpoints.map((endpoint) => {\n const url = new URL(endpoint);\n url.pathname = finalEndpoints as string;\n return url.href;\n })\n : torusNodeSSSEndpoints;\n }\n\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n /**\n * Creates and caches the metadata store instance.\n *\n * @returns The metadata store.\n */\n async #createMetadataStore(): Promise<MetadataStore> {\n if (this.#metadataStoreCache) {\n return this.#metadataStoreCache;\n }\n\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n const metadataEndpointsMap =\n await this.#getMetadataEndpointsMap(nodeEndpointsMap);\n const node1MetadataEndpoint = metadataEndpointsMap['1'];\n\n const metadataStore = new MetadataStore({\n metadataEndpoint: node1MetadataEndpoint,\n fetchMetadataAccessCreds: this.#fetchMetadataAccessCreds,\n });\n\n this.#metadataStoreCache = metadataStore;\n\n return metadataStore;\n }\n\n /**\n * Gets the metadata endpoints.\n *\n * @param nodeEndpointsMap - The node endpoints map.\n *\n * @returns The metadata endpoints map with node index as key and metadata endpoint as value.\n */\n async #getMetadataEndpointsMap(\n nodeEndpointsMap: Record<number, string>,\n ): Promise<{ [nodeIndex: string]: string }> {\n const metadataEndpointsMap: { [nodeIndex: string]: string } = {};\n Object.entries(nodeEndpointsMap).forEach(([key, value]) => {\n const url = new URL(value);\n metadataEndpointsMap[key] = `${url.origin}/metadata`;\n });\n return metadataEndpointsMap;\n }\n\n /**\n * Gets the previous password and keys.\n *\n * @param params - The parameters for getting the previous password and keys.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n *\n * @returns The previous password and keys.\n */\n async #getPrevPasswordAndKeys(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }): Promise<{\n password: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }> {\n const metadataStore = await this.#createMetadataStore();\n\n const pwBackupData = await metadataStore.fetchAllSecretDataItems(\n params.encKey,\n params.authKeyPair,\n PW_BACKUP_ITEM_ID,\n );\n\n if (pwBackupData.length === 0) {\n throw new Error('Failed to get previous password and keys');\n }\n\n // Parse JSON object.\n const pwBackupDataJson = deserializePwBackup(pwBackupData[0].data);\n\n return {\n password: pwBackupDataJson.pw,\n encKey: pwBackupDataJson.encKey,\n authKeyPair: pwBackupDataJson.authKeyPair,\n };\n }\n\n /**\n * Validates that the lengths of node detail arrays are consistent.\n *\n * @param indexes - Array of node indexes.\n * @param pubKeys - Array of node public keys.\n * @param endpoints - Array of SSS endpoint URLs.\n * @throws If lengths are inconsistent.\n */\n static #validateNodeDetailsLengths(\n indexes: unknown[],\n pubKeys: unknown[],\n endpoints: unknown[],\n ): void {\n if (\n indexes.length !== pubKeys.length ||\n indexes.length !== endpoints.length\n ) {\n const message =\n 'Node details arrays (indexes, pubKeys, endpoints) must have equal lengths';\n throw new Error(message);\n }\n }\n}\n\n/**\n * Serializes the password, encryption key, and authentication key pair into a JSON string.\n *\n * @param pw - The password.\n * @param encKey - The encryption key.\n * @param authKeyPair - The authentication key pair.\n * @returns The serialized JSON string.\n */\nfunction serializePwBackup(\n pw: string,\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n): Uint8Array {\n return utf8ToBytes(\n JSON.stringify({\n pw,\n encKey: bytesToHex(encKey),\n authKeyPair: {\n sk: authKeyPair.sk.toString(),\n pk: bytesToHex(authKeyPair.pk),\n },\n }),\n );\n}\n\n/**\n * Deserializes the password, encryption key, and authentication key pair from a JSON string.\n *\n * @param data - The serialized JSON string.\n * @returns The password, encryption key, and authentication key pair.\n */\nfunction deserializePwBackup(data: Uint8Array): {\n pw: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n} {\n const json = JSON.parse(bytesToUtf8(data));\n return {\n pw: json.pw,\n encKey: hexToBytes(json.encKey),\n authKeyPair: {\n sk: BigInt(json.authKeyPair.sk),\n pk: hexToBytes(json.authKeyPair.pk),\n },\n };\n}\n"]}
{"version":3,"file":"toprfSecureBackup.cjs","sourceRoot":"","sources":["../src/toprfSecureBackup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAA4E;AAC5E,gDAA+D;AAC/D,wDAA2D;AAC3D,uDAAoD;AACpD,+CAA6D;AAK7D,sEAAkE;AAElE,mEAAyD;AACzD,uDAAgD;AAChD,+CAIqB;AACrB,yCAAsC;AACtC,6DAA+C;AA6B/C,uDAIyB;AACzB,6CAA2C;AAE3C,qCAAoD;AACpD,2DAAoD;AACpD,iEAAuE;AACvE,6DAAsD;AACtD,uCAAiD;AAEjD;;;GAGG;AACH,MAAa,iBAAiB;IAW5B;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,MAKX;;QAhCQ,uDAAsC;QAEtC,yDAA2C;QAE3C,gDAAyB;QAEzB,8DAAoD;QAE7D,wDAA+C;QAyB7C,uBAAA,IAAI,wCAAsB,IAAI,sCAAiB,CAAC;YAC9C,OAAO,EAAE,MAAM,CAAC,OAAO;SACxB,CAAC,MAAA,CAAC;QACH,uBAAA,IAAI,0CAAwB,MAAM,CAAC,mBAAmB,MAAA,CAAC;QACvD,uBAAA,IAAI,iCAAe,MAAM,CAAC,UAAU,MAAA,CAAC;QACrC,uBAAA,IAAI,+CAA6B,MAAM,CAAC,wBAAwB,MAAA,CAAC;IACnE,CAAC;I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["import { keccak256AndHexify, remove0x } from '@metamask/auth-network-utils';\nimport { bytesToUtf8, equalBytes } from '@noble/ciphers/utils';\nimport { utf8ToBytes } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\nimport type {\n INodePub,\n TORUS_SAPPHIRE_NETWORK_TYPE,\n} from '@toruslabs/constants';\nimport { NodeDetailManager } from '@toruslabs/fetch-node-details';\n\nimport { authenticateUser } from './authenticateRequest';\nimport { commitIdToken } from './commitRequest';\nimport {\n FIRST_KEY_INDEX,\n MAX_PASSWORD_CHAIN_LENGTH,\n PW_BACKUP_ITEM_ID,\n} from './constants';\nimport { TOPRFError } from './errors';\nimport { getPubKey } from './getPubKeyRequest';\nimport type {\n AuthenticateParams,\n AuthenticateResult,\n CreateEncryptionKeyParams,\n CreateEncryptionKeyResult,\n FetchAllSecretDataParams,\n IToprfSecureBackup,\n RecoverEncryptionKeyParams,\n RecoverEncryptionKeyResult,\n AddSecretDataItemParams,\n ChangeEncryptionKeyParams,\n ChangeEncryptionKeyResult,\n FetchAuthPubKeyParams,\n FetchAuthPubKeyResult,\n PersistLocalKeyParams,\n CreateLocalKeyParams,\n CreateLocalKeyResult,\n BatchAddSecretDataItemParams,\n RecoverPwEncKeyParams,\n KeyPair,\n RecoverPwEncKeyResult,\n NodeDetailsOverride,\n FetchMetadataAccessCreds,\n UpdateSecretDataItemParams,\n BatchUpdateSecretDataItemParams,\n FetchedSecretDataItem,\n SecretDataItem,\n} from './interfaces';\nimport {\n deriveAuthenticationKeyPair,\n deriveEncryptionKey,\n derivePwEncKey,\n} from './keyDerivation';\nimport { MetadataStore } from './metadata';\nimport type { KeyDeriver } from './oprf';\nimport { OPRF, generateRandomScalar } from './oprf';\nimport { resetRateLimits } from './resetRateLimits';\nimport { storeKeyShares, changeKeyShares } from './storeSharesRequest';\nimport { recoverTOPRFSeed } from './toprfEvalRequest';\nimport { createNodeEndpointsMap } from './utils';\n\n/**\n * ToprfSecureBackup - The main class for the tOPRF Secure Backup service.\n *\n */\nexport class ToprfSecureBackup implements IToprfSecureBackup {\n readonly #nodeDetailManager: NodeDetailManager;\n\n readonly #nodeDetailsOverride?: NodeDetailsOverride;\n\n readonly #keyDeriver?: KeyDeriver;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n #metadataStoreCache: MetadataStore | undefined;\n\n /**\n * The constructor for the ToprfSecureBackup class.\n *\n * If `keyDeriver` is provided, it will be used as an additional step during\n * key derivation. This can be used, for example, to inject a slow key\n * derivation step to protect against local brute force attacks on the\n * password.\n *\n * @param params - The parameters for the constructor.\n * @param params.network - The web3auth network to be used for key management\n * and authentication.\n * @param params.nodeDetailsOverride - Optional overrides for node details\n * like SSS endpoints, indexes, and public keys.\n * @param params.keyDeriver - Optional key deriver to be used for an\n * additional layer of security.\n * @param params.fetchMetadataAccessCreds - Function to fetch metadata access credentials.\n */\n constructor(params: {\n network: TORUS_SAPPHIRE_NETWORK_TYPE;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n nodeDetailsOverride?: NodeDetailsOverride;\n keyDeriver?: KeyDeriver;\n }) {\n this.#nodeDetailManager = new NodeDetailManager({\n network: params.network,\n });\n this.#nodeDetailsOverride = params.nodeDetailsOverride;\n this.#keyDeriver = params.keyDeriver;\n this.#fetchMetadataAccessCreds = params.fetchMetadataAccessCreds;\n }\n\n /**\n * This function is used to authenticate the user by sending the oauth idToken to the nodes and\n * getting the authentication tokens from the nodes in return.\n *\n * @param params - The authentication parameters.\n * @param params.idTokens - An array of id tokens for authentication.\n * @param params.authConnectionId - The auth connection name to be used for the authenticate request\n * @param params.userId - The user id of the user issued by authentication service\n * @param params.groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n *\n * @returns - The authentication result containing the authentication tokens and a boolean indicating if the user is new or not.\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n * @throws {Error} If idToken is older than 6 minutes.\n */\n async authenticate(params: AuthenticateParams): Promise<AuthenticateResult> {\n const { nodeEndpoints, nodeEndpointsMap } = await this.#getNodeDetails();\n let sessionPrivKey: Uint8Array | null = secp256k1.utils.randomPrivateKey();\n\n try {\n const sessionPubKey =\n secp256k1.ProjectivePoint.fromPrivateKey(sessionPrivKey);\n const sessionPubKeyX = sessionPubKey.x.toString(16);\n const sessionPubKeyY = sessionPubKey.y.toString(16);\n\n let hashedIdToken: string | undefined;\n if (params.groupedAuthConnectionId) {\n // if groupedAuthConnectionId is provided, we'll compute the hashedIdToken for the aggregate (single id) verifier login\n hashedIdToken = remove0x(\n keccak256AndHexify(Buffer.from(params.idTokens[0], 'utf8')),\n );\n }\n\n // commit idToken to nodes\n const commitmentResults = await commitIdToken({\n idToken: hashedIdToken ?? params.idTokens[0],\n authConnectionId:\n params.groupedAuthConnectionId ?? params.authConnectionId,\n sessionPubKeyX,\n sessionPubKeyY,\n endpoints: nodeEndpoints,\n });\n\n // use only the node indexes that returned valid commitment responses\n const selectedEndpointsMap = commitmentResults.reduce<\n Record<number, string>\n >((acc, result) => {\n acc[result.nodeIndex] = nodeEndpointsMap[result.nodeIndex];\n return acc;\n }, {});\n\n // get auth tokens from nodes\n const { authTokensData, isNewUser } = await authenticateUser({\n idToken: params.idTokens[0],\n authConnectionId: params.authConnectionId,\n userId: params.userId,\n sessionPrivateKey: sessionPrivKey,\n nodeEndpointsMap: selectedEndpointsMap,\n commitmentSignatures: commitmentResults,\n groupedAuthConnectionId: params.groupedAuthConnectionId,\n hashedIdToken,\n });\n\n return {\n nodeAuthTokens: authTokensData.map((tokenData) => ({\n authToken: tokenData.authToken,\n nodeIndex: tokenData.nodeIndex,\n nodePubKey: tokenData.nodePubKey,\n })),\n isNewUser,\n };\n } finally {\n // Clean up session private key\n sessionPrivKey.fill(0);\n sessionPrivKey = null;\n }\n }\n\n /**\n * This function locally creates an OPRF and encryption keys without storing them at the\n * key management service. It returns the OPRF key, derives the corresponding key seed,\n * authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns The OPRF key, seed, and derived keys.\n */\n async createLocalKey(\n params: CreateLocalKeyParams,\n ): Promise<CreateLocalKeyResult> {\n const { password, oprfKey = generateRandomScalar() } = params;\n let pwBytes: Uint8Array | null = null;\n\n try {\n pwBytes = utf8ToBytes(password);\n const seed = await OPRF.localEval(oprfKey, pwBytes, this.#keyDeriver);\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n return {\n oprfKey,\n seed,\n authKeyPair,\n encKey,\n pwEncKey,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n }\n }\n\n /**\n * This function persists the OPRF key's shares at the servers.\n *\n * @param params - The parameters for persisting the OPRF key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authPubKey - The authentication public key.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n */\n async persistLocalKey(params: PersistLocalKeyParams): Promise<void> {\n const {\n nodeAuthTokens,\n oprfKey,\n authPubKey,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex = FIRST_KEY_INDEX,\n oldAuthKeyPair,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n\n const selectedEndpointsMap = nodeAuthTokens.reduce<Record<number, string>>(\n (acc, tokenData) => {\n acc[tokenData.nodeIndex] = nodeEndpointsMap[tokenData.nodeIndex];\n return acc;\n },\n {},\n );\n\n if (oldAuthKeyPair) {\n await changeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n newOprfKey: oprfKey,\n newAuthPubKey: authPubKey,\n oldAuthPrivKey: oldAuthKeyPair.sk,\n });\n } else {\n await storeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n oprfKey,\n authPubKey,\n });\n }\n }\n\n /**\n * This function creates the encryption key which is used to encrypt/decrypt the secret data.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - New password of the user.\n *\n * @returns The encryption key.\n */\n async createAndPersistEncKey(\n params: CreateEncryptionKeyParams,\n ): Promise<CreateEncryptionKeyResult> {\n const { nodeAuthTokens, password, authConnectionId, userId } = params;\n const { oprfKey, authKeyPair, encKey, pwEncKey } =\n await this.createLocalKey({\n password,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n userId,\n });\n\n return {\n authKeyPair: {\n sk: authKeyPair.sk,\n pk: authKeyPair.pk,\n },\n encKey,\n pwEncKey,\n };\n }\n\n /**\n * This function recovers the encryption key which is used to decrypt the secret data.\n *\n * @param params - The parameters for recovering the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - The password of the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The encryption key result with auth key pair, encryption key and key share index.\n */\n async recoverEncKey(\n params: RecoverEncryptionKeyParams,\n ): Promise<RecoverEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n password,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n } = params;\n\n let pwBytes: Uint8Array | null = null;\n let seed: Uint8Array | null = null;\n\n try {\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n pwBytes = utf8ToBytes(password);\n\n const { seed: seedValue, keyShareIndex } = await recoverTOPRFSeed({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n userInput: pwBytes,\n keyDeriver: this.#keyDeriver,\n });\n\n seed = seedValue;\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n const rateLimitResetResult = new Promise<void>((resolve, reject) => {\n resetRateLimits({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authPrivKey: authKeyPair.sk,\n })\n .then(() => {\n return resolve();\n })\n .catch((error) => {\n reject(error as Error);\n });\n });\n\n return {\n authKeyPair,\n encKey,\n pwEncKey,\n keyShareIndex,\n rateLimitResetResult,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n\n if (seed) {\n seed.fill(0);\n seed = null;\n }\n }\n }\n\n /**\n * This function replaces the existing encryption key with a new one by generating a new key from\n * the new password, copying all existing secret data encrypted with the old key to be encrypted\n * with the new key, and updating the key shares on the nodes.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n * @param params.oldEncKey - The old encryption key of the user.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user.\n * @param params.newKeyShareIndex - The key share index to be used for the new key.\n * @param params.newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n * @param params.pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n *\n * @returns The new key pair and encryption key.\n * @throws {Error} If both newPassword and pregeneratedOprfKey are provided.\n * @throws {Error} If neither newPassword nor pregeneratedOprfKey is provided.\n */\n async changeEncKey(\n params: ChangeEncryptionKeyParams,\n ): Promise<ChangeEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n oldEncKey,\n oldPwEncKey,\n oldAuthKeyPair,\n newPassword,\n newKeyShareIndex,\n pregeneratedOprfKey,\n transformDataItems,\n } = params;\n\n if (!pregeneratedOprfKey && !newPassword) {\n throw new Error('Either newPassword or pregeneratedOprfKey is required');\n }\n\n if (pregeneratedOprfKey && newPassword) {\n throw new Error(\n 'Only one of newPassword or pregeneratedOprfKey is allowed',\n );\n }\n\n // if newPassword is provided, create a new key from the password\n // else use the pregeneratedOprfKey, both can't be undefined as per check above.\n const { oprfKey, authKeyPair, encKey, pwEncKey } = newPassword\n ? await this.createLocalKey({ password: newPassword })\n : (pregeneratedOprfKey as CreateLocalKeyResult);\n\n let metadataStore: MetadataStore | undefined;\n let oldMetadataLockId: string | undefined;\n let newMetadataLockId: string | undefined;\n\n try {\n metadataStore = await this.#createMetadataStore();\n\n [oldMetadataLockId, newMetadataLockId] = await Promise.all([\n metadataStore.acquireMetadataLock(oldAuthKeyPair),\n metadataStore.acquireMetadataLock(authKeyPair),\n ]);\n\n const fetched = await metadataStore.fetchAllSecretDataItems(\n oldEncKey,\n oldAuthKeyPair,\n );\n const existingData = transformDataItems\n ? transformDataItems(fetched)\n : fetched.map(({ data, dataType, version }) => ({\n data,\n dataType,\n version: dataType === undefined ? 'v1' : version,\n }));\n\n // Validate that this is actually a key change scenario\n if (!existingData || existingData.length === 0) {\n throw new Error('No existing data found to change key');\n }\n\n const pwBackup: SecretDataItem = {\n data: serializePwBackup('', oldPwEncKey, oldAuthKeyPair),\n itemId: PW_BACKUP_ITEM_ID,\n };\n\n const secretDataItems = [pwBackup, ...existingData];\n const encKeys = [pwEncKey, ...existingData.map(() => encKey)];\n await metadataStore.batchAddSecretData({\n secretData: secretDataItems,\n encKey: encKeys,\n authKeyPair,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex: newKeyShareIndex,\n oldAuthKeyPair,\n });\n\n return { authKeyPair, encKey, pwEncKey };\n } finally {\n if (metadataStore && oldMetadataLockId && newMetadataLockId) {\n try {\n await Promise.all([\n metadataStore.releaseMetadataLock(\n oldAuthKeyPair,\n oldMetadataLockId,\n ),\n metadataStore.releaseMetadataLock(authKeyPair, newMetadataLockId),\n ]);\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key which is used to encrypt the secret data before storing it.\n * @param params.secretData - The secret data to be registered.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the user to the storage service.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.dataType - Optional data type for categorizing the secret data. Required for v2.\n */\n async addSecretDataItem(params: AddSecretDataItemParams): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.addSecretDataItem({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: {\n data: params.secretData,\n itemId: params.itemId,\n version: params.version,\n dataType: params.dataType,\n },\n });\n }\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\n async batchAddSecretDataItems(\n params: BatchAddSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchAddSecretData({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: params.secretData.map((item) => ({\n data: item.data,\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n })),\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async updateSecretDataItem(\n params: UpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.updateSecretDataItem({\n updateItem: {\n itemId: params.itemId,\n fields: { dataType: params.dataType },\n },\n authKeyPair: params.authKeyPair,\n });\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async batchUpdateSecretDataItems(\n params: BatchUpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchUpdateSecretData({\n updateItems: params.updateItems.map((item) => ({\n itemId: item.itemId,\n fields: { dataType: item.dataType },\n })),\n authKeyPair: params.authKeyPair,\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns The decrypted secret data. Returns an empty array if no secret data is found.\n */\n async fetchAllSecretDataItems(\n params: FetchAllSecretDataParams,\n ): Promise<FetchedSecretDataItem[]> {\n const metadataStore = await this.#createMetadataStore();\n const dataItems = await metadataStore.fetchAllSecretDataItems(\n params.decKey,\n params.authKeyPair,\n );\n return dataItems;\n }\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for getting the authentication public key.\n * @param params.authTokens - The auth tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The authentication public key.\n */\n async fetchAuthPubKey(\n params: FetchAuthPubKeyParams,\n ): Promise<FetchAuthPubKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n return getPubKey({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n });\n }\n\n /**\n * This function looks up a password encryption key from the password\n * encryption key history.\n *\n * @param params - The parameters for getting the password encryption key.\n * @param params.targetPwPubKey - The target password public key.\n * @param params.curPwEncKey - The current password encryption key.\n * @param params.curAuthKeyPair - The current authentication key pair.\n * @param params.maxPwChainLength - Optional maximum password chain length\n * allowed to be traversed.\n *\n * @returns The password encryption key.\n */\n async recoverPwEncKey(\n params: RecoverPwEncKeyParams,\n ): Promise<RecoverPwEncKeyResult> {\n const {\n targetAuthPubKey: targetPwPubKey,\n curPwEncKey,\n curAuthKeyPair,\n maxPwChainLength = MAX_PASSWORD_CHAIN_LENGTH,\n } = params;\n\n let pwAndKeys = {\n password: '',\n encKey: curPwEncKey,\n authKeyPair: curAuthKeyPair,\n };\n\n for (let i = 0; i < maxPwChainLength; i++) {\n try {\n pwAndKeys = await this.#getPrevPasswordAndKeys({\n encKey: pwAndKeys.encKey,\n authKeyPair: pwAndKeys.authKeyPair,\n });\n if (equalBytes(pwAndKeys.authKeyPair.pk, targetPwPubKey)) {\n return { pwEncKey: pwAndKeys.encKey };\n }\n } catch (error) {\n throw TOPRFError.couldNotFetchPassword((error as Error).message);\n }\n }\n\n throw TOPRFError.maxKeyChainLengthExceeded();\n }\n\n /**\n * Gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n return this.#getNodeDetails();\n }\n\n /**\n * Gets the node details.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async #getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n let finalIndexes = this.#nodeDetailsOverride?.indexes;\n let finalPubKeys = this.#nodeDetailsOverride?.pubKeys;\n let finalEndpoints = this.#nodeDetailsOverride?.endpoints;\n\n if (finalIndexes && finalPubKeys && Array.isArray(finalEndpoints)) {\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n // NodeDetailManager has internal caching after first call to getNodeDetails\n // so we don't need internal caching here.\n // reference: {@link https://github.com/torusresearch/fetch-node-details/blob/master/packages/fetch-node-details/src/nodeDetailManager.ts#L88}\n const { torusNodeSSSEndpoints, torusIndexes, torusNodePub } =\n await this.#nodeDetailManager.getNodeDetails({\n verifier: 'auth-connection-id',\n verifierId: 'user-id',\n });\n\n finalIndexes ??= torusIndexes;\n finalPubKeys ??= torusNodePub;\n\n if (!Array.isArray(finalEndpoints)) {\n if (!torusNodeSSSEndpoints) {\n const message = 'Failed to get node details';\n throw new Error(message);\n }\n\n finalEndpoints = finalEndpoints\n ? torusNodeSSSEndpoints.map((endpoint) => {\n const url = new URL(endpoint);\n url.pathname = finalEndpoints as string;\n return url.href;\n })\n : torusNodeSSSEndpoints;\n }\n\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n /**\n * Creates and caches the metadata store instance.\n *\n * @returns The metadata store.\n */\n async #createMetadataStore(): Promise<MetadataStore> {\n if (this.#metadataStoreCache) {\n return this.#metadataStoreCache;\n }\n\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n const metadataEndpointsMap =\n await this.#getMetadataEndpointsMap(nodeEndpointsMap);\n const node1MetadataEndpoint = metadataEndpointsMap['1'];\n\n const metadataStore = new MetadataStore({\n metadataEndpoint: node1MetadataEndpoint,\n fetchMetadataAccessCreds: this.#fetchMetadataAccessCreds,\n });\n\n this.#metadataStoreCache = metadataStore;\n\n return metadataStore;\n }\n\n /**\n * Gets the metadata endpoints.\n *\n * @param nodeEndpointsMap - The node endpoints map.\n *\n * @returns The metadata endpoints map with node index as key and metadata endpoint as value.\n */\n async #getMetadataEndpointsMap(\n nodeEndpointsMap: Record<number, string>,\n ): Promise<{ [nodeIndex: string]: string }> {\n const metadataEndpointsMap: { [nodeIndex: string]: string } = {};\n Object.entries(nodeEndpointsMap).forEach(([key, value]) => {\n const url = new URL(value);\n metadataEndpointsMap[key] = `${url.origin}/metadata`;\n });\n return metadataEndpointsMap;\n }\n\n /**\n * Gets the previous password and keys.\n *\n * @param params - The parameters for getting the previous password and keys.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n *\n * @returns The previous password and keys.\n */\n async #getPrevPasswordAndKeys(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }): Promise<{\n password: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }> {\n const metadataStore = await this.#createMetadataStore();\n\n const pwBackupData = await metadataStore.fetchAllSecretDataItems(\n params.encKey,\n params.authKeyPair,\n PW_BACKUP_ITEM_ID,\n );\n\n if (pwBackupData.length === 0) {\n throw new Error('Failed to get previous password and keys');\n }\n\n // Parse JSON object.\n const pwBackupDataJson = deserializePwBackup(pwBackupData[0].data);\n\n return {\n password: pwBackupDataJson.pw,\n encKey: pwBackupDataJson.encKey,\n authKeyPair: pwBackupDataJson.authKeyPair,\n };\n }\n\n /**\n * Validates that the lengths of node detail arrays are consistent.\n *\n * @param indexes - Array of node indexes.\n * @param pubKeys - Array of node public keys.\n * @param endpoints - Array of SSS endpoint URLs.\n * @throws If lengths are inconsistent.\n */\n static #validateNodeDetailsLengths(\n indexes: unknown[],\n pubKeys: unknown[],\n endpoints: unknown[],\n ): void {\n if (\n indexes.length !== pubKeys.length ||\n indexes.length !== endpoints.length\n ) {\n const message =\n 'Node details arrays (indexes, pubKeys, endpoints) must have equal lengths';\n throw new Error(message);\n }\n }\n}\n\n/**\n * Serializes the password, encryption key, and authentication key pair into a JSON string.\n *\n * @param pw - The password.\n * @param encKey - The encryption key.\n * @param authKeyPair - The authentication key pair.\n * @returns The serialized JSON string.\n */\nfunction serializePwBackup(\n pw: string,\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n): Uint8Array {\n return utf8ToBytes(\n JSON.stringify({\n pw,\n encKey: bytesToHex(encKey),\n authKeyPair: {\n sk: authKeyPair.sk.toString(),\n pk: bytesToHex(authKeyPair.pk),\n },\n }),\n );\n}\n\n/**\n * Deserializes the password, encryption key, and authentication key pair from a JSON string.\n *\n * @param data - The serialized JSON string.\n * @returns The password, encryption key, and authentication key pair.\n */\nfunction deserializePwBackup(data: Uint8Array): {\n pw: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n} {\n const json = JSON.parse(bytesToUtf8(data));\n return {\n pw: json.pw,\n encKey: hexToBytes(json.encKey),\n authKeyPair: {\n sk: BigInt(json.authKeyPair.sk),\n pk: hexToBytes(json.authKeyPair.pk),\n },\n };\n}\n"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"toprfSecureBackup.d.cts","sourceRoot":"","sources":["../src/toprfSecureBackup.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,QAAQ,EACR,2BAA2B,EAC5B,6BAA6B;AAY9B,OAAO,KAAK,EACV,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,yBAAyB,EACzB,wBAAwB,EACxB,kBAAkB,EAClB,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,yBAAyB,EACzB,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,4BAA4B,EAC5B,qBAAqB,EAErB,qBAAqB,EACrB,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACtB,yBAAqB;AAQtB,OAAO,KAAK,EAAE,UAAU,EAAE,mBAAe;AAOzC;;;GAGG;AACH,qBAAa,iBAAkB,YAAW,kBAAkB;;IAW1D;;;;;;;;;;;;;;;;OAgBG;gBACS,MAAM,EAAE;QAClB,OAAO,EAAE,2BAA2B,CAAC;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this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

async changeEncKey(params) {
const { nodeAuthTokens, authConnectionId, groupedAuthConnectionId, userId, oldEncKey, oldPwEncKey, oldAuthKeyPair, newPassword, newKeyShareIndex, pregeneratedOprfKey, } = params;
const { nodeAuthTokens, authConnectionId, groupedAuthConnectionId, userId, oldEncKey, oldPwEncKey, oldAuthKeyPair, newPassword, newKeyShareIndex, pregeneratedOprfKey, transformDataItems, } = params;
if (!pregeneratedOprfKey && !newPassword) {

@@ -358,8 +358,10 @@ throw new Error('Either newPassword or pregeneratedOprfKey is required');

]);
const existingData = (await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair)).map((dataItem) => ({
data: dataItem.data,
dataType: dataItem.dataType,
// Use v1 to bypass dataType validation for legacy data without dataType
version: dataItem.dataType === undefined ? 'v1' : dataItem.version,
}));
const fetched = await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair);
const existingData = transformDataItems
? transformDataItems(fetched)
: fetched.map(({ data, dataType, version }) => ({
data,
dataType,
version: dataType === undefined ? 'v1' : version,
}));
// Validate that this is actually a key change scenario

@@ -366,0 +368,0 @@ if (!existingData || existingData.length === 0) {

@@ -1,1 +0,1 @@

{"version":3,"file":"toprfSecureBackup.mjs","sourceRoot":"","sources":["../src/toprfSecureBackup.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,qCAAqC;AAC5E,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,6BAA6B;AAC/D,OAAO,EAAE,WAAW,EAAE,qCAAqC;AAC3D,OAAO,EAAE,SAAS,EAAE,gCAAgC;AACpD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,4BAA4B;AAK7D,OAAO,EAAE,iBAAiB,EAAE,sCAAsC;AAElE,OAAO,EAAE,gBAAgB,EAAE,kCAA8B;AACzD,OAAO,EAAE,aAAa,EAAE,4BAAwB;AAChD,OAAO,EACL,eA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AAI,CAAC,SAAS,CAAC;QACb,EAAE;QACF,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC;QAC1B,WAAW,EAAE;YACX,EAAE,EAAE,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE;YAC7B,EAAE,EAAE,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;SAC/B;KACF,CAAC,CACH,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,IAAgB;IAK3C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3C,OAAO;QACL,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC;QAC/B,WAAW,EAAE;YACX,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YAC/B,EAAE,EAAE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { keccak256AndHexify, remove0x } from '@metamask/auth-network-utils';\nimport { bytesToUtf8, equalBytes } from '@noble/ciphers/utils';\nimport { utf8ToBytes } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\nimport type {\n INodePub,\n TORUS_SAPPHIRE_NETWORK_TYPE,\n} from '@toruslabs/constants';\nimport { NodeDetailManager } from '@toruslabs/fetch-node-details';\n\nimport { authenticateUser } from './authenticateRequest';\nimport { commitIdToken } from './commitRequest';\nimport {\n FIRST_KEY_INDEX,\n MAX_PASSWORD_CHAIN_LENGTH,\n PW_BACKUP_ITEM_ID,\n} from './constants';\nimport { TOPRFError } from './errors';\nimport { getPubKey } from './getPubKeyRequest';\nimport type {\n AuthenticateParams,\n AuthenticateResult,\n CreateEncryptionKeyParams,\n CreateEncryptionKeyResult,\n FetchAllSecretDataParams,\n IToprfSecureBackup,\n RecoverEncryptionKeyParams,\n RecoverEncryptionKeyResult,\n AddSecretDataItemParams,\n ChangeEncryptionKeyParams,\n ChangeEncryptionKeyResult,\n FetchAuthPubKeyParams,\n FetchAuthPubKeyResult,\n PersistLocalKeyParams,\n CreateLocalKeyParams,\n CreateLocalKeyResult,\n BatchAddSecretDataItemParams,\n RecoverPwEncKeyParams,\n KeyPair,\n RecoverPwEncKeyResult,\n NodeDetailsOverride,\n FetchMetadataAccessCreds,\n UpdateSecretDataItemParams,\n BatchUpdateSecretDataItemParams,\n FetchedSecretDataItem,\n} from './interfaces';\nimport {\n deriveAuthenticationKeyPair,\n deriveEncryptionKey,\n derivePwEncKey,\n} from './keyDerivation';\nimport type { SecretDataItem } from './metadata';\nimport { MetadataStore } from './metadata';\nimport type { KeyDeriver } from './oprf';\nimport { OPRF, generateRandomScalar } from './oprf';\nimport { resetRateLimits } from './resetRateLimits';\nimport { storeKeyShares, changeKeyShares } from './storeSharesRequest';\nimport { recoverTOPRFSeed } from './toprfEvalRequest';\nimport { createNodeEndpointsMap } from './utils';\n\n/**\n * ToprfSecureBackup - The main class for the tOPRF Secure Backup service.\n *\n */\nexport class ToprfSecureBackup implements IToprfSecureBackup {\n readonly #nodeDetailManager: NodeDetailManager;\n\n readonly #nodeDetailsOverride?: NodeDetailsOverride;\n\n readonly #keyDeriver?: KeyDeriver;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n #metadataStoreCache: MetadataStore | undefined;\n\n /**\n * The constructor for the ToprfSecureBackup class.\n *\n * If `keyDeriver` is provided, it will be used as an additional step during\n * key derivation. This can be used, for example, to inject a slow key\n * derivation step to protect against local brute force attacks on the\n * password.\n *\n * @param params - The parameters for the constructor.\n * @param params.network - The web3auth network to be used for key management\n * and authentication.\n * @param params.nodeDetailsOverride - Optional overrides for node details\n * like SSS endpoints, indexes, and public keys.\n * @param params.keyDeriver - Optional key deriver to be used for an\n * additional layer of security.\n * @param params.fetchMetadataAccessCreds - Function to fetch metadata access credentials.\n */\n constructor(params: {\n network: TORUS_SAPPHIRE_NETWORK_TYPE;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n nodeDetailsOverride?: NodeDetailsOverride;\n keyDeriver?: KeyDeriver;\n }) {\n this.#nodeDetailManager = new NodeDetailManager({\n network: params.network,\n });\n this.#nodeDetailsOverride = params.nodeDetailsOverride;\n this.#keyDeriver = params.keyDeriver;\n this.#fetchMetadataAccessCreds = params.fetchMetadataAccessCreds;\n }\n\n /**\n * This function is used to authenticate the user by sending the oauth idToken to the nodes and\n * getting the authentication tokens from the nodes in return.\n *\n * @param params - The authentication parameters.\n * @param params.idTokens - An array of id tokens for authentication.\n * @param params.authConnectionId - The auth connection name to be used for the authenticate request\n * @param params.userId - The user id of the user issued by authentication service\n * @param params.groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n *\n * @returns - The authentication result containing the authentication tokens and a boolean indicating if the user is new or not.\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n * @throws {Error} If idToken is older than 6 minutes.\n */\n async authenticate(params: AuthenticateParams): Promise<AuthenticateResult> {\n const { nodeEndpoints, nodeEndpointsMap } = await this.#getNodeDetails();\n let sessionPrivKey: Uint8Array | null = secp256k1.utils.randomPrivateKey();\n\n try {\n const sessionPubKey =\n secp256k1.ProjectivePoint.fromPrivateKey(sessionPrivKey);\n const sessionPubKeyX = sessionPubKey.x.toString(16);\n const sessionPubKeyY = sessionPubKey.y.toString(16);\n\n let hashedIdToken: string | undefined;\n if (params.groupedAuthConnectionId) {\n // if groupedAuthConnectionId is provided, we'll compute the hashedIdToken for the aggregate (single id) verifier login\n hashedIdToken = remove0x(\n keccak256AndHexify(Buffer.from(params.idTokens[0], 'utf8')),\n );\n }\n\n // commit idToken to nodes\n const commitmentResults = await commitIdToken({\n idToken: hashedIdToken ?? params.idTokens[0],\n authConnectionId:\n params.groupedAuthConnectionId ?? params.authConnectionId,\n sessionPubKeyX,\n sessionPubKeyY,\n endpoints: nodeEndpoints,\n });\n\n // use only the node indexes that returned valid commitment responses\n const selectedEndpointsMap = commitmentResults.reduce<\n Record<number, string>\n >((acc, result) => {\n acc[result.nodeIndex] = nodeEndpointsMap[result.nodeIndex];\n return acc;\n }, {});\n\n // get auth tokens from nodes\n const { authTokensData, isNewUser } = await authenticateUser({\n idToken: params.idTokens[0],\n authConnectionId: params.authConnectionId,\n userId: params.userId,\n sessionPrivateKey: sessionPrivKey,\n nodeEndpointsMap: selectedEndpointsMap,\n commitmentSignatures: commitmentResults,\n groupedAuthConnectionId: params.groupedAuthConnectionId,\n hashedIdToken,\n });\n\n return {\n nodeAuthTokens: authTokensData.map((tokenData) => ({\n authToken: tokenData.authToken,\n nodeIndex: tokenData.nodeIndex,\n nodePubKey: tokenData.nodePubKey,\n })),\n isNewUser,\n };\n } finally {\n // Clean up session private key\n sessionPrivKey.fill(0);\n sessionPrivKey = null;\n }\n }\n\n /**\n * This function locally creates an OPRF and encryption keys without storing them at the\n * key management service. It returns the OPRF key, derives the corresponding key seed,\n * authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns The OPRF key, seed, and derived keys.\n */\n async createLocalKey(\n params: CreateLocalKeyParams,\n ): Promise<CreateLocalKeyResult> {\n const { password, oprfKey = generateRandomScalar() } = params;\n let pwBytes: Uint8Array | null = null;\n\n try {\n pwBytes = utf8ToBytes(password);\n const seed = await OPRF.localEval(oprfKey, pwBytes, this.#keyDeriver);\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n return {\n oprfKey,\n seed,\n authKeyPair,\n encKey,\n pwEncKey,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n }\n }\n\n /**\n * This function persists the OPRF key's shares at the servers.\n *\n * @param params - The parameters for persisting the OPRF key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authPubKey - The authentication public key.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n */\n async persistLocalKey(params: PersistLocalKeyParams): Promise<void> {\n const {\n nodeAuthTokens,\n oprfKey,\n authPubKey,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex = FIRST_KEY_INDEX,\n oldAuthKeyPair,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n\n const selectedEndpointsMap = nodeAuthTokens.reduce<Record<number, string>>(\n (acc, tokenData) => {\n acc[tokenData.nodeIndex] = nodeEndpointsMap[tokenData.nodeIndex];\n return acc;\n },\n {},\n );\n\n if (oldAuthKeyPair) {\n await changeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n newOprfKey: oprfKey,\n newAuthPubKey: authPubKey,\n oldAuthPrivKey: oldAuthKeyPair.sk,\n });\n } else {\n await storeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n oprfKey,\n authPubKey,\n });\n }\n }\n\n /**\n * This function creates the encryption key which is used to encrypt/decrypt the secret data.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - New password of the user.\n *\n * @returns The encryption key.\n */\n async createAndPersistEncKey(\n params: CreateEncryptionKeyParams,\n ): Promise<CreateEncryptionKeyResult> {\n const { nodeAuthTokens, password, authConnectionId, userId } = params;\n const { oprfKey, authKeyPair, encKey, pwEncKey } =\n await this.createLocalKey({\n password,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n userId,\n });\n\n return {\n authKeyPair: {\n sk: authKeyPair.sk,\n pk: authKeyPair.pk,\n },\n encKey,\n pwEncKey,\n };\n }\n\n /**\n * This function recovers the encryption key which is used to decrypt the secret data.\n *\n * @param params - The parameters for recovering the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - The password of the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The encryption key result with auth key pair, encryption key and key share index.\n */\n async recoverEncKey(\n params: RecoverEncryptionKeyParams,\n ): Promise<RecoverEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n password,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n } = params;\n\n let pwBytes: Uint8Array | null = null;\n let seed: Uint8Array | null = null;\n\n try {\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n pwBytes = utf8ToBytes(password);\n\n const { seed: seedValue, keyShareIndex } = await recoverTOPRFSeed({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n userInput: pwBytes,\n keyDeriver: this.#keyDeriver,\n });\n\n seed = seedValue;\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n const rateLimitResetResult = new Promise<void>((resolve, reject) => {\n resetRateLimits({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authPrivKey: authKeyPair.sk,\n })\n .then(() => {\n return resolve();\n })\n .catch((error) => {\n reject(error as Error);\n });\n });\n\n return {\n authKeyPair,\n encKey,\n pwEncKey,\n keyShareIndex,\n rateLimitResetResult,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n\n if (seed) {\n seed.fill(0);\n seed = null;\n }\n }\n }\n\n /**\n * This function replaces the existing encryption key with a new one by generating a new key from\n * the new password, copying all existing secret data encrypted with the old key to be encrypted\n * with the new key, and updating the key shares on the nodes.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n * @param params.oldEncKey - The old encryption key of the user.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user.\n * @param params.newKeyShareIndex - The key share index to be used for the new key.\n * @param params.newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n * @param params.pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n *\n * @returns The new key pair and encryption key.\n * @throws {Error} If both newPassword and pregeneratedOprfKey are provided.\n * @throws {Error} If neither newPassword nor pregeneratedOprfKey is provided.\n */\n async changeEncKey(\n params: ChangeEncryptionKeyParams,\n ): Promise<ChangeEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n oldEncKey,\n oldPwEncKey,\n oldAuthKeyPair,\n newPassword,\n newKeyShareIndex,\n pregeneratedOprfKey,\n } = params;\n\n if (!pregeneratedOprfKey && !newPassword) {\n throw new Error('Either newPassword or pregeneratedOprfKey is required');\n }\n\n if (pregeneratedOprfKey && newPassword) {\n throw new Error(\n 'Only one of newPassword or pregeneratedOprfKey is allowed',\n );\n }\n\n // if newPassword is provided, create a new key from the password\n // else use the pregeneratedOprfKey, both can't be undefined as per check above.\n const { oprfKey, authKeyPair, encKey, pwEncKey } = newPassword\n ? await this.createLocalKey({ password: newPassword })\n : (pregeneratedOprfKey as CreateLocalKeyResult);\n\n let metadataStore: MetadataStore | undefined;\n let oldMetadataLockId: string | undefined;\n let newMetadataLockId: string | undefined;\n\n try {\n metadataStore = await this.#createMetadataStore();\n\n [oldMetadataLockId, newMetadataLockId] = await Promise.all([\n metadataStore.acquireMetadataLock(oldAuthKeyPair),\n metadataStore.acquireMetadataLock(authKeyPair),\n ]);\n\n const existingData = (\n await metadataStore.fetchAllSecretDataItems(oldEncKey, oldAuthKeyPair)\n ).map((dataItem) => ({\n data: dataItem.data,\n dataType: dataItem.dataType,\n // Use v1 to bypass dataType validation for legacy data without dataType\n version:\n dataItem.dataType === undefined ? ('v1' as const) : dataItem.version,\n }));\n\n // Validate that this is actually a key change scenario\n if (!existingData || existingData.length === 0) {\n throw new Error('No existing data found to change key');\n }\n\n const pwBackup: SecretDataItem = {\n data: serializePwBackup('', oldPwEncKey, oldAuthKeyPair),\n itemId: PW_BACKUP_ITEM_ID,\n };\n\n const secretDataItems = [pwBackup, ...existingData];\n const encKeys = [pwEncKey, ...existingData.map(() => encKey)];\n await metadataStore.batchAddSecretData({\n secretData: secretDataItems,\n encKey: encKeys,\n authKeyPair,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex: newKeyShareIndex,\n oldAuthKeyPair,\n });\n\n return { authKeyPair, encKey, pwEncKey };\n } finally {\n if (metadataStore && oldMetadataLockId && newMetadataLockId) {\n try {\n await Promise.all([\n metadataStore.releaseMetadataLock(\n oldAuthKeyPair,\n oldMetadataLockId,\n ),\n metadataStore.releaseMetadataLock(authKeyPair, newMetadataLockId),\n ]);\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key which is used to encrypt the secret data before storing it.\n * @param params.secretData - The secret data to be registered.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the user to the storage service.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.dataType - Optional data type for categorizing the secret data. Required for v2.\n */\n async addSecretDataItem(params: AddSecretDataItemParams): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.addSecretDataItem({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: {\n data: params.secretData,\n itemId: params.itemId,\n version: params.version,\n dataType: params.dataType,\n },\n });\n }\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\n async batchAddSecretDataItems(\n params: BatchAddSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchAddSecretData({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: params.secretData.map((item) => ({\n data: item.data,\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n })),\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async updateSecretDataItem(\n params: UpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.updateSecretDataItem({\n updateItem: {\n itemId: params.itemId,\n fields: { dataType: params.dataType },\n },\n authKeyPair: params.authKeyPair,\n });\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async batchUpdateSecretDataItems(\n params: BatchUpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchUpdateSecretData({\n updateItems: params.updateItems.map((item) => ({\n itemId: item.itemId,\n fields: { dataType: item.dataType },\n })),\n authKeyPair: params.authKeyPair,\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns The decrypted secret data. Returns an empty array if no secret data is found.\n */\n async fetchAllSecretDataItems(\n params: FetchAllSecretDataParams,\n ): Promise<FetchedSecretDataItem[]> {\n const metadataStore = await this.#createMetadataStore();\n const dataItems = await metadataStore.fetchAllSecretDataItems(\n params.decKey,\n params.authKeyPair,\n );\n return dataItems;\n }\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for getting the authentication public key.\n * @param params.authTokens - The auth tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The authentication public key.\n */\n async fetchAuthPubKey(\n params: FetchAuthPubKeyParams,\n ): Promise<FetchAuthPubKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n return getPubKey({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n });\n }\n\n /**\n * This function looks up a password encryption key from the password\n * encryption key history.\n *\n * @param params - The parameters for getting the password encryption key.\n * @param params.targetPwPubKey - The target password public key.\n * @param params.curPwEncKey - The current password encryption key.\n * @param params.curAuthKeyPair - The current authentication key pair.\n * @param params.maxPwChainLength - Optional maximum password chain length\n * allowed to be traversed.\n *\n * @returns The password encryption key.\n */\n async recoverPwEncKey(\n params: RecoverPwEncKeyParams,\n ): Promise<RecoverPwEncKeyResult> {\n const {\n targetAuthPubKey: targetPwPubKey,\n curPwEncKey,\n curAuthKeyPair,\n maxPwChainLength = MAX_PASSWORD_CHAIN_LENGTH,\n } = params;\n\n let pwAndKeys = {\n password: '',\n encKey: curPwEncKey,\n authKeyPair: curAuthKeyPair,\n };\n\n for (let i = 0; i < maxPwChainLength; i++) {\n try {\n pwAndKeys = await this.#getPrevPasswordAndKeys({\n encKey: pwAndKeys.encKey,\n authKeyPair: pwAndKeys.authKeyPair,\n });\n if (equalBytes(pwAndKeys.authKeyPair.pk, targetPwPubKey)) {\n return { pwEncKey: pwAndKeys.encKey };\n }\n } catch (error) {\n throw TOPRFError.couldNotFetchPassword((error as Error).message);\n }\n }\n\n throw TOPRFError.maxKeyChainLengthExceeded();\n }\n\n /**\n * Gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n return this.#getNodeDetails();\n }\n\n /**\n * Gets the node details.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async #getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n let finalIndexes = this.#nodeDetailsOverride?.indexes;\n let finalPubKeys = this.#nodeDetailsOverride?.pubKeys;\n let finalEndpoints = this.#nodeDetailsOverride?.endpoints;\n\n if (finalIndexes && finalPubKeys && Array.isArray(finalEndpoints)) {\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n // NodeDetailManager has internal caching after first call to getNodeDetails\n // so we don't need internal caching here.\n // reference: {@link https://github.com/torusresearch/fetch-node-details/blob/master/packages/fetch-node-details/src/nodeDetailManager.ts#L88}\n const { torusNodeSSSEndpoints, torusIndexes, torusNodePub } =\n await this.#nodeDetailManager.getNodeDetails({\n verifier: 'auth-connection-id',\n verifierId: 'user-id',\n });\n\n finalIndexes ??= torusIndexes;\n finalPubKeys ??= torusNodePub;\n\n if (!Array.isArray(finalEndpoints)) {\n if (!torusNodeSSSEndpoints) {\n const message = 'Failed to get node details';\n throw new Error(message);\n }\n\n finalEndpoints = finalEndpoints\n ? torusNodeSSSEndpoints.map((endpoint) => {\n const url = new URL(endpoint);\n url.pathname = finalEndpoints as string;\n return url.href;\n })\n : torusNodeSSSEndpoints;\n }\n\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n /**\n * Creates and caches the metadata store instance.\n *\n * @returns The metadata store.\n */\n async #createMetadataStore(): Promise<MetadataStore> {\n if (this.#metadataStoreCache) {\n return this.#metadataStoreCache;\n }\n\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n const metadataEndpointsMap =\n await this.#getMetadataEndpointsMap(nodeEndpointsMap);\n const node1MetadataEndpoint = metadataEndpointsMap['1'];\n\n const metadataStore = new MetadataStore({\n metadataEndpoint: node1MetadataEndpoint,\n fetchMetadataAccessCreds: this.#fetchMetadataAccessCreds,\n });\n\n this.#metadataStoreCache = metadataStore;\n\n return metadataStore;\n }\n\n /**\n * Gets the metadata endpoints.\n *\n * @param nodeEndpointsMap - The node endpoints map.\n *\n * @returns The metadata endpoints map with node index as key and metadata endpoint as value.\n */\n async #getMetadataEndpointsMap(\n nodeEndpointsMap: Record<number, string>,\n ): Promise<{ [nodeIndex: string]: string }> {\n const metadataEndpointsMap: { [nodeIndex: string]: string } = {};\n Object.entries(nodeEndpointsMap).forEach(([key, value]) => {\n const url = new URL(value);\n metadataEndpointsMap[key] = `${url.origin}/metadata`;\n });\n return metadataEndpointsMap;\n }\n\n /**\n * Gets the previous password and keys.\n *\n * @param params - The parameters for getting the previous password and keys.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n *\n * @returns The previous password and keys.\n */\n async #getPrevPasswordAndKeys(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }): Promise<{\n password: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }> {\n const metadataStore = await this.#createMetadataStore();\n\n const pwBackupData = await metadataStore.fetchAllSecretDataItems(\n params.encKey,\n params.authKeyPair,\n PW_BACKUP_ITEM_ID,\n );\n\n if (pwBackupData.length === 0) {\n throw new Error('Failed to get previous password and keys');\n }\n\n // Parse JSON object.\n const pwBackupDataJson = deserializePwBackup(pwBackupData[0].data);\n\n return {\n password: pwBackupDataJson.pw,\n encKey: pwBackupDataJson.encKey,\n authKeyPair: pwBackupDataJson.authKeyPair,\n };\n }\n\n /**\n * Validates that the lengths of node detail arrays are consistent.\n *\n * @param indexes - Array of node indexes.\n * @param pubKeys - Array of node public keys.\n * @param endpoints - Array of SSS endpoint URLs.\n * @throws If lengths are inconsistent.\n */\n static #validateNodeDetailsLengths(\n indexes: unknown[],\n pubKeys: unknown[],\n endpoints: unknown[],\n ): void {\n if (\n indexes.length !== pubKeys.length ||\n indexes.length !== endpoints.length\n ) {\n const message =\n 'Node details arrays (indexes, pubKeys, endpoints) must have equal lengths';\n throw new Error(message);\n }\n }\n}\n\n/**\n * Serializes the password, encryption key, and authentication key pair into a JSON string.\n *\n * @param pw - The password.\n * @param encKey - The encryption key.\n * @param authKeyPair - The authentication key pair.\n * @returns The serialized JSON string.\n */\nfunction serializePwBackup(\n pw: string,\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n): Uint8Array {\n return utf8ToBytes(\n JSON.stringify({\n pw,\n encKey: bytesToHex(encKey),\n authKeyPair: {\n sk: authKeyPair.sk.toString(),\n pk: bytesToHex(authKeyPair.pk),\n },\n }),\n );\n}\n\n/**\n * Deserializes the password, encryption key, and authentication key pair from a JSON string.\n *\n * @param data - The serialized JSON string.\n * @returns The password, encryption key, and authentication key pair.\n */\nfunction deserializePwBackup(data: Uint8Array): {\n pw: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n} {\n const json = JSON.parse(bytesToUtf8(data));\n return {\n pw: json.pw,\n encKey: hexToBytes(json.encKey),\n authKeyPair: {\n sk: BigInt(json.authKeyPair.sk),\n pk: hexToBytes(json.authKeyPair.pk),\n },\n };\n}\n"]}
{"version":3,"file":"toprfSecureBackup.mjs","sourceR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AE,gBAAgB,CAAC,EAAE;QAC7B,MAAM,EAAE,gBAAgB,CAAC,MAAM;QAC/B,WAAW,EAAE,gBAAgB,CAAC,WAAW;KAC1C,CAAC;AACJ,CAAC,yGAWC,OAAkB,EAClB,OAAkB,EAClB,SAAoB;IAEpB,IACE,OAAO,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QACjC,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EACnC;QACA,MAAM,OAAO,GACX,2EAA2E,CAAC;QAC9E,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;KAC1B;AACH,CAAC;AAGH;;;;;;;GAOG;AACH,SAAS,iBAAiB,CACxB,EAAU,EACV,MAAkB,EAClB,WAAoB;IAEpB,OAAO,WAAW,CAChB,IAAI,CAAC,SAAS,CAAC;QACb,EAAE;QACF,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC;QAC1B,WAAW,EAAE;YACX,EAAE,EAAE,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE;YAC7B,EAAE,EAAE,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;SAC/B;KACF,CAAC,CACH,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,IAAgB;IAK3C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3C,OAAO;QACL,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC;QAC/B,WAAW,EAAE;YACX,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YAC/B,EAAE,EAAE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { keccak256AndHexify, remove0x } from '@metamask/auth-network-utils';\nimport { bytesToUtf8, equalBytes } from '@noble/ciphers/utils';\nimport { utf8ToBytes } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\nimport type {\n INodePub,\n TORUS_SAPPHIRE_NETWORK_TYPE,\n} from '@toruslabs/constants';\nimport { NodeDetailManager } from '@toruslabs/fetch-node-details';\n\nimport { authenticateUser } from './authenticateRequest';\nimport { commitIdToken } from './commitRequest';\nimport {\n FIRST_KEY_INDEX,\n MAX_PASSWORD_CHAIN_LENGTH,\n PW_BACKUP_ITEM_ID,\n} from './constants';\nimport { TOPRFError } from './errors';\nimport { getPubKey } from './getPubKeyRequest';\nimport type {\n AuthenticateParams,\n AuthenticateResult,\n CreateEncryptionKeyParams,\n CreateEncryptionKeyResult,\n FetchAllSecretDataParams,\n IToprfSecureBackup,\n RecoverEncryptionKeyParams,\n RecoverEncryptionKeyResult,\n AddSecretDataItemParams,\n ChangeEncryptionKeyParams,\n ChangeEncryptionKeyResult,\n FetchAuthPubKeyParams,\n FetchAuthPubKeyResult,\n PersistLocalKeyParams,\n CreateLocalKeyParams,\n CreateLocalKeyResult,\n BatchAddSecretDataItemParams,\n RecoverPwEncKeyParams,\n KeyPair,\n RecoverPwEncKeyResult,\n NodeDetailsOverride,\n FetchMetadataAccessCreds,\n UpdateSecretDataItemParams,\n BatchUpdateSecretDataItemParams,\n FetchedSecretDataItem,\n SecretDataItem,\n} from './interfaces';\nimport {\n deriveAuthenticationKeyPair,\n deriveEncryptionKey,\n derivePwEncKey,\n} from './keyDerivation';\nimport { MetadataStore } from './metadata';\nimport type { KeyDeriver } from './oprf';\nimport { OPRF, generateRandomScalar } from './oprf';\nimport { resetRateLimits } from './resetRateLimits';\nimport { storeKeyShares, changeKeyShares } from './storeSharesRequest';\nimport { recoverTOPRFSeed } from './toprfEvalRequest';\nimport { createNodeEndpointsMap } from './utils';\n\n/**\n * ToprfSecureBackup - The main class for the tOPRF Secure Backup service.\n *\n */\nexport class ToprfSecureBackup implements IToprfSecureBackup {\n readonly #nodeDetailManager: NodeDetailManager;\n\n readonly #nodeDetailsOverride?: NodeDetailsOverride;\n\n readonly #keyDeriver?: KeyDeriver;\n\n readonly #fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n\n #metadataStoreCache: MetadataStore | undefined;\n\n /**\n * The constructor for the ToprfSecureBackup class.\n *\n * If `keyDeriver` is provided, it will be used as an additional step during\n * key derivation. This can be used, for example, to inject a slow key\n * derivation step to protect against local brute force attacks on the\n * password.\n *\n * @param params - The parameters for the constructor.\n * @param params.network - The web3auth network to be used for key management\n * and authentication.\n * @param params.nodeDetailsOverride - Optional overrides for node details\n * like SSS endpoints, indexes, and public keys.\n * @param params.keyDeriver - Optional key deriver to be used for an\n * additional layer of security.\n * @param params.fetchMetadataAccessCreds - Function to fetch metadata access credentials.\n */\n constructor(params: {\n network: TORUS_SAPPHIRE_NETWORK_TYPE;\n fetchMetadataAccessCreds: FetchMetadataAccessCreds;\n nodeDetailsOverride?: NodeDetailsOverride;\n keyDeriver?: KeyDeriver;\n }) {\n this.#nodeDetailManager = new NodeDetailManager({\n network: params.network,\n });\n this.#nodeDetailsOverride = params.nodeDetailsOverride;\n this.#keyDeriver = params.keyDeriver;\n this.#fetchMetadataAccessCreds = params.fetchMetadataAccessCreds;\n }\n\n /**\n * This function is used to authenticate the user by sending the oauth idToken to the nodes and\n * getting the authentication tokens from the nodes in return.\n *\n * @param params - The authentication parameters.\n * @param params.idTokens - An array of id tokens for authentication.\n * @param params.authConnectionId - The auth connection name to be used for the authenticate request\n * @param params.userId - The user id of the user issued by authentication service\n * @param params.groupedAuthConnectionParams - Optional groupedAuthConnectionParams to be used for the authenticate request.\n * You can pass this to use aggregate verifier.\n *\n * @returns - The authentication result containing the authentication tokens and a boolean indicating if the user is new or not.\n * isNewUser - Indicates if the user has completed the key setup process or not.\n * if `true` then the user hasn't completed the social + password setup process.\n * if `false` then the user has completed the social + password setup process.\n * @throws {Error} If idToken is older than 6 minutes.\n */\n async authenticate(params: AuthenticateParams): Promise<AuthenticateResult> {\n const { nodeEndpoints, nodeEndpointsMap } = await this.#getNodeDetails();\n let sessionPrivKey: Uint8Array | null = secp256k1.utils.randomPrivateKey();\n\n try {\n const sessionPubKey =\n secp256k1.ProjectivePoint.fromPrivateKey(sessionPrivKey);\n const sessionPubKeyX = sessionPubKey.x.toString(16);\n const sessionPubKeyY = sessionPubKey.y.toString(16);\n\n let hashedIdToken: string | undefined;\n if (params.groupedAuthConnectionId) {\n // if groupedAuthConnectionId is provided, we'll compute the hashedIdToken for the aggregate (single id) verifier login\n hashedIdToken = remove0x(\n keccak256AndHexify(Buffer.from(params.idTokens[0], 'utf8')),\n );\n }\n\n // commit idToken to nodes\n const commitmentResults = await commitIdToken({\n idToken: hashedIdToken ?? params.idTokens[0],\n authConnectionId:\n params.groupedAuthConnectionId ?? params.authConnectionId,\n sessionPubKeyX,\n sessionPubKeyY,\n endpoints: nodeEndpoints,\n });\n\n // use only the node indexes that returned valid commitment responses\n const selectedEndpointsMap = commitmentResults.reduce<\n Record<number, string>\n >((acc, result) => {\n acc[result.nodeIndex] = nodeEndpointsMap[result.nodeIndex];\n return acc;\n }, {});\n\n // get auth tokens from nodes\n const { authTokensData, isNewUser } = await authenticateUser({\n idToken: params.idTokens[0],\n authConnectionId: params.authConnectionId,\n userId: params.userId,\n sessionPrivateKey: sessionPrivKey,\n nodeEndpointsMap: selectedEndpointsMap,\n commitmentSignatures: commitmentResults,\n groupedAuthConnectionId: params.groupedAuthConnectionId,\n hashedIdToken,\n });\n\n return {\n nodeAuthTokens: authTokensData.map((tokenData) => ({\n authToken: tokenData.authToken,\n nodeIndex: tokenData.nodeIndex,\n nodePubKey: tokenData.nodePubKey,\n })),\n isNewUser,\n };\n } finally {\n // Clean up session private key\n sessionPrivKey.fill(0);\n sessionPrivKey = null;\n }\n }\n\n /**\n * This function locally creates an OPRF and encryption keys without storing them at the\n * key management service. It returns the OPRF key, derives the corresponding key seed,\n * authentication key pair and encryption key.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.password - New password of the user.\n * @param params.oprfKey - Optional OPRF key to be used for the OPRF evaluation.\n *\n * @returns The OPRF key, seed, and derived keys.\n */\n async createLocalKey(\n params: CreateLocalKeyParams,\n ): Promise<CreateLocalKeyResult> {\n const { password, oprfKey = generateRandomScalar() } = params;\n let pwBytes: Uint8Array | null = null;\n\n try {\n pwBytes = utf8ToBytes(password);\n const seed = await OPRF.localEval(oprfKey, pwBytes, this.#keyDeriver);\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n return {\n oprfKey,\n seed,\n authKeyPair,\n encKey,\n pwEncKey,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n }\n }\n\n /**\n * This function persists the OPRF key's shares at the servers.\n *\n * @param params - The parameters for persisting the OPRF key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.oprfKey - The OPRF key to be persisted.\n * @param params.authPubKey - The authentication public key.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user issued by authentication service.\n * @param params.keyShareIndex - The key share index to be persisted. Required only during key change, defaults to FIRST_KEY_INDEX for first-time storage.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user. Required only during key change, not needed for first-time storage.\n */\n async persistLocalKey(params: PersistLocalKeyParams): Promise<void> {\n const {\n nodeAuthTokens,\n oprfKey,\n authPubKey,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex = FIRST_KEY_INDEX,\n oldAuthKeyPair,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n\n const selectedEndpointsMap = nodeAuthTokens.reduce<Record<number, string>>(\n (acc, tokenData) => {\n acc[tokenData.nodeIndex] = nodeEndpointsMap[tokenData.nodeIndex];\n return acc;\n },\n {},\n );\n\n if (oldAuthKeyPair) {\n await changeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n newOprfKey: oprfKey,\n newAuthPubKey: authPubKey,\n oldAuthPrivKey: oldAuthKeyPair.sk,\n });\n } else {\n await storeKeyShares({\n nodeEndpointsMap: selectedEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authTokens: nodeAuthTokens,\n keyShareIndex,\n oprfKey,\n authPubKey,\n });\n }\n }\n\n /**\n * This function creates the encryption key which is used to encrypt/decrypt the secret data.\n *\n * @param params - The parameters for creating the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - New password of the user.\n *\n * @returns The encryption key.\n */\n async createAndPersistEncKey(\n params: CreateEncryptionKeyParams,\n ): Promise<CreateEncryptionKeyResult> {\n const { nodeAuthTokens, password, authConnectionId, userId } = params;\n const { oprfKey, authKeyPair, encKey, pwEncKey } =\n await this.createLocalKey({\n password,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n userId,\n });\n\n return {\n authKeyPair: {\n sk: authKeyPair.sk,\n pk: authKeyPair.pk,\n },\n encKey,\n pwEncKey,\n };\n }\n\n /**\n * This function recovers the encryption key which is used to decrypt the secret data.\n *\n * @param params - The parameters for recovering the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.password - The password of the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The encryption key result with auth key pair, encryption key and key share index.\n */\n async recoverEncKey(\n params: RecoverEncryptionKeyParams,\n ): Promise<RecoverEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n password,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n } = params;\n\n let pwBytes: Uint8Array | null = null;\n let seed: Uint8Array | null = null;\n\n try {\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n pwBytes = utf8ToBytes(password);\n\n const { seed: seedValue, keyShareIndex } = await recoverTOPRFSeed({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n userInput: pwBytes,\n keyDeriver: this.#keyDeriver,\n });\n\n seed = seedValue;\n\n const authKeyPair = deriveAuthenticationKeyPair(seed);\n const encKey = deriveEncryptionKey(seed);\n const pwEncKey = derivePwEncKey(seed);\n\n const rateLimitResetResult = new Promise<void>((resolve, reject) => {\n resetRateLimits({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n authPrivKey: authKeyPair.sk,\n })\n .then(() => {\n return resolve();\n })\n .catch((error) => {\n reject(error as Error);\n });\n });\n\n return {\n authKeyPair,\n encKey,\n pwEncKey,\n keyShareIndex,\n rateLimitResetResult,\n };\n } finally {\n // Clean up sensitive intermediate data\n if (pwBytes) {\n pwBytes.fill(0);\n pwBytes = null;\n }\n\n if (seed) {\n seed.fill(0);\n seed = null;\n }\n }\n }\n\n /**\n * This function replaces the existing encryption key with a new one by generating a new key from\n * the new password, copying all existing secret data encrypted with the old key to be encrypted\n * with the new key, and updating the key shares on the nodes.\n *\n * @param params - The parameters for changing the encryption key.\n * @param params.nodeAuthTokens - The tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n * @param params.oldEncKey - The old encryption key of the user.\n * @param params.oldAuthKeyPair - The old authentication key pair of the user.\n * @param params.newKeyShareIndex - The key share index to be used for the new key.\n * @param params.newPassword - Optional new password of the user, either this or pregeneratedOprfKey is required.\n * @param params.pregeneratedOprfKey - Optional pregenerated OPRF key to be used for the key change, if not provided, a new key will be generated from the new password.\n *\n * @returns The new key pair and encryption key.\n * @throws {Error} If both newPassword and pregeneratedOprfKey are provided.\n * @throws {Error} If neither newPassword nor pregeneratedOprfKey is provided.\n */\n async changeEncKey(\n params: ChangeEncryptionKeyParams,\n ): Promise<ChangeEncryptionKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n oldEncKey,\n oldPwEncKey,\n oldAuthKeyPair,\n newPassword,\n newKeyShareIndex,\n pregeneratedOprfKey,\n transformDataItems,\n } = params;\n\n if (!pregeneratedOprfKey && !newPassword) {\n throw new Error('Either newPassword or pregeneratedOprfKey is required');\n }\n\n if (pregeneratedOprfKey && newPassword) {\n throw new Error(\n 'Only one of newPassword or pregeneratedOprfKey is allowed',\n );\n }\n\n // if newPassword is provided, create a new key from the password\n // else use the pregeneratedOprfKey, both can't be undefined as per check above.\n const { oprfKey, authKeyPair, encKey, pwEncKey } = newPassword\n ? await this.createLocalKey({ password: newPassword })\n : (pregeneratedOprfKey as CreateLocalKeyResult);\n\n let metadataStore: MetadataStore | undefined;\n let oldMetadataLockId: string | undefined;\n let newMetadataLockId: string | undefined;\n\n try {\n metadataStore = await this.#createMetadataStore();\n\n [oldMetadataLockId, newMetadataLockId] = await Promise.all([\n metadataStore.acquireMetadataLock(oldAuthKeyPair),\n metadataStore.acquireMetadataLock(authKeyPair),\n ]);\n\n const fetched = await metadataStore.fetchAllSecretDataItems(\n oldEncKey,\n oldAuthKeyPair,\n );\n const existingData = transformDataItems\n ? transformDataItems(fetched)\n : fetched.map(({ data, dataType, version }) => ({\n data,\n dataType,\n version: dataType === undefined ? 'v1' : version,\n }));\n\n // Validate that this is actually a key change scenario\n if (!existingData || existingData.length === 0) {\n throw new Error('No existing data found to change key');\n }\n\n const pwBackup: SecretDataItem = {\n data: serializePwBackup('', oldPwEncKey, oldAuthKeyPair),\n itemId: PW_BACKUP_ITEM_ID,\n };\n\n const secretDataItems = [pwBackup, ...existingData];\n const encKeys = [pwEncKey, ...existingData.map(() => encKey)];\n await metadataStore.batchAddSecretData({\n secretData: secretDataItems,\n encKey: encKeys,\n authKeyPair,\n });\n\n await this.persistLocalKey({\n nodeAuthTokens,\n oprfKey,\n authPubKey: authKeyPair.pk,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n keyShareIndex: newKeyShareIndex,\n oldAuthKeyPair,\n });\n\n return { authKeyPair, encKey, pwEncKey };\n } finally {\n if (metadataStore && oldMetadataLockId && newMetadataLockId) {\n try {\n await Promise.all([\n metadataStore.releaseMetadataLock(\n oldAuthKeyPair,\n oldMetadataLockId,\n ),\n metadataStore.releaseMetadataLock(authKeyPair, newMetadataLockId),\n ]);\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function encrypts the secret data using the encryption key and stores it nodes metadata store in encrypted form.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.encKey - The encryption key which is used to encrypt the secret data before storing it.\n * @param params.secretData - The secret data to be registered.\n * @param params.authKeyPair - The authentication key pair which is used to authenticate the user to the storage service.\n * @param params.itemId - Optional item ID for the data item.\n * @param params.version - Optional version ('v1' | 'v2'). Defaults to 'v2'.\n * @param params.dataType - Optional data type for categorizing the secret data. Required for v2.\n */\n async addSecretDataItem(params: AddSecretDataItemParams): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.addSecretDataItem({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: {\n data: params.secretData,\n itemId: params.itemId,\n version: params.version,\n dataType: params.dataType,\n },\n });\n }\n\n /**\n * This function encrypts the array of secret data using the encryption key and stores in the metadata store in encrypted form as a batch.\n *\n * @param params - The parameters for registering new secret data.\n * @param params.secretData - Array of items to store, each with data and optional itemId/dataType.\n * @param params.encKey - The encryption key to be used to encrypt the secret data before storing it.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for storing the secret data.\n */\n async batchAddSecretDataItems(\n params: BatchAddSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchAddSecretData({\n encKey: params.encKey,\n authKeyPair: params.authKeyPair,\n secretData: params.secretData.map((item) => ({\n data: item.data,\n itemId: item.itemId,\n version: item.version,\n dataType: item.dataType,\n })),\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * Updates fields for an existing secret data item by itemId.\n *\n * @param params - The parameters for updating the secret data item.\n * @param params.itemId - The ID of the item to update.\n * @param params.dataType - The data type to set for the item.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async updateSecretDataItem(\n params: UpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n await metadataStore.updateSecretDataItem({\n updateItem: {\n itemId: params.itemId,\n fields: { dataType: params.dataType },\n },\n authKeyPair: params.authKeyPair,\n });\n }\n\n /**\n * Updates fields for multiple existing secret data items by their itemIds.\n *\n * @param params - The parameters for batch updating the secret data items.\n * @param params.updateItems - Array of items to update, each with itemId and fields to update.\n * @param params.authKeyPair - The authentication key pair for signing the request.\n */\n async batchUpdateSecretDataItems(\n params: BatchUpdateSecretDataItemParams,\n ): Promise<void> {\n const metadataStore = await this.#createMetadataStore();\n\n let metadataLockId: string | undefined;\n\n try {\n // acquire metadata lock\n metadataLockId = await metadataStore.acquireMetadataLock(\n params.authKeyPair,\n );\n\n await metadataStore.batchUpdateSecretData({\n updateItems: params.updateItems.map((item) => ({\n itemId: item.itemId,\n fields: { dataType: item.dataType },\n })),\n authKeyPair: params.authKeyPair,\n });\n } finally {\n // release metadata lock\n if (metadataLockId) {\n try {\n await metadataStore.releaseMetadataLock(\n params.authKeyPair,\n metadataLockId,\n );\n } catch (error) {\n console.error('Failed to release metadata lock:', error);\n }\n }\n }\n }\n\n /**\n * This function fetches all secret data items associated with the given\n * auth pub key, decrypts, and returns them.\n *\n * @param params - The parameters for fetching the secret data.\n * @param params.decKey - The decryption key to be used to decrypt the secret data.\n * @param params.authKeyPair - The authentication key to be used to provide valid signature for fetching the secret data.\n *\n * @returns The decrypted secret data. Returns an empty array if no secret data is found.\n */\n async fetchAllSecretDataItems(\n params: FetchAllSecretDataParams,\n ): Promise<FetchedSecretDataItem[]> {\n const metadataStore = await this.#createMetadataStore();\n const dataItems = await metadataStore.fetchAllSecretDataItems(\n params.decKey,\n params.authKeyPair,\n );\n return dataItems;\n }\n\n /**\n * This function fetches the authentication public key.\n *\n * @param params - The parameters for getting the authentication public key.\n * @param params.authTokens - The auth tokens issued by the nodes on authenticating the user.\n * @param params.authConnectionId - The auth connection name used for authentication.\n * @param params.groupedAuthConnectionId - An optional grouped auth connection name used for authentication with aggregate (single id) verifier.\n * @param params.userId - The user id of the user.\n *\n * @returns The authentication public key.\n */\n async fetchAuthPubKey(\n params: FetchAuthPubKeyParams,\n ): Promise<FetchAuthPubKeyResult> {\n const {\n nodeAuthTokens,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n } = params;\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n return getPubKey({\n authTokens: nodeAuthTokens,\n nodeEndpointsMap,\n authConnectionId,\n userId,\n groupedAuthConnectionId,\n });\n }\n\n /**\n * This function looks up a password encryption key from the password\n * encryption key history.\n *\n * @param params - The parameters for getting the password encryption key.\n * @param params.targetPwPubKey - The target password public key.\n * @param params.curPwEncKey - The current password encryption key.\n * @param params.curAuthKeyPair - The current authentication key pair.\n * @param params.maxPwChainLength - Optional maximum password chain length\n * allowed to be traversed.\n *\n * @returns The password encryption key.\n */\n async recoverPwEncKey(\n params: RecoverPwEncKeyParams,\n ): Promise<RecoverPwEncKeyResult> {\n const {\n targetAuthPubKey: targetPwPubKey,\n curPwEncKey,\n curAuthKeyPair,\n maxPwChainLength = MAX_PASSWORD_CHAIN_LENGTH,\n } = params;\n\n let pwAndKeys = {\n password: '',\n encKey: curPwEncKey,\n authKeyPair: curAuthKeyPair,\n };\n\n for (let i = 0; i < maxPwChainLength; i++) {\n try {\n pwAndKeys = await this.#getPrevPasswordAndKeys({\n encKey: pwAndKeys.encKey,\n authKeyPair: pwAndKeys.authKeyPair,\n });\n if (equalBytes(pwAndKeys.authKeyPair.pk, targetPwPubKey)) {\n return { pwEncKey: pwAndKeys.encKey };\n }\n } catch (error) {\n throw TOPRFError.couldNotFetchPassword((error as Error).message);\n }\n }\n\n throw TOPRFError.maxKeyChainLengthExceeded();\n }\n\n /**\n * Gets the node details.\n * This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n return this.#getNodeDetails();\n }\n\n /**\n * Gets the node details.\n *\n * @returns The node details containing the node endpoints, indexes and pubkeys.\n */\n async #getNodeDetails(): Promise<{\n nodeEndpoints: string[];\n nodeEndpointsMap: Record<number, string>;\n nodeIndexes: number[];\n nodePubkeys: INodePub[];\n }> {\n let finalIndexes = this.#nodeDetailsOverride?.indexes;\n let finalPubKeys = this.#nodeDetailsOverride?.pubKeys;\n let finalEndpoints = this.#nodeDetailsOverride?.endpoints;\n\n if (finalIndexes && finalPubKeys && Array.isArray(finalEndpoints)) {\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n // NodeDetailManager has internal caching after first call to getNodeDetails\n // so we don't need internal caching here.\n // reference: {@link https://github.com/torusresearch/fetch-node-details/blob/master/packages/fetch-node-details/src/nodeDetailManager.ts#L88}\n const { torusNodeSSSEndpoints, torusIndexes, torusNodePub } =\n await this.#nodeDetailManager.getNodeDetails({\n verifier: 'auth-connection-id',\n verifierId: 'user-id',\n });\n\n finalIndexes ??= torusIndexes;\n finalPubKeys ??= torusNodePub;\n\n if (!Array.isArray(finalEndpoints)) {\n if (!torusNodeSSSEndpoints) {\n const message = 'Failed to get node details';\n throw new Error(message);\n }\n\n finalEndpoints = finalEndpoints\n ? torusNodeSSSEndpoints.map((endpoint) => {\n const url = new URL(endpoint);\n url.pathname = finalEndpoints as string;\n return url.href;\n })\n : torusNodeSSSEndpoints;\n }\n\n ToprfSecureBackup.#validateNodeDetailsLengths(\n finalIndexes,\n finalPubKeys,\n finalEndpoints,\n );\n\n return {\n nodeEndpoints: finalEndpoints,\n nodeEndpointsMap: createNodeEndpointsMap(finalEndpoints, finalIndexes),\n nodeIndexes: finalIndexes,\n nodePubkeys: finalPubKeys,\n };\n }\n\n /**\n * Creates and caches the metadata store instance.\n *\n * @returns The metadata store.\n */\n async #createMetadataStore(): Promise<MetadataStore> {\n if (this.#metadataStoreCache) {\n return this.#metadataStoreCache;\n }\n\n const { nodeEndpointsMap } = await this.#getNodeDetails();\n const metadataEndpointsMap =\n await this.#getMetadataEndpointsMap(nodeEndpointsMap);\n const node1MetadataEndpoint = metadataEndpointsMap['1'];\n\n const metadataStore = new MetadataStore({\n metadataEndpoint: node1MetadataEndpoint,\n fetchMetadataAccessCreds: this.#fetchMetadataAccessCreds,\n });\n\n this.#metadataStoreCache = metadataStore;\n\n return metadataStore;\n }\n\n /**\n * Gets the metadata endpoints.\n *\n * @param nodeEndpointsMap - The node endpoints map.\n *\n * @returns The metadata endpoints map with node index as key and metadata endpoint as value.\n */\n async #getMetadataEndpointsMap(\n nodeEndpointsMap: Record<number, string>,\n ): Promise<{ [nodeIndex: string]: string }> {\n const metadataEndpointsMap: { [nodeIndex: string]: string } = {};\n Object.entries(nodeEndpointsMap).forEach(([key, value]) => {\n const url = new URL(value);\n metadataEndpointsMap[key] = `${url.origin}/metadata`;\n });\n return metadataEndpointsMap;\n }\n\n /**\n * Gets the previous password and keys.\n *\n * @param params - The parameters for getting the previous password and keys.\n * @param params.encKey - The encryption key to be used for decrypting the secret data.\n * @param params.authKeyPair - The authentication key pair to be used for authenticating the secret data.\n *\n * @returns The previous password and keys.\n */\n async #getPrevPasswordAndKeys(params: {\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }): Promise<{\n password: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n }> {\n const metadataStore = await this.#createMetadataStore();\n\n const pwBackupData = await metadataStore.fetchAllSecretDataItems(\n params.encKey,\n params.authKeyPair,\n PW_BACKUP_ITEM_ID,\n );\n\n if (pwBackupData.length === 0) {\n throw new Error('Failed to get previous password and keys');\n }\n\n // Parse JSON object.\n const pwBackupDataJson = deserializePwBackup(pwBackupData[0].data);\n\n return {\n password: pwBackupDataJson.pw,\n encKey: pwBackupDataJson.encKey,\n authKeyPair: pwBackupDataJson.authKeyPair,\n };\n }\n\n /**\n * Validates that the lengths of node detail arrays are consistent.\n *\n * @param indexes - Array of node indexes.\n * @param pubKeys - Array of node public keys.\n * @param endpoints - Array of SSS endpoint URLs.\n * @throws If lengths are inconsistent.\n */\n static #validateNodeDetailsLengths(\n indexes: unknown[],\n pubKeys: unknown[],\n endpoints: unknown[],\n ): void {\n if (\n indexes.length !== pubKeys.length ||\n indexes.length !== endpoints.length\n ) {\n const message =\n 'Node details arrays (indexes, pubKeys, endpoints) must have equal lengths';\n throw new Error(message);\n }\n }\n}\n\n/**\n * Serializes the password, encryption key, and authentication key pair into a JSON string.\n *\n * @param pw - The password.\n * @param encKey - The encryption key.\n * @param authKeyPair - The authentication key pair.\n * @returns The serialized JSON string.\n */\nfunction serializePwBackup(\n pw: string,\n encKey: Uint8Array,\n authKeyPair: KeyPair,\n): Uint8Array {\n return utf8ToBytes(\n JSON.stringify({\n pw,\n encKey: bytesToHex(encKey),\n authKeyPair: {\n sk: authKeyPair.sk.toString(),\n pk: bytesToHex(authKeyPair.pk),\n },\n }),\n );\n}\n\n/**\n * Deserializes the password, encryption key, and authentication key pair from a JSON string.\n *\n * @param data - The serialized JSON string.\n * @returns The password, encryption key, and authentication key pair.\n */\nfunction deserializePwBackup(data: Uint8Array): {\n pw: string;\n encKey: Uint8Array;\n authKeyPair: KeyPair;\n} {\n const json = JSON.parse(bytesToUtf8(data));\n return {\n pw: json.pw,\n encKey: hexToBytes(json.encKey),\n authKeyPair: {\n sk: BigInt(json.authKeyPair.sk),\n pk: hexToBytes(json.authKeyPair.pk),\n },\n };\n}\n"]}
{
"name": "@metamask/toprf-secure-backup",
"version": "1.0.0",
"version": "1.1.0",
"description": "The MetaMask Node module template",

@@ -5,0 +5,0 @@ "keywords": [