@metamask/profile-sync-controller 3.1.0 → 3.2.0

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 (110) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/dist/controllers/authentication/services.cjs +10 -3
  3. package/dist/controllers/authentication/services.cjs.map +1 -1
  4. package/dist/controllers/authentication/services.d.cts.map +1 -1
  5. package/dist/controllers/authentication/services.d.mts.map +1 -1
  6. package/dist/controllers/authentication/services.mjs +14 -3
  7. package/dist/controllers/authentication/services.mjs.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.cjs +39 -218
  9. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  10. package/dist/controllers/user-storage/UserStorageController.d.cts +7 -2
  11. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  12. package/dist/controllers/user-storage/UserStorageController.d.mts +7 -2
  13. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  14. package/dist/controllers/user-storage/UserStorageController.mjs +36 -216
  15. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  16. package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.cts +1 -1
  17. package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.mts +1 -1
  18. package/dist/controllers/user-storage/__fixtures__/test-utils.cjs +45 -1
  19. package/dist/controllers/user-storage/__fixtures__/test-utils.cjs.map +1 -1
  20. package/dist/controllers/user-storage/__fixtures__/test-utils.d.cts +21 -0
  21. package/dist/controllers/user-storage/__fixtures__/test-utils.d.cts.map +1 -1
  22. package/dist/controllers/user-storage/__fixtures__/test-utils.d.mts +21 -0
  23. package/dist/controllers/user-storage/__fixtures__/test-utils.d.mts.map +1 -1
  24. package/dist/controllers/user-storage/__fixtures__/test-utils.mjs +38 -0
  25. package/dist/controllers/user-storage/__fixtures__/test-utils.mjs.map +1 -1
  26. package/dist/controllers/user-storage/{__fixtures__ → account-syncing/__fixtures__}/mockAccounts.cjs +3 -3
  27. package/dist/controllers/user-storage/account-syncing/__fixtures__/mockAccounts.cjs.map +1 -0
  28. package/dist/controllers/user-storage/{__fixtures__ → account-syncing/__fixtures__}/mockAccounts.d.cts +6 -6
  29. package/dist/controllers/user-storage/account-syncing/__fixtures__/mockAccounts.d.cts.map +1 -0
  30. package/dist/controllers/user-storage/{__fixtures__ → account-syncing/__fixtures__}/mockAccounts.d.mts +6 -6
  31. package/dist/controllers/user-storage/account-syncing/__fixtures__/mockAccounts.d.mts.map +1 -0
  32. package/dist/controllers/user-storage/{__fixtures__ → account-syncing/__fixtures__}/mockAccounts.mjs +3 -4
  33. package/dist/controllers/user-storage/account-syncing/__fixtures__/mockAccounts.mjs.map +1 -0
  34. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.cjs +50 -0
  35. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.cjs.map +1 -0
  36. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.cts +85 -0
  37. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.cts.map +1 -0
  38. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.mts +85 -0
  39. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.mts.map +1 -0
  40. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.mjs +44 -0
  41. package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.mjs.map +1 -0
  42. package/dist/controllers/user-storage/account-syncing/constants.cjs.map +1 -0
  43. package/dist/controllers/user-storage/account-syncing/constants.d.cts.map +1 -0
  44. package/dist/controllers/user-storage/account-syncing/constants.d.mts.map +1 -0
  45. package/dist/controllers/user-storage/account-syncing/constants.mjs.map +1 -0
  46. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +194 -0
  47. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +1 -0
  48. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts +31 -0
  49. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts.map +1 -0
  50. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts +31 -0
  51. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts.map +1 -0
  52. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +188 -0
  53. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +1 -0
  54. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs +35 -0
  55. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs.map +1 -0
  56. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts +8 -0
  57. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts.map +1 -0
  58. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts +8 -0
  59. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts.map +1 -0
  60. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs +31 -0
  61. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs.map +1 -0
  62. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs +47 -0
  63. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs.map +1 -0
  64. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts +20 -0
  65. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts.map +1 -0
  66. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts +20 -0
  67. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts.map +1 -0
  68. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs +41 -0
  69. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs.map +1 -0
  70. package/dist/controllers/user-storage/account-syncing/types.cjs +3 -0
  71. package/dist/controllers/user-storage/account-syncing/types.cjs.map +1 -0
  72. package/dist/controllers/user-storage/account-syncing/types.d.cts +26 -0
  73. package/dist/controllers/user-storage/account-syncing/types.d.cts.map +1 -0
  74. package/dist/controllers/user-storage/account-syncing/types.d.mts +26 -0
  75. package/dist/controllers/user-storage/account-syncing/types.d.mts.map +1 -0
  76. package/dist/controllers/user-storage/account-syncing/types.mjs +2 -0
  77. package/dist/controllers/user-storage/account-syncing/types.mjs.map +1 -0
  78. package/dist/controllers/user-storage/{accounts/user-storage.cjs → account-syncing/utils.cjs} +12 -2
  79. package/dist/controllers/user-storage/account-syncing/utils.cjs.map +1 -0
  80. package/dist/controllers/user-storage/account-syncing/utils.d.cts +23 -0
  81. package/dist/controllers/user-storage/account-syncing/utils.d.cts.map +1 -0
  82. package/dist/controllers/user-storage/account-syncing/utils.d.mts +23 -0
  83. package/dist/controllers/user-storage/account-syncing/utils.d.mts.map +1 -0
  84. package/dist/controllers/user-storage/{accounts/user-storage.mjs → account-syncing/utils.mjs} +10 -1
  85. package/dist/controllers/user-storage/account-syncing/utils.mjs.map +1 -0
  86. package/dist/controllers/user-storage/services.cjs +10 -10
  87. package/dist/controllers/user-storage/services.cjs.map +1 -1
  88. package/dist/controllers/user-storage/services.d.cts.map +1 -1
  89. package/dist/controllers/user-storage/services.d.mts.map +1 -1
  90. package/dist/controllers/user-storage/services.mjs +10 -10
  91. package/dist/controllers/user-storage/services.mjs.map +1 -1
  92. package/package.json +6 -5
  93. package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs.map +0 -1
  94. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts.map +0 -1
  95. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts.map +0 -1
  96. package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs.map +0 -1
  97. package/dist/controllers/user-storage/accounts/constants.cjs.map +0 -1
  98. package/dist/controllers/user-storage/accounts/constants.d.cts.map +0 -1
  99. package/dist/controllers/user-storage/accounts/constants.d.mts.map +0 -1
  100. package/dist/controllers/user-storage/accounts/constants.mjs.map +0 -1
  101. package/dist/controllers/user-storage/accounts/user-storage.cjs.map +0 -1
  102. package/dist/controllers/user-storage/accounts/user-storage.d.cts +0 -32
  103. package/dist/controllers/user-storage/accounts/user-storage.d.cts.map +0 -1
  104. package/dist/controllers/user-storage/accounts/user-storage.d.mts +0 -32
  105. package/dist/controllers/user-storage/accounts/user-storage.d.mts.map +0 -1
  106. package/dist/controllers/user-storage/accounts/user-storage.mjs.map +0 -1
  107. /package/dist/controllers/user-storage/{accounts → account-syncing}/constants.cjs +0 -0
  108. /package/dist/controllers/user-storage/{accounts → account-syncing}/constants.d.cts +0 -0
  109. /package/dist/controllers/user-storage/{accounts → account-syncing}/constants.d.mts +0 -0
  110. /package/dist/controllers/user-storage/{accounts → account-syncing}/constants.mjs +0 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.2.0]
11
+
12
+ ### Added
13
+
14
+ - feat: improve profile sync services logs ([#5101](https://github.com/MetaMask/core/pull/5101))
15
+
16
+ ### Changed
17
+
18
+ - feat: decouple account sync logic from `UserStorageController` ([#5078](https://github.com/MetaMask/core/pull/5078))
19
+ - Bump `@metamask/base-controller` from `^7.0.0` to `^7.1.0` ([#5079](https://github.com/MetaMask/core/pull/5079))
20
+
21
+ ## [3.1.1]
22
+
23
+ ### Changed
24
+
25
+ - Use new `@metamask/keyring-internal-api@^1.0.0`( [#4695](https://github.com/MetaMask/core/pull/4695))
26
+ - This package has been split out from the Keyring API.
27
+ - Bump `@metamask/keyring-api` from `^10.1.0` to `^12.0.0` ([#4695](https://github.com/MetaMask/core/pull/4695))
28
+
10
29
  ## [3.1.0]
11
30
 
12
31
  ### Changed
@@ -370,7 +389,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
370
389
 
371
390
  - Initial release
372
391
 
373
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@3.1.0...HEAD
392
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@3.2.0...HEAD
393
+ [3.2.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@3.1.1...@metamask/profile-sync-controller@3.2.0
394
+ [3.1.1]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@3.1.0...@metamask/profile-sync-controller@3.1.1
374
395
  [3.1.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@3.0.0...@metamask/profile-sync-controller@3.1.0
375
396
  [3.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@2.0.0...@metamask/profile-sync-controller@3.0.0
376
397
  [2.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@1.0.2...@metamask/profile-sync-controller@2.0.0
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.createLoginRawMessage = exports.getAccessToken = exports.login = exports.getNonce = exports.OIDC_TOKENS_ENDPOINT = exports.AUTH_LOGIN_ENDPOINT = exports.AUTH_NONCE_ENDPOINT = void 0;
7
+ const loglevel_1 = __importDefault(require("loglevel"));
4
8
  const env_1 = require("../../shared/env.cjs");
5
9
  const ENV_URLS = (0, env_1.getEnvUrls)(env_1.Env.PRD);
6
10
  const AUTH_ENDPOINT = ENV_URLS.authApiUrl;
@@ -30,13 +34,14 @@ async function getNonce(publicKey) {
30
34
  try {
31
35
  const nonceResponse = await fetch(nonceUrl.toString());
32
36
  if (!nonceResponse.ok) {
37
+ loglevel_1.default.error(`authentication-controller/services: unable to get nonce - HTTP ${nonceResponse.status}`);
33
38
  return null;
34
39
  }
35
40
  const nonceJson = await nonceResponse.json();
36
41
  return nonceJson?.nonce ?? null;
37
42
  }
38
43
  catch (e) {
39
- console.error('authentication-controller/services: unable to get nonce', e);
44
+ loglevel_1.default.error('authentication-controller/services: unable to get nonce', e);
40
45
  return null;
41
46
  }
42
47
  }
@@ -68,13 +73,14 @@ async function login(rawMessage, signature, clientMetaMetrics) {
68
73
  }),
69
74
  });
70
75
  if (!response.ok) {
76
+ loglevel_1.default.error(`authentication-controller/services: unable to login - HTTP ${response.status}`);
71
77
  return null;
72
78
  }
73
79
  const loginResponse = await response.json();
74
80
  return loginResponse ?? null;
75
81
  }
76
82
  catch (e) {
77
- console.error('authentication-controller/services: unable to login', e);
83
+ loglevel_1.default.error('authentication-controller/services: unable to login', e);
78
84
  return null;
79
85
  }
80
86
  }
@@ -102,13 +108,14 @@ async function getAccessToken(jwtToken, platform) {
102
108
  body: urlEncodedBody.toString(),
103
109
  });
104
110
  if (!response.ok) {
111
+ loglevel_1.default.error(`authentication-controller/services: unable to get access token - HTTP ${response.status}`);
105
112
  return null;
106
113
  }
107
114
  const accessTokenResponse = await response.json();
108
115
  return accessTokenResponse?.access_token ?? null;
109
116
  }
110
117
  catch (e) {
111
- console.error('authentication-controller/services: unable to get access token', e);
118
+ loglevel_1.default.error('authentication-controller/services: unable to get access token', e);
112
119
  return null;
113
120
  }
114
121
  }
@@ -1 +1 @@
1
- {"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":";;;AAAA,8CAA8E;AAE9E,MAAM,QAAQ,GAAG,IAAA,gBAAU,EAAC,SAAG,CAAC,GAAG,CAAC,CAAC;AAErC,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,CAAC;AACrC,QAAA,mBAAmB,GAAG,GAAG,aAAa,eAAe,CAAC;AACtD,QAAA,mBAAmB,GAAG,GAAG,aAAa,mBAAmB,CAAC;AAEvE,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,IAAI,EAAE,CAAC;AAC3C,QAAA,oBAAoB,GAAG,GAAG,aAAa,eAAe,CAAC;AACpE,MAAM,cAAc,GAAG,CAAC,QAAgC,EAAE,EAAE;IAC1D,IAAI,QAAQ,KAAK,WAAW,EAAE;QAC5B,OAAO,IAAA,qBAAe,EAAC,SAAG,CAAC,GAAG,EAAE,cAAQ,CAAC,SAAS,CAAC,CAAC;KACrD;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AK,CACX,gEAAgE,EAChE,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AAjCD,wCAiCC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CACnC,KAAa,EACb,SAAiB;IAEjB,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;AACnD,CAAC;AALD,sDAKC","sourcesContent":["import { Env, Platform, getEnvUrls, getOidcClientId } from '../../shared/env';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nconst AUTH_ENDPOINT: string = ENV_URLS.authApiUrl;\nexport const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;\nexport const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;\n\nconst OIDC_ENDPOINT: string = ENV_URLS.oidcApiUrl || '';\nexport const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;\nconst OIDC_CLIENT_ID = (platform: 'mobile' | 'extension') => {\n if (platform === 'extension') {\n return getOidcClientId(Env.PRD, Platform.EXTENSION);\n }\n if (platform === 'mobile') {\n return getOidcClientId(Env.PRD, Platform.MOBILE);\n }\n\n throw new Error(`Unsupported platform - ${platform as string}`);\n};\nconst OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n\nexport type NonceResponse = {\n nonce: string;\n};\n\n/**\n * Auth Service - Get Nonce. Used for the initial JWTBearer flow\n *\n * @param publicKey - public key to associate a nonce with\n * @returns the nonce or null if failed\n */\nexport async function getNonce(publicKey: string): Promise<string | null> {\n const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);\n nonceUrl.searchParams.set('identifier', publicKey);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n return null;\n }\n\n const nonceJson: NonceResponse = await nonceResponse.json();\n return nonceJson?.nonce ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to get nonce', e);\n return null;\n }\n}\n\n/**\n * The Login API Server Response Shape\n */\nexport type LoginResponse = {\n token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * @property identifier_id - a deterministic unique identifier on the method used to sign in\n * @property profile_id - a unique id for a given profile\n * @property metametrics_id - an anonymous server id\n */\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: string;\n };\n};\n\ntype ClientMetaMetrics = {\n metametricsId: string;\n agent: 'extension' | 'mobile';\n};\n\n/**\n * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.\n *\n * @param rawMessage - the original message before signing\n * @param signature - the signed message\n * @param clientMetaMetrics - optional client metametrics id (to associate on backend)\n * @returns The Login Response\n */\nexport async function login(\n rawMessage: string,\n signature: string,\n clientMetaMetrics: ClientMetaMetrics,\n): Promise<LoginResponse | null> {\n try {\n const response = await fetch(AUTH_LOGIN_ENDPOINT, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n signature,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: rawMessage,\n metametrics: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n metametrics_id: clientMetaMetrics.metametricsId,\n agent: clientMetaMetrics.agent,\n },\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const loginResponse: LoginResponse = await response.json();\n return loginResponse ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to login', e);\n return null;\n }\n}\n\n/**\n * The Auth API Token Response Shape\n */\nexport type OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: number;\n};\n\n/**\n * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)\n * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints\n *\n * @param jwtToken - the JWT Auth Token, received from `/login`\n * @param platform - the OIDC platform to retrieve access token\n * @returns JWT Access token to store and use on authorized endpoints.\n */\nexport async function getAccessToken(\n jwtToken: string,\n platform: ClientMetaMetrics['agent'],\n): Promise<string | null> {\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);\n urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKENS_ENDPOINT, {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const accessTokenResponse: OAuthTokenResponse = await response.json();\n return accessTokenResponse?.access_token ?? null;\n } catch (e) {\n console.error(\n 'authentication-controller/services: unable to get access token',\n e,\n );\n return null;\n }\n}\n\n/**\n * Utility to create the raw login message for the JWT bearer flow (via SRP)\n *\n * @param nonce - nonce received from `/nonce` endpoint\n * @param publicKey - public key used to retrieve nonce and for message signing\n * @returns Raw Message which will be used for signing & logging in.\n */\nexport function createLoginRawMessage(\n nonce: string,\n publicKey: string,\n): `metamask:${string}:${string}` {\n return `metamask:${nonce}:${publicKey}` as const;\n}\n"]}
1
+ {"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":";;;;;;AAAA,wDAA2B;AAE3B,8CAA8E;AAE9E,MAAM,QAAQ,GAAG,IAAA,gBAAU,EAAC,SAAG,CAAC,GAAG,CAAC,CAAC;AAErC,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,CAAC;AACrC,QAAA,mBAAmB,GAAG,GAAG,aAAa,eAAe,CAAC;AACtD,QAAA,mBAAmB,GAAG,GAAG,aAAa,mBAAmB,CAAC;AAEvE,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,IAAI,EAAE,CAAC;AAC3C,QAAA,oBAAoB,GAAG,GAAG,aAAa,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AoB,EAAE;YACjD,MAAM,EAAE,MAAM;YACd,OAAO;YACP,IAAI,EAAE,cAAc,CAAC,QAAQ,EAAE;SAChC,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,kBAAG,CAAC,KAAK,CACP,yEAAyE,QAAQ,CAAC,MAAM,EAAE,CAC3F,CAAC;YACF,OAAO,IAAI,CAAC;SACb;QAED,MAAM,mBAAmB,GAAuB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtE,OAAO,mBAAmB,EAAE,YAAY,IAAI,IAAI,CAAC;KAClD;IAAC,OAAO,CAAC,EAAE;QACV,kBAAG,CAAC,KAAK,CACP,gEAAgE,EAChE,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AApCD,wCAoCC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CACnC,KAAa,EACb,SAAiB;IAEjB,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;AACnD,CAAC;AALD,sDAKC","sourcesContent":["import log from 'loglevel';\n\nimport { Env, Platform, getEnvUrls, getOidcClientId } from '../../shared/env';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nconst AUTH_ENDPOINT: string = ENV_URLS.authApiUrl;\nexport const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;\nexport const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;\n\nconst OIDC_ENDPOINT: string = ENV_URLS.oidcApiUrl || '';\nexport const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;\nconst OIDC_CLIENT_ID = (platform: 'mobile' | 'extension') => {\n if (platform === 'extension') {\n return getOidcClientId(Env.PRD, Platform.EXTENSION);\n }\n if (platform === 'mobile') {\n return getOidcClientId(Env.PRD, Platform.MOBILE);\n }\n\n throw new Error(`Unsupported platform - ${platform as string}`);\n};\nconst OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n\nexport type NonceResponse = {\n nonce: string;\n};\n\n/**\n * Auth Service - Get Nonce. Used for the initial JWTBearer flow\n *\n * @param publicKey - public key to associate a nonce with\n * @returns the nonce or null if failed\n */\nexport async function getNonce(publicKey: string): Promise<string | null> {\n const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);\n nonceUrl.searchParams.set('identifier', publicKey);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n log.error(\n `authentication-controller/services: unable to get nonce - HTTP ${nonceResponse.status}`,\n );\n return null;\n }\n\n const nonceJson: NonceResponse = await nonceResponse.json();\n return nonceJson?.nonce ?? null;\n } catch (e) {\n log.error('authentication-controller/services: unable to get nonce', e);\n return null;\n }\n}\n\n/**\n * The Login API Server Response Shape\n */\nexport type LoginResponse = {\n token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * @property identifier_id - a deterministic unique identifier on the method used to sign in\n * @property profile_id - a unique id for a given profile\n * @property metametrics_id - an anonymous server id\n */\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: string;\n };\n};\n\ntype ClientMetaMetrics = {\n metametricsId: string;\n agent: 'extension' | 'mobile';\n};\n\n/**\n * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.\n *\n * @param rawMessage - the original message before signing\n * @param signature - the signed message\n * @param clientMetaMetrics - optional client metametrics id (to associate on backend)\n * @returns The Login Response\n */\nexport async function login(\n rawMessage: string,\n signature: string,\n clientMetaMetrics: ClientMetaMetrics,\n): Promise<LoginResponse | null> {\n try {\n const response = await fetch(AUTH_LOGIN_ENDPOINT, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n signature,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: rawMessage,\n metametrics: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n metametrics_id: clientMetaMetrics.metametricsId,\n agent: clientMetaMetrics.agent,\n },\n }),\n });\n\n if (!response.ok) {\n log.error(\n `authentication-controller/services: unable to login - HTTP ${response.status}`,\n );\n return null;\n }\n\n const loginResponse: LoginResponse = await response.json();\n return loginResponse ?? null;\n } catch (e) {\n log.error('authentication-controller/services: unable to login', e);\n return null;\n }\n}\n\n/**\n * The Auth API Token Response Shape\n */\nexport type OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: number;\n};\n\n/**\n * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)\n * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints\n *\n * @param jwtToken - the JWT Auth Token, received from `/login`\n * @param platform - the OIDC platform to retrieve access token\n * @returns JWT Access token to store and use on authorized endpoints.\n */\nexport async function getAccessToken(\n jwtToken: string,\n platform: ClientMetaMetrics['agent'],\n): Promise<string | null> {\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);\n urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKENS_ENDPOINT, {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n log.error(\n `authentication-controller/services: unable to get access token - HTTP ${response.status}`,\n );\n return null;\n }\n\n const accessTokenResponse: OAuthTokenResponse = await response.json();\n return accessTokenResponse?.access_token ?? null;\n } catch (e) {\n log.error(\n 'authentication-controller/services: unable to get access token',\n e,\n );\n return null;\n }\n}\n\n/**\n * Utility to create the raw login message for the JWT bearer flow (via SRP)\n *\n * @param nonce - nonce received from `/nonce` endpoint\n * @param publicKey - public key used to retrieve nonce and for message signing\n * @returns Raw Message which will be used for signing & logging in.\n */\nexport function createLoginRawMessage(\n nonce: string,\n publicKey: string,\n): `metamask:${string}:${string}` {\n return `metamask:${nonce}:${publicKey}` as const;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,mBAAmB,QAAkC,CAAC;AACnE,eAAO,MAAM,mBAAmB,QAAsC,CAAC;AAGvE,eAAO,MAAM,oBAAoB,QAAkC,CAAC;AAapE,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgBxE;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IAEd,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE;QAEP,aAAa,EAAE,MAAM,CAAC;QAEtB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,GAAG,QAAQ,CAAC;CAC/B,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,KAAK,CACzB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,iBAAiB,GACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CA6B/B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAE/B,YAAY,EAAE,MAAM,CAAC;IAErB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,iBAAiB,CAAC,OAAO,CAAC,GACnC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8BxB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAChB,YAAY,MAAM,IAAI,MAAM,EAAE,CAEhC"}
1
+ {"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,mBAAmB,QAAkC,CAAC;AACnE,eAAO,MAAM,mBAAmB,QAAsC,CAAC;AAGvE,eAAO,MAAM,oBAAoB,QAAkC,CAAC;AAapE,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAmBxE;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IAEd,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE;QAEP,aAAa,EAAE,MAAM,CAAC;QAEtB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,GAAG,QAAQ,CAAC;CAC/B,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,KAAK,CACzB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,iBAAiB,GACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAgC/B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAE/B,YAAY,EAAE,MAAM,CAAC;IAErB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,iBAAiB,CAAC,OAAO,CAAC,GACnC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAiCxB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAChB,YAAY,MAAM,IAAI,MAAM,EAAE,CAEhC"}
@@ -1 +1 @@
1
- {"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,mBAAmB,QAAkC,CAAC;AACnE,eAAO,MAAM,mBAAmB,QAAsC,CAAC;AAGvE,eAAO,MAAM,oBAAoB,QAAkC,CAAC;AAapE,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgBxE;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IAEd,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE;QAEP,aAAa,EAAE,MAAM,CAAC;QAEtB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,GAAG,QAAQ,CAAC;CAC/B,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,KAAK,CACzB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,iBAAiB,GACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CA6B/B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAE/B,YAAY,EAAE,MAAM,CAAC;IAErB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,iBAAiB,CAAC,OAAO,CAAC,GACnC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8BxB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAChB,YAAY,MAAM,IAAI,MAAM,EAAE,CAEhC"}
1
+ {"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,mBAAmB,QAAkC,CAAC;AACnE,eAAO,MAAM,mBAAmB,QAAsC,CAAC;AAGvE,eAAO,MAAM,oBAAoB,QAAkC,CAAC;AAapE,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAmBxE;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IAEd,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE;QAEP,aAAa,EAAE,MAAM,CAAC;QAEtB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,GAAG,QAAQ,CAAC;CAC/B,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,KAAK,CACzB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,iBAAiB,GACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAgC/B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAE/B,YAAY,EAAE,MAAM,CAAC;IAErB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,iBAAiB,CAAC,OAAO,CAAC,GACnC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAiCxB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAChB,YAAY,MAAM,IAAI,MAAM,EAAE,CAEhC"}
@@ -1,3 +1,11 @@
1
+ function $importDefault(module) {
2
+ if (module?.__esModule) {
3
+ return module.default;
4
+ }
5
+ return module;
6
+ }
7
+ import $log from "loglevel";
8
+ const log = $importDefault($log);
1
9
  import { Env, Platform, getEnvUrls, getOidcClientId } from "../../shared/env.mjs";
2
10
  const ENV_URLS = getEnvUrls(Env.PRD);
3
11
  const AUTH_ENDPOINT = ENV_URLS.authApiUrl;
@@ -27,13 +35,14 @@ export async function getNonce(publicKey) {
27
35
  try {
28
36
  const nonceResponse = await fetch(nonceUrl.toString());
29
37
  if (!nonceResponse.ok) {
38
+ log.error(`authentication-controller/services: unable to get nonce - HTTP ${nonceResponse.status}`);
30
39
  return null;
31
40
  }
32
41
  const nonceJson = await nonceResponse.json();
33
42
  return nonceJson?.nonce ?? null;
34
43
  }
35
44
  catch (e) {
36
- console.error('authentication-controller/services: unable to get nonce', e);
45
+ log.error('authentication-controller/services: unable to get nonce', e);
37
46
  return null;
38
47
  }
39
48
  }
@@ -64,13 +73,14 @@ export async function login(rawMessage, signature, clientMetaMetrics) {
64
73
  }),
65
74
  });
66
75
  if (!response.ok) {
76
+ log.error(`authentication-controller/services: unable to login - HTTP ${response.status}`);
67
77
  return null;
68
78
  }
69
79
  const loginResponse = await response.json();
70
80
  return loginResponse ?? null;
71
81
  }
72
82
  catch (e) {
73
- console.error('authentication-controller/services: unable to login', e);
83
+ log.error('authentication-controller/services: unable to login', e);
74
84
  return null;
75
85
  }
76
86
  }
@@ -97,13 +107,14 @@ export async function getAccessToken(jwtToken, platform) {
97
107
  body: urlEncodedBody.toString(),
98
108
  });
99
109
  if (!response.ok) {
110
+ log.error(`authentication-controller/services: unable to get access token - HTTP ${response.status}`);
100
111
  return null;
101
112
  }
102
113
  const accessTokenResponse = await response.json();
103
114
  return accessTokenResponse?.access_token ?? null;
104
115
  }
105
116
  catch (e) {
106
- console.error('authentication-controller/services: unable to get access token', e);
117
+ log.error('authentication-controller/services: unable to get access token', e);
107
118
  return null;
108
119
  }
109
120
  }
@@ -1 +1 @@
1
- {"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe,EAAE,6BAAyB;AAE9E,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAErC,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,CAAC;AAClD,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,aAAa,eAAe,CAAC;AACnE,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,aAAa,mBAAmB,CAAC;AAEvE,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,IAAI,EAAE,CAAC;AACxD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,aAAa,eAAe,CAAC;AACpE,MAAM,cAAc,GAAG,CAAC,QAAgC,EAAE,EAAE;IAC1D,IAAI,QAAQ,KAAK,WAAW,EAAE;QAC5B,OAAO,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;KACrD;IACD,IAAI,QAAQ,KAAK,QAAQ,EAAE;QACzB,OAAO,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CA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AqB,CACnC,KAAa,EACb,SAAiB;IAEjB,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;AACnD,CAAC","sourcesContent":["import { Env, Platform, getEnvUrls, getOidcClientId } from '../../shared/env';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nconst AUTH_ENDPOINT: string = ENV_URLS.authApiUrl;\nexport const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;\nexport const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;\n\nconst OIDC_ENDPOINT: string = ENV_URLS.oidcApiUrl || '';\nexport const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;\nconst OIDC_CLIENT_ID = (platform: 'mobile' | 'extension') => {\n if (platform === 'extension') {\n return getOidcClientId(Env.PRD, Platform.EXTENSION);\n }\n if (platform === 'mobile') {\n return getOidcClientId(Env.PRD, Platform.MOBILE);\n }\n\n throw new Error(`Unsupported platform - ${platform as string}`);\n};\nconst OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n\nexport type NonceResponse = {\n nonce: string;\n};\n\n/**\n * Auth Service - Get Nonce. Used for the initial JWTBearer flow\n *\n * @param publicKey - public key to associate a nonce with\n * @returns the nonce or null if failed\n */\nexport async function getNonce(publicKey: string): Promise<string | null> {\n const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);\n nonceUrl.searchParams.set('identifier', publicKey);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n return null;\n }\n\n const nonceJson: NonceResponse = await nonceResponse.json();\n return nonceJson?.nonce ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to get nonce', e);\n return null;\n }\n}\n\n/**\n * The Login API Server Response Shape\n */\nexport type LoginResponse = {\n token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * @property identifier_id - a deterministic unique identifier on the method used to sign in\n * @property profile_id - a unique id for a given profile\n * @property metametrics_id - an anonymous server id\n */\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: string;\n };\n};\n\ntype ClientMetaMetrics = {\n metametricsId: string;\n agent: 'extension' | 'mobile';\n};\n\n/**\n * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.\n *\n * @param rawMessage - the original message before signing\n * @param signature - the signed message\n * @param clientMetaMetrics - optional client metametrics id (to associate on backend)\n * @returns The Login Response\n */\nexport async function login(\n rawMessage: string,\n signature: string,\n clientMetaMetrics: ClientMetaMetrics,\n): Promise<LoginResponse | null> {\n try {\n const response = await fetch(AUTH_LOGIN_ENDPOINT, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n signature,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: rawMessage,\n metametrics: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n metametrics_id: clientMetaMetrics.metametricsId,\n agent: clientMetaMetrics.agent,\n },\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const loginResponse: LoginResponse = await response.json();\n return loginResponse ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to login', e);\n return null;\n }\n}\n\n/**\n * The Auth API Token Response Shape\n */\nexport type OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: number;\n};\n\n/**\n * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)\n * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints\n *\n * @param jwtToken - the JWT Auth Token, received from `/login`\n * @param platform - the OIDC platform to retrieve access token\n * @returns JWT Access token to store and use on authorized endpoints.\n */\nexport async function getAccessToken(\n jwtToken: string,\n platform: ClientMetaMetrics['agent'],\n): Promise<string | null> {\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);\n urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKENS_ENDPOINT, {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const accessTokenResponse: OAuthTokenResponse = await response.json();\n return accessTokenResponse?.access_token ?? null;\n } catch (e) {\n console.error(\n 'authentication-controller/services: unable to get access token',\n e,\n );\n return null;\n }\n}\n\n/**\n * Utility to create the raw login message for the JWT bearer flow (via SRP)\n *\n * @param nonce - nonce received from `/nonce` endpoint\n * @param publicKey - public key used to retrieve nonce and for message signing\n * @returns Raw Message which will be used for signing & logging in.\n */\nexport function createLoginRawMessage(\n nonce: string,\n publicKey: string,\n): `metamask:${string}:${string}` {\n return `metamask:${nonce}:${publicKey}` as const;\n}\n"]}
1
+ {"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/controllers/authentication/services.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe,EAAE,6BAAyB;AAE9E,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAErC,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,CAAC;AAClD,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,aAAa,eAAe,CAAC;AACnE,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,aAAa,mBAAmB,CAAC;AAEvE,MAAM,aAAa,GAAW,QAAQ,CAAC,UAAU,IAAI,EAAE,CAAC;AACxD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,aAAa,eAAe,CAAC;AACpE,MAAM,cAAc,GAAG,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,IAAI,EAAE,cAAc,CAAC,QAAQ,EAAE;SAChC,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,GAAG,CAAC,KAAK,CACP,yEAAyE,QAAQ,CAAC,MAAM,EAAE,CAC3F,CAAC;YACF,OAAO,IAAI,CAAC;SACb;QAED,MAAM,mBAAmB,GAAuB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtE,OAAO,mBAAmB,EAAE,YAAY,IAAI,IAAI,CAAC;KAClD;IAAC,OAAO,CAAC,EAAE;QACV,GAAG,CAAC,KAAK,CACP,gEAAgE,EAChE,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CACnC,KAAa,EACb,SAAiB;IAEjB,OAAO,YAAY,KAAK,IAAI,SAAS,EAAW,CAAC;AACnD,CAAC","sourcesContent":["import log from 'loglevel';\n\nimport { Env, Platform, getEnvUrls, getOidcClientId } from '../../shared/env';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nconst AUTH_ENDPOINT: string = ENV_URLS.authApiUrl;\nexport const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;\nexport const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;\n\nconst OIDC_ENDPOINT: string = ENV_URLS.oidcApiUrl || '';\nexport const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;\nconst OIDC_CLIENT_ID = (platform: 'mobile' | 'extension') => {\n if (platform === 'extension') {\n return getOidcClientId(Env.PRD, Platform.EXTENSION);\n }\n if (platform === 'mobile') {\n return getOidcClientId(Env.PRD, Platform.MOBILE);\n }\n\n throw new Error(`Unsupported platform - ${platform as string}`);\n};\nconst OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n\nexport type NonceResponse = {\n nonce: string;\n};\n\n/**\n * Auth Service - Get Nonce. Used for the initial JWTBearer flow\n *\n * @param publicKey - public key to associate a nonce with\n * @returns the nonce or null if failed\n */\nexport async function getNonce(publicKey: string): Promise<string | null> {\n const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);\n nonceUrl.searchParams.set('identifier', publicKey);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n log.error(\n `authentication-controller/services: unable to get nonce - HTTP ${nonceResponse.status}`,\n );\n return null;\n }\n\n const nonceJson: NonceResponse = await nonceResponse.json();\n return nonceJson?.nonce ?? null;\n } catch (e) {\n log.error('authentication-controller/services: unable to get nonce', e);\n return null;\n }\n}\n\n/**\n * The Login API Server Response Shape\n */\nexport type LoginResponse = {\n token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * @property identifier_id - a deterministic unique identifier on the method used to sign in\n * @property profile_id - a unique id for a given profile\n * @property metametrics_id - an anonymous server id\n */\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: string;\n };\n};\n\ntype ClientMetaMetrics = {\n metametricsId: string;\n agent: 'extension' | 'mobile';\n};\n\n/**\n * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.\n *\n * @param rawMessage - the original message before signing\n * @param signature - the signed message\n * @param clientMetaMetrics - optional client metametrics id (to associate on backend)\n * @returns The Login Response\n */\nexport async function login(\n rawMessage: string,\n signature: string,\n clientMetaMetrics: ClientMetaMetrics,\n): Promise<LoginResponse | null> {\n try {\n const response = await fetch(AUTH_LOGIN_ENDPOINT, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n signature,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: rawMessage,\n metametrics: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n metametrics_id: clientMetaMetrics.metametricsId,\n agent: clientMetaMetrics.agent,\n },\n }),\n });\n\n if (!response.ok) {\n log.error(\n `authentication-controller/services: unable to login - HTTP ${response.status}`,\n );\n return null;\n }\n\n const loginResponse: LoginResponse = await response.json();\n return loginResponse ?? null;\n } catch (e) {\n log.error('authentication-controller/services: unable to login', e);\n return null;\n }\n}\n\n/**\n * The Auth API Token Response Shape\n */\nexport type OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: number;\n};\n\n/**\n * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)\n * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints\n *\n * @param jwtToken - the JWT Auth Token, received from `/login`\n * @param platform - the OIDC platform to retrieve access token\n * @returns JWT Access token to store and use on authorized endpoints.\n */\nexport async function getAccessToken(\n jwtToken: string,\n platform: ClientMetaMetrics['agent'],\n): Promise<string | null> {\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);\n urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKENS_ENDPOINT, {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n log.error(\n `authentication-controller/services: unable to get access token - HTTP ${response.status}`,\n );\n return null;\n }\n\n const accessTokenResponse: OAuthTokenResponse = await response.json();\n return accessTokenResponse?.access_token ?? null;\n } catch (e) {\n log.error(\n 'authentication-controller/services: unable to get access token',\n e,\n );\n return null;\n }\n}\n\n/**\n * Utility to create the raw login message for the JWT bearer flow (via SRP)\n *\n * @param nonce - nonce received from `/nonce` endpoint\n * @param publicKey - public key used to retrieve nonce and for message signing\n * @returns Raw Message which will be used for signing & logging in.\n */\nexport function createLoginRawMessage(\n nonce: string,\n publicKey: string,\n): `metamask:${string}:${string}` {\n return `metamask:${nonce}:${publicKey}` as const;\n}\n"]}
@@ -10,17 +10,15 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  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");
11
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
12
  };
13
- var _UserStorageController_instances, _UserStorageController_env, _UserStorageController_auth, _UserStorageController_accounts, _UserStorageController_config, _UserStorageController_notificationServices, _UserStorageController_isUnlocked, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_registerMessageHandlers, _UserStorageController_getStorageOptions, _UserStorageController_assertProfileSyncingEnabled, _UserStorageController_getStorageKeyAndBearerToken, _UserStorageController_createStorageKey, _UserStorageController__snapSignMessageCache, _UserStorageController_snapSignMessage, _UserStorageController_setIsProfileSyncingUpdateLoading;
13
+ var _UserStorageController_instances, _UserStorageController_env, _UserStorageController_auth, _UserStorageController_config, _UserStorageController_notificationServices, _UserStorageController_isUnlocked, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_registerMessageHandlers, _UserStorageController_getStorageOptions, _UserStorageController_assertProfileSyncingEnabled, _UserStorageController_getStorageKeyAndBearerToken, _UserStorageController_createStorageKey, _UserStorageController__snapSignMessageCache, _UserStorageController_snapSignMessage, _UserStorageController_setIsProfileSyncingUpdateLoading;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.defaultState = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
17
- const keyring_api_1 = require("@metamask/keyring-api");
18
- const keyring_controller_1 = require("@metamask/keyring-controller");
19
17
  const encryption_1 = require("../../shared/encryption/index.cjs");
20
- const storage_schema_1 = require("../../shared/storage-schema.cjs");
21
18
  const auth_snap_requests_1 = require("../authentication/auth-snap-requests.cjs");
22
- const user_storage_1 = require("./accounts/user-storage.cjs");
23
- const controller_integration_1 = require("./network-syncing/controller-integration.cjs");
19
+ const controller_integration_1 = require("./account-syncing/controller-integration.cjs");
20
+ const setup_subscriptions_1 = require("./account-syncing/setup-subscriptions.cjs");
21
+ const controller_integration_2 = require("./network-syncing/controller-integration.cjs");
24
22
  const services_1 = require("./services.cjs");
25
23
  const controllerName = 'UserStorageController';
26
24
  exports.defaultState = {
@@ -28,6 +26,7 @@ exports.defaultState = {
28
26
  isProfileSyncingUpdateLoading: false,
29
27
  hasAccountSyncingSyncedAtLeastOnce: false,
30
28
  isAccountSyncingReadyToBeDispatched: false,
29
+ isAccountSyncingInProgress: false,
31
30
  };
32
31
  const metadata = {
33
32
  isProfileSyncingEnabled: {
@@ -46,6 +45,10 @@ const metadata = {
46
45
  persist: false,
47
46
  anonymous: false,
48
47
  },
48
+ isAccountSyncingInProgress: {
49
+ persist: false,
50
+ anonymous: false,
51
+ },
49
52
  hasNetworkSyncingSyncedAtLeastOnce: {
50
53
  persist: true,
51
54
  anonymous: false,
@@ -92,80 +95,6 @@ class UserStorageController extends base_controller_1.BaseController {
92
95
  return this.messagingSystem.call('AuthenticationController:performSignOut');
93
96
  },
94
97
  });
95
- _UserStorageController_accounts.set(this, {
96
- isAccountSyncingInProgress: false,
97
- maxNumberOfAccountsToAdd: 0,
98
- canSync: () => {
99
- try {
100
- __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
101
- if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress) {
102
- return false;
103
- }
104
- if (!__classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled) {
105
- return false;
106
- }
107
- if (!__classPrivateFieldGet(this, _UserStorageController_auth, "f").isAuthEnabled()) {
108
- return false;
109
- }
110
- return true;
111
- }
112
- catch {
113
- return false;
114
- }
115
- },
116
- setupAccountSyncingSubscriptions: () => {
117
- this.messagingSystem.subscribe('AccountsController:accountAdded',
118
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
119
- async (account) => {
120
- if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
121
- !this.state.hasAccountSyncingSyncedAtLeastOnce) {
122
- return;
123
- }
124
- await this.saveInternalAccountToUserStorage(account);
125
- });
126
- this.messagingSystem.subscribe('AccountsController:accountRenamed',
127
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
128
- async (account) => {
129
- if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
130
- !this.state.hasAccountSyncingSyncedAtLeastOnce) {
131
- return;
132
- }
133
- await this.saveInternalAccountToUserStorage(account);
134
- });
135
- },
136
- doesInternalAccountHaveCorrectKeyringType: (account) => {
137
- return account.metadata.keyring.type === keyring_controller_1.KeyringTypes.hd;
138
- },
139
- getInternalAccountsList: async () => {
140
- // eslint-disable-next-line @typescript-eslint/await-thenable
141
- const internalAccountsList = await this.messagingSystem.call('AccountsController:listAccounts');
142
- return internalAccountsList?.filter(__classPrivateFieldGet(this, _UserStorageController_accounts, "f").doesInternalAccountHaveCorrectKeyringType);
143
- },
144
- getUserStorageAccountsList: async () => {
145
- const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts);
146
- return (rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??
147
- null);
148
- },
149
- saveInternalAccountToUserStorage: async (internalAccount) => {
150
- // Map the internal account to the user storage account schema
151
- const mappedAccount = (0, user_storage_1.mapInternalAccountToUserStorageAccount)(internalAccount);
152
- await this.performSetStorage(
153
- // ESLint is confused here.
154
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
155
- `${storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`, JSON.stringify(mappedAccount));
156
- },
157
- saveInternalAccountsListToUserStorage: async () => {
158
- const internalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
159
- if (!internalAccountsList) {
160
- return;
161
- }
162
- const internalAccountsListFormattedForUserStorage = internalAccountsList.map(user_storage_1.mapInternalAccountToUserStorageAccount);
163
- await this.performBatchSetStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsListFormattedForUserStorage.map((account) => [
164
- account.a,
165
- JSON.stringify(account),
166
- ]));
167
- },
168
- });
169
98
  _UserStorageController_config.set(this, void 0);
170
99
  _UserStorageController_notificationServices.set(this, {
171
100
  disableNotificationServices: async () => {
@@ -193,16 +122,20 @@ class UserStorageController extends base_controller_1.BaseController {
193
122
  __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled = Boolean(env?.isAccountSyncingEnabled);
194
123
  __classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);
195
124
  __classPrivateFieldSet(this, _UserStorageController_config, config, "f");
196
- __classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd =
197
- config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;
198
125
  this.getMetaMetricsState = getMetaMetricsState;
199
126
  __classPrivateFieldGet(this, _UserStorageController_keyringController, "f").setupLockedStateSubscriptions();
200
127
  __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_registerMessageHandlers).call(this);
201
128
  __classPrivateFieldSet(this, _UserStorageController_nativeScryptCrypto, nativeScryptCrypto, "f");
202
- __classPrivateFieldGet(this, _UserStorageController_accounts, "f").setupAccountSyncingSubscriptions();
129
+ // Account Syncing
130
+ if (__classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled) {
131
+ (0, setup_subscriptions_1.setupAccountSyncingSubscriptions)({ isAccountSyncingEnabled: true }, {
132
+ getUserStorageControllerInstance: () => this,
133
+ getMessenger: () => this.messagingSystem,
134
+ });
135
+ }
203
136
  // Network Syncing
204
137
  if (__classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled) {
205
- (0, controller_integration_1.startNetworkSyncing)({
138
+ (0, controller_integration_2.startNetworkSyncing)({
206
139
  messenger,
207
140
  getStorageConfig: () => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getStorageOptions).call(this),
208
141
  isMutationSyncBlocked: () => !this.state.hasNetworkSyncingSyncedAtLeastOnce,
@@ -401,157 +334,45 @@ class UserStorageController extends base_controller_1.BaseController {
401
334
  isAccountSyncingReadyToBeDispatched;
402
335
  });
403
336
  }
337
+ async setIsAccountSyncingInProgress(isAccountSyncingInProgress) {
338
+ this.update((state) => {
339
+ state.isAccountSyncingInProgress = isAccountSyncingInProgress;
340
+ });
341
+ }
404
342
  /**
405
343
  * Syncs the internal accounts list with the user storage accounts list.
406
344
  * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
407
345
  * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
408
346
  */
409
347
  async syncInternalAccountsWithUserStorage() {
410
- if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
411
- return;
412
- }
413
- try {
414
- __classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress = true;
415
- const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
416
- const userStorageAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getUserStorageAccountsList();
417
- if (!userStorageAccountsList || !userStorageAccountsList.length) {
418
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountsListToUserStorage();
419
- await this.setHasAccountSyncingSyncedAtLeastOnce(true);
420
- return;
421
- }
422
- // Prepare an array of internal accounts to be saved to the user storage
423
- const internalAccountsToBeSavedToUserStorage = [];
424
- // Compare internal accounts list with user storage accounts list
425
- // First step: compare lengths
426
- const internalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
427
- if (!internalAccountsList || !internalAccountsList.length) {
428
- throw new Error(`Failed to get internal accounts list`);
429
- }
430
- const hasMoreUserStorageAccountsThanInternalAccounts = userStorageAccountsList.length > internalAccountsList.length;
431
- // We don't want to remove existing accounts for a user
432
- // so we only add new accounts if the user has more accounts in user storage than internal accounts
433
- if (hasMoreUserStorageAccountsThanInternalAccounts) {
434
- const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, __classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd) - internalAccountsList.length;
435
- // Create new accounts to match the user storage accounts list
436
- for (let i = 0; i < numberOfAccountsToAdd; i++) {
437
- await this.messagingSystem.call('KeyringController:addNewAccount');
438
- __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountAdded?.(profileId);
439
- }
440
- }
441
- // Second step: compare account names
442
- // Get the internal accounts list again since new accounts might have been added in the previous step
443
- const refreshedInternalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
444
- const newlyAddedAccounts = refreshedInternalAccountsList.filter((account) => !internalAccountsList.find((a) => a.address === account.address));
445
- for (const internalAccount of refreshedInternalAccountsList) {
446
- const userStorageAccount = userStorageAccountsList.find((account) => account.a === internalAccount.address);
447
- // If the account is not present in user storage
448
- if (!userStorageAccount) {
449
- // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account
450
- if (newlyAddedAccounts.includes(internalAccount)) {
451
- __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountSyncErroneousSituation?.(profileId, 'An account was added to the internal accounts list but was not present in the user storage accounts list');
452
- continue;
453
- }
454
- // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage
455
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
456
- continue;
457
- }
458
- // From this point on, we know that the account is present in
459
- // both the internal accounts list and the user storage accounts list
460
- // One or both accounts have default names
461
- const isInternalAccountNameDefault = (0, user_storage_1.isNameDefaultAccountName)(internalAccount.metadata.name);
462
- const isUserStorageAccountNameDefault = (0, user_storage_1.isNameDefaultAccountName)(userStorageAccount.n);
463
- // Internal account has default name
464
- if (isInternalAccountNameDefault) {
465
- if (!isUserStorageAccountNameDefault) {
466
- this.messagingSystem.call('AccountsController:updateAccountMetadata', internalAccount.id, {
467
- name: userStorageAccount.n,
468
- });
469
- __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountNameUpdated?.(profileId);
470
- }
471
- continue;
472
- }
473
- // Internal account has custom name but user storage account has default name
474
- if (isUserStorageAccountNameDefault) {
475
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
476
- continue;
477
- }
478
- // Both accounts have custom names
479
- // User storage account has a nameLastUpdatedAt timestamp
480
- // Note: not storing the undefined checks in constants to act as a type guard
481
- if (userStorageAccount.nlu !== undefined) {
482
- if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {
483
- const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt >
484
- userStorageAccount.nlu;
485
- if (isInternalAccountNameNewer) {
486
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
487
- continue;
488
- }
489
- }
490
- this.messagingSystem.call('AccountsController:updateAccountMetadata', internalAccount.id, {
491
- name: userStorageAccount.n,
492
- nameLastUpdatedAt: userStorageAccount.nlu,
493
- });
494
- const areInternalAndUserStorageAccountNamesEqual = internalAccount.metadata.name === userStorageAccount.n;
495
- if (!areInternalAndUserStorageAccountNamesEqual) {
496
- __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountNameUpdated?.(profileId);
497
- }
498
- continue;
499
- }
500
- else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {
501
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
502
- continue;
503
- }
504
- }
505
- // Save the internal accounts list to the user storage
506
- if (internalAccountsToBeSavedToUserStorage.length) {
507
- await this.performBatchSetStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsToBeSavedToUserStorage.map((account) => [
508
- account.address,
509
- JSON.stringify((0, user_storage_1.mapInternalAccountToUserStorageAccount)(account)),
510
- ]));
511
- }
512
- // In case we have corrupted user storage with accounts that don't exist in the internal accounts list
513
- // Delete those accounts from the user storage
514
- const userStorageAccountsToBeDeleted = userStorageAccountsList.filter((account) => !refreshedInternalAccountsList.find((a) => a.address === account.a));
515
- if (userStorageAccountsToBeDeleted.length) {
516
- await this.performBatchDeleteStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, userStorageAccountsToBeDeleted.map((account) => account.a));
517
- __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountSyncErroneousSituation?.(profileId, 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync');
518
- }
519
- // We do this here and not in the finally statement because we want to make sure that
520
- // the accounts are saved / updated / deleted at least once before we set this flag
521
- await this.setHasAccountSyncingSyncedAtLeastOnce(true);
522
- }
523
- catch (e) {
524
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
525
- throw new Error(`${controllerName} - failed to sync user storage accounts list - ${errorMessage}`);
526
- }
527
- finally {
528
- __classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress = false;
529
- }
348
+ const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
349
+ await (0, controller_integration_1.syncInternalAccountsWithUserStorage)({
350
+ isAccountSyncingEnabled: __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled,
351
+ maxNumberOfAccountsToAdd: __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.maxNumberOfAccountsToAdd,
352
+ onAccountAdded: () => __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountAdded?.(profileId),
353
+ onAccountNameUpdated: () => __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountNameUpdated?.(profileId),
354
+ onAccountSyncErroneousSituation: (situationMessage) => __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountSyncErroneousSituation?.(profileId, situationMessage),
355
+ }, {
356
+ getMessenger: () => this.messagingSystem,
357
+ getUserStorageControllerInstance: () => this,
358
+ });
530
359
  }
531
360
  /**
532
361
  * Saves an individual internal account to the user storage.
533
362
  * @param internalAccount - The internal account to save
534
363
  */
535
364
  async saveInternalAccountToUserStorage(internalAccount) {
536
- if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
537
- !(0, keyring_api_1.isEvmAccountType)(internalAccount.type) ||
538
- !__classPrivateFieldGet(this, _UserStorageController_accounts, "f").doesInternalAccountHaveCorrectKeyringType(internalAccount)) {
539
- return;
540
- }
541
- try {
542
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountToUserStorage(internalAccount);
543
- }
544
- catch (e) {
545
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
546
- throw new Error(`${controllerName} - failed to save account to user storage - ${errorMessage}`);
547
- }
365
+ await (0, controller_integration_1.saveInternalAccountToUserStorage)(internalAccount, { isAccountSyncingEnabled: __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled }, {
366
+ getMessenger: () => this.messagingSystem,
367
+ getUserStorageControllerInstance: () => this,
368
+ });
548
369
  }
549
370
  async syncNetworks() {
550
371
  if (!__classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled) {
551
372
  return;
552
373
  }
553
374
  const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
554
- await (0, controller_integration_1.performMainNetworkSync)({
375
+ await (0, controller_integration_2.performMainNetworkSync)({
555
376
  messenger: this.messagingSystem,
556
377
  getStorageConfig: () => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getStorageOptions).call(this),
557
378
  maxNetworksToAdd: __classPrivateFieldGet(this, _UserStorageController_config, "f")?.networkSyncing?.maxNumberOfNetworksToAdd,
@@ -564,7 +385,7 @@ class UserStorageController extends base_controller_1.BaseController {
564
385
  });
565
386
  }
566
387
  }
567
- _UserStorageController_env = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_accounts = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_notificationServices = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
388
+ _UserStorageController_env = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_notificationServices = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
568
389
  this.messagingSystem.registerActionHandler('UserStorageController:performGetStorage', this.performGetStorage.bind(this));
569
390
  this.messagingSystem.registerActionHandler('UserStorageController:performGetStorageAllFeatureEntries', this.performGetStorageAllFeatureEntries.bind(this));
570
391
  this.messagingSystem.registerActionHandler('UserStorageController:performSetStorage', this.performSetStorage.bind(this));