@metamask-previews/profile-sync-controller 29.0.0-preview-6b4bcdab3 → 29.0.0-preview-0b5bfc2

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 (50) hide show
  1. package/CHANGELOG.md +5 -2
  2. package/dist/controllers/authentication/AuthenticationController.cjs +39 -22
  3. package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
  4. package/dist/controllers/authentication/AuthenticationController.d.cts +2 -3
  5. package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
  6. package/dist/controllers/authentication/AuthenticationController.d.mts +2 -3
  7. package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
  8. package/dist/controllers/authentication/AuthenticationController.mjs +39 -22
  9. package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
  10. package/dist/controllers/user-storage/UserStorageController.cjs +18 -14
  11. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  12. package/dist/controllers/user-storage/UserStorageController.d.cts +2 -3
  13. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  14. package/dist/controllers/user-storage/UserStorageController.d.mts +2 -3
  15. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  16. package/dist/controllers/user-storage/UserStorageController.mjs +18 -14
  17. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  18. package/dist/shared/storage-schema.cjs +0 -1
  19. package/dist/shared/storage-schema.cjs.map +1 -1
  20. package/dist/shared/storage-schema.d.cts +0 -1
  21. package/dist/shared/storage-schema.d.cts.map +1 -1
  22. package/dist/shared/storage-schema.d.mts +0 -1
  23. package/dist/shared/storage-schema.d.mts.map +1 -1
  24. package/dist/shared/storage-schema.mjs +0 -1
  25. package/dist/shared/storage-schema.mjs.map +1 -1
  26. package/dist/shared/utils/hd-keyring-seed.cjs +49 -0
  27. package/dist/shared/utils/hd-keyring-seed.cjs.map +1 -0
  28. package/dist/shared/utils/hd-keyring-seed.d.cts +27 -0
  29. package/dist/shared/utils/hd-keyring-seed.d.cts.map +1 -0
  30. package/dist/shared/utils/hd-keyring-seed.d.mts +27 -0
  31. package/dist/shared/utils/hd-keyring-seed.d.mts.map +1 -0
  32. package/dist/shared/utils/hd-keyring-seed.mjs +45 -0
  33. package/dist/shared/utils/hd-keyring-seed.mjs.map +1 -0
  34. package/dist/shared/utils/message-signing.cjs +147 -0
  35. package/dist/shared/utils/message-signing.cjs.map +1 -0
  36. package/dist/shared/utils/message-signing.d.cts +73 -0
  37. package/dist/shared/utils/message-signing.d.cts.map +1 -0
  38. package/dist/shared/utils/message-signing.d.mts +73 -0
  39. package/dist/shared/utils/message-signing.d.mts.map +1 -0
  40. package/dist/shared/utils/message-signing.mjs +140 -0
  41. package/dist/shared/utils/message-signing.mjs.map +1 -0
  42. package/package.json +4 -4
  43. package/dist/controllers/authentication/auth-snap-requests.cjs +0 -44
  44. package/dist/controllers/authentication/auth-snap-requests.cjs.map +0 -1
  45. package/dist/controllers/authentication/auth-snap-requests.d.cts +0 -21
  46. package/dist/controllers/authentication/auth-snap-requests.d.cts.map +0 -1
  47. package/dist/controllers/authentication/auth-snap-requests.d.mts +0 -21
  48. package/dist/controllers/authentication/auth-snap-requests.d.mts.map +0 -1
  49. package/dist/controllers/authentication/auth-snap-requests.mjs +0 -39
  50. package/dist/controllers/authentication/auth-snap-requests.mjs.map +0 -1
@@ -9,12 +9,13 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
11
  };
12
- var _UserStorageController_instances, _UserStorageController_userStorage, _UserStorageController_auth, _UserStorageController_config, _UserStorageController_trace, _UserStorageController_isUnlocked, _UserStorageController_storageKeyCache, _UserStorageController_snapSignMessageCache, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_getHdKeyringEntropySourceIds, _UserStorageController_getPrimaryEntropySourceId, _UserStorageController_scopedCacheKey, _UserStorageController_snapSignMessage, _UserStorageController_setIsBackupAndSyncUpdateLoading;
12
+ var _UserStorageController_instances, _UserStorageController_userStorage, _UserStorageController_auth, _UserStorageController_config, _UserStorageController_trace, _UserStorageController_isUnlocked, _UserStorageController_storageKeyCache, _UserStorageController_signMessageCache, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_getHdKeyringEntropySourceIds, _UserStorageController_getPrimaryEntropySourceId, _UserStorageController_scopedCacheKey, _UserStorageController_signMessage, _UserStorageController_setIsBackupAndSyncUpdateLoading;
13
13
  import { BaseController } from "@metamask/base-controller";
14
14
  import { Env, UserStorage } from "../../sdk/index.mjs";
15
15
  import { getHdKeyringEntropySourceIds, getPrimaryHdKeyringEntropySourceId } from "../../shared/utils/entropy-source.mjs";
16
16
  import { EventQueue } from "../../shared/utils/event-queue.mjs";
17
- import { createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
17
+ import { getHdKeyringSeed } from "../../shared/utils/hd-keyring-seed.mjs";
18
+ import { signMessageWithMessageSigningKey } from "../../shared/utils/message-signing.mjs";
18
19
  import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
19
20
  import { syncContactsWithUserStorage } from "./contact-syncing/controller-integration.mjs";
20
21
  import { setupContactSyncingSubscriptions } from "./contact-syncing/setup-subscriptions.mjs";
@@ -112,7 +113,7 @@ export class UserStorageController extends BaseController {
112
113
  // resolve to the same `profileId` can never share a cached storage key /
113
114
  // signature and leak data across each other's user storage.
114
115
  _UserStorageController_storageKeyCache.set(this, {});
115
- _UserStorageController_snapSignMessageCache.set(this, {});
116
+ _UserStorageController_signMessageCache.set(this, {});
116
117
  _UserStorageController_keyringController.set(this, {
117
118
  setupLockedStateSubscriptions: () => {
118
119
  const { isUnlocked } = this.messenger.call('KeyringController:getState');
@@ -145,7 +146,7 @@ export class UserStorageController extends BaseController {
145
146
  getUserProfile: async (entropySourceId) => {
146
147
  return await this.messenger.call('AuthenticationController:getSessionProfile', entropySourceId);
147
148
  },
148
- signMessage: (message, entropySourceId) => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapSignMessage).call(this, message, entropySourceId),
149
+ signMessage: (message, entropySourceId) => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_signMessage).call(this, message, entropySourceId),
149
150
  },
150
151
  }, {
151
152
  storage: {
@@ -368,7 +369,7 @@ export class UserStorageController extends BaseController {
368
369
  });
369
370
  }
370
371
  }
371
- _UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_trace = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_snapSignMessageCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_getHdKeyringEntropySourceIds = function _UserStorageController_getHdKeyringEntropySourceIds() {
372
+ _UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_trace = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_signMessageCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_getHdKeyringEntropySourceIds = function _UserStorageController_getHdKeyringEntropySourceIds() {
372
373
  const { keyrings } = this.messenger.call('KeyringController:getState');
373
374
  return getHdKeyringEntropySourceIds(keyrings);
374
375
  }, _UserStorageController_getPrimaryEntropySourceId = function _UserStorageController_getPrimaryEntropySourceId() {
@@ -376,25 +377,28 @@ _UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth
376
377
  return getPrimaryHdKeyringEntropySourceId(keyrings);
377
378
  }, _UserStorageController_scopedCacheKey = function _UserStorageController_scopedCacheKey(message, entropySourceId) {
378
379
  return `${entropySourceId ?? __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getPrimaryEntropySourceId).call(this)}:${message}`;
379
- }, _UserStorageController_snapSignMessage =
380
+ }, _UserStorageController_signMessage =
380
381
  /**
381
- * Signs a specific message using an underlying auth snap.
382
+ * Signs a `metamask:…` message with the native SIP-6 message-signing key
383
+ * (same key as `@metamask/message-signing-snap` with empty salt).
382
384
  *
383
385
  * @param message - A specific tagged message to sign.
384
386
  * @param entropySourceId - The entropy source ID used to derive the key,
385
387
  * when multiple sources are available (Multi-SRP).
386
- * @returns A Signature created by the snap.
388
+ * @returns Compact secp256k1 signature hex.
387
389
  */
388
- async function _UserStorageController_snapSignMessage(message, entropySourceId) {
390
+ async function _UserStorageController_signMessage(message, entropySourceId) {
389
391
  if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
390
- throw new Error('#snapSignMessage - unable to call snap, wallet is locked');
392
+ throw new Error('#signMessage - unable to proceed, wallet is locked');
391
393
  }
392
394
  const cacheKey = __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_scopedCacheKey).call(this, message, entropySourceId);
393
- if (__classPrivateFieldGet(this, _UserStorageController_snapSignMessageCache, "f")[cacheKey]) {
394
- return __classPrivateFieldGet(this, _UserStorageController_snapSignMessageCache, "f")[cacheKey];
395
+ if (__classPrivateFieldGet(this, _UserStorageController_signMessageCache, "f")[cacheKey]) {
396
+ return __classPrivateFieldGet(this, _UserStorageController_signMessageCache, "f")[cacheKey];
395
397
  }
396
- const result = (await this.messenger.call('SnapController:handleRequest', createSnapSignMessageRequest(message, entropySourceId)));
397
- __classPrivateFieldGet(this, _UserStorageController_snapSignMessageCache, "f")[cacheKey] = result;
398
+ const resolvedId = entropySourceId ?? __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getPrimaryEntropySourceId).call(this);
399
+ const seed = await getHdKeyringSeed(this.messenger, resolvedId);
400
+ const result = await signMessageWithMessageSigningKey(message, seed);
401
+ __classPrivateFieldGet(this, _UserStorageController_signMessageCache, "f")[cacheKey] = result;
398
402
  return result;
399
403
  }, _UserStorageController_setIsBackupAndSyncUpdateLoading = function _UserStorageController_setIsBackupAndSyncUpdateLoading(isBackupAndSyncUpdateLoading) {
400
404
  this.update((state) => {
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAwB3D,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,4BAA2B;AAEtD,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EACnC,8CAA6C;AAC9C,OAAO,EAAE,UAAU,EAAE,2CAA0C;AAC/D,OAAO,EAAE,4BAA4B,EAAE,iDAAgD;AAOvF,OAAO,EAAE,sBAAsB,EAAE,wBAAuB;AACxD,OAAO,EAAE,2BAA2B,EAAE,qDAAoD;AAC1F,OAAO,EAAE,gCAAgC,EAAE,kDAAiD;AAG5F,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA0B/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,uBAAuB,EAAE,IAAI;IAC7B,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,4BAA4B,EAAE;QAC5B,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI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C,CAAC,QAAQ,CAAC,CAAC;AACtD,CAAC,yFAkBC,OAA6B,EAC7B,eAAwB;IAExB,OAAO,GAAG,eAAe,IAAI,uBAAA,IAAI,0FAA2B,MAA/B,IAAI,CAA6B,IAAI,OAAO,EAAE,CAAC;AAC9E,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,iDACH,OAA6B,EAC7B,eAAwB;IAExB,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;IACJ,CAAC;IAED,MAAM,QAAQ,GAAG,uBAAA,IAAI,+EAAgB,MAApB,IAAI,EAAiB,OAAO,EAAE,eAAe,CAAC,CAAC;IAChE,IAAI,uBAAA,IAAI,mDAAsB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACzC,OAAO,uBAAA,IAAI,mDAAsB,CAAC,QAAQ,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,mDAAsB,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC","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} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\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 { createSnapSignMessageRequest } from '../authentication/auth-snap-requests.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\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\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};\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 // Snap Requests\n | SnapControllerHandleRequestAction\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 #snapSignMessageCache: 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.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\n ),\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 specific message using an underlying auth snap.\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 A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const cacheKey = this.#scopedCacheKey(message, entropySourceId);\n if (this.#snapSignMessageCache[cacheKey]) {\n return this.#snapSignMessageCache[cacheKey];\n }\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#snapSignMessageCache[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 } 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.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAwB3D,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,4BAA2B;AAEtD,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EACnC,8CAA6C;AAC9C,OAAO,EAAE,UAAU,EAAE,2CAA0C;AAC/D,OAAO,EAAE,gBAAgB,EAAE,+CAA8C;AACzE,OAAO,EAAE,gCAAgC,EAAE,+CAA8C;AAOzF,OAAO,EAAE,sBAAsB,EAAE,wBAAuB;AACxD,OAAO,EAAE,2BAA2B,EAAE,qDAAoD;AAC1F,OAAO,EAAE,gCAAgC,EAAE,kDAAiD;AAG5F,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA0B/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,uBAAuB,EAAE,IAAI;IAC7B,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,4BAA4B,EAAE;QAC5B,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,uBAAuB,EAAE;QACvB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,uBAAuB,EAAE;QACvB,k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,CAAC;AAC9E,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,6CACH,OAAe,EACf,eAAwB;IAExB,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,QAAQ,GAAG,uBAAA,IAAI,+EAAgB,MAApB,IAAI,EACnB,OAA+B,EAC/B,eAAe,CAChB,CAAC;IACF,IAAI,uBAAA,IAAI,+CAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACrC,OAAO,uBAAA,IAAI,+CAAkB,CAAC,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED,MAAM,UAAU,GAAG,eAAe,IAAI,uBAAA,IAAI,0FAA2B,MAA/B,IAAI,CAA6B,CAAC;IACxE,MAAM,IAAI,GAAG,MAAM,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAErE,uBAAA,IAAI,+CAAkB,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;IAE1C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC","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\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\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};\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 } 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"]}
@@ -14,7 +14,6 @@ exports.USER_STORAGE_FEATURE_NAMES = {
14
14
  notifications: 'notifications',
15
15
  accounts: 'accounts_v2',
16
16
  addressBook: 'addressBook',
17
- rampsAutoramps: 'rampsAutoramps',
18
17
  };
19
18
  const getFeatureAndKeyFromPath = (path) => {
20
19
  const pathRegex = /^\w+\.\w+$/u;
@@ -1 +1 @@
1
- {"version":3,"file":"storage-schema.cjs","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":";;;AAAA,qDAAyD;AAEzD;;;GAGG;AAEH;;;GAGG;AACU,QAAA,0BAA0B,GAAG;IACxC,aAAa,EAAE,eAAe;IAC9B,QAAQ,EAAE,aAAa;IACvB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,gBAAgB;CACjC,CAAC;AAcK,MAAM,wBAAwB,GAAG,CACtC,IAA6C,EACZ,EAAE;IACnC,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEvC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAqC,CAAC;AAC7D,CAAC,CAAC;AAdW,QAAA,wBAAwB,4BAcnC;AAEF;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAC7B,IAA6C,EAC7C,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,IAAA,gCAAwB,EAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,IAAA,2BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC;AARD,0CAQC","sourcesContent":["import { createSHA256Hash } from './encryption/index.js';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Any user storage path should be in the form of `feature.key`.\n */\n\n/**\n * Helper object that contains the feature names used in the controllers and SDK.\n * Developers don't need to add new feature names to this object anymore, as the schema enforcement has been deprecated.\n */\nexport const USER_STORAGE_FEATURE_NAMES = {\n notifications: 'notifications',\n accounts: 'accounts_v2',\n addressBook: 'addressBook',\n rampsAutoramps: 'rampsAutoramps',\n};\n\nexport type UserStorageGenericFeatureName = string;\nexport type UserStorageGenericFeatureKey = string;\nexport type UserStorageGenericPathWithFeatureAndKey =\n `${UserStorageGenericFeatureName}.${UserStorageGenericFeatureKey}`;\nexport type UserStorageGenericPathWithFeatureOnly =\n UserStorageGenericFeatureName;\n\ntype UserStorageGenericFeatureAndKey = {\n feature: UserStorageGenericFeatureName;\n key: UserStorageGenericFeatureKey;\n};\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStorageGenericPathWithFeatureAndKey,\n): UserStorageGenericFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.');\n\n return { feature, key } as UserStorageGenericFeatureAndKey;\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStorageGenericPathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
1
+ {"version":3,"file":"storage-schema.cjs","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":";;;AAAA,qDAAyD;AAEzD;;;GAGG;AAEH;;;GAGG;AACU,QAAA,0BAA0B,GAAG;IACxC,aAAa,EAAE,eAAe;IAC9B,QAAQ,EAAE,aAAa;IACvB,WAAW,EAAE,aAAa;CAC3B,CAAC;AAcK,MAAM,wBAAwB,GAAG,CACtC,IAA6C,EACZ,EAAE;IACnC,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEvC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAqC,CAAC;AAC7D,CAAC,CAAC;AAdW,QAAA,wBAAwB,4BAcnC;AAEF;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAC7B,IAA6C,EAC7C,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,IAAA,gCAAwB,EAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,IAAA,2BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC;AARD,0CAQC","sourcesContent":["import { createSHA256Hash } from './encryption/index.js';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Any user storage path should be in the form of `feature.key`.\n */\n\n/**\n * Helper object that contains the feature names used in the controllers and SDK.\n * Developers don't need to add new feature names to this object anymore, as the schema enforcement has been deprecated.\n */\nexport const USER_STORAGE_FEATURE_NAMES = {\n notifications: 'notifications',\n accounts: 'accounts_v2',\n addressBook: 'addressBook',\n};\n\nexport type UserStorageGenericFeatureName = string;\nexport type UserStorageGenericFeatureKey = string;\nexport type UserStorageGenericPathWithFeatureAndKey =\n `${UserStorageGenericFeatureName}.${UserStorageGenericFeatureKey}`;\nexport type UserStorageGenericPathWithFeatureOnly =\n UserStorageGenericFeatureName;\n\ntype UserStorageGenericFeatureAndKey = {\n feature: UserStorageGenericFeatureName;\n key: UserStorageGenericFeatureKey;\n};\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStorageGenericPathWithFeatureAndKey,\n): UserStorageGenericFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.');\n\n return { feature, key } as UserStorageGenericFeatureAndKey;\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStorageGenericPathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
@@ -10,7 +10,6 @@ export declare const USER_STORAGE_FEATURE_NAMES: {
10
10
  notifications: string;
11
11
  accounts: string;
12
12
  addressBook: string;
13
- rampsAutoramps: string;
14
13
  };
15
14
  export type UserStorageGenericFeatureName = string;
16
15
  export type UserStorageGenericFeatureKey = string;
@@ -1 +1 @@
1
- {"version":3,"file":"storage-schema.d.cts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH;;;GAGG;AACH,eAAO,MAAM,0BAA0B;;;;;CAKtC,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC;AACnD,MAAM,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAClD,MAAM,MAAM,uCAAuC,GACjD,GAAG,6BAA6B,IAAI,4BAA4B,EAAE,CAAC;AACrE,MAAM,MAAM,qCAAqC,GAC/C,6BAA6B,CAAC;AAEhC,KAAK,+BAA+B,GAAG;IACrC,OAAO,EAAE,6BAA6B,CAAC;IACvC,GAAG,EAAE,4BAA4B,CAAC;CACnC,CAAC;AAEF,eAAO,MAAM,wBAAwB,SAC7B,uCAAuC,KAC5C,+BAYF,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,uCAAuC,EAC7C,UAAU,EAAE,MAAM,GACjB,MAAM,CAKR"}
1
+ {"version":3,"file":"storage-schema.d.cts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH;;;GAGG;AACH,eAAO,MAAM,0BAA0B;;;;CAItC,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC;AACnD,MAAM,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAClD,MAAM,MAAM,uCAAuC,GACjD,GAAG,6BAA6B,IAAI,4BAA4B,EAAE,CAAC;AACrE,MAAM,MAAM,qCAAqC,GAC/C,6BAA6B,CAAC;AAEhC,KAAK,+BAA+B,GAAG;IACrC,OAAO,EAAE,6BAA6B,CAAC;IACvC,GAAG,EAAE,4BAA4B,CAAC;CACnC,CAAC;AAEF,eAAO,MAAM,wBAAwB,SAC7B,uCAAuC,KAC5C,+BAYF,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,uCAAuC,EAC7C,UAAU,EAAE,MAAM,GACjB,MAAM,CAKR"}
@@ -10,7 +10,6 @@ export declare const USER_STORAGE_FEATURE_NAMES: {
10
10
  notifications: string;
11
11
  accounts: string;
12
12
  addressBook: string;
13
- rampsAutoramps: string;
14
13
  };
15
14
  export type UserStorageGenericFeatureName = string;
16
15
  export type UserStorageGenericFeatureKey = string;
@@ -1 +1 @@
1
- {"version":3,"file":"storage-schema.d.mts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH;;;GAGG;AACH,eAAO,MAAM,0BAA0B;;;;;CAKtC,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC;AACnD,MAAM,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAClD,MAAM,MAAM,uCAAuC,GACjD,GAAG,6BAA6B,IAAI,4BAA4B,EAAE,CAAC;AACrE,MAAM,MAAM,qCAAqC,GAC/C,6BAA6B,CAAC;AAEhC,KAAK,+BAA+B,GAAG;IACrC,OAAO,EAAE,6BAA6B,CAAC;IACvC,GAAG,EAAE,4BAA4B,CAAC;CACnC,CAAC;AAEF,eAAO,MAAM,wBAAwB,SAC7B,uCAAuC,KAC5C,+BAYF,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,uCAAuC,EAC7C,UAAU,EAAE,MAAM,GACjB,MAAM,CAKR"}
1
+ {"version":3,"file":"storage-schema.d.mts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH;;;GAGG;AACH,eAAO,MAAM,0BAA0B;;;;CAItC,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC;AACnD,MAAM,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAClD,MAAM,MAAM,uCAAuC,GACjD,GAAG,6BAA6B,IAAI,4BAA4B,EAAE,CAAC;AACrE,MAAM,MAAM,qCAAqC,GAC/C,6BAA6B,CAAC;AAEhC,KAAK,+BAA+B,GAAG;IACrC,OAAO,EAAE,6BAA6B,CAAC;IACvC,GAAG,EAAE,4BAA4B,CAAC;CACnC,CAAC;AAEF,eAAO,MAAM,wBAAwB,SAC7B,uCAAuC,KAC5C,+BAYF,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,uCAAuC,EAC7C,UAAU,EAAE,MAAM,GACjB,MAAM,CAKR"}
@@ -11,7 +11,6 @@ export const USER_STORAGE_FEATURE_NAMES = {
11
11
  notifications: 'notifications',
12
12
  accounts: 'accounts_v2',
13
13
  addressBook: 'addressBook',
14
- rampsAutoramps: 'rampsAutoramps',
15
14
  };
16
15
  export const getFeatureAndKeyFromPath = (path) => {
17
16
  const pathRegex = /^\w+\.\w+$/u;
@@ -1 +1 @@
1
- {"version":3,"file":"storage-schema.mjs","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,+BAA8B;AAEzD;;;GAGG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,aAAa,EAAE,eAAe;IAC9B,QAAQ,EAAE,aAAa;IACvB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,gBAAgB;CACjC,CAAC;AAcF,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,IAA6C,EACZ,EAAE;IACnC,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEvC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAqC,CAAC;AAC7D,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,IAA6C,EAC7C,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,wBAAwB,CAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC","sourcesContent":["import { createSHA256Hash } from './encryption/index.js';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Any user storage path should be in the form of `feature.key`.\n */\n\n/**\n * Helper object that contains the feature names used in the controllers and SDK.\n * Developers don't need to add new feature names to this object anymore, as the schema enforcement has been deprecated.\n */\nexport const USER_STORAGE_FEATURE_NAMES = {\n notifications: 'notifications',\n accounts: 'accounts_v2',\n addressBook: 'addressBook',\n rampsAutoramps: 'rampsAutoramps',\n};\n\nexport type UserStorageGenericFeatureName = string;\nexport type UserStorageGenericFeatureKey = string;\nexport type UserStorageGenericPathWithFeatureAndKey =\n `${UserStorageGenericFeatureName}.${UserStorageGenericFeatureKey}`;\nexport type UserStorageGenericPathWithFeatureOnly =\n UserStorageGenericFeatureName;\n\ntype UserStorageGenericFeatureAndKey = {\n feature: UserStorageGenericFeatureName;\n key: UserStorageGenericFeatureKey;\n};\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStorageGenericPathWithFeatureAndKey,\n): UserStorageGenericFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.');\n\n return { feature, key } as UserStorageGenericFeatureAndKey;\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStorageGenericPathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
1
+ {"version":3,"file":"storage-schema.mjs","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,+BAA8B;AAEzD;;;GAGG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,aAAa,EAAE,eAAe;IAC9B,QAAQ,EAAE,aAAa;IACvB,WAAW,EAAE,aAAa;CAC3B,CAAC;AAcF,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,IAA6C,EACZ,EAAE;IACnC,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEvC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAqC,CAAC;AAC7D,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,IAA6C,EAC7C,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,wBAAwB,CAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC","sourcesContent":["import { createSHA256Hash } from './encryption/index.js';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Any user storage path should be in the form of `feature.key`.\n */\n\n/**\n * Helper object that contains the feature names used in the controllers and SDK.\n * Developers don't need to add new feature names to this object anymore, as the schema enforcement has been deprecated.\n */\nexport const USER_STORAGE_FEATURE_NAMES = {\n notifications: 'notifications',\n accounts: 'accounts_v2',\n addressBook: 'addressBook',\n};\n\nexport type UserStorageGenericFeatureName = string;\nexport type UserStorageGenericFeatureKey = string;\nexport type UserStorageGenericPathWithFeatureAndKey =\n `${UserStorageGenericFeatureName}.${UserStorageGenericFeatureKey}`;\nexport type UserStorageGenericPathWithFeatureOnly =\n UserStorageGenericFeatureName;\n\ntype UserStorageGenericFeatureAndKey = {\n feature: UserStorageGenericFeatureName;\n key: UserStorageGenericFeatureKey;\n};\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStorageGenericPathWithFeatureAndKey,\n): UserStorageGenericFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.');\n\n return { feature, key } as UserStorageGenericFeatureAndKey;\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStorageGenericPathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHdKeyringSeed = void 0;
4
+ /**
5
+ * HD keyring seed access for native SIP-6 message signing.
6
+ *
7
+ * This mirrors `@metamask/snaps-rpc-methods` `getMnemonicSeed` (when called
8
+ * with an entropy source id):
9
+ * `KeyringController:withKeyringV2Unsafe` → assert HD → return `keyring.seed`.
10
+ *
11
+ * Those helpers are not a public export of snaps-rpc-methods, so this thin wrapper lives here.
12
+ *
13
+ * @see https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts
14
+ */
15
+ /**
16
+ * V2 HD keyring type (`KeyringType.Hd`). The template type keeps the literal
17
+ * aligned with `@metamask/keyring-api/v2` without a runtime dependency.
18
+ */
19
+ const HD_KEYRING_TYPE = 'hd';
20
+ const ENTROPY_SOURCE_NOT_FOUND_ERROR = 'Entropy source not found or is not an HD keyring.';
21
+ /**
22
+ * Reads the BIP-39 seed for an HD keyring entropy source via
23
+ * `KeyringController:withKeyringV2Unsafe`.
24
+ *
25
+ * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a
26
+ * concrete entropy source id.
27
+ *
28
+ * @param messenger - Messenger that can call `withKeyringV2Unsafe`.
29
+ * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).
30
+ * @returns The HD keyring seed.
31
+ * @throws If the keyring is missing or is not an HD keyring with a seed.
32
+ */
33
+ async function getHdKeyringSeed(messenger, entropySourceId) {
34
+ try {
35
+ const keyringData = (await messenger.call('KeyringController:withKeyringV2Unsafe', { id: entropySourceId }, async ({ keyring }) => {
36
+ const hdKeyring = keyring;
37
+ return { type: hdKeyring.type, seed: hdKeyring.seed };
38
+ }));
39
+ if (keyringData.type !== HD_KEYRING_TYPE || !keyringData.seed) {
40
+ throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);
41
+ }
42
+ return keyringData.seed;
43
+ }
44
+ catch {
45
+ throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);
46
+ }
47
+ }
48
+ exports.getHdKeyringSeed = getHdKeyringSeed;
49
+ //# sourceMappingURL=hd-keyring-seed.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-seed.cjs","sourceRoot":"","sources":["../../../src/shared/utils/hd-keyring-seed.ts"],"names":[],"mappings":";;;AAKA;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,MAAM,eAAe,GAAwB,IAAI,CAAC;AAElD,MAAM,8BAA8B,GAClC,mDAAmD,CAAC;AAiBtD;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,gBAAgB,CACpC,SAAuC,EACvC,eAAuB;IAEvB,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CACvC,uCAAuC,EACvC,EAAE,EAAE,EAAE,eAAe,EAAE,EACvB,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;YACpB,MAAM,SAAS,GAAG,OAAoB,CAAC;YACvC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC;QACxD,CAAC,CACF,CAA+C,CAAC;QAEjD,IAAI,WAAW,CAAC,IAAI,KAAK,eAAe,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC9D,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;QAClD,CAAC;QAED,OAAO,WAAW,CAAC,IAAI,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AAtBD,4CAsBC","sourcesContent":["import type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type { KeyringType } from '@metamask/keyring-api/v2';\nimport type { KeyringControllerWithKeyringV2UnsafeAction } from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\n\n/**\n * HD keyring seed access for native SIP-6 message signing.\n *\n * This mirrors `@metamask/snaps-rpc-methods` `getMnemonicSeed` (when called\n * with an entropy source id):\n * `KeyringController:withKeyringV2Unsafe` → assert HD → return `keyring.seed`.\n *\n * Those helpers are not a public export of snaps-rpc-methods, so this thin wrapper lives here.\n *\n * @see https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts\n */\n\n/**\n * V2 HD keyring type (`KeyringType.Hd`). The template type keeps the literal\n * aligned with `@metamask/keyring-api/v2` without a runtime dependency.\n */\nconst HD_KEYRING_TYPE: `${KeyringType.Hd}` = 'hd';\n\nconst ENTROPY_SOURCE_NOT_FOUND_ERROR =\n 'Entropy source not found or is not an HD keyring.';\n\n/**\n * Structural messenger shape for `withKeyringV2Unsafe`.\n *\n * Not `Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>` because\n * `Messenger` is invariant in its action union — Auth / UserStorage messengers\n * (which allow additional actions) are not assignable to that narrow type.\n */\ntype MessengerWithKeyringV2Unsafe = {\n call: (\n ...args: Parameters<\n Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>['call']\n >\n ) => unknown;\n};\n\n/**\n * Reads the BIP-39 seed for an HD keyring entropy source via\n * `KeyringController:withKeyringV2Unsafe`.\n *\n * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a\n * concrete entropy source id.\n *\n * @param messenger - Messenger that can call `withKeyringV2Unsafe`.\n * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).\n * @returns The HD keyring seed.\n * @throws If the keyring is missing or is not an HD keyring with a seed.\n */\nexport async function getHdKeyringSeed(\n messenger: MessengerWithKeyringV2Unsafe,\n entropySourceId: string,\n): Promise<Uint8Array> {\n try {\n const keyringData = (await messenger.call(\n 'KeyringController:withKeyringV2Unsafe',\n { id: entropySourceId },\n async ({ keyring }) => {\n const hdKeyring = keyring as HdKeyring;\n return { type: hdKeyring.type, seed: hdKeyring.seed };\n },\n )) as { type: string; seed?: Uint8Array | null };\n\n if (keyringData.type !== HD_KEYRING_TYPE || !keyringData.seed) {\n throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);\n }\n\n return keyringData.seed;\n } catch {\n throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import type { KeyringControllerWithKeyringV2UnsafeAction } from "@metamask/keyring-controller";
2
+ import type { Messenger } from "@metamask/messenger";
3
+ /**
4
+ * Structural messenger shape for `withKeyringV2Unsafe`.
5
+ *
6
+ * Not `Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>` because
7
+ * `Messenger` is invariant in its action union — Auth / UserStorage messengers
8
+ * (which allow additional actions) are not assignable to that narrow type.
9
+ */
10
+ type MessengerWithKeyringV2Unsafe = {
11
+ call: (...args: Parameters<Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>['call']>) => unknown;
12
+ };
13
+ /**
14
+ * Reads the BIP-39 seed for an HD keyring entropy source via
15
+ * `KeyringController:withKeyringV2Unsafe`.
16
+ *
17
+ * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a
18
+ * concrete entropy source id.
19
+ *
20
+ * @param messenger - Messenger that can call `withKeyringV2Unsafe`.
21
+ * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).
22
+ * @returns The HD keyring seed.
23
+ * @throws If the keyring is missing or is not an HD keyring with a seed.
24
+ */
25
+ export declare function getHdKeyringSeed(messenger: MessengerWithKeyringV2Unsafe, entropySourceId: string): Promise<Uint8Array>;
26
+ export {};
27
+ //# sourceMappingURL=hd-keyring-seed.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-seed.d.cts","sourceRoot":"","sources":["../../../src/shared/utils/hd-keyring-seed.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0CAA0C,EAAE,qCAAqC;AAC/F,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAuBrD;;;;;;GAMG;AACH,KAAK,4BAA4B,GAAG;IAClC,IAAI,EAAE,CACJ,GAAG,IAAI,EAAE,UAAU,CACjB,SAAS,CAAC,MAAM,EAAE,0CAA0C,CAAC,CAAC,MAAM,CAAC,CACtE,KACE,OAAO,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,gBAAgB,CACpC,SAAS,EAAE,4BAA4B,EACvC,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,UAAU,CAAC,CAmBrB"}
@@ -0,0 +1,27 @@
1
+ import type { KeyringControllerWithKeyringV2UnsafeAction } from "@metamask/keyring-controller";
2
+ import type { Messenger } from "@metamask/messenger";
3
+ /**
4
+ * Structural messenger shape for `withKeyringV2Unsafe`.
5
+ *
6
+ * Not `Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>` because
7
+ * `Messenger` is invariant in its action union — Auth / UserStorage messengers
8
+ * (which allow additional actions) are not assignable to that narrow type.
9
+ */
10
+ type MessengerWithKeyringV2Unsafe = {
11
+ call: (...args: Parameters<Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>['call']>) => unknown;
12
+ };
13
+ /**
14
+ * Reads the BIP-39 seed for an HD keyring entropy source via
15
+ * `KeyringController:withKeyringV2Unsafe`.
16
+ *
17
+ * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a
18
+ * concrete entropy source id.
19
+ *
20
+ * @param messenger - Messenger that can call `withKeyringV2Unsafe`.
21
+ * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).
22
+ * @returns The HD keyring seed.
23
+ * @throws If the keyring is missing or is not an HD keyring with a seed.
24
+ */
25
+ export declare function getHdKeyringSeed(messenger: MessengerWithKeyringV2Unsafe, entropySourceId: string): Promise<Uint8Array>;
26
+ export {};
27
+ //# sourceMappingURL=hd-keyring-seed.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-seed.d.mts","sourceRoot":"","sources":["../../../src/shared/utils/hd-keyring-seed.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0CAA0C,EAAE,qCAAqC;AAC/F,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAuBrD;;;;;;GAMG;AACH,KAAK,4BAA4B,GAAG;IAClC,IAAI,EAAE,CACJ,GAAG,IAAI,EAAE,UAAU,CACjB,SAAS,CAAC,MAAM,EAAE,0CAA0C,CAAC,CAAC,MAAM,CAAC,CACtE,KACE,OAAO,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,gBAAgB,CACpC,SAAS,EAAE,4BAA4B,EACvC,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,UAAU,CAAC,CAmBrB"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * HD keyring seed access for native SIP-6 message signing.
3
+ *
4
+ * This mirrors `@metamask/snaps-rpc-methods` `getMnemonicSeed` (when called
5
+ * with an entropy source id):
6
+ * `KeyringController:withKeyringV2Unsafe` → assert HD → return `keyring.seed`.
7
+ *
8
+ * Those helpers are not a public export of snaps-rpc-methods, so this thin wrapper lives here.
9
+ *
10
+ * @see https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts
11
+ */
12
+ /**
13
+ * V2 HD keyring type (`KeyringType.Hd`). The template type keeps the literal
14
+ * aligned with `@metamask/keyring-api/v2` without a runtime dependency.
15
+ */
16
+ const HD_KEYRING_TYPE = 'hd';
17
+ const ENTROPY_SOURCE_NOT_FOUND_ERROR = 'Entropy source not found or is not an HD keyring.';
18
+ /**
19
+ * Reads the BIP-39 seed for an HD keyring entropy source via
20
+ * `KeyringController:withKeyringV2Unsafe`.
21
+ *
22
+ * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a
23
+ * concrete entropy source id.
24
+ *
25
+ * @param messenger - Messenger that can call `withKeyringV2Unsafe`.
26
+ * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).
27
+ * @returns The HD keyring seed.
28
+ * @throws If the keyring is missing or is not an HD keyring with a seed.
29
+ */
30
+ export async function getHdKeyringSeed(messenger, entropySourceId) {
31
+ try {
32
+ const keyringData = (await messenger.call('KeyringController:withKeyringV2Unsafe', { id: entropySourceId }, async ({ keyring }) => {
33
+ const hdKeyring = keyring;
34
+ return { type: hdKeyring.type, seed: hdKeyring.seed };
35
+ }));
36
+ if (keyringData.type !== HD_KEYRING_TYPE || !keyringData.seed) {
37
+ throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);
38
+ }
39
+ return keyringData.seed;
40
+ }
41
+ catch {
42
+ throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);
43
+ }
44
+ }
45
+ //# sourceMappingURL=hd-keyring-seed.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-seed.mjs","sourceRoot":"","sources":["../../../src/shared/utils/hd-keyring-seed.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AAEH;;;GAGG;AACH,MAAM,eAAe,GAAwB,IAAI,CAAC;AAElD,MAAM,8BAA8B,GAClC,mDAAmD,CAAC;AAiBtD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,SAAuC,EACvC,eAAuB;IAEvB,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CACvC,uCAAuC,EACvC,EAAE,EAAE,EAAE,eAAe,EAAE,EACvB,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;YACpB,MAAM,SAAS,GAAG,OAAoB,CAAC;YACvC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC;QACxD,CAAC,CACF,CAA+C,CAAC;QAEjD,IAAI,WAAW,CAAC,IAAI,KAAK,eAAe,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC9D,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;QAClD,CAAC;QAED,OAAO,WAAW,CAAC,IAAI,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["import type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type { KeyringType } from '@metamask/keyring-api/v2';\nimport type { KeyringControllerWithKeyringV2UnsafeAction } from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\n\n/**\n * HD keyring seed access for native SIP-6 message signing.\n *\n * This mirrors `@metamask/snaps-rpc-methods` `getMnemonicSeed` (when called\n * with an entropy source id):\n * `KeyringController:withKeyringV2Unsafe` → assert HD → return `keyring.seed`.\n *\n * Those helpers are not a public export of snaps-rpc-methods, so this thin wrapper lives here.\n *\n * @see https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts\n */\n\n/**\n * V2 HD keyring type (`KeyringType.Hd`). The template type keeps the literal\n * aligned with `@metamask/keyring-api/v2` without a runtime dependency.\n */\nconst HD_KEYRING_TYPE: `${KeyringType.Hd}` = 'hd';\n\nconst ENTROPY_SOURCE_NOT_FOUND_ERROR =\n 'Entropy source not found or is not an HD keyring.';\n\n/**\n * Structural messenger shape for `withKeyringV2Unsafe`.\n *\n * Not `Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>` because\n * `Messenger` is invariant in its action union — Auth / UserStorage messengers\n * (which allow additional actions) are not assignable to that narrow type.\n */\ntype MessengerWithKeyringV2Unsafe = {\n call: (\n ...args: Parameters<\n Messenger<string, KeyringControllerWithKeyringV2UnsafeAction>['call']\n >\n ) => unknown;\n};\n\n/**\n * Reads the BIP-39 seed for an HD keyring entropy source via\n * `KeyringController:withKeyringV2Unsafe`.\n *\n * Equivalent to snaps-rpc-methods `getMnemonicSeed(messenger, source)` for a\n * concrete entropy source id.\n *\n * @param messenger - Messenger that can call `withKeyringV2Unsafe`.\n * @param entropySourceId - Keyring metadata ID (SIP-30 entropy source).\n * @returns The HD keyring seed.\n * @throws If the keyring is missing or is not an HD keyring with a seed.\n */\nexport async function getHdKeyringSeed(\n messenger: MessengerWithKeyringV2Unsafe,\n entropySourceId: string,\n): Promise<Uint8Array> {\n try {\n const keyringData = (await messenger.call(\n 'KeyringController:withKeyringV2Unsafe',\n { id: entropySourceId },\n async ({ keyring }) => {\n const hdKeyring = keyring as HdKeyring;\n return { type: hdKeyring.type, seed: hdKeyring.seed };\n },\n )) as { type: string; seed?: Uint8Array | null };\n\n if (keyringData.type !== HD_KEYRING_TYPE || !keyringData.seed) {\n throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);\n }\n\n return keyringData.seed;\n } catch {\n throw new Error(ENTROPY_SOURCE_NOT_FOUND_ERROR);\n }\n}\n"]}