@metamask-previews/profile-sync-controller 8.1.1-preview-0ae65d9e → 8.1.1-preview-1b0ea93a

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 (153) hide show
  1. package/dist/controllers/authentication/AuthenticationController.cjs +55 -86
  2. package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
  3. package/dist/controllers/authentication/AuthenticationController.d.cts +11 -23
  4. package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
  5. package/dist/controllers/authentication/AuthenticationController.d.mts +11 -23
  6. package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
  7. package/dist/controllers/authentication/AuthenticationController.mjs +55 -86
  8. package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
  9. package/dist/controllers/authentication/mocks/mockResponses.cjs +10 -23
  10. package/dist/controllers/authentication/mocks/mockResponses.cjs.map +1 -1
  11. package/dist/controllers/authentication/mocks/mockResponses.d.cts +42 -10
  12. package/dist/controllers/authentication/mocks/mockResponses.d.cts.map +1 -1
  13. package/dist/controllers/authentication/mocks/mockResponses.d.mts +42 -10
  14. package/dist/controllers/authentication/mocks/mockResponses.d.mts.map +1 -1
  15. package/dist/controllers/authentication/mocks/mockResponses.mjs +9 -22
  16. package/dist/controllers/authentication/mocks/mockResponses.mjs.map +1 -1
  17. package/dist/controllers/user-storage/UserStorageController.cjs +71 -127
  18. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  19. package/dist/controllers/user-storage/UserStorageController.d.cts +5 -4
  20. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  21. package/dist/controllers/user-storage/UserStorageController.d.mts +5 -4
  22. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  23. package/dist/controllers/user-storage/UserStorageController.mjs +71 -127
  24. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  25. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +1 -1
  26. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +1 -1
  27. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +1 -1
  28. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +1 -1
  29. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs +1 -0
  30. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs.map +1 -1
  31. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts.map +1 -1
  32. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts.map +1 -1
  33. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs +1 -0
  34. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs.map +1 -1
  35. package/dist/controllers/user-storage/mocks/mockResponses.cjs +3 -3
  36. package/dist/controllers/user-storage/mocks/mockResponses.cjs.map +1 -1
  37. package/dist/controllers/user-storage/mocks/mockResponses.d.cts +1 -1
  38. package/dist/controllers/user-storage/mocks/mockResponses.d.cts.map +1 -1
  39. package/dist/controllers/user-storage/mocks/mockResponses.d.mts +1 -1
  40. package/dist/controllers/user-storage/mocks/mockResponses.d.mts.map +1 -1
  41. package/dist/controllers/user-storage/mocks/mockResponses.mjs +3 -3
  42. package/dist/controllers/user-storage/mocks/mockResponses.mjs.map +1 -1
  43. package/dist/controllers/user-storage/network-syncing/controller-integration.cjs +14 -14
  44. package/dist/controllers/user-storage/network-syncing/controller-integration.cjs.map +1 -1
  45. package/dist/controllers/user-storage/network-syncing/controller-integration.d.cts +3 -3
  46. package/dist/controllers/user-storage/network-syncing/controller-integration.d.cts.map +1 -1
  47. package/dist/controllers/user-storage/network-syncing/controller-integration.d.mts +3 -3
  48. package/dist/controllers/user-storage/network-syncing/controller-integration.d.mts.map +1 -1
  49. package/dist/controllers/user-storage/network-syncing/controller-integration.mjs +14 -14
  50. package/dist/controllers/user-storage/network-syncing/controller-integration.mjs.map +1 -1
  51. package/dist/controllers/user-storage/network-syncing/services.cjs +27 -23
  52. package/dist/controllers/user-storage/network-syncing/services.cjs.map +1 -1
  53. package/dist/controllers/user-storage/network-syncing/services.d.cts +16 -7
  54. package/dist/controllers/user-storage/network-syncing/services.d.cts.map +1 -1
  55. package/dist/controllers/user-storage/network-syncing/services.d.mts +16 -7
  56. package/dist/controllers/user-storage/network-syncing/services.d.mts.map +1 -1
  57. package/dist/controllers/user-storage/network-syncing/services.mjs +27 -23
  58. package/dist/controllers/user-storage/network-syncing/services.mjs.map +1 -1
  59. package/dist/controllers/user-storage/network-syncing/sync-mutations.cjs.map +1 -1
  60. package/dist/controllers/user-storage/network-syncing/sync-mutations.d.cts +13 -5
  61. package/dist/controllers/user-storage/network-syncing/sync-mutations.d.cts.map +1 -1
  62. package/dist/controllers/user-storage/network-syncing/sync-mutations.d.mts +13 -5
  63. package/dist/controllers/user-storage/network-syncing/sync-mutations.d.mts.map +1 -1
  64. package/dist/controllers/user-storage/network-syncing/sync-mutations.mjs.map +1 -1
  65. package/dist/controllers/user-storage/types.cjs +3 -0
  66. package/dist/controllers/user-storage/types.cjs.map +1 -0
  67. package/dist/controllers/user-storage/types.d.cts +23 -0
  68. package/dist/controllers/user-storage/types.d.cts.map +1 -0
  69. package/dist/controllers/user-storage/types.d.mts +23 -0
  70. package/dist/controllers/user-storage/types.d.mts.map +1 -0
  71. package/dist/controllers/user-storage/types.mjs +2 -0
  72. package/dist/controllers/user-storage/types.mjs.map +1 -0
  73. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs +7 -8
  74. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs.map +1 -1
  75. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.cts +2 -0
  76. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.cts.map +1 -1
  77. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.mts +2 -0
  78. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.mts.map +1 -1
  79. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +8 -9
  80. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs.map +1 -1
  81. package/dist/sdk/authentication-jwt-bearer/services.cjs +10 -2
  82. package/dist/sdk/authentication-jwt-bearer/services.cjs.map +1 -1
  83. package/dist/sdk/authentication-jwt-bearer/services.d.cts +3 -1
  84. package/dist/sdk/authentication-jwt-bearer/services.d.cts.map +1 -1
  85. package/dist/sdk/authentication-jwt-bearer/services.d.mts +3 -1
  86. package/dist/sdk/authentication-jwt-bearer/services.d.mts.map +1 -1
  87. package/dist/sdk/authentication-jwt-bearer/services.mjs +10 -2
  88. package/dist/sdk/authentication-jwt-bearer/services.mjs.map +1 -1
  89. package/dist/sdk/authentication-jwt-bearer/types.cjs.map +1 -1
  90. package/dist/sdk/authentication-jwt-bearer/types.mjs.map +1 -1
  91. package/dist/sdk/authentication.cjs.map +1 -1
  92. package/dist/sdk/authentication.d.cts +1 -1
  93. package/dist/sdk/authentication.d.cts.map +1 -1
  94. package/dist/sdk/authentication.d.mts +1 -1
  95. package/dist/sdk/authentication.d.mts.map +1 -1
  96. package/dist/sdk/authentication.mjs.map +1 -1
  97. package/dist/sdk/mocks/auth.cjs +44 -0
  98. package/dist/sdk/mocks/auth.cjs.map +1 -0
  99. package/dist/sdk/mocks/auth.d.cts +39 -0
  100. package/dist/sdk/mocks/auth.d.cts.map +1 -0
  101. package/dist/sdk/mocks/auth.d.mts +39 -0
  102. package/dist/sdk/mocks/auth.d.mts.map +1 -0
  103. package/dist/sdk/mocks/auth.mjs +41 -0
  104. package/dist/sdk/mocks/auth.mjs.map +1 -0
  105. package/dist/sdk/mocks/userstorage.cjs +43 -0
  106. package/dist/sdk/mocks/userstorage.cjs.map +1 -0
  107. package/dist/sdk/mocks/userstorage.d.cts +10 -0
  108. package/dist/sdk/mocks/userstorage.d.cts.map +1 -0
  109. package/dist/sdk/mocks/userstorage.d.mts +10 -0
  110. package/dist/sdk/mocks/userstorage.d.mts.map +1 -0
  111. package/dist/sdk/mocks/userstorage.mjs +15 -0
  112. package/dist/sdk/mocks/userstorage.mjs.map +1 -0
  113. package/dist/sdk/user-storage.cjs +29 -38
  114. package/dist/sdk/user-storage.cjs.map +1 -1
  115. package/dist/sdk/user-storage.d.cts +11 -6
  116. package/dist/sdk/user-storage.d.cts.map +1 -1
  117. package/dist/sdk/user-storage.d.mts +11 -6
  118. package/dist/sdk/user-storage.d.mts.map +1 -1
  119. package/dist/sdk/user-storage.mjs +29 -38
  120. package/dist/sdk/user-storage.mjs.map +1 -1
  121. package/dist/sdk/utils/messaging-signing-snap-requests.cjs +12 -1
  122. package/dist/sdk/utils/messaging-signing-snap-requests.cjs.map +1 -1
  123. package/dist/sdk/utils/messaging-signing-snap-requests.d.cts +6 -0
  124. package/dist/sdk/utils/messaging-signing-snap-requests.d.cts.map +1 -1
  125. package/dist/sdk/utils/messaging-signing-snap-requests.d.mts +6 -0
  126. package/dist/sdk/utils/messaging-signing-snap-requests.d.mts.map +1 -1
  127. package/dist/sdk/utils/messaging-signing-snap-requests.mjs +10 -0
  128. package/dist/sdk/utils/messaging-signing-snap-requests.mjs.map +1 -1
  129. package/dist/shared/types/services.cjs +3 -0
  130. package/dist/shared/types/services.cjs.map +1 -0
  131. package/dist/shared/types/services.d.cts +10 -0
  132. package/dist/shared/types/services.d.cts.map +1 -0
  133. package/dist/shared/types/services.d.mts +10 -0
  134. package/dist/shared/types/services.d.mts.map +1 -0
  135. package/dist/shared/types/services.mjs +2 -0
  136. package/dist/shared/types/services.mjs.map +1 -0
  137. package/package.json +1 -1
  138. package/dist/controllers/authentication/services.cjs +0 -132
  139. package/dist/controllers/authentication/services.cjs.map +0 -1
  140. package/dist/controllers/authentication/services.d.cts +0 -72
  141. package/dist/controllers/authentication/services.d.cts.map +0 -1
  142. package/dist/controllers/authentication/services.d.mts +0 -72
  143. package/dist/controllers/authentication/services.d.mts.map +0 -1
  144. package/dist/controllers/authentication/services.mjs +0 -129
  145. package/dist/controllers/authentication/services.mjs.map +0 -1
  146. package/dist/controllers/user-storage/services.cjs +0 -306
  147. package/dist/controllers/user-storage/services.cjs.map +0 -1
  148. package/dist/controllers/user-storage/services.d.cts +0 -85
  149. package/dist/controllers/user-storage/services.d.cts.map +0 -1
  150. package/dist/controllers/user-storage/services.d.mts +0 -85
  151. package/dist/controllers/user-storage/services.d.mts.map +0 -1
  152. package/dist/controllers/user-storage/services.mjs +0 -276
  153. package/dist/controllers/user-storage/services.mjs.map +0 -1
@@ -1 +0,0 @@
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;;;;;;;;OAQG;IACH,OAAO,EAAE;QACP,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,CA+B/B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/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,129 +0,0 @@
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);
9
- import { Env, Platform, getEnvUrls, getOidcClientId } from "../../shared/env.mjs";
10
- const ENV_URLS = getEnvUrls(Env.PRD);
11
- const AUTH_ENDPOINT = ENV_URLS.authApiUrl;
12
- export const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;
13
- export const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;
14
- const OIDC_ENDPOINT = ENV_URLS.oidcApiUrl || '';
15
- export const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;
16
- const OIDC_CLIENT_ID = (platform) => {
17
- if (platform === 'extension') {
18
- return getOidcClientId(Env.PRD, Platform.EXTENSION);
19
- }
20
- if (platform === 'mobile') {
21
- return getOidcClientId(Env.PRD, Platform.MOBILE);
22
- }
23
- throw new Error(`Unsupported platform - ${platform}`);
24
- };
25
- const OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
26
- /**
27
- * Auth Service - Get Nonce. Used for the initial JWTBearer flow
28
- *
29
- * @param publicKey - public key to associate a nonce with
30
- * @returns the nonce or null if failed
31
- */
32
- export async function getNonce(publicKey) {
33
- const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);
34
- nonceUrl.searchParams.set('identifier', publicKey);
35
- try {
36
- const nonceResponse = await fetch(nonceUrl.toString());
37
- if (!nonceResponse.ok) {
38
- log.error(`authentication-controller/services: unable to get nonce - HTTP ${nonceResponse.status}`);
39
- return null;
40
- }
41
- const nonceJson = await nonceResponse.json();
42
- return nonceJson?.nonce ?? null;
43
- }
44
- catch (e) {
45
- log.error('authentication-controller/services: unable to get nonce', e);
46
- return null;
47
- }
48
- }
49
- /**
50
- * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.
51
- *
52
- * @param rawMessage - the original message before signing
53
- * @param signature - the signed message
54
- * @param clientMetaMetrics - optional client metametrics id (to associate on backend)
55
- * @returns The Login Response
56
- */
57
- export async function login(rawMessage, signature, clientMetaMetrics) {
58
- try {
59
- const response = await fetch(AUTH_LOGIN_ENDPOINT, {
60
- method: 'POST',
61
- headers: {
62
- 'Content-Type': 'application/json',
63
- },
64
- body: JSON.stringify({
65
- signature,
66
- raw_message: rawMessage,
67
- metametrics: {
68
- metametrics_id: clientMetaMetrics.metametricsId,
69
- agent: clientMetaMetrics.agent,
70
- },
71
- }),
72
- });
73
- if (!response.ok) {
74
- log.error(`authentication-controller/services: unable to login - HTTP ${response.status}`);
75
- return null;
76
- }
77
- const loginResponse = await response.json();
78
- return loginResponse ?? null;
79
- }
80
- catch (e) {
81
- log.error('authentication-controller/services: unable to login', e);
82
- return null;
83
- }
84
- }
85
- /**
86
- * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)
87
- * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints
88
- *
89
- * @param jwtToken - the JWT Auth Token, received from `/login`
90
- * @param platform - the OIDC platform to retrieve access token
91
- * @returns JWT Access token to store and use on authorized endpoints.
92
- */
93
- export async function getAccessToken(jwtToken, platform) {
94
- const headers = new Headers({
95
- 'Content-Type': 'application/x-www-form-urlencoded',
96
- });
97
- const urlEncodedBody = new URLSearchParams();
98
- urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);
99
- urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));
100
- urlEncodedBody.append('assertion', jwtToken);
101
- try {
102
- const response = await fetch(OIDC_TOKENS_ENDPOINT, {
103
- method: 'POST',
104
- headers,
105
- body: urlEncodedBody.toString(),
106
- });
107
- if (!response.ok) {
108
- log.error(`authentication-controller/services: unable to get access token - HTTP ${response.status}`);
109
- return null;
110
- }
111
- const accessTokenResponse = await response.json();
112
- return accessTokenResponse?.access_token ?? null;
113
- }
114
- catch (e) {
115
- log.error('authentication-controller/services: unable to get access token', e);
116
- return null;
117
- }
118
- }
119
- /**
120
- * Utility to create the raw login message for the JWT bearer flow (via SRP)
121
- *
122
- * @param nonce - nonce received from `/nonce` endpoint
123
- * @param publicKey - public key used to retrieve nonce and for message signing
124
- * @returns Raw Message which will be used for signing & logging in.
125
- */
126
- export function createLoginRawMessage(nonce, publicKey) {
127
- return `metamask:${nonce}:${publicKey}`;
128
- }
129
- //# sourceMappingURL=services.mjs.map
@@ -1 +0,0 @@
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,CAAC,QAAgC,EAAE,EAAE;IAC1D,IAAI,QAAQ,KAAK,WAAW,EAAE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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\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * identifier_id - a deterministic unique identifier on the method used to sign in\n *\n * profile_id - a unique id for a given profile\n *\n * metametrics_id - an anonymous server id\n */\n profile: {\n identifier_id: string;\n\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\n raw_message: rawMessage,\n metametrics: {\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 access_token: string;\n\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,306 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.deleteUserStorageAllFeatureEntries = exports.batchDeleteUserStorage = exports.deleteUserStorage = exports.batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries = exports.batchUpsertUserStorage = exports.upsertUserStorage = exports.getUserStorageAllFeatureEntries = exports.getUserStorage = exports.USER_STORAGE_ENDPOINT = exports.USER_STORAGE_API = void 0;
30
- const loglevel_1 = __importDefault(require("loglevel"));
31
- const encryption_1 = __importStar(require("../../shared/encryption/index.cjs"));
32
- const constants_1 = require("../../shared/encryption/constants.cjs");
33
- const env_1 = require("../../shared/env.cjs");
34
- const storage_schema_1 = require("../../shared/storage-schema.cjs");
35
- const ENV_URLS = (0, env_1.getEnvUrls)(env_1.Env.PRD);
36
- exports.USER_STORAGE_API = ENV_URLS.userStorageApiUrl;
37
- exports.USER_STORAGE_ENDPOINT = `${exports.USER_STORAGE_API}/api/v1/userstorage`;
38
- /**
39
- * User Storage Service - Get Storage Entry.
40
- *
41
- * @param opts - User Storage Options
42
- * @returns The storage entry, or null if fails to find entry
43
- */
44
- async function getUserStorage(opts) {
45
- try {
46
- const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
47
- const encryptedPath = (0, storage_schema_1.createEntryPath)(path, storageKey);
48
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${encryptedPath}`);
49
- const userStorageResponse = await fetch(url.toString(), {
50
- headers: {
51
- 'Content-Type': 'application/json',
52
- Authorization: `Bearer ${bearerToken}`,
53
- },
54
- });
55
- // Acceptable error - since indicates entry does not exist.
56
- if (userStorageResponse.status === 404) {
57
- return null;
58
- }
59
- if (userStorageResponse.status !== 200) {
60
- throw new Error(`Unable to get User Storage - HTTP ${userStorageResponse.status}`);
61
- }
62
- const userStorage = await userStorageResponse.json();
63
- const encryptedData = userStorage?.Data ?? null;
64
- /* istanbul ignore if - this is an edge case where our endpoint returns invalid JSON payload */
65
- if (!encryptedData) {
66
- return null;
67
- }
68
- const decryptedData = await encryption_1.default.decryptString(encryptedData, opts.storageKey, nativeScryptCrypto);
69
- // Re-encrypt and re-upload the entry if the salt is random
70
- const salt = encryption_1.default.getSalt(encryptedData);
71
- if (salt.toString() !== constants_1.SHARED_SALT.toString()) {
72
- await upsertUserStorage(decryptedData, opts);
73
- }
74
- return decryptedData;
75
- }
76
- catch (e) {
77
- loglevel_1.default.error('Failed to get user storage', e);
78
- return null;
79
- }
80
- }
81
- exports.getUserStorage = getUserStorage;
82
- /**
83
- * User Storage Service - Get all storage entries for a specific feature.
84
- *
85
- * @param opts - User Storage Options
86
- * @returns The storage entry, or null if fails to find entry
87
- */
88
- async function getUserStorageAllFeatureEntries(opts) {
89
- try {
90
- const { bearerToken, path, nativeScryptCrypto } = opts;
91
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${path}`);
92
- const userStorageResponse = await fetch(url.toString(), {
93
- headers: {
94
- 'Content-Type': 'application/json',
95
- Authorization: `Bearer ${bearerToken}`,
96
- },
97
- });
98
- // Acceptable error - since indicates feature does not exist.
99
- if (userStorageResponse.status === 404) {
100
- return null;
101
- }
102
- if (userStorageResponse.status !== 200) {
103
- throw new Error(`Unable to get User Storage - HTTP ${userStorageResponse.status}`);
104
- }
105
- const userStorage = await userStorageResponse.json();
106
- if (!Array.isArray(userStorage)) {
107
- return null;
108
- }
109
- const decryptedData = [];
110
- const reEncryptedEntries = [];
111
- for (const entry of userStorage) {
112
- /* istanbul ignore if - unreachable if statement, but kept as edge case */
113
- if (!entry.Data) {
114
- continue;
115
- }
116
- try {
117
- const data = await encryption_1.default.decryptString(entry.Data, opts.storageKey, nativeScryptCrypto);
118
- decryptedData.push(data);
119
- // Re-encrypt the entry if the salt is different from the shared one
120
- const salt = encryption_1.default.getSalt(entry.Data);
121
- if (salt.toString() !== constants_1.SHARED_SALT.toString()) {
122
- reEncryptedEntries.push([
123
- entry.HashedKey,
124
- await encryption_1.default.encryptString(data, opts.storageKey, nativeScryptCrypto),
125
- ]);
126
- }
127
- }
128
- catch {
129
- // do nothing
130
- }
131
- }
132
- // Re-upload the re-encrypted entries
133
- if (reEncryptedEntries.length) {
134
- await batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(reEncryptedEntries, opts);
135
- }
136
- return decryptedData;
137
- }
138
- catch (e) {
139
- loglevel_1.default.error('Failed to get user storage', e);
140
- return null;
141
- }
142
- }
143
- exports.getUserStorageAllFeatureEntries = getUserStorageAllFeatureEntries;
144
- /**
145
- * User Storage Service - Set Storage Entry.
146
- *
147
- * @param data - data to store
148
- * @param opts - storage options
149
- */
150
- async function upsertUserStorage(data, opts) {
151
- const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
152
- const encryptedData = await encryption_1.default.encryptString(data, opts.storageKey, nativeScryptCrypto);
153
- const encryptedPath = (0, storage_schema_1.createEntryPath)(path, storageKey);
154
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${encryptedPath}`);
155
- const res = await fetch(url.toString(), {
156
- method: 'PUT',
157
- headers: {
158
- 'Content-Type': 'application/json',
159
- Authorization: `Bearer ${bearerToken}`,
160
- },
161
- body: JSON.stringify({ data: encryptedData }),
162
- });
163
- if (!res.ok) {
164
- throw new Error(`user-storage - unable to upsert data - HTTP ${res.status}`);
165
- }
166
- }
167
- exports.upsertUserStorage = upsertUserStorage;
168
- /**
169
- * User Storage Service - Set multiple storage entries for one specific feature.
170
- * You cannot use this method to set multiple features at once.
171
- *
172
- * @param data - data to store, in the form of an array of [entryKey, entryValue] pairs
173
- * @param opts - storage options
174
- */
175
- async function batchUpsertUserStorage(data, opts) {
176
- if (!data.length) {
177
- return;
178
- }
179
- const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
180
- const encryptedData = [];
181
- for (const d of data) {
182
- encryptedData.push([
183
- (0, encryption_1.createSHA256Hash)(d[0] + storageKey),
184
- await encryption_1.default.encryptString(d[1], opts.storageKey, nativeScryptCrypto),
185
- ]);
186
- }
187
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${path}`);
188
- const formattedData = Object.fromEntries(encryptedData);
189
- const res = await fetch(url.toString(), {
190
- method: 'PUT',
191
- headers: {
192
- 'Content-Type': 'application/json',
193
- Authorization: `Bearer ${bearerToken}`,
194
- },
195
- body: JSON.stringify({ data: formattedData }),
196
- });
197
- if (!res.ok) {
198
- throw new Error(`user-storage - unable to batch upsert data - HTTP ${res.status}`);
199
- }
200
- }
201
- exports.batchUpsertUserStorage = batchUpsertUserStorage;
202
- /**
203
- * User Storage Service - Set multiple storage entries for one specific feature.
204
- * You cannot use this method to set multiple features at once.
205
- *
206
- * @param encryptedData - data to store, in the form of an array of [hashedKey, encryptedData] pairs
207
- * @param opts - storage options
208
- */
209
- async function batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(encryptedData, opts) {
210
- if (!encryptedData.length) {
211
- return;
212
- }
213
- const { bearerToken, path } = opts;
214
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${path}`);
215
- const formattedData = Object.fromEntries(encryptedData);
216
- const res = await fetch(url.toString(), {
217
- method: 'PUT',
218
- headers: {
219
- 'Content-Type': 'application/json',
220
- Authorization: `Bearer ${bearerToken}`,
221
- },
222
- body: JSON.stringify({ data: formattedData }),
223
- });
224
- if (!res.ok) {
225
- throw new Error(`user-storage - unable to batch upsert data - HTTP ${res.status}`);
226
- }
227
- }
228
- exports.batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries = batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries;
229
- /**
230
- * User Storage Service - Delete Storage Entry.
231
- *
232
- * @param opts - User Storage Options
233
- */
234
- async function deleteUserStorage(opts) {
235
- const { bearerToken, path, storageKey } = opts;
236
- const encryptedPath = (0, storage_schema_1.createEntryPath)(path, storageKey);
237
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${encryptedPath}`);
238
- const userStorageResponse = await fetch(url.toString(), {
239
- method: 'DELETE',
240
- headers: {
241
- 'Content-Type': 'application/json',
242
- Authorization: `Bearer ${bearerToken}`,
243
- },
244
- });
245
- if (userStorageResponse.status === 404) {
246
- throw new Error(`user-storage - feature/entry not found - HTTP ${userStorageResponse.status}`);
247
- }
248
- if (!userStorageResponse.ok) {
249
- throw new Error(`user-storage - unable to delete data - HTTP ${userStorageResponse.status}`);
250
- }
251
- }
252
- exports.deleteUserStorage = deleteUserStorage;
253
- /**
254
- * User Storage Service - Delete multiple storage entries for one specific feature.
255
- * You cannot use this method to delete multiple features at once.
256
- *
257
- * @param data - data to delete, in the form of an array entryKey[]
258
- * @param opts - storage options
259
- */
260
- async function batchDeleteUserStorage(data, opts) {
261
- if (!data.length) {
262
- return;
263
- }
264
- const { bearerToken, path, storageKey } = opts;
265
- const encryptedData = [];
266
- for (const d of data) {
267
- encryptedData.push((0, encryption_1.createSHA256Hash)(d + storageKey));
268
- }
269
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${path}`);
270
- const res = await fetch(url.toString(), {
271
- method: 'PUT',
272
- headers: {
273
- 'Content-Type': 'application/json',
274
- Authorization: `Bearer ${bearerToken}`,
275
- },
276
- body: JSON.stringify({ batch_delete: encryptedData }),
277
- });
278
- if (!res.ok) {
279
- throw new Error(`user-storage - unable to batch delete data - HTTP ${res.status}`);
280
- }
281
- }
282
- exports.batchDeleteUserStorage = batchDeleteUserStorage;
283
- /**
284
- * User Storage Service - Delete all storage entries for a specific feature.
285
- *
286
- * @param opts - User Storage Options
287
- */
288
- async function deleteUserStorageAllFeatureEntries(opts) {
289
- const { bearerToken, path } = opts;
290
- const url = new URL(`${exports.USER_STORAGE_ENDPOINT}/${path}`);
291
- const userStorageResponse = await fetch(url.toString(), {
292
- method: 'DELETE',
293
- headers: {
294
- 'Content-Type': 'application/json',
295
- Authorization: `Bearer ${bearerToken}`,
296
- },
297
- });
298
- if (userStorageResponse.status === 404) {
299
- throw new Error(`user-storage - feature not found - HTTP ${userStorageResponse.status}`);
300
- }
301
- if (!userStorageResponse.ok) {
302
- throw new Error(`user-storage - unable to delete data - HTTP ${userStorageResponse.status}`);
303
- }
304
- }
305
- exports.deleteUserStorageAllFeatureEntries = deleteUserStorageAllFeatureEntries;
306
- //# sourceMappingURL=services.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/services.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA2B;AAE3B,gFAAuE;AACvE,qEAAgE;AAChE,8CAAmD;AAKnD,oEAA8D;AAG9D,MAAM,QAAQ,GAAG,IAAA,gBAAU,EAAC,SAAG,CAAC,GAAG,CAAC,CAAC;AAExB,QAAA,gBAAgB,GAAW,QAAQ,CAAC,iBAAiB,CAAC;AACtD,QAAA,qBAAqB,GAAG,GAAG,wBAAgB,qBAAqB,CAAC;AA+B9E;;;;;GAKG;AACI,KAAK,UAAU,cAAc,CAClC,IAAwB;IAExB,IAAI;QACF,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAAC;QAEnE,MAAM,aAAa,GAAG,IAAA,gCAAe,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,6BAAqB,IAA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EzC,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;IACnC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,6BAAqB,IAAI,IAAI,EAAE,CAAC,CAAC;IAExD,MAAM,mBAAmB,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE;QACtD,MAAM,EAAE,QAAQ;QAChB,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,WAAW,EAAE;SACvC;KACF,CAAC,CAAC;IAEH,IAAI,mBAAmB,CAAC,MAAM,KAAK,GAAG,EAAE;QACtC,MAAM,IAAI,KAAK,CACb,2CAA2C,mBAAmB,CAAC,MAAM,EAAE,CACxE,CAAC;KACH;IAED,IAAI,CAAC,mBAAmB,CAAC,EAAE,EAAE;QAC3B,MAAM,IAAI,KAAK,CACb,+CAA+C,mBAAmB,CAAC,MAAM,EAAE,CAC5E,CAAC;KACH;AACH,CAAC;AAzBD,gFAyBC","sourcesContent":["import log from 'loglevel';\n\nimport encryption, { createSHA256Hash } from '../../shared/encryption';\nimport { SHARED_SALT } from '../../shared/encryption/constants';\nimport { Env, getEnvUrls } from '../../shared/env';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../../shared/storage-schema';\nimport { createEntryPath } from '../../shared/storage-schema';\nimport type { NativeScrypt } from '../../shared/types/encryption';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nexport const USER_STORAGE_API: string = ENV_URLS.userStorageApiUrl;\nexport const USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;\n\n/**\n * This is the Server Response shape for a feature entry.\n */\nexport type GetUserStorageResponse = {\n HashedKey: string;\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n nativeScryptCrypto?: NativeScrypt;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n};\n\nexport type UserStorageBatchUpsertOptions = UserStorageAllFeatureEntriesOptions;\n\n/**\n * User Storage Service - Get Storage Entry.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorage(\n opts: UserStorageOptions,\n): Promise<string | null> {\n try {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${encryptedPath}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates entry does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error(\n `Unable to get User Storage - HTTP ${userStorageResponse.status}`,\n );\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n /* istanbul ignore if - this is an edge case where our endpoint returns invalid JSON payload */\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n opts.storageKey,\n nativeScryptCrypto,\n );\n\n // Re-encrypt and re-upload the entry if the salt is random\n const salt = encryption.getSalt(encryptedData);\n if (salt.toString() !== SHARED_SALT.toString()) {\n await upsertUserStorage(decryptedData, opts);\n }\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Get all storage entries for a specific feature.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorageAllFeatureEntries(\n opts: UserStorageAllFeatureEntriesOptions,\n): Promise<string[] | null> {\n try {\n const { bearerToken, path, nativeScryptCrypto } = opts;\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates feature does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error(\n `Unable to get User Storage - HTTP ${userStorageResponse.status}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await userStorageResponse.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n /* istanbul ignore if - unreachable if statement, but kept as edge case */\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n opts.storageKey,\n nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Re-encrypt the entry if the salt is different from the shared one\n const salt = encryption.getSalt(entry.Data);\n if (salt.toString() !== SHARED_SALT.toString()) {\n reEncryptedEntries.push([\n entry.HashedKey,\n await encryption.encryptString(\n data,\n opts.storageKey,\n nativeScryptCrypto,\n ),\n ]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n reEncryptedEntries,\n opts,\n );\n }\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Set Storage Entry.\n *\n * @param data - data to store\n * @param opts - storage options\n */\nexport async function upsertUserStorage(\n data: string,\n opts: UserStorageOptions,\n): Promise<void> {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedData = await encryption.encryptString(\n data,\n opts.storageKey,\n nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${encryptedPath}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error(\n `user-storage - unable to upsert data - HTTP ${res.status}`,\n );\n }\n}\n\n/**\n * User Storage Service - Set multiple storage entries for one specific feature.\n * You cannot use this method to set multiple features at once.\n *\n * @param data - data to store, in the form of an array of [entryKey, entryValue] pairs\n * @param opts - storage options\n */\nexport async function batchUpsertUserStorage(\n data: [string, string][],\n opts: UserStorageBatchUpsertOptions,\n): Promise<void> {\n if (!data.length) {\n return;\n }\n\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedData: string[][] = [];\n\n for (const d of data) {\n encryptedData.push([\n createSHA256Hash(d[0] + storageKey),\n await encryption.encryptString(d[1], opts.storageKey, nativeScryptCrypto),\n ]);\n }\n\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const formattedData = Object.fromEntries(encryptedData);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: formattedData }),\n });\n\n if (!res.ok) {\n throw new Error(\n `user-storage - unable to batch upsert data - HTTP ${res.status}`,\n );\n }\n}\n\n/**\n * User Storage Service - Set multiple storage entries for one specific feature.\n * You cannot use this method to set multiple features at once.\n *\n * @param encryptedData - data to store, in the form of an array of [hashedKey, encryptedData] pairs\n * @param opts - storage options\n */\nexport async function batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n encryptedData: [string, string][],\n opts: UserStorageBatchUpsertOptions,\n): Promise<void> {\n if (!encryptedData.length) {\n return;\n }\n\n const { bearerToken, path } = opts;\n\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const formattedData = Object.fromEntries(encryptedData);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: formattedData }),\n });\n\n if (!res.ok) {\n throw new Error(\n `user-storage - unable to batch upsert data - HTTP ${res.status}`,\n );\n }\n}\n\n/**\n * User Storage Service - Delete Storage Entry.\n *\n * @param opts - User Storage Options\n */\nexport async function deleteUserStorage(\n opts: UserStorageOptions,\n): Promise<void> {\n const { bearerToken, path, storageKey } = opts;\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${encryptedPath}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n if (userStorageResponse.status === 404) {\n throw new Error(\n `user-storage - feature/entry not found - HTTP ${userStorageResponse.status}`,\n );\n }\n\n if (!userStorageResponse.ok) {\n throw new Error(\n `user-storage - unable to delete data - HTTP ${userStorageResponse.status}`,\n );\n }\n}\n\n/**\n * User Storage Service - Delete multiple storage entries for one specific feature.\n * You cannot use this method to delete multiple features at once.\n *\n * @param data - data to delete, in the form of an array entryKey[]\n * @param opts - storage options\n */\nexport async function batchDeleteUserStorage(\n data: string[],\n opts: UserStorageBatchUpsertOptions,\n): Promise<void> {\n if (!data.length) {\n return;\n }\n\n const { bearerToken, path, storageKey } = opts;\n\n const encryptedData: string[] = [];\n\n for (const d of data) {\n encryptedData.push(createSHA256Hash(d + storageKey));\n }\n\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n\n body: JSON.stringify({ batch_delete: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error(\n `user-storage - unable to batch delete data - HTTP ${res.status}`,\n );\n }\n}\n\n/**\n * User Storage Service - Delete all storage entries for a specific feature.\n *\n * @param opts - User Storage Options\n */\nexport async function deleteUserStorageAllFeatureEntries(\n opts: UserStorageAllFeatureEntriesOptions,\n): Promise<void> {\n const { bearerToken, path } = opts;\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n if (userStorageResponse.status === 404) {\n throw new Error(\n `user-storage - feature not found - HTTP ${userStorageResponse.status}`,\n );\n }\n\n if (!userStorageResponse.ok) {\n throw new Error(\n `user-storage - unable to delete data - HTTP ${userStorageResponse.status}`,\n );\n }\n}\n"]}
@@ -1,85 +0,0 @@
1
- import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly } from "../../shared/storage-schema.cjs";
2
- import type { NativeScrypt } from "../../shared/types/encryption.cjs";
3
- export declare const USER_STORAGE_API: string;
4
- export declare const USER_STORAGE_ENDPOINT: string;
5
- /**
6
- * This is the Server Response shape for a feature entry.
7
- */
8
- export type GetUserStorageResponse = {
9
- HashedKey: string;
10
- Data: string;
11
- };
12
- export type GetUserStorageAllFeatureEntriesResponse = {
13
- HashedKey: string;
14
- Data: string;
15
- }[];
16
- export type UserStorageBaseOptions = {
17
- bearerToken: string;
18
- storageKey: string;
19
- nativeScryptCrypto?: NativeScrypt;
20
- };
21
- export type UserStorageOptions = UserStorageBaseOptions & {
22
- path: UserStoragePathWithFeatureAndKey;
23
- };
24
- export type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {
25
- path: UserStoragePathWithFeatureOnly;
26
- };
27
- export type UserStorageBatchUpsertOptions = UserStorageAllFeatureEntriesOptions;
28
- /**
29
- * User Storage Service - Get Storage Entry.
30
- *
31
- * @param opts - User Storage Options
32
- * @returns The storage entry, or null if fails to find entry
33
- */
34
- export declare function getUserStorage(opts: UserStorageOptions): Promise<string | null>;
35
- /**
36
- * User Storage Service - Get all storage entries for a specific feature.
37
- *
38
- * @param opts - User Storage Options
39
- * @returns The storage entry, or null if fails to find entry
40
- */
41
- export declare function getUserStorageAllFeatureEntries(opts: UserStorageAllFeatureEntriesOptions): Promise<string[] | null>;
42
- /**
43
- * User Storage Service - Set Storage Entry.
44
- *
45
- * @param data - data to store
46
- * @param opts - storage options
47
- */
48
- export declare function upsertUserStorage(data: string, opts: UserStorageOptions): Promise<void>;
49
- /**
50
- * User Storage Service - Set multiple storage entries for one specific feature.
51
- * You cannot use this method to set multiple features at once.
52
- *
53
- * @param data - data to store, in the form of an array of [entryKey, entryValue] pairs
54
- * @param opts - storage options
55
- */
56
- export declare function batchUpsertUserStorage(data: [string, string][], opts: UserStorageBatchUpsertOptions): Promise<void>;
57
- /**
58
- * User Storage Service - Set multiple storage entries for one specific feature.
59
- * You cannot use this method to set multiple features at once.
60
- *
61
- * @param encryptedData - data to store, in the form of an array of [hashedKey, encryptedData] pairs
62
- * @param opts - storage options
63
- */
64
- export declare function batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(encryptedData: [string, string][], opts: UserStorageBatchUpsertOptions): Promise<void>;
65
- /**
66
- * User Storage Service - Delete Storage Entry.
67
- *
68
- * @param opts - User Storage Options
69
- */
70
- export declare function deleteUserStorage(opts: UserStorageOptions): Promise<void>;
71
- /**
72
- * User Storage Service - Delete multiple storage entries for one specific feature.
73
- * You cannot use this method to delete multiple features at once.
74
- *
75
- * @param data - data to delete, in the form of an array entryKey[]
76
- * @param opts - storage options
77
- */
78
- export declare function batchDeleteUserStorage(data: string[], opts: UserStorageBatchUpsertOptions): Promise<void>;
79
- /**
80
- * User Storage Service - Delete all storage entries for a specific feature.
81
- *
82
- * @param opts - User Storage Options
83
- */
84
- export declare function deleteUserStorageAllFeatureEntries(opts: UserStorageAllFeatureEntriesOptions): Promise<void>;
85
- //# sourceMappingURL=services.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/controllers/user-storage/services.ts"],"names":[],"mappings":"AAKA,OAAO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