@metamask-previews/profile-sync-controller 32.1.1-preview-d3f9964be → 32.1.1-preview-a2f6118d2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +0 -3
  2. package/dist/controllers/authentication/AuthenticationController-method-action-types.d.ts +1 -38
  3. package/dist/controllers/authentication/AuthenticationController-method-action-types.d.ts.map +1 -1
  4. package/dist/controllers/authentication/AuthenticationController-method-action-types.js.map +1 -1
  5. package/dist/controllers/authentication/AuthenticationController.d.ts +2 -38
  6. package/dist/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  7. package/dist/controllers/authentication/AuthenticationController.js +7 -185
  8. package/dist/controllers/authentication/AuthenticationController.js.map +1 -1
  9. package/dist/controllers/authentication/index.d.ts +1 -1
  10. package/dist/controllers/authentication/index.d.ts.map +1 -1
  11. package/dist/controllers/authentication/index.js.map +1 -1
  12. package/dist/controllers/authentication/mocks/mockResponses.d.ts +0 -5
  13. package/dist/controllers/authentication/mocks/mockResponses.d.ts.map +1 -1
  14. package/dist/controllers/authentication/mocks/mockResponses.js +1 -26
  15. package/dist/controllers/authentication/mocks/mockResponses.js.map +1 -1
  16. package/dist/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  17. package/dist/controllers/user-storage/UserStorageController.js +5 -6
  18. package/dist/controllers/user-storage/UserStorageController.js.map +1 -1
  19. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.ts +1 -56
  20. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.ts.map +1 -1
  21. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +1 -119
  22. package/dist/sdk/authentication-jwt-bearer/flow-srp.js.map +1 -1
  23. package/dist/sdk/authentication.d.ts +6 -15
  24. package/dist/sdk/authentication.d.ts.map +1 -1
  25. package/dist/sdk/authentication.js +0 -24
  26. package/dist/sdk/authentication.js.map +1 -1
  27. package/dist/sdk/constants.d.ts +0 -2
  28. package/dist/sdk/constants.d.ts.map +1 -1
  29. package/dist/sdk/constants.js +0 -2
  30. package/dist/sdk/constants.js.map +1 -1
  31. package/dist/sdk/errors.d.ts +0 -91
  32. package/dist/sdk/errors.d.ts.map +1 -1
  33. package/dist/sdk/errors.js +0 -161
  34. package/dist/sdk/errors.js.map +1 -1
  35. package/dist/sdk/index.d.ts +0 -3
  36. package/dist/sdk/index.d.ts.map +1 -1
  37. package/dist/sdk/index.js +0 -1
  38. package/dist/sdk/index.js.map +1 -1
  39. package/dist/sdk/mocks/auth.d.ts +0 -63
  40. package/dist/sdk/mocks/auth.d.ts.map +1 -1
  41. package/dist/sdk/mocks/auth.js +0 -90
  42. package/dist/sdk/mocks/auth.js.map +1 -1
  43. package/dist/sdk/utils/validate-login-response.d.ts.map +1 -1
  44. package/dist/sdk/utils/validate-login-response.js +7 -5
  45. package/dist/sdk/utils/validate-login-response.js.map +1 -1
  46. package/dist/shared/utils/entropy-source.d.ts +12 -3
  47. package/dist/shared/utils/entropy-source.d.ts.map +1 -1
  48. package/dist/shared/utils/entropy-source.js +17 -4
  49. package/dist/shared/utils/entropy-source.js.map +1 -1
  50. package/package.json +1 -4
  51. package/dist/sdk/authentication-jwt-bearer/mfa/schemas.d.ts +0 -691
  52. package/dist/sdk/authentication-jwt-bearer/mfa/schemas.d.ts.map +0 -1
  53. package/dist/sdk/authentication-jwt-bearer/mfa/schemas.js +0 -265
  54. package/dist/sdk/authentication-jwt-bearer/mfa/schemas.js.map +0 -1
  55. package/dist/sdk/authentication-jwt-bearer/mfa/services.d.ts +0 -104
  56. package/dist/sdk/authentication-jwt-bearer/mfa/services.d.ts.map +0 -1
  57. package/dist/sdk/authentication-jwt-bearer/mfa/services.js +0 -363
  58. package/dist/sdk/authentication-jwt-bearer/mfa/services.js.map +0 -1
  59. package/dist/sdk/authentication-jwt-bearer/mfa/types.d.ts +0 -125
  60. package/dist/sdk/authentication-jwt-bearer/mfa/types.d.ts.map +0 -1
  61. package/dist/sdk/authentication-jwt-bearer/mfa/types.js +0 -3
  62. package/dist/sdk/authentication-jwt-bearer/mfa/types.js.map +0 -1
  63. package/dist/sdk/utils/as-record.d.ts +0 -10
  64. package/dist/sdk/utils/as-record.d.ts.map +0 -1
  65. package/dist/sdk/utils/as-record.js +0 -14
  66. package/dist/sdk/utils/as-record.js.map +0 -1
  67. package/dist/sdk/utils/jwt.d.ts +0 -13
  68. package/dist/sdk/utils/jwt.d.ts.map +0 -1
  69. package/dist/sdk/utils/jwt.js +0 -21
  70. package/dist/sdk/utils/jwt.js.map +0 -1
  71. package/dist/sdk/utils/to-error-message.d.ts +0 -8
  72. package/dist/sdk/utils/to-error-message.d.ts.map +0 -1
  73. package/dist/sdk/utils/to-error-message.js +0 -10
  74. package/dist/sdk/utils/to-error-message.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.js","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAiB3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAQ/E,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAOzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6CAA6C,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAG5F,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA8B/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,sBAAsB,EAA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AAC;YAC9D,CAAC;YACD,+BAA+B,EAAE,CAC/B,YAAoB,EACpB,aAAuC,EACvC,EAAE;gBACF,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,+BAA+B,EAAE,CAC7D,SAAS,EACT,YAAY,EACZ,aAAa,CACd,CAAC;YACJ,CAAC;SACF,CAAC;QAEF,MAAM,2BAA2B,CAAC,MAAM,EAAE;YACxC,YAAY,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS;YAClC,gCAAgC,EAAE,GAAG,EAAE,CAAC,IAAI;YAC5C,KAAK,EAAE,IAAI,CAAC,MAAM;SACnB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerWithKeyringV2UnsafeAction,\n} from '@metamask/keyring-controller';\nimport { selectHdKeyringEntropySourceIds } from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk/index.js';\nimport { Env, UserStorage } from '../../sdk/index.js';\nimport type { NativeScrypt } from '../../shared/types/encryption.js';\nimport { getPrimaryHdKeyringEntropySourceId } from '../../shared/utils/entropy-source.js';\nimport { EventQueue } from '../../shared/utils/event-queue.js';\nimport { getHdKeyringSeed } from '../../shared/utils/hd-keyring-seed.js';\nimport { signMessageWithMessageSigningKey } from '../../shared/utils/message-signing.js';\nimport type {\n AuthenticationControllerGetBearerTokenAction,\n AuthenticationControllerGetSessionProfileAction,\n AuthenticationControllerIsSignedInAction,\n AuthenticationControllerPerformSignInAction,\n} from '../authentication/AuthenticationController-method-action-types.js';\nimport { BACKUPANDSYNC_FEATURES } from './constants.js';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration.js';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions.js';\nimport type { UserStorageControllerMethodActions } from './UserStorageController-method-action-types.js';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n /**\n * Condition used by UI to determine if ramps order syncing is enabled.\n */\n isRampsSyncingEnabled: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n isRampsSyncingEnabled: true,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isRampsSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performGetStorage',\n 'performGetStorageAllFeatureEntries',\n 'performSetStorage',\n 'performBatchSetStorage',\n 'performDeleteStorage',\n 'performBatchDeleteStorage',\n 'getStorageKey',\n 'performDeleteStorageAllFeatureEntries',\n 'listEntropySources',\n 'setIsBackupAndSyncFeatureEnabled',\n 'setIsContactSyncingInProgress',\n 'syncContactsWithUserStorage',\n] as const;\n\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | UserStorageControllerGetStateAction\n | UserStorageControllerMethodActions;\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n | KeyringControllerWithKeyringV2UnsafeAction\n // Auth Requests\n | AuthenticationControllerGetBearerTokenAction\n | AuthenticationControllerGetSessionProfileAction\n | AuthenticationControllerPerformSignInAction\n | AuthenticationControllerIsSignedInAction\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n // Both caches are keyed by `${entropySourceId}:${message}` (the primary SRP\n // resolves to its HD keyring metadata ID) so two SRPs that transiently\n // resolve to the same `profileId` can never share a cached storage key /\n // signature and leak data across each other's user storage.\n #storageKeyCache: Record<string, string> = {};\n\n #signMessageCache: Record<string, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#signMessage(message, entropySourceId),\n },\n },\n {\n storage: {\n getStorageKey: async (message, entropySourceId) => {\n // No derived key can exist while locked (the KeyringController\n // clears its keyrings on lock, so the scope is unresolvable).\n if (!this.#isUnlocked) {\n return null;\n }\n return (\n this.#storageKeyCache[\n this.#scopedCacheKey(message, entropySourceId)\n ] ?? null\n );\n },\n // Only ever reached after a successful signature, i.e. while unlocked.\n setStorageKey: async (message, key, entropySourceId) => {\n this.#storageKeyCache[\n this.#scopedCacheKey(message, entropySourceId)\n ] = key;\n },\n },\n },\n );\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messenger,\n trace: this.#trace,\n });\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources(): Promise<string[]> {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n return this.#getHdKeyringEntropySourceIds();\n }\n\n /**\n * Reads the HD keyring entropy source IDs from KeyringController.\n *\n * @returns The HD keyring metadata IDs, primary first.\n */\n #getHdKeyringEntropySourceIds(): string[] {\n const keyringState = this.messenger.call('KeyringController:getState');\n return selectHdKeyringEntropySourceIds(keyringState);\n }\n\n /**\n * Resolves the primary SRP's entropy source ID, used to scope the primary's\n * cache entries. The ID is randomly regenerated whenever the vault is\n * recreated (e.g. on restore), so a new primary can never inherit a previous\n * vault's cached key.\n *\n * @returns The primary HD keyring metadata ID.\n * @throws If no HD keyring is available; callers must only resolve the scope\n * while the wallet is unlocked.\n */\n #getPrimaryEntropySourceId(): string {\n const keyringState = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyringState);\n }\n\n /**\n * Builds a cache key scoped to a specific entropy source, so each SRP's\n * signature/storage key derivation stays isolated even when two SRPs\n * transiently resolve to the same `profileId` (see `#storageKeyCache`).\n *\n * When `entropySourceId` is omitted (primary SRP), it is resolved to the\n * primary HD keyring's metadata ID rather than a stable literal. Because that\n * ID is randomly regenerated whenever the vault is recreated (e.g. on\n * restore), the cached entry is naturally invalidated across vaults — a\n * different SRP can never inherit the previous primary's cached key.\n *\n * @param message - The tagged message used for signing.\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The scoped cache key.\n */\n #scopedCacheKey(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): string {\n return `${entropySourceId ?? this.#getPrimaryEntropySourceId()}:${message}`;\n }\n\n /**\n * Signs a `metamask:…` message with the native SIP-6 message-signing key\n * (same key as `@metamask/message-signing-snap` with empty salt).\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns Compact secp256k1 signature hex.\n */\n async #signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n if (!this.#isUnlocked) {\n throw new Error('#signMessage - unable to proceed, wallet is locked');\n }\n\n const cacheKey = this.#scopedCacheKey(\n message as `metamask:${string}`,\n entropySourceId,\n );\n if (this.#signMessageCache[cacheKey]) {\n return this.#signMessageCache[cacheKey];\n }\n\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n const seed = await getHdKeyringSeed(this.messenger, resolvedId);\n const result = await signMessageWithMessageSigningKey(message, seed);\n\n this.#signMessageCache[cacheKey] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.rampsSyncing) {\n state.isRampsSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messenger,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"UserStorageController.js","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAwB3D,OAAO,EAAE,GAAG,EAAE,WAAW,EA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CAAC,6BAA6B,CACjC,0BAAmC;QAEnC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,0BAA0B,GAAG,0BAA0B,CAAC;QAChE,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,2BAA2B;QAC/B,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;QAElD,MAAM,MAAM,GAAG;YACb,gBAAgB,EAAE,GAAG,EAAE;gBACrB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,CAAC,SAAS,CAAC,CAAC;YAC9D,CAAC;YACD,gBAAgB,EAAE,GAAG,EAAE;gBACrB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,CAAC,SAAS,CAAC,CAAC;YAC9D,CAAC;YACD,+BAA+B,EAAE,CAC/B,YAAoB,EACpB,aAAuC,EACvC,EAAE;gBACF,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,+BAA+B,EAAE,CAC7D,SAAS,EACT,YAAY,EACZ,aAAa,CACd,CAAC;YACJ,CAAC;SACF,CAAC;QAEF,MAAM,2BAA2B,CAAC,MAAM,EAAE;YACxC,YAAY,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS;YAClC,gCAAgC,EAAE,GAAG,EAAE,CAAC,IAAI;YAC5C,KAAK,EAAE,IAAI,CAAC,MAAM;SACnB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerWithKeyringV2UnsafeAction,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk/index.js';\nimport { Env, UserStorage } from '../../sdk/index.js';\nimport type { NativeScrypt } from '../../shared/types/encryption.js';\nimport {\n getHdKeyringEntropySourceIds,\n getPrimaryHdKeyringEntropySourceId,\n} from '../../shared/utils/entropy-source.js';\nimport { EventQueue } from '../../shared/utils/event-queue.js';\nimport { getHdKeyringSeed } from '../../shared/utils/hd-keyring-seed.js';\nimport { signMessageWithMessageSigningKey } from '../../shared/utils/message-signing.js';\nimport type {\n AuthenticationControllerGetBearerTokenAction,\n AuthenticationControllerGetSessionProfileAction,\n AuthenticationControllerIsSignedInAction,\n AuthenticationControllerPerformSignInAction,\n} from '../authentication/AuthenticationController-method-action-types.js';\nimport { BACKUPANDSYNC_FEATURES } from './constants.js';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration.js';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions.js';\nimport type { UserStorageControllerMethodActions } from './UserStorageController-method-action-types.js';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n /**\n * Condition used by UI to determine if ramps order syncing is enabled.\n */\n isRampsSyncingEnabled: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n isRampsSyncingEnabled: true,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isRampsSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'performGetStorage',\n 'performGetStorageAllFeatureEntries',\n 'performSetStorage',\n 'performBatchSetStorage',\n 'performDeleteStorage',\n 'performBatchDeleteStorage',\n 'getStorageKey',\n 'performDeleteStorageAllFeatureEntries',\n 'listEntropySources',\n 'setIsBackupAndSyncFeatureEnabled',\n 'setIsContactSyncingInProgress',\n 'syncContactsWithUserStorage',\n] as const;\n\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | UserStorageControllerGetStateAction\n | UserStorageControllerMethodActions;\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n | KeyringControllerWithKeyringV2UnsafeAction\n // Auth Requests\n | AuthenticationControllerGetBearerTokenAction\n | AuthenticationControllerGetSessionProfileAction\n | AuthenticationControllerPerformSignInAction\n | AuthenticationControllerIsSignedInAction\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n // Both caches are keyed by `${entropySourceId}:${message}` (the primary SRP\n // resolves to its HD keyring metadata ID) so two SRPs that transiently\n // resolve to the same `profileId` can never share a cached storage key /\n // signature and leak data across each other's user storage.\n #storageKeyCache: Record<string, string> = {};\n\n #signMessageCache: Record<string, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#signMessage(message, entropySourceId),\n },\n },\n {\n storage: {\n getStorageKey: async (message, entropySourceId) => {\n // No derived key can exist while locked (the KeyringController\n // clears its keyrings on lock, so the scope is unresolvable).\n if (!this.#isUnlocked) {\n return null;\n }\n return (\n this.#storageKeyCache[\n this.#scopedCacheKey(message, entropySourceId)\n ] ?? null\n );\n },\n // Only ever reached after a successful signature, i.e. while unlocked.\n setStorageKey: async (message, key, entropySourceId) => {\n this.#storageKeyCache[\n this.#scopedCacheKey(message, entropySourceId)\n ] = key;\n },\n },\n },\n );\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messenger,\n trace: this.#trace,\n });\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources(): Promise<string[]> {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n return this.#getHdKeyringEntropySourceIds();\n }\n\n /**\n * Reads the HD keyring entropy source IDs from KeyringController.\n *\n * @returns The HD keyring metadata IDs, primary first.\n */\n #getHdKeyringEntropySourceIds(): string[] {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getHdKeyringEntropySourceIds(keyrings);\n }\n\n /**\n * Resolves the primary SRP's entropy source ID, used to scope the primary's\n * cache entries. The ID is randomly regenerated whenever the vault is\n * recreated (e.g. on restore), so a new primary can never inherit a previous\n * vault's cached key.\n *\n * @returns The primary HD keyring metadata ID.\n * @throws If no HD keyring is available; callers must only resolve the scope\n * while the wallet is unlocked.\n */\n #getPrimaryEntropySourceId(): string {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return getPrimaryHdKeyringEntropySourceId(keyrings);\n }\n\n /**\n * Builds a cache key scoped to a specific entropy source, so each SRP's\n * signature/storage key derivation stays isolated even when two SRPs\n * transiently resolve to the same `profileId` (see `#storageKeyCache`).\n *\n * When `entropySourceId` is omitted (primary SRP), it is resolved to the\n * primary HD keyring's metadata ID rather than a stable literal. Because that\n * ID is randomly regenerated whenever the vault is recreated (e.g. on\n * restore), the cached entry is naturally invalidated across vaults — a\n * different SRP can never inherit the previous primary's cached key.\n *\n * @param message - The tagged message used for signing.\n * @param entropySourceId - The entropy source ID. Omit for the primary SRP.\n * @returns The scoped cache key.\n */\n #scopedCacheKey(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): string {\n return `${entropySourceId ?? this.#getPrimaryEntropySourceId()}:${message}`;\n }\n\n /**\n * Signs a `metamask:…` message with the native SIP-6 message-signing key\n * (same key as `@metamask/message-signing-snap` with empty salt).\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns Compact secp256k1 signature hex.\n */\n async #signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n if (!this.#isUnlocked) {\n throw new Error('#signMessage - unable to proceed, wallet is locked');\n }\n\n const cacheKey = this.#scopedCacheKey(\n message as `metamask:${string}`,\n entropySourceId,\n );\n if (this.#signMessageCache[cacheKey]) {\n return this.#signMessageCache[cacheKey];\n }\n\n const resolvedId = entropySourceId ?? this.#getPrimaryEntropySourceId();\n const seed = await getHdKeyringSeed(this.messenger, resolvedId);\n const result = await signMessageWithMessageSigningKey(message, seed);\n\n this.#signMessageCache[cacheKey] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.rampsSyncing) {\n state.isRampsSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messenger,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
@@ -1,9 +1,7 @@
1
1
  import type { Eip1193Provider } from 'ethers';
2
2
  import type { MetaMetricsAuth } from '../../shared/types/services.js';
3
- import type { MfaStepUpAssertion } from './mfa/services.js';
4
- import type { EnrolledCredential, EnrollmentChallenge, EnrollmentProof, MfaCredentialType, StepUpChallenge, StepUpProof } from './mfa/types.js';
5
3
  import type { PairProfilesResponse } from './services.js';
6
- import type { AuthConfig, AccessToken, AuthSigningOptions, AuthStorageOptions, AuthType, IBaseAuth, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, SrpLoginTag, UserProfile, UserProfileLineage } from './types.js';
4
+ import type { AuthConfig, AuthSigningOptions, AuthStorageOptions, AuthType, IBaseAuth, LoginIdentifierType, OidcTokenAudience, OidcTokenClaims, PairSocialIdentifierParams, SrpLoginTag, UserProfile, UserProfileLineage } from './types.js';
7
5
  type JwtBearerAuth_SRP_Options = {
8
6
  storage: AuthStorageOptions;
9
7
  signing?: AuthSigningOptions;
@@ -38,59 +36,6 @@ export declare class SRPJwtBearerAuth implements IBaseAuth {
38
36
  getUserProfileLineage(entropySourceId?: string): Promise<UserProfileLineage>;
39
37
  getCustomerServiceToken(entropySourceId?: string): Promise<string>;
40
38
  getPartnerIdentityToken(claims: OidcTokenClaims, audience: OidcTokenAudience, entropySourceId?: string): Promise<string>;
41
- /**
42
- * Begins enrollment of an MFA credential for the primary profile.
43
- *
44
- * @param type - Credential type to enroll.
45
- * @param options - Enrollment options.
46
- * @param options.email - Email address, required for email OTP.
47
- * @param options.entropySourceId - Entropy source whose profile owns the
48
- * credential.
49
- * @returns Enrollment challenge for the client ceremony.
50
- */
51
- beginMfaEnrollment(type: MfaCredentialType, options?: {
52
- email?: string;
53
- entropySourceId?: string;
54
- }): Promise<EnrollmentChallenge>;
55
- /**
56
- * Completes enrollment of an MFA credential.
57
- *
58
- * @param flowId - Identifier returned by the begin call.
59
- * @param proof - Platform attestation or email code.
60
- * @param entropySourceId - Entropy source whose profile owns the credential.
61
- */
62
- completeMfaEnrollment(flowId: string, proof: EnrollmentProof, entropySourceId?: string): Promise<void>;
63
- /**
64
- * Begins step-up verification with an enrolled credential.
65
- *
66
- * @param type - Credential type to verify.
67
- * @param entropySourceId - Entropy source whose profile owns the credential.
68
- * @returns Verification challenge for the client ceremony.
69
- */
70
- beginMfaVerification(type: MfaCredentialType, entropySourceId?: string): Promise<StepUpChallenge>;
71
- /**
72
- * Completes step-up verification with an enrolled credential.
73
- *
74
- * @param flowId - Identifier returned by the begin call.
75
- * @param proof - Platform assertion or email code.
76
- * @param entropySourceId - Entropy source whose profile owns the credential.
77
- * @returns AAL2 assertion issued after verification.
78
- */
79
- completeMfaVerification(flowId: string, proof: StepUpProof, entropySourceId?: string): Promise<MfaStepUpAssertion>;
80
- /**
81
- * Gets credentials enrolled on the primary profile.
82
- *
83
- * @param entropySourceId - Entropy source whose profile owns the credentials.
84
- * @returns Supported enrolled credentials.
85
- */
86
- getMfaCredentials(entropySourceId?: string): Promise<EnrolledCredential[]>;
87
- /**
88
- * Exchanges an MFA assertion for an elevated access token.
89
- *
90
- * @param assertionJwt - AAL2 authentication assertion.
91
- * @returns Elevated access token.
92
- */
93
- exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken>;
94
39
  pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<void>;
95
40
  pairSrpProfiles(accessTokens: string[], authAccessToken: string): Promise<PairProfilesResponse>;
96
41
  signMessage(message: string, entropySourceId?: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"flow-srp.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAiBtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,WAAW,EACZ,MAAM,gBAAgB,CAAC;AAWxB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,EACV,UAAU,EACV,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EAClB,QAAQ,EACR,SAAS,EACT,mBAAmB,EAEnB,iBAAiB,EACjB,eAAe,EACf,0BAA0B,EAC1B,WAAW,EACX,WAAW,EACX,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAIpB,KAAK,yBAAyB,GAAG;IAC/B,OAAO,EAAE,kBAAkB,CAAC;IAC5B,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,eAAe,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IACjE;;;OAGG;IACH,sBAAsB,CAAC,EAAE,CACvB,eAAe,CAAC,EAAE,MAAM,KACrB,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAClC,cAAc,CAAC,EAAE;QACf,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH,CAAC;AAIF,eAAO,MAAM,kBAAkB,QAAS,CAAC;AA+BzC,qBAAa,gBAAiB,YAAW,SAAS;;IAsChD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,QAAQ,EAAE,iBAAiB,EAC3B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAQjB;IAEK,oBAAoB,CACxB,MAAM,EAAE,0BAA0B,EAClC,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CAEf;IAEK,eAAe,CACnB,YAAY,EAAE,MAAM,EAAE,EACtB,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,oBAAoB,CAAC,CAqC/B;IAEK,WAAW,CACf,OAAO,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,CAEjB;IAEK,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,CASxC;IAEK,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,CAMnC;CAyKF"}
@@ -1,8 +1,7 @@
1
- import { MfaError, ValidationError, RateLimitedError } from '../errors.js';
1
+ import { ValidationError, RateLimitedError } from '../errors.js';
2
2
  import { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider.js';
3
3
  import { MESSAGE_SIGNING_SNAP, assertMessageStartsWithMetamask, connectSnap, isSnapConnected, } from '../utils/messaging-signing-snap-requests.js';
4
4
  import { validateLoginResponse } from '../utils/validate-login-response.js';
5
- import { getMfaCredentials, mfaEnroll, mfaEnrollComplete, mfaVerify, mfaVerifyComplete, } from './mfa/services.js';
6
5
  import { authenticate, authorizeOIDC, getCustomerServiceToken, getNonce, getPartnerIdentityToken, getUserProfileLineage, pairProfiles, pairSocialIdentifier, } from './services.js';
7
6
  import { computeIdentifierId } from './utils/identifier.js';
8
7
  import * as timeUtils from './utils/time.js';
@@ -96,123 +95,6 @@ export class SRPJwtBearerAuth {
96
95
  const accessToken = await this.getAccessToken(entropySourceId);
97
96
  return await getPartnerIdentityToken(this.#config.env, accessToken, claims, audience);
98
97
  }
99
- /**
100
- * Begins enrollment of an MFA credential for the primary profile.
101
- *
102
- * @param type - Credential type to enroll.
103
- * @param options - Enrollment options.
104
- * @param options.email - Email address, required for email OTP.
105
- * @param options.entropySourceId - Entropy source whose profile owns the
106
- * credential.
107
- * @returns Enrollment challenge for the client ceremony.
108
- */
109
- async beginMfaEnrollment(type, options) {
110
- const { email, entropySourceId } = options ?? {};
111
- const accessToken = await this.getAccessToken(entropySourceId);
112
- const result = await mfaEnroll(this.#config.env, accessToken, {
113
- credential_type: type,
114
- ...(email ? { identifier: email } : {}),
115
- });
116
- if (type === 'passkey') {
117
- if (!result.publicKey) {
118
- throw new MfaError('invalid_response', 'Passkey enrollment response is missing creation data');
119
- }
120
- return {
121
- type,
122
- flowId: result.flowId,
123
- expiresAt: result.expiresAt,
124
- publicKey: result.publicKey,
125
- };
126
- }
127
- return {
128
- type,
129
- flowId: result.flowId,
130
- expiresAt: result.expiresAt,
131
- };
132
- }
133
- /**
134
- * Completes enrollment of an MFA credential.
135
- *
136
- * @param flowId - Identifier returned by the begin call.
137
- * @param proof - Platform attestation or email code.
138
- * @param entropySourceId - Entropy source whose profile owns the credential.
139
- */
140
- async completeMfaEnrollment(flowId, proof, entropySourceId) {
141
- const accessToken = await this.getAccessToken(entropySourceId);
142
- await mfaEnrollComplete(this.#config.env, accessToken, {
143
- credential_type: proof.type,
144
- flow_id: flowId,
145
- ...(proof.type === 'passkey'
146
- ? { passkey_attestation: proof.attestation }
147
- : { otp_code: proof.code }),
148
- });
149
- }
150
- /**
151
- * Begins step-up verification with an enrolled credential.
152
- *
153
- * @param type - Credential type to verify.
154
- * @param entropySourceId - Entropy source whose profile owns the credential.
155
- * @returns Verification challenge for the client ceremony.
156
- */
157
- async beginMfaVerification(type, entropySourceId) {
158
- const accessToken = await this.getAccessToken(entropySourceId);
159
- const result = await mfaVerify(this.#config.env, accessToken, {
160
- credential_type: type,
161
- });
162
- if (type === 'passkey') {
163
- if (!result.publicKey) {
164
- throw new MfaError('invalid_response', 'Passkey verification response is missing request data');
165
- }
166
- return {
167
- type,
168
- flowId: result.flowId,
169
- expiresAt: result.expiresAt,
170
- publicKey: result.publicKey,
171
- };
172
- }
173
- return {
174
- type,
175
- flowId: result.flowId,
176
- expiresAt: result.expiresAt,
177
- };
178
- }
179
- /**
180
- * Completes step-up verification with an enrolled credential.
181
- *
182
- * @param flowId - Identifier returned by the begin call.
183
- * @param proof - Platform assertion or email code.
184
- * @param entropySourceId - Entropy source whose profile owns the credential.
185
- * @returns AAL2 assertion issued after verification.
186
- */
187
- async completeMfaVerification(flowId, proof, entropySourceId) {
188
- const accessToken = await this.getAccessToken(entropySourceId);
189
- return await mfaVerifyComplete(this.#config.env, accessToken, {
190
- credential_type: proof.type,
191
- flow_id: flowId,
192
- ...(proof.type === 'passkey'
193
- ? { passkey_assertion: proof.assertion }
194
- : { otp_code: proof.code }),
195
- });
196
- }
197
- /**
198
- * Gets credentials enrolled on the primary profile.
199
- *
200
- * @param entropySourceId - Entropy source whose profile owns the credentials.
201
- * @returns Supported enrolled credentials.
202
- */
203
- async getMfaCredentials(entropySourceId) {
204
- const accessToken = await this.getAccessToken(entropySourceId);
205
- return await getMfaCredentials(this.#config.env, accessToken);
206
- }
207
- /**
208
- * Exchanges an MFA assertion for an elevated access token.
209
- *
210
- * @param assertionJwt - AAL2 authentication assertion.
211
- * @returns Elevated access token.
212
- */
213
- async exchangeMfaAssertion(assertionJwt) {
214
- return await authorizeOIDC(assertionJwt, this.#config.env, this.#config.platform);
215
- }
216
98
  async pairSocialIdentifier(params, authAccessToken) {
217
99
  await pairSocialIdentifier(params, authAccessToken, this.#config.env);
218
100
  }
@@ -1 +1 @@
1
- {"version":3,"file":"flow-srp.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EACL,oBAAoB,EACpB,+BAA+B,EAC/B,WAAW,EACX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AAc,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,eAAwB;QAC5C,uDAAuD;QACvD,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,gBAAgB,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;YACxE,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;YACnD,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,wCAAwC;gBACxC,IAAI,CAAC,gBAAgB,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC1C,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,uCAAuC;gBACvC,IAAI,OAAO,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;oBACrC,MAAM,CAAC,CAAC;gBACV,CAAC;gBAED,2CAA2C;gBAC3C,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI,IAAI,CAAC,kBAAkB,CAAC;gBACzD,MAAM,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBAE9B,0BAA0B;YAC5B,CAAC;QACH,CAAC;QAED,2EAA2E;QAC3E,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IAED,yBAAyB,CACvB,KAAa,EACb,SAAiB,EACjB,GAAiB;QAIjB,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,YAAY,KAAK,IAAI,SAAS,IAAI,GAAG,EAAW,CAAC;QAC1D,CAAC;QACD,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { MfaError, ValidationError, RateLimitedError } from '../errors.js';\nimport { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider.js';\nimport {\n MESSAGE_SIGNING_SNAP,\n assertMessageStartsWithMetamask,\n connectSnap,\n isSnapConnected,\n} from '../utils/messaging-signing-snap-requests.js';\nimport { validateLoginResponse } from '../utils/validate-login-response.js';\nimport {\n getMfaCredentials,\n mfaEnroll,\n mfaEnrollComplete,\n mfaVerify,\n mfaVerifyComplete,\n} from './mfa/services.js';\nimport type { MfaStepUpAssertion } from './mfa/services.js';\nimport type {\n EnrolledCredential,\n EnrollmentChallenge,\n EnrollmentProof,\n MfaCredentialType,\n StepUpChallenge,\n StepUpProof,\n} from './mfa/types.js';\nimport {\n authenticate,\n authorizeOIDC,\n getCustomerServiceToken,\n getNonce,\n getPartnerIdentityToken,\n getUserProfileLineage,\n pairProfiles,\n pairSocialIdentifier,\n} from './services.js';\nimport type { PairProfilesResponse } from './services.js';\nimport type {\n AuthConfig,\n AccessToken,\n AuthSigningOptions,\n AuthStorageOptions,\n AuthType,\n IBaseAuth,\n LoginIdentifierType,\n LoginResponse,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { computeIdentifierId } from './utils/identifier.js';\nimport * as timeUtils from './utils/time.js';\n\ntype JwtBearerAuth_SRP_Options = {\n storage: AuthStorageOptions;\n signing?: AuthSigningOptions;\n /**\n * Resolves the login tag for a given entropy source.\n * When omitted, `raw_message` stays untagged (`metamask:<nonce>:<pubkey>`).\n */\n getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n /**\n * Resolves the metametrics `identifier_type` for a given entropy source.\n * Defaults to `'SRP'` when omitted.\n */\n getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n rateLimitRetry?: {\n cooldownDefaultMs?: number; // default cooldown when 429 has no Retry-After\n maxLoginRetries?: number; // maximum number of login retries on rate limit\n };\n};\n\n// How long a successful pairing result stays cached so identical payloads\n// (concurrent or sequential retries) reuse it instead of re-hitting the endpoint.\nexport const PAIR_DEDUPE_TTL_MS = 30_000;\n\nconst getDefaultEIP6963Provider = async () => {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new ValidationError('No MetaMask wallet connected');\n }\n return provider;\n};\n\nconst getDefaultEIP6963SigningOptions = (\n customProvider?: Eip1193Provider,\n): AuthSigningOptions => ({\n getIdentifier: async (entropySourceId?: string): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n return await MESSAGE_SIGNING_SNAP.getPublicKey(provider, entropySourceId);\n },\n signMessage: async (\n message: string,\n entropySourceId?: string,\n ): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n assertMessageStartsWithMetamask(message);\n return await MESSAGE_SIGNING_SNAP.signMessage(\n provider,\n message,\n entropySourceId,\n );\n },\n});\n\nexport class SRPJwtBearerAuth implements IBaseAuth {\n readonly #config: AuthConfig;\n\n readonly #options: {\n storage: AuthStorageOptions;\n signing: AuthSigningOptions;\n };\n\n readonly #metametrics?: MetaMetricsAuth;\n\n // Map to store ongoing login promises by entropySourceId\n readonly #ongoingLogins = new Map<\n string | undefined,\n Promise<LoginResponse>\n >();\n\n // Map to dedupe pairing calls by an order-insensitive token-set key.\n // Holds the in-flight promise (coalescing concurrent callers) and keeps it\n // for a short TTL after success (collapsing sequential retries).\n readonly #ongoingPairings = new Map<\n string,\n { promise: Promise<PairProfilesResponse>; expiresAt: number }\n >();\n\n // Default cooldown when 429 has no Retry-After header\n readonly #cooldownDefaultMs: number;\n\n // Maximum number of login retries on rate limit errors\n readonly #maxLoginRetries: number;\n\n readonly #getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n\n readonly #getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n\n #customProvider?: Eip1193Provider;\n\n constructor(\n config: AuthConfig & { type: AuthType.SRP },\n options: JwtBearerAuth_SRP_Options & {\n customProvider?: Eip1193Provider;\n metametrics?: MetaMetricsAuth;\n },\n ) {\n this.#config = config;\n this.#customProvider = options.customProvider;\n this.#getLoginTag = options.getLoginTag;\n this.#getLoginIdentifierType = options.getLoginIdentifierType;\n this.#options = {\n storage: options.storage,\n signing:\n options.signing ??\n getDefaultEIP6963SigningOptions(this.#customProvider),\n };\n this.#metametrics = options.metametrics;\n\n // Apply rate limit retry config if provided\n this.#cooldownDefaultMs =\n options.rateLimitRetry?.cooldownDefaultMs ?? 10000;\n this.#maxLoginRetries = options.rateLimitRetry?.maxLoginRetries ?? 1;\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#customProvider = provider;\n this.#options.signing = getDefaultEIP6963SigningOptions(provider);\n }\n\n // TODO: might be easier to keep entropySourceId as a class param and use multiple SRPJwtBearerAuth instances where needed\n async getAccessToken(entropySourceId?: string): Promise<string> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.token.accessToken;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.token.accessToken;\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.profile;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.profile;\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#options.signing.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getUserProfileLineage(this.#config.env, accessToken);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getCustomerServiceToken(this.#config.env, accessToken);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getPartnerIdentityToken(\n this.#config.env,\n accessToken,\n claims,\n audience,\n );\n }\n\n /**\n * Begins enrollment of an MFA credential for the primary profile.\n *\n * @param type - Credential type to enroll.\n * @param options - Enrollment options.\n * @param options.email - Email address, required for email OTP.\n * @param options.entropySourceId - Entropy source whose profile owns the\n * credential.\n * @returns Enrollment challenge for the client ceremony.\n */\n async beginMfaEnrollment(\n type: MfaCredentialType,\n options?: { email?: string; entropySourceId?: string },\n ): Promise<EnrollmentChallenge> {\n const { email, entropySourceId } = options ?? {};\n const accessToken = await this.getAccessToken(entropySourceId);\n const result = await mfaEnroll(this.#config.env, accessToken, {\n credential_type: type,\n ...(email ? { identifier: email } : {}),\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey enrollment response is missing creation data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes enrollment of an MFA credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform attestation or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n */\n async completeMfaEnrollment(\n flowId: string,\n proof: EnrollmentProof,\n entropySourceId?: string,\n ): Promise<void> {\n const accessToken = await this.getAccessToken(entropySourceId);\n await mfaEnrollComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_attestation: proof.attestation }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Begins step-up verification with an enrolled credential.\n *\n * @param type - Credential type to verify.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns Verification challenge for the client ceremony.\n */\n async beginMfaVerification(\n type: MfaCredentialType,\n entropySourceId?: string,\n ): Promise<StepUpChallenge> {\n const accessToken = await this.getAccessToken(entropySourceId);\n const result = await mfaVerify(this.#config.env, accessToken, {\n credential_type: type,\n });\n\n if (type === 'passkey') {\n if (!result.publicKey) {\n throw new MfaError(\n 'invalid_response',\n 'Passkey verification response is missing request data',\n );\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n publicKey: result.publicKey,\n };\n }\n return {\n type,\n flowId: result.flowId,\n expiresAt: result.expiresAt,\n };\n }\n\n /**\n * Completes step-up verification with an enrolled credential.\n *\n * @param flowId - Identifier returned by the begin call.\n * @param proof - Platform assertion or email code.\n * @param entropySourceId - Entropy source whose profile owns the credential.\n * @returns AAL2 assertion issued after verification.\n */\n async completeMfaVerification(\n flowId: string,\n proof: StepUpProof,\n entropySourceId?: string,\n ): Promise<MfaStepUpAssertion> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await mfaVerifyComplete(this.#config.env, accessToken, {\n credential_type: proof.type,\n flow_id: flowId,\n ...(proof.type === 'passkey'\n ? { passkey_assertion: proof.assertion }\n : { otp_code: proof.code }),\n });\n }\n\n /**\n * Gets credentials enrolled on the primary profile.\n *\n * @param entropySourceId - Entropy source whose profile owns the credentials.\n * @returns Supported enrolled credentials.\n */\n async getMfaCredentials(\n entropySourceId?: string,\n ): Promise<EnrolledCredential[]> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getMfaCredentials(this.#config.env, accessToken);\n }\n\n /**\n * Exchanges an MFA assertion for an elevated access token.\n *\n * @param assertionJwt - AAL2 authentication assertion.\n * @returns Elevated access token.\n */\n async exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken> {\n return await authorizeOIDC(\n assertionJwt,\n this.#config.env,\n this.#config.platform,\n );\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<void> {\n await pairSocialIdentifier(params, authAccessToken, this.#config.env);\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n // Order-insensitive key: the same token set in any order maps to the same\n // entry. Sort a copy so the request payload itself stays primary-first.\n const key = JSON.stringify([...accessTokens].sort());\n\n const cached = this.#ongoingPairings.get(key);\n if (cached && cached.expiresAt > Date.now()) {\n return await cached.promise;\n }\n\n const promise = pairProfiles(\n accessTokens,\n authAccessToken,\n this.#config.env,\n );\n // Store the in-flight promise immediately so concurrent callers coalesce\n // regardless of how long the request takes.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Number.MAX_SAFE_INTEGER,\n });\n\n try {\n const result = await promise;\n // Keep the resolved result cached for a short window so sequential\n // retries with the same payload reuse it.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Date.now() + PAIR_DEDUPE_TTL_MS,\n });\n return result;\n } catch (error) {\n // Never cache failures: the pairing retry loop must be able to re-hit\n // the endpoint on the next attempt.\n this.#ongoingPairings.delete(key);\n throw error;\n }\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#options.signing.signMessage(message, entropySourceId);\n }\n\n async isSnapConnected(): Promise<boolean> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n if (!provider) {\n return false;\n }\n\n const isConnected = await isSnapConnected(provider);\n return isConnected;\n }\n\n async connectSnap(): Promise<string> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n\n const res = await connectSnap(provider);\n return res;\n }\n\n // convert expiresIn from seconds to milliseconds and use 90% of expiresIn\n async #getAuthSession(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const auth = await this.#options.storage.getLoginResponse(entropySourceId);\n if (!validateLoginResponse(auth)) {\n return null;\n }\n\n // get canonical profile id from server if not present in the cached session\n if (!auth.profile.canonicalProfileId) {\n return null;\n }\n\n const currentTime = Date.now();\n const sessionAge = currentTime - auth.token.obtainedAt;\n const refreshThreshold = auth.token.expiresIn * 1000 * 0.9;\n\n if (sessionAge < refreshThreshold) {\n return auth;\n }\n return null;\n }\n\n async #login(entropySourceId?: string): Promise<LoginResponse> {\n // Use a deferred login to avoid race conditions\n return await this.#deferredLogin(entropySourceId);\n }\n\n async #performLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Nonce\n const publicKey = await this.getIdentifier(entropySourceId);\n const nonceRes = await getNonce(publicKey, this.#config.env);\n\n // Tag only when the wallet supplies getLoginTag. SDK callers keep the\n // legacy 3-part message rather than guessing `primary`.\n const tag = await this.#getLoginTag?.(entropySourceId);\n const identifierType =\n (await this.#getLoginIdentifierType?.(entropySourceId)) ?? 'SRP';\n const rawMessage = this.#createSrpLoginRawMessage(\n nonceRes.nonce,\n publicKey,\n tag,\n );\n const signature = await this.signMessage(rawMessage, entropySourceId);\n\n // Authenticate\n const authResponse = await authenticate(\n rawMessage,\n signature,\n this.#config.type,\n this.#config.env,\n this.#metametrics,\n identifierType,\n );\n\n // Resolve original profileId from aliases.\n // This is done mainly to preserve the original profileId for storage key derivation\n // until we migrate to the canonical profileId storage system.\n const canonicalProfileId = authResponse.profile.profileId;\n const profile = { ...authResponse.profile };\n\n if (authResponse.profileAliases?.length > 0) {\n const targetIdentifierId = computeIdentifierId(\n publicKey,\n this.#config.env,\n );\n\n const matchingAliases = authResponse.profileAliases.filter((alias) =>\n alias.identifierIds.some((id) => id.id === targetIdentifierId),\n );\n\n // Prefer the leaf alias (single identifier) — it's the original profile\n // created for this SRP. Multi-identifier aliases are former canonicals\n // that absorbed other profiles; they are correct only when this SRP's\n // original profile was itself a canonical before being absorbed.\n const targetAlias =\n matchingAliases.find((alias) => alias.identifierIds.length === 1) ??\n matchingAliases[0];\n\n if (targetAlias) {\n profile.profileId = targetAlias.aliasProfileId;\n }\n }\n\n profile.canonicalProfileId = canonicalProfileId;\n\n // Authorize\n const tokenResponse = await authorizeOIDC(\n authResponse.token,\n this.#config.env,\n this.#config.platform,\n );\n\n // Save\n const result: LoginResponse = {\n profile,\n token: tokenResponse,\n };\n\n await this.#options.storage.setLoginResponse(result, entropySourceId);\n\n return result;\n }\n\n async #deferredLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Check if there's already an ongoing login for this entropySourceId\n const existingLogin = this.#ongoingLogins.get(entropySourceId);\n if (existingLogin) {\n return existingLogin;\n }\n\n // Create a new login promise\n const loginPromise = this.#loginWithRetry(entropySourceId);\n\n // Store the promise in the map\n this.#ongoingLogins.set(entropySourceId, loginPromise);\n\n try {\n // Wait for the login to complete\n return await loginPromise;\n } finally {\n // Always clean up the ongoing login promise when done\n this.#ongoingLogins.delete(entropySourceId);\n }\n }\n\n async #loginWithRetry(entropySourceId?: string): Promise<LoginResponse> {\n // Allow max attempts: initial + maxLoginRetries on 429\n for (let attempt = 0; attempt < 1 + this.#maxLoginRetries; attempt += 1) {\n try {\n return await this.#performLogin(entropySourceId);\n } catch (e) {\n // Only retry on rate-limit (429) errors\n if (!RateLimitedError.isRateLimitError(e)) {\n throw e;\n }\n\n // If we've exhausted attempts, rethrow\n if (attempt >= this.#maxLoginRetries) {\n throw e;\n }\n\n // Wait for Retry-After or default cooldown\n const waitMs = e.retryAfterMs ?? this.#cooldownDefaultMs;\n await timeUtils.delay(waitMs);\n\n // Loop continues to retry\n }\n }\n\n // Should never reach here due to loop logic, but TypeScript needs a return\n throw new Error('Unexpected: login loop exhausted without result');\n }\n\n #createSrpLoginRawMessage(\n nonce: string,\n publicKey: string,\n tag?: SrpLoginTag,\n ):\n | `metamask:${string}:${string}`\n | `metamask:${string}:${string}:${SrpLoginTag}` {\n if (tag) {\n return `metamask:${nonce}:${publicKey}:${tag}` as const;\n }\n return `metamask:${nonce}:${publicKey}` as const;\n }\n}\n"]}
1
+ {"version":3,"file":"flow-srp.js","sourceRoot":"","sources":["../../../src/sdk/authentication-jwt-bearer/flow-srp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EACL,oBAAoB,EACpB,+BAA+B,EAC/B,WAAW,EACX,eAAe,GAChB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,YAAY,EACZ,aAAa,EACb,uBAAuB,EACvB,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CAAC,CAAC;IACrE,CAAC;IAED,yBAAyB,CACvB,KAAa,EACb,SAAiB,EACjB,GAAiB;QAIjB,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,YAAY,KAAK,IAAI,SAAS,IAAI,GAAG,EAAW,CAAC;QAC1D,CAAC;QACD,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nimport type { MetaMetricsAuth } from '../../shared/types/services.js';\nimport { ValidationError, RateLimitedError } from '../errors.js';\nimport { getMetaMaskProviderEIP6963 } from '../utils/eip-6963-metamask-provider.js';\nimport {\n MESSAGE_SIGNING_SNAP,\n assertMessageStartsWithMetamask,\n connectSnap,\n isSnapConnected,\n} from '../utils/messaging-signing-snap-requests.js';\nimport { validateLoginResponse } from '../utils/validate-login-response.js';\nimport {\n authenticate,\n authorizeOIDC,\n getCustomerServiceToken,\n getNonce,\n getPartnerIdentityToken,\n getUserProfileLineage,\n pairProfiles,\n pairSocialIdentifier,\n} from './services.js';\nimport type { PairProfilesResponse } from './services.js';\nimport type {\n AuthConfig,\n AuthSigningOptions,\n AuthStorageOptions,\n AuthType,\n IBaseAuth,\n LoginIdentifierType,\n LoginResponse,\n OidcTokenAudience,\n OidcTokenClaims,\n PairSocialIdentifierParams,\n SrpLoginTag,\n UserProfile,\n UserProfileLineage,\n} from './types.js';\nimport { computeIdentifierId } from './utils/identifier.js';\nimport * as timeUtils from './utils/time.js';\n\ntype JwtBearerAuth_SRP_Options = {\n storage: AuthStorageOptions;\n signing?: AuthSigningOptions;\n /**\n * Resolves the login tag for a given entropy source.\n * When omitted, `raw_message` stays untagged (`metamask:<nonce>:<pubkey>`).\n */\n getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n /**\n * Resolves the metametrics `identifier_type` for a given entropy source.\n * Defaults to `'SRP'` when omitted.\n */\n getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n rateLimitRetry?: {\n cooldownDefaultMs?: number; // default cooldown when 429 has no Retry-After\n maxLoginRetries?: number; // maximum number of login retries on rate limit\n };\n};\n\n// How long a successful pairing result stays cached so identical payloads\n// (concurrent or sequential retries) reuse it instead of re-hitting the endpoint.\nexport const PAIR_DEDUPE_TTL_MS = 30_000;\n\nconst getDefaultEIP6963Provider = async () => {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new ValidationError('No MetaMask wallet connected');\n }\n return provider;\n};\n\nconst getDefaultEIP6963SigningOptions = (\n customProvider?: Eip1193Provider,\n): AuthSigningOptions => ({\n getIdentifier: async (entropySourceId?: string): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n return await MESSAGE_SIGNING_SNAP.getPublicKey(provider, entropySourceId);\n },\n signMessage: async (\n message: string,\n entropySourceId?: string,\n ): Promise<string> => {\n const provider = customProvider ?? (await getDefaultEIP6963Provider());\n assertMessageStartsWithMetamask(message);\n return await MESSAGE_SIGNING_SNAP.signMessage(\n provider,\n message,\n entropySourceId,\n );\n },\n});\n\nexport class SRPJwtBearerAuth implements IBaseAuth {\n readonly #config: AuthConfig;\n\n readonly #options: {\n storage: AuthStorageOptions;\n signing: AuthSigningOptions;\n };\n\n readonly #metametrics?: MetaMetricsAuth;\n\n // Map to store ongoing login promises by entropySourceId\n readonly #ongoingLogins = new Map<\n string | undefined,\n Promise<LoginResponse>\n >();\n\n // Map to dedupe pairing calls by an order-insensitive token-set key.\n // Holds the in-flight promise (coalescing concurrent callers) and keeps it\n // for a short TTL after success (collapsing sequential retries).\n readonly #ongoingPairings = new Map<\n string,\n { promise: Promise<PairProfilesResponse>; expiresAt: number }\n >();\n\n // Default cooldown when 429 has no Retry-After header\n readonly #cooldownDefaultMs: number;\n\n // Maximum number of login retries on rate limit errors\n readonly #maxLoginRetries: number;\n\n readonly #getLoginTag?: (entropySourceId?: string) => Promise<SrpLoginTag>;\n\n readonly #getLoginIdentifierType?: (\n entropySourceId?: string,\n ) => Promise<LoginIdentifierType>;\n\n #customProvider?: Eip1193Provider;\n\n constructor(\n config: AuthConfig & { type: AuthType.SRP },\n options: JwtBearerAuth_SRP_Options & {\n customProvider?: Eip1193Provider;\n metametrics?: MetaMetricsAuth;\n },\n ) {\n this.#config = config;\n this.#customProvider = options.customProvider;\n this.#getLoginTag = options.getLoginTag;\n this.#getLoginIdentifierType = options.getLoginIdentifierType;\n this.#options = {\n storage: options.storage,\n signing:\n options.signing ??\n getDefaultEIP6963SigningOptions(this.#customProvider),\n };\n this.#metametrics = options.metametrics;\n\n // Apply rate limit retry config if provided\n this.#cooldownDefaultMs =\n options.rateLimitRetry?.cooldownDefaultMs ?? 10000;\n this.#maxLoginRetries = options.rateLimitRetry?.maxLoginRetries ?? 1;\n }\n\n setCustomProvider(provider: Eip1193Provider) {\n this.#customProvider = provider;\n this.#options.signing = getDefaultEIP6963SigningOptions(provider);\n }\n\n // TODO: might be easier to keep entropySourceId as a class param and use multiple SRPJwtBearerAuth instances where needed\n async getAccessToken(entropySourceId?: string): Promise<string> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.token.accessToken;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.token.accessToken;\n }\n\n async getUserProfile(entropySourceId?: string): Promise<UserProfile> {\n const session = await this.#getAuthSession(entropySourceId);\n if (session) {\n return session.profile;\n }\n\n const loginResponse = await this.#login(entropySourceId);\n return loginResponse.profile;\n }\n\n async getIdentifier(entropySourceId?: string): Promise<string> {\n return await this.#options.signing.getIdentifier(entropySourceId);\n }\n\n async getUserProfileLineage(\n entropySourceId?: string,\n ): Promise<UserProfileLineage> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getUserProfileLineage(this.#config.env, accessToken);\n }\n\n async getCustomerServiceToken(entropySourceId?: string): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getCustomerServiceToken(this.#config.env, accessToken);\n }\n\n async getPartnerIdentityToken(\n claims: OidcTokenClaims,\n audience: OidcTokenAudience,\n entropySourceId?: string,\n ): Promise<string> {\n const accessToken = await this.getAccessToken(entropySourceId);\n return await getPartnerIdentityToken(\n this.#config.env,\n accessToken,\n claims,\n audience,\n );\n }\n\n async pairSocialIdentifier(\n params: PairSocialIdentifierParams,\n authAccessToken: string,\n ): Promise<void> {\n await pairSocialIdentifier(params, authAccessToken, this.#config.env);\n }\n\n async pairSrpProfiles(\n accessTokens: string[],\n authAccessToken: string,\n ): Promise<PairProfilesResponse> {\n // Order-insensitive key: the same token set in any order maps to the same\n // entry. Sort a copy so the request payload itself stays primary-first.\n const key = JSON.stringify([...accessTokens].sort());\n\n const cached = this.#ongoingPairings.get(key);\n if (cached && cached.expiresAt > Date.now()) {\n return await cached.promise;\n }\n\n const promise = pairProfiles(\n accessTokens,\n authAccessToken,\n this.#config.env,\n );\n // Store the in-flight promise immediately so concurrent callers coalesce\n // regardless of how long the request takes.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Number.MAX_SAFE_INTEGER,\n });\n\n try {\n const result = await promise;\n // Keep the resolved result cached for a short window so sequential\n // retries with the same payload reuse it.\n this.#ongoingPairings.set(key, {\n promise,\n expiresAt: Date.now() + PAIR_DEDUPE_TTL_MS,\n });\n return result;\n } catch (error) {\n // Never cache failures: the pairing retry loop must be able to re-hit\n // the endpoint on the next attempt.\n this.#ongoingPairings.delete(key);\n throw error;\n }\n }\n\n async signMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n return await this.#options.signing.signMessage(message, entropySourceId);\n }\n\n async isSnapConnected(): Promise<boolean> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n if (!provider) {\n return false;\n }\n\n const isConnected = await isSnapConnected(provider);\n return isConnected;\n }\n\n async connectSnap(): Promise<string> {\n const provider =\n this.#customProvider ?? (await getDefaultEIP6963Provider());\n\n const res = await connectSnap(provider);\n return res;\n }\n\n // convert expiresIn from seconds to milliseconds and use 90% of expiresIn\n async #getAuthSession(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n const auth = await this.#options.storage.getLoginResponse(entropySourceId);\n if (!validateLoginResponse(auth)) {\n return null;\n }\n\n // get canonical profile id from server if not present in the cached session\n if (!auth.profile.canonicalProfileId) {\n return null;\n }\n\n const currentTime = Date.now();\n const sessionAge = currentTime - auth.token.obtainedAt;\n const refreshThreshold = auth.token.expiresIn * 1000 * 0.9;\n\n if (sessionAge < refreshThreshold) {\n return auth;\n }\n return null;\n }\n\n async #login(entropySourceId?: string): Promise<LoginResponse> {\n // Use a deferred login to avoid race conditions\n return await this.#deferredLogin(entropySourceId);\n }\n\n async #performLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Nonce\n const publicKey = await this.getIdentifier(entropySourceId);\n const nonceRes = await getNonce(publicKey, this.#config.env);\n\n // Tag only when the wallet supplies getLoginTag. SDK callers keep the\n // legacy 3-part message rather than guessing `primary`.\n const tag = await this.#getLoginTag?.(entropySourceId);\n const identifierType =\n (await this.#getLoginIdentifierType?.(entropySourceId)) ?? 'SRP';\n const rawMessage = this.#createSrpLoginRawMessage(\n nonceRes.nonce,\n publicKey,\n tag,\n );\n const signature = await this.signMessage(rawMessage, entropySourceId);\n\n // Authenticate\n const authResponse = await authenticate(\n rawMessage,\n signature,\n this.#config.type,\n this.#config.env,\n this.#metametrics,\n identifierType,\n );\n\n // Resolve original profileId from aliases.\n // This is done mainly to preserve the original profileId for storage key derivation\n // until we migrate to the canonical profileId storage system.\n const canonicalProfileId = authResponse.profile.profileId;\n const profile = { ...authResponse.profile };\n\n if (authResponse.profileAliases?.length > 0) {\n const targetIdentifierId = computeIdentifierId(\n publicKey,\n this.#config.env,\n );\n\n const matchingAliases = authResponse.profileAliases.filter((alias) =>\n alias.identifierIds.some((id) => id.id === targetIdentifierId),\n );\n\n // Prefer the leaf alias (single identifier) — it's the original profile\n // created for this SRP. Multi-identifier aliases are former canonicals\n // that absorbed other profiles; they are correct only when this SRP's\n // original profile was itself a canonical before being absorbed.\n const targetAlias =\n matchingAliases.find((alias) => alias.identifierIds.length === 1) ??\n matchingAliases[0];\n\n if (targetAlias) {\n profile.profileId = targetAlias.aliasProfileId;\n }\n }\n\n profile.canonicalProfileId = canonicalProfileId;\n\n // Authorize\n const tokenResponse = await authorizeOIDC(\n authResponse.token,\n this.#config.env,\n this.#config.platform,\n );\n\n // Save\n const result: LoginResponse = {\n profile,\n token: tokenResponse,\n };\n\n await this.#options.storage.setLoginResponse(result, entropySourceId);\n\n return result;\n }\n\n async #deferredLogin(entropySourceId?: string): Promise<LoginResponse> {\n // Check if there's already an ongoing login for this entropySourceId\n const existingLogin = this.#ongoingLogins.get(entropySourceId);\n if (existingLogin) {\n return existingLogin;\n }\n\n // Create a new login promise\n const loginPromise = this.#loginWithRetry(entropySourceId);\n\n // Store the promise in the map\n this.#ongoingLogins.set(entropySourceId, loginPromise);\n\n try {\n // Wait for the login to complete\n return await loginPromise;\n } finally {\n // Always clean up the ongoing login promise when done\n this.#ongoingLogins.delete(entropySourceId);\n }\n }\n\n async #loginWithRetry(entropySourceId?: string): Promise<LoginResponse> {\n // Allow max attempts: initial + maxLoginRetries on 429\n for (let attempt = 0; attempt < 1 + this.#maxLoginRetries; attempt += 1) {\n try {\n return await this.#performLogin(entropySourceId);\n } catch (e) {\n // Only retry on rate-limit (429) errors\n if (!RateLimitedError.isRateLimitError(e)) {\n throw e;\n }\n\n // If we've exhausted attempts, rethrow\n if (attempt >= this.#maxLoginRetries) {\n throw e;\n }\n\n // Wait for Retry-After or default cooldown\n const waitMs = e.retryAfterMs ?? this.#cooldownDefaultMs;\n await timeUtils.delay(waitMs);\n\n // Loop continues to retry\n }\n }\n\n // Should never reach here due to loop logic, but TypeScript needs a return\n throw new Error('Unexpected: login loop exhausted without result');\n }\n\n #createSrpLoginRawMessage(\n nonce: string,\n publicKey: string,\n tag?: SrpLoginTag,\n ):\n | `metamask:${string}:${string}`\n | `metamask:${string}:${string}:${SrpLoginTag}` {\n if (tag) {\n return `metamask:${nonce}:${publicKey}:${tag}` as const;\n }\n return `metamask:${nonce}:${publicKey}` as const;\n }\n}\n"]}
@@ -1,13 +1,13 @@
1
- import type { PublicInterface } from '@metamask/utils';
2
1
  import type { Eip1193Provider } from 'ethers';
3
2
  import { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe.js';
4
3
  import { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp.js';
5
- import type { MfaStepUpAssertion } from './authentication-jwt-bearer/mfa/services.js';
6
- import type { EnrolledCredential, EnrollmentChallenge, EnrollmentProof, MfaCredentialType, StepUpChallenge, StepUpProof } from './authentication-jwt-bearer/mfa/types.js';
7
4
  import type { PairProfilesResponse } from './authentication-jwt-bearer/services.js';
8
- import type { AccessToken, UserProfile, Pair, PairSocialIdentifierParams, OidcTokenAudience, OidcTokenClaims, UserProfileLineage } from './authentication-jwt-bearer/types.js';
9
- type SIWEInterface = PublicInterface<SIWEJwtBearerAuth>;
10
- export type SRPInterface = PublicInterface<SRPJwtBearerAuth>;
5
+ import type { UserProfile, Pair, PairSocialIdentifierParams, OidcTokenAudience, OidcTokenClaims, UserProfileLineage } from './authentication-jwt-bearer/types.js';
6
+ type Compute<T> = T extends infer U ? {
7
+ [K in keyof U]: U[K];
8
+ } : never;
9
+ type SIWEInterface = Compute<SIWEJwtBearerAuth>;
10
+ export type SRPInterface = Compute<SRPJwtBearerAuth>;
11
11
  type SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;
12
12
  type SRPParams = ConstructorParameters<typeof SRPJwtBearerAuth>;
13
13
  type JwtBearerAuthParams = SiweParams | SRPParams;
@@ -23,15 +23,6 @@ export declare class JwtBearerAuth implements SIWEInterface, SRPInterface {
23
23
  getUserProfileLineage(entropySourceId?: string): Promise<UserProfileLineage>;
24
24
  getCustomerServiceToken(entropySourceId?: string): Promise<string>;
25
25
  getPartnerIdentityToken(claims: OidcTokenClaims, audience: OidcTokenAudience, entropySourceId?: string): Promise<string>;
26
- beginMfaEnrollment(type: MfaCredentialType, options?: {
27
- email?: string;
28
- entropySourceId?: string;
29
- }): Promise<EnrollmentChallenge>;
30
- completeMfaEnrollment(flowId: string, proof: EnrollmentProof, entropySourceId?: string): Promise<void>;
31
- beginMfaVerification(type: MfaCredentialType, entropySourceId?: string): Promise<StepUpChallenge>;
32
- completeMfaVerification(flowId: string, proof: StepUpProof, entropySourceId?: string): Promise<MfaStepUpAssertion>;
33
- getMfaCredentials(entropySourceId?: string): Promise<EnrolledCredential[]>;
34
- exchangeMfaAssertion(assertionJwt: string): Promise<AccessToken>;
35
26
  pairSrpProfiles(accessTokens: string[], authAccessToken: string): Promise<PairProfilesResponse>;
36
27
  pairSocialIdentifier(params: PairSocialIdentifierParams, authAccessToken: string): Promise<void>;
37
28
  signMessage(message: string, entropySourceId?: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.d.ts","sourceRoot":"","sources":["../../src/sdk/authentication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACtF,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,WAAW,EACZ,MAAM,0CAA0C,CAAC;AAKlD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,IAAI,EACJ,0BAA0B,EAC1B,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EACnB,MAAM,sCAAsC,CAAC;AAM9C,KAAK,aAAa,GAAG,eAAe,CAAC,iBAAiB,CAAC,CAAC;AACxD,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erIdentityToken(claims, audience, entropySourceId) {
51
51
  return await this.#sdk.getPartnerIdentityToken(claims, audience, entropySourceId);
52
52
  }
53
- async beginMfaEnrollment(type, options) {
54
- this.#assertSRP(this.#type, this.#sdk);
55
- return await this.#sdk.beginMfaEnrollment(type, options);
56
- }
57
- async completeMfaEnrollment(flowId, proof, entropySourceId) {
58
- this.#assertSRP(this.#type, this.#sdk);
59
- await this.#sdk.completeMfaEnrollment(flowId, proof, entropySourceId);
60
- }
61
- async beginMfaVerification(type, entropySourceId) {
62
- this.#assertSRP(this.#type, this.#sdk);
63
- return await this.#sdk.beginMfaVerification(type, entropySourceId);
64
- }
65
- async completeMfaVerification(flowId, proof, entropySourceId) {
66
- this.#assertSRP(this.#type, this.#sdk);
67
- return await this.#sdk.completeMfaVerification(flowId, proof, entropySourceId);
68
- }
69
- async getMfaCredentials(entropySourceId) {
70
- this.#assertSRP(this.#type, this.#sdk);
71
- return await this.#sdk.getMfaCredentials(entropySourceId);
72
- }
73
- async exchangeMfaAssertion(assertionJwt) {
74
- this.#assertSRP(this.#type, this.#sdk);
75
- return await this.#sdk.exchangeMfaAssertion(assertionJwt);
76
- }
77
53
  async pairSrpProfiles(accessTokens, authAccessToken) {
78
54
  this.#assertSRP(this.#type, this.#sdk);
79
55
  return await this.#sdk.pairSrpProfiles(accessTokens, authAccessToken);