@metamask-previews/profile-sync-controller 29.0.0-preview-4758e65ff → 29.0.0-preview-bbf9454b2

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 (42) hide show
  1. package/CHANGELOG.md +3 -0
  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/utils/hd-keyring-seed.cjs +49 -0
  19. package/dist/shared/utils/hd-keyring-seed.cjs.map +1 -0
  20. package/dist/shared/utils/hd-keyring-seed.d.cts +27 -0
  21. package/dist/shared/utils/hd-keyring-seed.d.cts.map +1 -0
  22. package/dist/shared/utils/hd-keyring-seed.d.mts +27 -0
  23. package/dist/shared/utils/hd-keyring-seed.d.mts.map +1 -0
  24. package/dist/shared/utils/hd-keyring-seed.mjs +45 -0
  25. package/dist/shared/utils/hd-keyring-seed.mjs.map +1 -0
  26. package/dist/shared/utils/message-signing.cjs +147 -0
  27. package/dist/shared/utils/message-signing.cjs.map +1 -0
  28. package/dist/shared/utils/message-signing.d.cts +73 -0
  29. package/dist/shared/utils/message-signing.d.cts.map +1 -0
  30. package/dist/shared/utils/message-signing.d.mts +73 -0
  31. package/dist/shared/utils/message-signing.d.mts.map +1 -0
  32. package/dist/shared/utils/message-signing.mjs +140 -0
  33. package/dist/shared/utils/message-signing.mjs.map +1 -0
  34. package/package.json +4 -4
  35. package/dist/controllers/authentication/auth-snap-requests.cjs +0 -44
  36. package/dist/controllers/authentication/auth-snap-requests.cjs.map +0 -1
  37. package/dist/controllers/authentication/auth-snap-requests.d.cts +0 -21
  38. package/dist/controllers/authentication/auth-snap-requests.d.cts.map +0 -1
  39. package/dist/controllers/authentication/auth-snap-requests.d.mts +0 -21
  40. package/dist/controllers/authentication/auth-snap-requests.d.mts.map +0 -1
  41. package/dist/controllers/authentication/auth-snap-requests.mjs +0 -39
  42. 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;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,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,0BAA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CAAY,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;AAE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Ae,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"]}
@@ -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"]}
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signMessageWithMessageSigningKey = exports.getMessageSigningPublicKey = exports.deriveMessageSigningPrivateKey = exports.deriveSip6PrivateKey = exports.MESSAGE_SIGNING_SNAP_ID = void 0;
4
+ const key_tree_1 = require("@metamask/key-tree");
5
+ const utils_1 = require("@metamask/utils");
6
+ const secp256k1_1 = require("@noble/curves/secp256k1");
7
+ const hmac_1 = require("@noble/hashes/hmac");
8
+ const sha2_1 = require("@noble/hashes/sha2");
9
+ const sha3_1 = require("@noble/hashes/sha3");
10
+ /**
11
+ * Native SIP-6 message-signing helpers for AuthenticationController /
12
+ * UserStorageController.
13
+ *
14
+ * These are intentional copies of the message-signing snap crypto path so auth
15
+ * and user-storage can derive/sign without booting
16
+ * `npm:@metamask/message-signing-snap`. Behavior must stay byte-identical to:
17
+ *
18
+ * - SIP-6 derivation:
19
+ * `@metamask/snaps-rpc-methods` `deriveEntropyFromSeed` /
20
+ * `getEntropyDerivationPath` / `getDerivationPathArray`
21
+ * (https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts)
22
+ * - Magic constant:
23
+ * `@metamask/snaps-utils` `SIP_6_MAGIC_VALUE`
24
+ * - Pubkey + `metamask:…` signing:
25
+ * `@metamask/message-signing-snap` `getPublicEntropyKey` /
26
+ * `signMessageWithEntropyKey`
27
+ * (https://github.com/MetaMask/message-signing-snap/blob/main/src/entropy-keys.ts)
28
+ *
29
+ * `deriveEntropyFromSeed` is not a public export of
30
+ * `@metamask/snaps-rpc-methods` today (and no core package depends on that
31
+ * package), so the SIP-6 math is vendored here rather than imported.
32
+ */
33
+ /**
34
+ * Snap ID used as the SIP-6 `input` so derived keys match
35
+ * `@metamask/message-signing-snap` (`snap_getEntropy` origin).
36
+ */
37
+ exports.MESSAGE_SIGNING_SNAP_ID = 'npm:@metamask/message-signing-snap';
38
+ /**
39
+ * Copy of `@metamask/snaps-utils` `SIP_6_MAGIC_VALUE`
40
+ * (`0xd36e6170 - 0x80000000`).
41
+ *
42
+ * @see https://metamask.github.io/SIPs/SIPS/sip-6
43
+ */
44
+ const SIP_6_MAGIC_VALUE = `1399742832'`;
45
+ const HARDENED_VALUE = 0x80000000;
46
+ /**
47
+ * HMAC-SHA-512 for `@metamask/key-tree`.
48
+ *
49
+ * Passed into `SLIP10Node.fromSeed` so SIP-6 never uses Web Crypto.
50
+ * `@metamask/key-tree` treats any `crypto.subtle` as complete and then HMAC
51
+ * via `importKey` / `sign`. React Native only implements `digest`; its
52
+ * SubtleCrypto cannot HMAC. Noble HMAC is byte-identical without SubtleCrypto.
53
+ */
54
+ const NOBLE_HMAC_SHA512 = {
55
+ hmacSha512: async (key, data) => (0, hmac_1.hmac)(sha2_1.sha512, key, data),
56
+ };
57
+ /**
58
+ * Copy of `@metamask/snaps-rpc-methods` `getDerivationPathArray`.
59
+ *
60
+ * Maps a 32-byte hash to eight hardened BIP-32 indices for `@metamask/key-tree`.
61
+ *
62
+ * @param hash - 32-byte hash.
63
+ * @returns Hardened BIP-32 path nodes.
64
+ */
65
+ function getDerivationPathArray(hash) {
66
+ const array = [];
67
+ const view = (0, utils_1.createDataView)(hash);
68
+ for (let index = 0; index < 8; index++) {
69
+ const uint32 = view.getUint32(index * 4);
70
+ // eslint-disable-next-line no-bitwise
71
+ const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;
72
+ array.push(`bip32:${pathIndex - HARDENED_VALUE}'`);
73
+ }
74
+ return array;
75
+ }
76
+ /**
77
+ * Copy of `@metamask/snaps-rpc-methods` `deriveEntropyFromSeed` (SIP-6),
78
+ * returning raw private-key bytes instead of a `0x`-prefixed hex string.
79
+ *
80
+ * @param options - Derivation options.
81
+ * @param options.seed - BIP-39 mnemonic seed.
82
+ * @param options.input - SIP-6 input (snap ID for `snap_getEntropy`).
83
+ * @param options.salt - Optional salt. Internal auth uses `''`.
84
+ * @returns 32-byte private key.
85
+ */
86
+ async function deriveSip6PrivateKey({ seed, input, salt = '', }) {
87
+ const hash = (0, sha3_1.keccak_256)((0, utils_1.concatBytes)([(0, utils_1.stringToBytes)(input), (0, sha3_1.keccak_256)((0, utils_1.stringToBytes)(salt))]));
88
+ const computedDerivationPath = getDerivationPathArray(hash);
89
+ const { privateKey } = await key_tree_1.SLIP10Node.fromSeed({
90
+ derivationPath: [
91
+ seed,
92
+ `bip32:${SIP_6_MAGIC_VALUE}`,
93
+ ...computedDerivationPath,
94
+ ],
95
+ curve: 'secp256k1',
96
+ }, NOBLE_HMAC_SHA512);
97
+ (0, utils_1.assert)(privateKey, 'Failed to derive SIP-6 entropy.');
98
+ return (0, utils_1.hexToBytes)(privateKey);
99
+ }
100
+ exports.deriveSip6PrivateKey = deriveSip6PrivateKey;
101
+ /**
102
+ * Derives the message-signing private key via SIP-6, matching
103
+ * `snap_getEntropy` for the message-signing snap with empty salt
104
+ * (internal `metamask` origin).
105
+ *
106
+ * @param seed - BIP-39 mnemonic seed from an HD keyring.
107
+ * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.
108
+ * @returns 32-byte private key.
109
+ */
110
+ async function deriveMessageSigningPrivateKey(seed, salt = '') {
111
+ return deriveSip6PrivateKey({
112
+ seed,
113
+ input: exports.MESSAGE_SIGNING_SNAP_ID,
114
+ salt,
115
+ });
116
+ }
117
+ exports.deriveMessageSigningPrivateKey = deriveMessageSigningPrivateKey;
118
+ /**
119
+ * Copy of message-signing-snap `getPublicEntropyKey`: secp256k1 pubkey hex
120
+ * for the SIP-6 message-signing private key.
121
+ *
122
+ * @param seed - BIP-39 mnemonic seed from an HD keyring.
123
+ * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.
124
+ * @returns Public key hex with `0x` prefix.
125
+ */
126
+ async function getMessageSigningPublicKey(seed, salt = '') {
127
+ const privateKey = await deriveMessageSigningPrivateKey(seed, salt);
128
+ return (0, utils_1.bytesToHex)(secp256k1_1.secp256k1.getPublicKey(privateKey));
129
+ }
130
+ exports.getMessageSigningPublicKey = getMessageSigningPublicKey;
131
+ /**
132
+ * Copy of message-signing-snap `signMessageWithEntropyKey`: sha256(message)
133
+ * then compact secp256k1 signature.
134
+ *
135
+ * @param message - Message to sign (must be validated by the caller).
136
+ * @param seed - BIP-39 mnemonic seed from an HD keyring.
137
+ * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.
138
+ * @returns Compact secp256k1 signature hex with `0x` prefix.
139
+ */
140
+ async function signMessageWithMessageSigningKey(message, seed, salt = '') {
141
+ const privateKey = await deriveMessageSigningPrivateKey(seed, salt);
142
+ const digest = (0, sha2_1.sha256)(message);
143
+ const signature = secp256k1_1.secp256k1.sign(digest, privateKey);
144
+ return `0x${signature.toCompactHex()}`;
145
+ }
146
+ exports.signMessageWithMessageSigningKey = signMessageWithMessageSigningKey;
147
+ //# sourceMappingURL=message-signing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message-signing.cjs","sourceRoot":"","sources":["../../../src/shared/utils/message-signing.ts"],"names":[],"mappings":";;;AACA,iDAAgD;AAChD,2CAOyB;AACzB,uDAAoD;AACpD,6CAA0C;AAC1C,6CAAoD;AACpD,6CAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;GAGG;AACU,QAAA,uBAAuB,GAAG,oCAAoC,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,aAA6B,CAAC;AAExD,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,iBAAiB,GAAG;IACxB,UAAU,EAAE,KAAK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CAAiC,CAAC,CAAC;IACtD,OAAO,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;AAChC,CAAC;AA5BD,oDA4BC;AAED;;;;;;;;GAQG;AACI,KAAK,UAAU,8BAA8B,CAClD,IAAgB,EAChB,IAAI,GAAG,EAAE;IAET,OAAO,oBAAoB,CAAC;QAC1B,IAAI;QACJ,KAAK,EAAE,+BAAuB;QAC9B,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AATD,wEASC;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,0BAA0B,CAC9C,IAAgB,EAChB,IAAI,GAAG,EAAE;IAET,MAAM,UAAU,GAAG,MAAM,8BAA8B,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACpE,OAAO,IAAA,kBAAU,EAAC,qBAAS,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC;AACxD,CAAC;AAND,gEAMC;AAED;;;;;;;;GAQG;AACI,KAAK,UAAU,gCAAgC,CACpD,OAAe,EACf,IAAgB,EAChB,IAAI,GAAG,EAAE;IAET,MAAM,UAAU,GAAG,MAAM,8BAA8B,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACpE,MAAM,MAAM,GAAG,IAAA,aAAM,EAAC,OAAO,CAAC,CAAC;IAC/B,MAAM,SAAS,GAAG,qBAAS,CAAC,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACrD,OAAO,KAAK,SAAS,CAAC,YAAY,EAAE,EAAE,CAAC;AACzC,CAAC;AATD,4EASC","sourcesContent":["import type { HardenedBIP32Node } from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport {\n assert,\n bytesToHex,\n concatBytes,\n createDataView,\n hexToBytes,\n stringToBytes,\n} from '@metamask/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\n/**\n * Native SIP-6 message-signing helpers for AuthenticationController /\n * UserStorageController.\n *\n * These are intentional copies of the message-signing snap crypto path so auth\n * and user-storage can derive/sign without booting\n * `npm:@metamask/message-signing-snap`. Behavior must stay byte-identical to:\n *\n * - SIP-6 derivation:\n * `@metamask/snaps-rpc-methods` `deriveEntropyFromSeed` /\n * `getEntropyDerivationPath` / `getDerivationPathArray`\n * (https://github.com/MetaMask/snaps/blob/main/packages/snaps-rpc-methods/src/utils.ts)\n * - Magic constant:\n * `@metamask/snaps-utils` `SIP_6_MAGIC_VALUE`\n * - Pubkey + `metamask:…` signing:\n * `@metamask/message-signing-snap` `getPublicEntropyKey` /\n * `signMessageWithEntropyKey`\n * (https://github.com/MetaMask/message-signing-snap/blob/main/src/entropy-keys.ts)\n *\n * `deriveEntropyFromSeed` is not a public export of\n * `@metamask/snaps-rpc-methods` today (and no core package depends on that\n * package), so the SIP-6 math is vendored here rather than imported.\n */\n\n/**\n * Snap ID used as the SIP-6 `input` so derived keys match\n * `@metamask/message-signing-snap` (`snap_getEntropy` origin).\n */\nexport const MESSAGE_SIGNING_SNAP_ID = 'npm:@metamask/message-signing-snap';\n\n/**\n * Copy of `@metamask/snaps-utils` `SIP_6_MAGIC_VALUE`\n * (`0xd36e6170 - 0x80000000`).\n *\n * @see https://metamask.github.io/SIPs/SIPS/sip-6\n */\nconst SIP_6_MAGIC_VALUE = `1399742832'` as `${number}'`;\n\nconst HARDENED_VALUE = 0x80000000;\n\n/**\n * HMAC-SHA-512 for `@metamask/key-tree`.\n *\n * Passed into `SLIP10Node.fromSeed` so SIP-6 never uses Web Crypto.\n * `@metamask/key-tree` treats any `crypto.subtle` as complete and then HMAC\n * via `importKey` / `sign`. React Native only implements `digest`; its\n * SubtleCrypto cannot HMAC. Noble HMAC is byte-identical without SubtleCrypto.\n */\nconst NOBLE_HMAC_SHA512 = {\n hmacSha512: async (key: Uint8Array, data: Uint8Array): Promise<Uint8Array> =>\n hmac(sha512, key, data),\n};\n\n/**\n * Copy of `@metamask/snaps-rpc-methods` `getDerivationPathArray`.\n *\n * Maps a 32-byte hash to eight hardened BIP-32 indices for `@metamask/key-tree`.\n *\n * @param hash - 32-byte hash.\n * @returns Hardened BIP-32 path nodes.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\n/**\n * Copy of `@metamask/snaps-rpc-methods` `deriveEntropyFromSeed` (SIP-6),\n * returning raw private-key bytes instead of a `0x`-prefixed hex string.\n *\n * @param options - Derivation options.\n * @param options.seed - BIP-39 mnemonic seed.\n * @param options.input - SIP-6 input (snap ID for `snap_getEntropy`).\n * @param options.salt - Optional salt. Internal auth uses `''`.\n * @returns 32-byte private key.\n */\nexport async function deriveSip6PrivateKey({\n seed,\n input,\n salt = '',\n}: {\n seed: Uint8Array;\n input: string;\n salt?: string;\n}): Promise<Uint8Array> {\n const hash = keccak256(\n concatBytes([stringToBytes(input), keccak256(stringToBytes(salt))]),\n );\n const computedDerivationPath = getDerivationPathArray(hash);\n\n const { privateKey } = await SLIP10Node.fromSeed(\n {\n derivationPath: [\n seed,\n `bip32:${SIP_6_MAGIC_VALUE}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n NOBLE_HMAC_SHA512,\n );\n\n assert(privateKey, 'Failed to derive SIP-6 entropy.');\n return hexToBytes(privateKey);\n}\n\n/**\n * Derives the message-signing private key via SIP-6, matching\n * `snap_getEntropy` for the message-signing snap with empty salt\n * (internal `metamask` origin).\n *\n * @param seed - BIP-39 mnemonic seed from an HD keyring.\n * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.\n * @returns 32-byte private key.\n */\nexport async function deriveMessageSigningPrivateKey(\n seed: Uint8Array,\n salt = '',\n): Promise<Uint8Array> {\n return deriveSip6PrivateKey({\n seed,\n input: MESSAGE_SIGNING_SNAP_ID,\n salt,\n });\n}\n\n/**\n * Copy of message-signing-snap `getPublicEntropyKey`: secp256k1 pubkey hex\n * for the SIP-6 message-signing private key.\n *\n * @param seed - BIP-39 mnemonic seed from an HD keyring.\n * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.\n * @returns Public key hex with `0x` prefix.\n */\nexport async function getMessageSigningPublicKey(\n seed: Uint8Array,\n salt = '',\n): Promise<string> {\n const privateKey = await deriveMessageSigningPrivateKey(seed, salt);\n return bytesToHex(secp256k1.getPublicKey(privateKey));\n}\n\n/**\n * Copy of message-signing-snap `signMessageWithEntropyKey`: sha256(message)\n * then compact secp256k1 signature.\n *\n * @param message - Message to sign (must be validated by the caller).\n * @param seed - BIP-39 mnemonic seed from an HD keyring.\n * @param salt - Optional SIP-6 salt. Auth / user-storage use `''`.\n * @returns Compact secp256k1 signature hex with `0x` prefix.\n */\nexport async function signMessageWithMessageSigningKey(\n message: string,\n seed: Uint8Array,\n salt = '',\n): Promise<string> {\n const privateKey = await deriveMessageSigningPrivateKey(seed, salt);\n const digest = sha256(message);\n const signature = secp256k1.sign(digest, privateKey);\n return `0x${signature.toCompactHex()}`;\n}\n"]}