@metamask/profile-sync-controller 0.1.4 → 0.2.1
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.
- package/CHANGELOG.md +41 -1
- package/dist/{chunk-5SXXO4MV.js → chunk-3TE6M5TV.js} +10 -8
- package/dist/chunk-3TE6M5TV.js.map +1 -0
- package/dist/{chunk-CSFHMILK.js → chunk-4DQF2YNS.js} +13 -16
- package/dist/chunk-4DQF2YNS.js.map +1 -0
- package/dist/{chunk-RT2GRG4S.mjs → chunk-7KMONAQI.mjs} +3 -3
- package/dist/{chunk-LDEIUP6J.mjs → chunk-CJLDMVV3.mjs} +2 -2
- package/dist/{chunk-2XGRQBXI.mjs → chunk-FU7PSGFP.mjs} +10 -8
- package/dist/chunk-FU7PSGFP.mjs.map +1 -0
- package/dist/{chunk-P52TG263.js → chunk-FUPEFLXB.js} +18 -24
- package/dist/chunk-FUPEFLXB.js.map +1 -0
- package/dist/chunk-ILIZJQ6X.mjs +40 -0
- package/dist/chunk-ILIZJQ6X.mjs.map +1 -0
- package/dist/{chunk-DDOYG42A.js → chunk-JENTMRXO.js} +36 -12
- package/dist/chunk-JENTMRXO.js.map +1 -0
- package/dist/{chunk-DHKZ2NEF.js → chunk-KW3X4TT5.js} +30 -2
- package/dist/chunk-KW3X4TT5.js.map +1 -0
- package/dist/{chunk-BXPL7ZFX.js → chunk-MNVUKRZC.js} +4 -4
- package/dist/{chunk-AXWK4Y23.mjs → chunk-NPH5AHLH.mjs} +19 -25
- package/dist/chunk-NPH5AHLH.mjs.map +1 -0
- package/dist/{chunk-3DMUUTKC.js → chunk-PSR2V3R4.js} +6 -6
- package/dist/{chunk-TUMNNWY6.mjs → chunk-QE5X2BT3.mjs} +35 -11
- package/dist/chunk-QE5X2BT3.mjs.map +1 -0
- package/dist/chunk-SLHAVOTE.js +40 -0
- package/dist/chunk-SLHAVOTE.js.map +1 -0
- package/dist/{chunk-JFVONPMM.mjs → chunk-VYZPOR47.mjs} +15 -1
- package/dist/chunk-VYZPOR47.mjs.map +1 -0
- package/dist/{chunk-Y7P3UH26.mjs → chunk-WWQ65CZY.mjs} +30 -2
- package/dist/chunk-WWQ65CZY.mjs.map +1 -0
- package/dist/{chunk-3SNLHEYU.mjs → chunk-XMYWJQNH.mjs} +10 -13
- package/dist/chunk-XMYWJQNH.mjs.map +1 -0
- package/dist/{chunk-KUTU3NNS.js → chunk-XSSIP3PJ.js} +15 -1
- package/dist/chunk-XSSIP3PJ.js.map +1 -0
- package/dist/controllers/authentication/AuthenticationController.js +10 -5
- package/dist/controllers/authentication/AuthenticationController.mjs +9 -4
- package/dist/controllers/authentication/index.js +11 -6
- package/dist/controllers/authentication/index.mjs +10 -5
- package/dist/controllers/authentication/services.js +8 -3
- package/dist/controllers/authentication/services.mjs +8 -3
- package/dist/controllers/index.js +14 -14
- package/dist/controllers/index.mjs +13 -13
- package/dist/controllers/user-storage/UserStorageController.js +11 -11
- package/dist/controllers/user-storage/UserStorageController.mjs +10 -10
- package/dist/controllers/user-storage/index.js +15 -15
- package/dist/controllers/user-storage/index.mjs +14 -14
- package/dist/controllers/user-storage/schema.js +4 -2
- package/dist/controllers/user-storage/schema.mjs +7 -5
- package/dist/controllers/user-storage/services.js +10 -10
- package/dist/controllers/user-storage/services.mjs +9 -9
- package/dist/index.js +14 -14
- package/dist/index.mjs +13 -13
- package/dist/sdk/authentication.js +2 -2
- package/dist/sdk/authentication.mjs +1 -1
- package/dist/sdk/index.js +9 -4
- package/dist/sdk/index.mjs +8 -3
- package/dist/sdk/user-storage.js +7 -2
- package/dist/sdk/user-storage.mjs +6 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/controllers/authentication/AuthenticationController.d.ts +4 -2
- package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/UserStorageController.d.ts +10 -8
- package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/schema.d.ts +18 -10
- package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/services.d.ts +2 -2
- package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
- package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
- package/dist/types/sdk/authentication.d.ts +1 -0
- package/dist/types/sdk/authentication.d.ts.map +1 -1
- package/dist/types/sdk/user-storage.d.ts +4 -3
- package/dist/types/sdk/user-storage.d.ts.map +1 -1
- package/package.json +13 -10
- package/dist/chunk-2XGRQBXI.mjs.map +0 -1
- package/dist/chunk-3SNLHEYU.mjs.map +0 -1
- package/dist/chunk-5SXXO4MV.js.map +0 -1
- package/dist/chunk-AUFUOKJW.mjs +0 -25
- package/dist/chunk-AUFUOKJW.mjs.map +0 -1
- package/dist/chunk-AXWK4Y23.mjs.map +0 -1
- package/dist/chunk-B6CSNLGE.js +0 -25
- package/dist/chunk-B6CSNLGE.js.map +0 -1
- package/dist/chunk-CSFHMILK.js.map +0 -1
- package/dist/chunk-DDOYG42A.js.map +0 -1
- package/dist/chunk-DHKZ2NEF.js.map +0 -1
- package/dist/chunk-JFVONPMM.mjs.map +0 -1
- package/dist/chunk-KUTU3NNS.js.map +0 -1
- package/dist/chunk-P52TG263.js.map +0 -1
- package/dist/chunk-TUMNNWY6.mjs.map +0 -1
- package/dist/chunk-Y7P3UH26.mjs.map +0 -1
- /package/dist/{chunk-RT2GRG4S.mjs.map → chunk-7KMONAQI.mjs.map} +0 -0
- /package/dist/{chunk-LDEIUP6J.mjs.map → chunk-CJLDMVV3.mjs.map} +0 -0
- /package/dist/{chunk-BXPL7ZFX.js.map → chunk-MNVUKRZC.js.map} +0 -0
- /package/dist/{chunk-3DMUUTKC.js.map → chunk-PSR2V3R4.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
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C5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH","sourcesContent":["import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport { createSHA256Hash } from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePath,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePath,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n"]}
|
|
@@ -32,7 +32,7 @@ var metadata = {
|
|
|
32
32
|
anonymous: false
|
|
33
33
|
}
|
|
34
34
|
};
|
|
35
|
-
var _metametrics, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
|
|
35
|
+
var _metametrics, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
|
|
36
36
|
var AuthenticationController = class extends _basecontroller.BaseController {
|
|
37
37
|
constructor({
|
|
38
38
|
messenger,
|
|
@@ -67,12 +67,28 @@ var AuthenticationController = class extends _basecontroller.BaseController {
|
|
|
67
67
|
*/
|
|
68
68
|
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _snapSignMessage);
|
|
69
69
|
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _metametrics, void 0);
|
|
70
|
+
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _isUnlocked, false);
|
|
71
|
+
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _keyringController, {
|
|
72
|
+
setupLockedStateSubscriptions: () => {
|
|
73
|
+
const { isUnlocked } = this.messagingSystem.call(
|
|
74
|
+
"KeyringController:getState"
|
|
75
|
+
);
|
|
76
|
+
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
|
|
77
|
+
this.messagingSystem.subscribe("KeyringController:unlock", () => {
|
|
78
|
+
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
|
|
79
|
+
});
|
|
80
|
+
this.messagingSystem.subscribe("KeyringController:lock", () => {
|
|
81
|
+
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
});
|
|
70
85
|
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapPublicKeyCache, void 0);
|
|
71
86
|
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
|
|
72
87
|
if (!metametrics) {
|
|
73
88
|
throw new Error("`metametrics` field is required");
|
|
74
89
|
}
|
|
75
90
|
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _metametrics, metametrics);
|
|
91
|
+
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
|
|
76
92
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
|
|
77
93
|
}
|
|
78
94
|
async performSignIn() {
|
|
@@ -113,6 +129,8 @@ var AuthenticationController = class extends _basecontroller.BaseController {
|
|
|
113
129
|
}
|
|
114
130
|
};
|
|
115
131
|
_metametrics = new WeakMap();
|
|
132
|
+
_isUnlocked = new WeakMap();
|
|
133
|
+
_keyringController = new WeakMap();
|
|
116
134
|
_registerMessageHandlers = new WeakSet();
|
|
117
135
|
registerMessageHandlers_fn = function() {
|
|
118
136
|
this.messagingSystem.registerActionHandler(
|
|
@@ -213,6 +231,11 @@ snapGetPublicKey_fn = async function() {
|
|
|
213
231
|
if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapPublicKeyCache)) {
|
|
214
232
|
return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapPublicKeyCache);
|
|
215
233
|
}
|
|
234
|
+
if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
|
|
235
|
+
throw new Error(
|
|
236
|
+
"#snapGetPublicKey - unable to call snap, wallet is locked"
|
|
237
|
+
);
|
|
238
|
+
}
|
|
216
239
|
const result = await this.messagingSystem.call(
|
|
217
240
|
"SnapController:handleRequest",
|
|
218
241
|
_chunkYHGWG3EQjs.createSnapPublicKeyRequest.call(void 0, )
|
|
@@ -226,6 +249,11 @@ snapSignMessage_fn = async function(message) {
|
|
|
226
249
|
if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message]) {
|
|
227
250
|
return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message];
|
|
228
251
|
}
|
|
252
|
+
if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
"#snapSignMessage - unable to call snap, wallet is locked"
|
|
255
|
+
);
|
|
256
|
+
}
|
|
229
257
|
const result = await this.messagingSystem.call(
|
|
230
258
|
"SnapController:handleRequest",
|
|
231
259
|
_chunkYHGWG3EQjs.createSnapSignMessageRequest.call(void 0, message)
|
|
@@ -238,4 +266,4 @@ snapSignMessage_fn = async function(message) {
|
|
|
238
266
|
|
|
239
267
|
|
|
240
268
|
exports.defaultState = defaultState; exports.AuthenticationController = AuthenticationController;
|
|
241
|
-
//# sourceMappingURL=chunk-
|
|
269
|
+
//# sourceMappingURL=chunk-KW3X4TT5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAmB/B,IAAM,gBAAgB,MAAO,KAAK;AAElC,IAAM,iBAAiB;AA8BhB,IAAM,eAA8C;AAAA,EACzD,YAAY;AACd;AACA,IAAM,WAAyD;AAAA,EAC7D,YAAY;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,aAAa;AAAA,IACX,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAnEA;AAmHA,IAAqB,2BAArB,cAAsD,eAIpD;AAAA,EAsBA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAQG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAgBH;AAAA;AAAA;AAAA;AAAA;AAyEA;AAQA,uBAAM;AA+DN;AAyBA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA6BN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA7PN;AAEA,oCAAc;AAEd,2CAAqB;AAAA,MACnB,+BAA+B,MAAM;AACnC,cAAM,EAAE,WAAW,IAAI,KAAK,gBAAgB;AAAA,UAC1C;AAAA,QACF;AACA,2BAAK,aAAc;AAEnB,aAAK,gBAAgB,UAAU,4BAA4B,MAAM;AAC/D,6BAAK,aAAc;AAAA,QACrB,CA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;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT","sourcesContent":["import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport {\n createLoginRawMessage,\n getAccessToken,\n getNonce,\n login,\n} from './services';\n\nconst THIRTY_MIN_MS = 1000 * 60 * 30;\n\nconst controllerName = 'AuthenticationController';\n\n// State\ntype SessionProfile = {\n identifierId: string;\n profileId: string;\n};\n\ntype SessionData = {\n /** profile - anonymous profile data for the given logged in user */\n profile: SessionProfile;\n /** accessToken - used to make requests authorized endpoints */\n accessToken: string;\n /** expiresIn - string date to determine if new access token is required */\n expiresIn: string;\n};\n\ntype MetaMetricsAuth = {\n getMetaMetricsId: () => string | Promise<string>;\n agent: 'extension' | 'mobile';\n};\n\nexport type AuthenticationControllerState = {\n /**\n * Global isSignedIn state.\n * Can be used to determine if \"Profile Syncing\" is enabled.\n */\n isSignedIn: boolean;\n sessionData?: SessionData;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n persist: true,\n anonymous: true,\n },\n sessionData: {\n persist: true,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'isSignedIn'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\n// Allowed Actions\nexport type AllowedActions =\n | HandleSnapRequest\n | KeyringControllerGetStateAction;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Global Profile Syncing and Notifications\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n #metametrics: MetaMetricsAuth;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#metametrics = metametrics;\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n }\n\n public async performSignIn(): Promise<string> {\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n public performSignOut(): void {\n this.#assertLoggedIn();\n\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = undefined;\n });\n }\n\n public async getBearerToken(): Promise<string> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.accessToken;\n }\n\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n /**\n * Will return a session profile.\n * Throws if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<SessionProfile> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.profile;\n }\n\n const { profile } = await this.#performAuthenticationFlow();\n return profile;\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n #assertLoggedIn(): void {\n if (!this.state.isSignedIn) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n async #performAuthenticationFlow(): Promise<{\n profile: SessionProfile;\n accessToken: string;\n }> {\n try {\n // 1. Nonce\n const publicKey = await this.#snapGetPublicKey();\n const nonce = await getNonce(publicKey);\n if (!nonce) {\n throw new Error(`Unable to get nonce`);\n }\n\n // 2. Login\n const rawMessage = createLoginRawMessage(nonce, publicKey);\n const signature = await this.#snapSignMessage(rawMessage);\n const loginResponse = await login(rawMessage, signature, {\n metametricsId: await this.#metametrics.getMetaMetricsId(),\n agent: this.#metametrics.agent,\n });\n if (!loginResponse?.token) {\n throw new Error(`Unable to login`);\n }\n\n const profile: SessionProfile = {\n identifierId: loginResponse.profile.identifier_id,\n profileId: loginResponse.profile.profile_id,\n };\n\n // 3. Trade for Access Token\n const accessToken = await getAccessToken(\n loginResponse.token,\n this.#metametrics.agent,\n );\n if (!accessToken) {\n throw new Error(`Unable to get Access Token`);\n }\n\n // Update Internal State\n this.update((state) => {\n state.isSignedIn = true;\n const expiresIn = new Date();\n expiresIn.setTime(expiresIn.getTime() + THIRTY_MIN_MS);\n state.sessionData = {\n profile,\n accessToken,\n expiresIn: expiresIn.toString(),\n };\n });\n\n return {\n profile,\n accessToken,\n };\n } catch (e) {\n console.error('Failed to authenticate', e);\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new Error(\n `${controllerName}: Failed to authenticate - ${errorMessage}`,\n );\n }\n }\n\n #hasValidSession(\n sessionData: SessionData | undefined,\n ): sessionData is SessionData {\n if (!sessionData) {\n return false;\n }\n\n const prevDate = Date.parse(sessionData.expiresIn);\n if (isNaN(prevDate)) {\n return false;\n }\n\n const currentDate = new Date();\n const diffMs = Math.abs(currentDate.getTime() - prevDate);\n\n return THIRTY_MIN_MS > diffMs;\n }\n\n #_snapPublicKeyCache: string | undefined;\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n if (this.#_snapPublicKeyCache) {\n return this.#_snapPublicKeyCache;\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapGetPublicKey - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as string;\n\n this.#_snapPublicKeyCache = result;\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkKW3X4TT5js = require('./chunk-KW3X4TT5.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
@@ -14,9 +14,9 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
|
|
|
14
14
|
// src/controllers/authentication/index.ts
|
|
15
15
|
var authentication_exports = {};
|
|
16
16
|
_chunkIGY2S5BCjs.__export.call(void 0, authentication_exports, {
|
|
17
|
-
Controller: () =>
|
|
17
|
+
Controller: () => _chunkKW3X4TT5js.AuthenticationController,
|
|
18
18
|
Mocks: () => fixtures_exports,
|
|
19
|
-
defaultState: () =>
|
|
19
|
+
defaultState: () => _chunkKW3X4TT5js.defaultState
|
|
20
20
|
});
|
|
21
21
|
|
|
22
22
|
// src/controllers/authentication/__fixtures__/index.ts
|
|
@@ -83,4 +83,4 @@ var getMockAuthAccessTokenResponse = () => {
|
|
|
83
83
|
|
|
84
84
|
|
|
85
85
|
exports.fixtures_exports = fixtures_exports; exports.authentication_exports = authentication_exports;
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
86
|
+
//# sourceMappingURL=chunk-MNVUKRZC.js.map
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createEntryPath
|
|
3
|
+
} from "./chunk-ILIZJQ6X.mjs";
|
|
1
4
|
import {
|
|
2
5
|
createSHA256Hash,
|
|
3
6
|
encryption_default
|
|
@@ -7,8 +10,7 @@ import {
|
|
|
7
10
|
} from "./chunk-FQ5SDMRE.mjs";
|
|
8
11
|
import {
|
|
9
12
|
NotFoundError,
|
|
10
|
-
UserStorageError
|
|
11
|
-
ValidationError
|
|
13
|
+
UserStorageError
|
|
12
14
|
} from "./chunk-TFFQFIJV.mjs";
|
|
13
15
|
import {
|
|
14
16
|
__privateAdd,
|
|
@@ -16,7 +18,7 @@ import {
|
|
|
16
18
|
} from "./chunk-U5UIDVOO.mjs";
|
|
17
19
|
|
|
18
20
|
// src/sdk/user-storage.ts
|
|
19
|
-
var STORAGE_URL = (env,
|
|
21
|
+
var STORAGE_URL = (env, encryptedPath) => `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;
|
|
20
22
|
var _upsertUserStorage, upsertUserStorage_fn, _getUserStorage, getUserStorage_fn, _createEntryKey, createEntryKey_fn, _getAuthorizationHeader, getAuthorizationHeader_fn;
|
|
21
23
|
var UserStorage = class {
|
|
22
24
|
constructor(config, options) {
|
|
@@ -30,17 +32,11 @@ var UserStorage = class {
|
|
|
30
32
|
this.config = config;
|
|
31
33
|
this.options = options;
|
|
32
34
|
}
|
|
33
|
-
async setItem(
|
|
34
|
-
|
|
35
|
-
throw new ValidationError("feature or key cannot be empty strings");
|
|
36
|
-
}
|
|
37
|
-
await __privateMethod(this, _upsertUserStorage, upsertUserStorage_fn).call(this, feature, key, value);
|
|
35
|
+
async setItem(path, value) {
|
|
36
|
+
await __privateMethod(this, _upsertUserStorage, upsertUserStorage_fn).call(this, path, value);
|
|
38
37
|
}
|
|
39
|
-
async getItem(
|
|
40
|
-
|
|
41
|
-
throw new ValidationError("feature or key cannot be empty strings");
|
|
42
|
-
}
|
|
43
|
-
return __privateMethod(this, _getUserStorage, getUserStorage_fn).call(this, feature, key);
|
|
38
|
+
async getItem(path) {
|
|
39
|
+
return __privateMethod(this, _getUserStorage, getUserStorage_fn).call(this, path);
|
|
44
40
|
}
|
|
45
41
|
async getStorageKey() {
|
|
46
42
|
const storageKey = await this.options.storage?.getStorageKey();
|
|
@@ -57,14 +53,13 @@ var UserStorage = class {
|
|
|
57
53
|
}
|
|
58
54
|
};
|
|
59
55
|
_upsertUserStorage = new WeakSet();
|
|
60
|
-
upsertUserStorage_fn = async function(
|
|
56
|
+
upsertUserStorage_fn = async function(path, data) {
|
|
61
57
|
try {
|
|
62
58
|
const headers = await __privateMethod(this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
|
|
63
59
|
const storageKey = await this.getStorageKey();
|
|
64
60
|
const encryptedData = encryption_default.encryptString(data, storageKey);
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
);
|
|
61
|
+
const encryptedPath = createEntryPath(path, storageKey);
|
|
62
|
+
const url = new URL(STORAGE_URL(this.env, encryptedPath));
|
|
68
63
|
const response = await fetch(url.toString(), {
|
|
69
64
|
method: "PUT",
|
|
70
65
|
headers: {
|
|
@@ -85,18 +80,17 @@ upsertUserStorage_fn = async function(feature, key, data) {
|
|
|
85
80
|
} catch (e) {
|
|
86
81
|
const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? "");
|
|
87
82
|
throw new UserStorageError(
|
|
88
|
-
`failed to upsert user storage for
|
|
83
|
+
`failed to upsert user storage for path '${path}'. ${errorMessage}`
|
|
89
84
|
);
|
|
90
85
|
}
|
|
91
86
|
};
|
|
92
87
|
_getUserStorage = new WeakSet();
|
|
93
|
-
getUserStorage_fn = async function(
|
|
88
|
+
getUserStorage_fn = async function(path) {
|
|
94
89
|
try {
|
|
95
90
|
const headers = await __privateMethod(this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
|
|
96
91
|
const storageKey = await this.getStorageKey();
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
);
|
|
92
|
+
const encryptedPath = createEntryPath(path, storageKey);
|
|
93
|
+
const url = new URL(STORAGE_URL(this.env, encryptedPath));
|
|
100
94
|
const response = await fetch(url.toString(), {
|
|
101
95
|
headers: {
|
|
102
96
|
"Content-Type": "application/json",
|
|
@@ -105,7 +99,7 @@ getUserStorage_fn = async function(feature, key) {
|
|
|
105
99
|
});
|
|
106
100
|
if (response.status === 404) {
|
|
107
101
|
throw new NotFoundError(
|
|
108
|
-
`feature/key set not found for
|
|
102
|
+
`feature/key set not found for path '${path}'.`
|
|
109
103
|
);
|
|
110
104
|
}
|
|
111
105
|
if (!response.ok) {
|
|
@@ -122,7 +116,7 @@ getUserStorage_fn = async function(feature, key) {
|
|
|
122
116
|
}
|
|
123
117
|
const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? "");
|
|
124
118
|
throw new UserStorageError(
|
|
125
|
-
`failed to get user storage for
|
|
119
|
+
`failed to get user storage for path '${path}'. ${errorMessage}`
|
|
126
120
|
);
|
|
127
121
|
}
|
|
128
122
|
};
|
|
@@ -141,4 +135,4 @@ export {
|
|
|
141
135
|
STORAGE_URL,
|
|
142
136
|
UserStorage
|
|
143
137
|
};
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
138
|
+
//# sourceMappingURL=chunk-NPH5AHLH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk/user-storage.ts"],"sourcesContent":["import type { UserStoragePath } from '../controllers/user-storage/schema';\nimport { createEntryPath } from '../controllers/user-storage/schema';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport encryption, { createSHA256Hash } from './encryption';\nimport type { Env } from './env';\nimport { getEnvUrls } from './env';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(path: UserStoragePath, value: string): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async getItem(path: UserStoragePath): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(path: UserStoragePath, data: string): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedData = encryption.encryptString(data, storageKey);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(path: UserStoragePath): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAQO,IAAM,cAAc,CAAC,KAAU,kBACpC,GAAG,WAAW,GAAG,EAAE,iBAAiB,uBAAuB,aAAa;AAT1E;AA8BO,IAAM,cAAN,MAAkB;AAAA,EAOvB,YAAY,QAA2B,SAA6B;AA6BpE,uBAAM;AAqCN,uBAAM;AA6CN;AAOA;AAAA;AAAA,uBAAM;AArHJ,SAAK,MAAM,OAAO;AAClB,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,QAAQ,MAAuB,OAA8B;AACjE,UAAM,sBAAK,0CAA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AAO,EAAE,eAAe,UAAU,WAAW,GAAG;AAClD;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkXSSIP3PJjs = require('./chunk-XSSIP3PJ.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
var _chunkG4NU4KP7js = require('./chunk-G4NU4KP7.js');
|
|
@@ -20,7 +20,7 @@ var _chunkPQ5T4GHYjs = require('./chunk-PQ5T4GHY.js');
|
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
var
|
|
23
|
+
var _chunkFUPEFLXBjs = require('./chunk-FUPEFLXB.js');
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
|
|
@@ -50,7 +50,7 @@ _chunkIGY2S5BCjs.__export.call(void 0, sdk_exports, {
|
|
|
50
50
|
AuthType: () => _chunkPBRUOBEQjs.AuthType,
|
|
51
51
|
Encryption: () => _chunkP4DUDLMYjs.Encryption,
|
|
52
52
|
Env: () => _chunkSMKTWM6Ijs.Env,
|
|
53
|
-
JwtBearerAuth: () =>
|
|
53
|
+
JwtBearerAuth: () => _chunkXSSIP3PJjs.JwtBearerAuth,
|
|
54
54
|
MESSAGE_SIGNING_SNAP: () => _chunkPQ5T4GHYjs.MESSAGE_SIGNING_SNAP,
|
|
55
55
|
NonceRetrievalError: () => _chunkMBTBE4P5js.NonceRetrievalError,
|
|
56
56
|
NotFoundError: () => _chunkMBTBE4P5js.NotFoundError,
|
|
@@ -59,10 +59,10 @@ _chunkIGY2S5BCjs.__export.call(void 0, sdk_exports, {
|
|
|
59
59
|
SIWEJwtBearerAuth: () => _chunkG4NU4KP7js.SIWEJwtBearerAuth,
|
|
60
60
|
SNAP_ORIGIN: () => _chunkPQ5T4GHYjs.SNAP_ORIGIN,
|
|
61
61
|
SRPJwtBearerAuth: () => _chunkVD2IGTS3js.SRPJwtBearerAuth,
|
|
62
|
-
STORAGE_URL: () =>
|
|
62
|
+
STORAGE_URL: () => _chunkFUPEFLXBjs.STORAGE_URL,
|
|
63
63
|
SignInError: () => _chunkMBTBE4P5js.SignInError,
|
|
64
64
|
UnsupportedAuthTypeError: () => _chunkMBTBE4P5js.UnsupportedAuthTypeError,
|
|
65
|
-
UserStorage: () =>
|
|
65
|
+
UserStorage: () => _chunkFUPEFLXBjs.UserStorage,
|
|
66
66
|
UserStorageError: () => _chunkMBTBE4P5js.UserStorageError,
|
|
67
67
|
ValidationError: () => _chunkMBTBE4P5js.ValidationError,
|
|
68
68
|
connectSnap: () => _chunkPQ5T4GHYjs.connectSnap,
|
|
@@ -76,4 +76,4 @@ _chunkIGY2S5BCjs.__export.call(void 0, sdk_exports, {
|
|
|
76
76
|
|
|
77
77
|
|
|
78
78
|
exports.sdk_exports = sdk_exports;
|
|
79
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
//# sourceMappingURL=chunk-PSR2V3R4.js.map
|
|
@@ -4,14 +4,15 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
getUserStorage,
|
|
6
6
|
upsertUserStorage
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-FU7PSGFP.mjs";
|
|
8
8
|
import {
|
|
9
9
|
createSHA256Hash
|
|
10
10
|
} from "./chunk-K5UKU454.mjs";
|
|
11
11
|
import {
|
|
12
12
|
__privateAdd,
|
|
13
13
|
__privateGet,
|
|
14
|
-
__privateMethod
|
|
14
|
+
__privateMethod,
|
|
15
|
+
__privateSet
|
|
15
16
|
} from "./chunk-U5UIDVOO.mjs";
|
|
16
17
|
|
|
17
18
|
// src/controllers/user-storage/UserStorageController.ts
|
|
@@ -31,7 +32,7 @@ var metadata = {
|
|
|
31
32
|
anonymous: false
|
|
32
33
|
}
|
|
33
34
|
};
|
|
34
|
-
var _auth, _notificationServices, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
|
|
35
|
+
var _auth, _notificationServices, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
|
|
35
36
|
var UserStorageController = class extends BaseController {
|
|
36
37
|
constructor(params) {
|
|
37
38
|
super({
|
|
@@ -102,8 +103,24 @@ var UserStorageController = class extends BaseController {
|
|
|
102
103
|
);
|
|
103
104
|
}
|
|
104
105
|
});
|
|
106
|
+
__privateAdd(this, _isUnlocked, false);
|
|
107
|
+
__privateAdd(this, _keyringController, {
|
|
108
|
+
setupLockedStateSubscriptions: () => {
|
|
109
|
+
const { isUnlocked } = this.messagingSystem.call(
|
|
110
|
+
"KeyringController:getState"
|
|
111
|
+
);
|
|
112
|
+
__privateSet(this, _isUnlocked, isUnlocked);
|
|
113
|
+
this.messagingSystem.subscribe("KeyringController:unlock", () => {
|
|
114
|
+
__privateSet(this, _isUnlocked, true);
|
|
115
|
+
});
|
|
116
|
+
this.messagingSystem.subscribe("KeyringController:lock", () => {
|
|
117
|
+
__privateSet(this, _isUnlocked, false);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
});
|
|
105
121
|
__privateAdd(this, __snapSignMessageCache, {});
|
|
106
122
|
this.getMetaMetricsState = params.getMetaMetricsState;
|
|
123
|
+
__privateGet(this, _keyringController).setupLockedStateSubscriptions();
|
|
107
124
|
__privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
|
|
108
125
|
}
|
|
109
126
|
async enableProfileSyncing() {
|
|
@@ -143,7 +160,7 @@ var UserStorageController = class extends BaseController {
|
|
|
143
160
|
}
|
|
144
161
|
const isMetaMetricsParticipation = this.getMetaMetricsState();
|
|
145
162
|
if (!isMetaMetricsParticipation) {
|
|
146
|
-
this.
|
|
163
|
+
await __privateGet(this, _auth).signOut();
|
|
147
164
|
}
|
|
148
165
|
__privateMethod(this, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn).call(this, false);
|
|
149
166
|
this.update((state) => {
|
|
@@ -161,14 +178,14 @@ var UserStorageController = class extends BaseController {
|
|
|
161
178
|
* Allows retrieval of stored data. Data stored is string formatted.
|
|
162
179
|
* Developers can extend the entry path and entry name through the `schema.ts` file.
|
|
163
180
|
*
|
|
164
|
-
* @param
|
|
181
|
+
* @param path - string in the form of `${feature}.${key}` that matches schema
|
|
165
182
|
* @returns the decrypted string contents found from user storage (or null if not found)
|
|
166
183
|
*/
|
|
167
|
-
async performGetStorage(
|
|
184
|
+
async performGetStorage(path) {
|
|
168
185
|
__privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
169
186
|
const { bearerToken, storageKey } = await __privateMethod(this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
|
|
170
187
|
const result = await getUserStorage({
|
|
171
|
-
|
|
188
|
+
path,
|
|
172
189
|
bearerToken,
|
|
173
190
|
storageKey
|
|
174
191
|
});
|
|
@@ -178,15 +195,15 @@ var UserStorageController = class extends BaseController {
|
|
|
178
195
|
* Allows storage of user data. Data stored must be string formatted.
|
|
179
196
|
* Developers can extend the entry path and entry name through the `schema.ts` file.
|
|
180
197
|
*
|
|
181
|
-
* @param
|
|
198
|
+
* @param path - string in the form of `${feature}.${key}` that matches schema
|
|
182
199
|
* @param value - The string data you want to store.
|
|
183
200
|
* @returns nothing. NOTE that an error is thrown if fails to store data.
|
|
184
201
|
*/
|
|
185
|
-
async performSetStorage(
|
|
202
|
+
async performSetStorage(path, value) {
|
|
186
203
|
__privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
187
204
|
const { bearerToken, storageKey } = await __privateMethod(this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
|
|
188
205
|
await upsertUserStorage(value, {
|
|
189
|
-
|
|
206
|
+
path,
|
|
190
207
|
bearerToken,
|
|
191
208
|
storageKey
|
|
192
209
|
});
|
|
@@ -204,6 +221,8 @@ var UserStorageController = class extends BaseController {
|
|
|
204
221
|
};
|
|
205
222
|
_auth = new WeakMap();
|
|
206
223
|
_notificationServices = new WeakMap();
|
|
224
|
+
_isUnlocked = new WeakMap();
|
|
225
|
+
_keyringController = new WeakMap();
|
|
207
226
|
_registerMessageHandlers = new WeakSet();
|
|
208
227
|
registerMessageHandlers_fn = function() {
|
|
209
228
|
this.messagingSystem.registerActionHandler(
|
|
@@ -260,6 +279,11 @@ snapSignMessage_fn = async function(message) {
|
|
|
260
279
|
if (__privateGet(this, __snapSignMessageCache)[message]) {
|
|
261
280
|
return __privateGet(this, __snapSignMessageCache)[message];
|
|
262
281
|
}
|
|
282
|
+
if (!__privateGet(this, _isUnlocked)) {
|
|
283
|
+
throw new Error(
|
|
284
|
+
"#snapSignMessage - unable to call snap, wallet is locked"
|
|
285
|
+
);
|
|
286
|
+
}
|
|
263
287
|
const result = await this.messagingSystem.call(
|
|
264
288
|
"SnapController:handleRequest",
|
|
265
289
|
createSnapSignMessageRequest(message)
|
|
@@ -278,4 +302,4 @@ export {
|
|
|
278
302
|
defaultState,
|
|
279
303
|
UserStorageController
|
|
280
304
|
};
|
|
281
|
-
//# sourceMappingURL=chunk-
|
|
305
|
+
//# sourceMappingURL=chunk-QE5X2BT3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"sourcesContent":["import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport { createSHA256Hash } from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePath,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePath,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAiC/B,IAAM,iBAAiB;AAchB,IAAM,eAA2C;AAAA,EACtD,yBAAyB;AAAA,EACzB,+BAA+B;AACjC;AAEA,IAAM,WAAsD;AAAA,EAC1D,yBAAyB;AAAA,IACvB,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,+BAA+B;AAAA,IAC7B,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAjEA;AAiIA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EA8DA,YAAY,QAIT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC5C,CAAC;AAWH;AAAA;AAAA;AAAA;AAAA;AAyJA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAqBN;AAhTA,8BAAQ;AAAA,MACN,gBAAgB,YAAY;AAC1B,eAAO,MAAM,KAAK,gBAAgB;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,MACA,cAAc,YAAY;AACxB,cAAM,iBAAiB,MAAM,KAAK,gBAAgB;AAAA,UAChD;AAAA,QACF;AACA,eAAO,gBAAgB;AAAA,MACzB;AAAA,MACA,eAAe,MAAM;AACnB,eAAO,KAAK,gBAAgB,KA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AEA,QAAM,sBAAsB,MAAM,sBAAK,sCAAL,WAAsB,YAAY,EAAE;AACtE,QAAM,aAAa,iBAAiB,mBAAmB;AACvD,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
|
|
4
|
+
|
|
5
|
+
// src/controllers/user-storage/schema.ts
|
|
6
|
+
var USER_STORAGE_SCHEMA = {
|
|
7
|
+
notifications: ["notificationSettings"]
|
|
8
|
+
};
|
|
9
|
+
var getFeatureAndKeyFromPath = (path) => {
|
|
10
|
+
const pathRegex = /^\w+\.\w+$/u;
|
|
11
|
+
if (!pathRegex.test(path)) {
|
|
12
|
+
throw new Error(
|
|
13
|
+
`user-storage - path is not in the correct format. Correct format: 'feature.key'`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
const [feature, key] = path.split(".");
|
|
17
|
+
if (!(feature in USER_STORAGE_SCHEMA)) {
|
|
18
|
+
throw new Error(`user-storage - invalid feature provided: ${feature}`);
|
|
19
|
+
}
|
|
20
|
+
const validFeature = USER_STORAGE_SCHEMA[feature];
|
|
21
|
+
if (!validFeature.includes(key)) {
|
|
22
|
+
const validKeys = USER_STORAGE_SCHEMA[feature].join(", ");
|
|
23
|
+
throw new Error(
|
|
24
|
+
`user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
return { feature, key };
|
|
28
|
+
};
|
|
29
|
+
function createEntryPath(path, storageKey) {
|
|
30
|
+
const { feature, key } = getFeatureAndKeyFromPath(path);
|
|
31
|
+
const hashedKey = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, key + storageKey);
|
|
32
|
+
return `/${feature}/${hashedKey}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
exports.USER_STORAGE_SCHEMA = USER_STORAGE_SCHEMA; exports.getFeatureAndKeyFromPath = getFeatureAndKeyFromPath; exports.createEntryPath = createEntryPath;
|
|
40
|
+
//# sourceMappingURL=chunk-SLHAVOTE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/user-storage/schema.ts"],"names":[],"mappings":";;;;;AAOO,IAAM,sBAAsB;AAAA,EACjC,eAAe,CAAC,sBAAsB;AACxC;AAgBO,IAAM,2BAA2B,CACtC,SAC6B;AAC7B,QAAM,YAAY;AAElB,MAAI,CAAC,UAAU,KAAK,IAAI,GAAG;AACzB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,CAAC,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG;AAKrC,MAAI,EAAE,WAAW,sBAAsB;AACrC,UAAM,IAAI,MAAM,4CAA4C,OAAO,EAAE;AAAA,EACvE;AAEA,QAAM,eAAe,oBAAoB,OAAO;AAEhD,MAAI,CAAC,aAAa,SAAS,GAAG,GAAG;AAC/B,UAAM,YAAY,oBAAoB,OAAO,EAAE,KAAK,IAAI;AAExD,UAAM,IAAI;AAAA,MACR,yDAAyD,GAAG,iBAAiB,SAAS;AAAA,IACxF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,IAAI;AACxB;AAWO,SAAS,gBACd,MACA,YACQ;AACR,QAAM,EAAE,SAAS,IAAI,IAAI,yBAAyB,IAAI;AACtD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AAEnD,SAAO,IAAI,OAAO,IAAI,SAAS;AACjC","sourcesContent":["import { createSHA256Hash } from './encryption';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Developers can provide additional features and keys by extending these types below.\n */\n\nexport const USER_STORAGE_SCHEMA = {\n notifications: ['notificationSettings'],\n} as const;\n\ntype UserStorageSchema = typeof USER_STORAGE_SCHEMA;\ntype UserStorageFeatures = keyof UserStorageSchema;\ntype UserStorageFeatureKeys<Feature extends UserStorageFeatures> =\n UserStorageSchema[Feature][number];\n\ntype UserStorageFeatureAndKey = {\n feature: UserStorageFeatures;\n key: UserStorageFeatureKeys<UserStorageFeatures>;\n};\n\nexport type UserStoragePath = {\n [K in keyof UserStorageSchema]: `${K}.${UserStorageSchema[K][number]}`;\n}[keyof UserStorageSchema];\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStoragePath,\n): UserStorageFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.') as [\n UserStorageFeatures,\n UserStorageFeatureKeys<UserStorageFeatures>,\n ];\n\n if (!(feature in USER_STORAGE_SCHEMA)) {\n throw new Error(`user-storage - invalid feature provided: ${feature}`);\n }\n\n const validFeature = USER_STORAGE_SCHEMA[feature] as readonly string[];\n\n if (!validFeature.includes(key)) {\n const validKeys = USER_STORAGE_SCHEMA[feature].join(', ');\n\n throw new Error(\n `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`,\n );\n }\n\n return { feature, key };\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStoragePath,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `/${feature}/${hashedKey}`;\n}\n"]}
|
|
@@ -8,6 +8,12 @@ import {
|
|
|
8
8
|
getNonce,
|
|
9
9
|
pairIdentifiers
|
|
10
10
|
} from "./chunk-WB6MUIML.mjs";
|
|
11
|
+
import {
|
|
12
|
+
getMetaMaskProviderEIP6963
|
|
13
|
+
} from "./chunk-5XSXZTED.mjs";
|
|
14
|
+
import {
|
|
15
|
+
connectSnap
|
|
16
|
+
} from "./chunk-5EBUFNAN.mjs";
|
|
11
17
|
import {
|
|
12
18
|
PairError,
|
|
13
19
|
UnsupportedAuthTypeError
|
|
@@ -42,6 +48,14 @@ var JwtBearerAuth = class {
|
|
|
42
48
|
async getAccessToken() {
|
|
43
49
|
return await __privateGet(this, _sdk).getAccessToken();
|
|
44
50
|
}
|
|
51
|
+
async connectSnap() {
|
|
52
|
+
const provider = await getMetaMaskProviderEIP6963();
|
|
53
|
+
if (!provider) {
|
|
54
|
+
throw new Error("failed to get MetaMaskProviderEIP6963 provider");
|
|
55
|
+
}
|
|
56
|
+
const res = await connectSnap(provider);
|
|
57
|
+
return res;
|
|
58
|
+
}
|
|
45
59
|
async getUserProfile() {
|
|
46
60
|
return await __privateGet(this, _sdk).getUserProfile();
|
|
47
61
|
}
|
|
@@ -103,4 +117,4 @@ assertSIWE_fn = function(type, sdk) {
|
|
|
103
117
|
export {
|
|
104
118
|
JwtBearerAuth
|
|
105
119
|
};
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
120
|
+
//# sourceMappingURL=chunk-VYZPOR47.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk/authentication.ts"],"sourcesContent":["import { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe';\nimport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp';\nimport {\n getNonce,\n pairIdentifiers,\n} from './authentication-jwt-bearer/services';\nimport type { UserProfile, Pair } from './authentication-jwt-bearer/types';\nimport { AuthType } from './authentication-jwt-bearer/types';\nimport type { Env } from './env';\nimport { PairError, UnsupportedAuthTypeError } from './errors';\nimport { getMetaMaskProviderEIP6963 } from './utils/eip-6963-metamask-provider';\nimport { connectSnap } from './utils/messaging-signing-snap-requests';\n\n// Computing the Classes, so we only get back the public methods for the interface.\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype Compute<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\ntype SIWEInterface = Compute<SIWEJwtBearerAuth>;\ntype SRPInterface = Compute<SRPJwtBearerAuth>;\n\ntype SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;\ntype SRPParams = ConstructorParameters<typeof SRPJwtBearerAuth>;\ntype JwtBearerAuthParams = SiweParams | SRPParams;\n\nexport class JwtBearerAuth implements SIWEInterface, SRPInterface {\n #type: AuthType;\n\n #env: Env;\n\n #sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth;\n\n constructor(...args: JwtBearerAuthParams) {\n this.#type = args[0].type;\n this.#env = args[0].env;\n\n if (args[0].type === AuthType.SRP) {\n this.#sdk = new SRPJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n if (args[0].type === AuthType.SiWE) {\n this.#sdk = new SIWEJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n throw new UnsupportedAuthTypeError('unsupported auth type');\n }\n\n async getAccessToken(): Promise<string> {\n return await this.#sdk.getAccessToken();\n }\n\n async connectSnap(): Promise<string> {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new Error('failed to get MetaMaskProviderEIP6963 provider');\n }\n const res = await connectSnap(provider);\n return res;\n }\n\n async getUserProfile(): Promise<UserProfile> {\n return await this.#sdk.getUserProfile();\n }\n\n async getIdentifier(): Promise<string> {\n return await this.#sdk.getIdentifier();\n }\n\n async signMessage(message: string): Promise<string> {\n return await this.#sdk.signMessage(message);\n }\n\n async pairIdentifiers(pairing: Pair[]): Promise<void> {\n const profile = await this.getUserProfile();\n const n = await getNonce(profile.profileId, this.#env);\n\n const logins = await Promise.all(\n pairing.map(async (p) => {\n try {\n const raw = `metamask:${n.nonce}:${p.identifier}`;\n const sig = await p.signMessage(raw);\n return {\n signature: sig,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: raw,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n encrypted_storage_key: p.encryptedStorageKey,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_type: p.identifierType,\n };\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new PairError(\n `failed to sign pairing message: ${errorMessage}`,\n );\n }\n }),\n );\n\n const accessToken = await this.getAccessToken();\n await pairIdentifiers(n.nonce, logins, accessToken, this.#env);\n }\n\n prepare(signer: {\n address: string;\n chainId: number;\n signMessage: (message: string) => Promise<string>;\n domain: string;\n }): void {\n this.#assertSIWE(this.#type, this.#sdk);\n this.#sdk.prepare(signer);\n }\n\n #assertSIWE(\n type: AuthType,\n sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts sdk is SIWEJwtBearerAuth {\n if (type === AuthType.SiWE) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SIWE auth type',\n );\n }\n}\n\nexport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe';\nexport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp';\nexport * from './authent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