@metamask/profile-sync-controller 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -1
- package/dist/{chunk-NSSHFDIS.mjs → chunk-2VEMA6OE.mjs} +2 -2
- package/dist/{chunk-HMRRB4EX.js → chunk-4LMFZDL4.js} +22 -13
- package/dist/chunk-4LMFZDL4.js.map +1 -0
- package/dist/{chunk-JJ5BDCKD.js → chunk-4TMLEABQ.js} +18 -16
- package/dist/chunk-4TMLEABQ.js.map +1 -0
- package/dist/{chunk-EYZFHZR2.js → chunk-5MQUI24U.js} +3 -3
- package/dist/{chunk-QU4EXKJO.mjs → chunk-6DAK2U35.mjs} +2 -2
- package/dist/{chunk-LYDHYB6I.mjs → chunk-76NMME23.mjs} +20 -11
- package/dist/chunk-76NMME23.mjs.map +1 -0
- package/dist/{chunk-T3FNDVE3.js → chunk-BKQE7DB5.js} +30 -18
- package/dist/chunk-BKQE7DB5.js.map +1 -0
- package/dist/{chunk-K5UKU454.mjs → chunk-COBJUBZE.mjs} +31 -19
- package/dist/chunk-COBJUBZE.mjs.map +1 -0
- package/dist/{chunk-5TOWF6UW.mjs → chunk-KHASG4H3.mjs} +2 -2
- package/dist/{chunk-4WXZXVLI.mjs → chunk-M7AUA5W7.mjs} +10 -8
- package/dist/{chunk-4WXZXVLI.mjs.map → chunk-M7AUA5W7.mjs.map} +1 -1
- package/dist/{chunk-E7Z5TCQT.mjs → chunk-MK7ABX2V.mjs} +5 -5
- package/dist/{chunk-E7Z5TCQT.mjs.map → chunk-MK7ABX2V.mjs.map} +1 -1
- package/dist/{chunk-ZYYAQJ56.mjs → chunk-NEBLEB3X.mjs} +19 -15
- package/dist/chunk-NEBLEB3X.mjs.map +1 -0
- package/dist/{chunk-AK7OTIWA.js → chunk-NIUQ34PY.js} +3 -3
- package/dist/{chunk-M23ZCTKE.mjs → chunk-OLFO6R7Z.mjs} +55 -20
- package/dist/chunk-OLFO6R7Z.mjs.map +1 -0
- package/dist/{chunk-LNECIW4K.js → chunk-PQMPSEVJ.js} +59 -24
- package/dist/chunk-PQMPSEVJ.js.map +1 -0
- package/dist/{chunk-YKOMKXG4.mjs → chunk-PU7MAIST.mjs} +13 -4
- package/dist/chunk-PU7MAIST.mjs.map +1 -0
- package/dist/{chunk-PQ5T4GHY.js → chunk-QCQU4BQL.js} +15 -2
- package/dist/chunk-QCQU4BQL.js.map +1 -0
- package/dist/{chunk-J7NSK6BO.mjs → chunk-TP7SP3AG.mjs} +2 -2
- package/dist/{chunk-4ZGRRVMI.js → chunk-UEHMUVQQ.js} +4 -4
- package/dist/{chunk-5EBUFNAN.mjs → chunk-UEWCUBMX.mjs} +14 -1
- package/dist/chunk-UEWCUBMX.mjs.map +1 -0
- package/dist/chunk-UHX7HJAI.js +11 -0
- package/dist/{chunk-ZMQRPWJN.js → chunk-UIRAMHNM.js} +12 -12
- package/dist/chunk-UIRAMHNM.js.map +1 -0
- package/dist/{chunk-WAFY3R2F.js → chunk-VWDRFRJU.js} +27 -23
- package/dist/chunk-VWDRFRJU.js.map +1 -0
- package/dist/{chunk-Q5KTSMRE.js → chunk-Y45XUW33.js} +14 -5
- package/dist/chunk-Y45XUW33.js.map +1 -0
- package/dist/controllers/index.js +7 -7
- package/dist/controllers/index.mjs +6 -6
- package/dist/controllers/user-storage/UserStorageController.js +6 -6
- package/dist/controllers/user-storage/UserStorageController.mjs +5 -5
- package/dist/controllers/user-storage/encryption/encryption.js +2 -2
- package/dist/controllers/user-storage/encryption/encryption.mjs +1 -1
- package/dist/controllers/user-storage/encryption/index.js +3 -3
- package/dist/controllers/user-storage/encryption/index.mjs +2 -2
- package/dist/controllers/user-storage/index.js +7 -7
- package/dist/controllers/user-storage/index.mjs +6 -6
- package/dist/controllers/user-storage/schema.js +4 -4
- package/dist/controllers/user-storage/schema.mjs +3 -3
- package/dist/controllers/user-storage/services.js +5 -5
- package/dist/controllers/user-storage/services.mjs +4 -4
- package/dist/index.js +13 -13
- package/dist/index.mjs +12 -12
- package/dist/sdk/authentication-jwt-bearer/flow-srp.js +3 -3
- package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +2 -2
- package/dist/sdk/authentication.js +4 -4
- package/dist/sdk/authentication.mjs +3 -3
- package/dist/sdk/encryption.js +3 -3
- package/dist/sdk/encryption.mjs +2 -2
- package/dist/sdk/index.js +12 -10
- package/dist/sdk/index.mjs +13 -11
- package/dist/sdk/user-storage.js +6 -6
- package/dist/sdk/user-storage.mjs +5 -5
- package/dist/sdk/utils/messaging-signing-snap-requests.js +4 -2
- package/dist/sdk/utils/messaging-signing-snap-requests.mjs +5 -3
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/controllers/user-storage/UserStorageController.d.ts +5 -3
- package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +4 -4
- package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +2 -2
- package/dist/types/controllers/user-storage/__fixtures__/mockServices.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/encryption/encryption.d.ts +3 -2
- package/dist/types/controllers/user-storage/encryption/encryption.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/services.d.ts +3 -0
- package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
- package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +5 -5
- 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.map +1 -1
- package/dist/types/sdk/utils/messaging-signing-snap-requests.d.ts +7 -0
- package/dist/types/sdk/utils/messaging-signing-snap-requests.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5EBUFNAN.mjs.map +0 -1
- package/dist/chunk-HMRRB4EX.js.map +0 -1
- package/dist/chunk-JJ5BDCKD.js.map +0 -1
- package/dist/chunk-K5UKU454.mjs.map +0 -1
- package/dist/chunk-LDYHGAP4.js +0 -11
- package/dist/chunk-LNECIW4K.js.map +0 -1
- package/dist/chunk-LYDHYB6I.mjs.map +0 -1
- package/dist/chunk-M23ZCTKE.mjs.map +0 -1
- package/dist/chunk-PQ5T4GHY.js.map +0 -1
- package/dist/chunk-Q5KTSMRE.js.map +0 -1
- package/dist/chunk-T3FNDVE3.js.map +0 -1
- package/dist/chunk-WAFY3R2F.js.map +0 -1
- package/dist/chunk-YKOMKXG4.mjs.map +0 -1
- package/dist/chunk-ZMQRPWJN.js.map +0 -1
- package/dist/chunk-ZYYAQJ56.mjs.map +0 -1
- /package/dist/{chunk-NSSHFDIS.mjs.map → chunk-2VEMA6OE.mjs.map} +0 -0
- /package/dist/{chunk-EYZFHZR2.js.map → chunk-5MQUI24U.js.map} +0 -0
- /package/dist/{chunk-QU4EXKJO.mjs.map → chunk-6DAK2U35.mjs.map} +0 -0
- /package/dist/{chunk-5TOWF6UW.mjs.map → chunk-KHASG4H3.mjs.map} +0 -0
- /package/dist/{chunk-AK7OTIWA.js.map → chunk-NIUQ34PY.js.map} +0 -0
- /package/dist/{chunk-J7NSK6BO.mjs.map → chunk-TP7SP3AG.mjs.map} +0 -0
- /package/dist/{chunk-4ZGRRVMI.js.map → chunk-UEHMUVQQ.js.map} +0 -0
- /package/dist/{chunk-LDYHGAP4.js.map → chunk-UHX7HJAI.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerGetAccountByAddressAction } from '@metamask/accounts-controller';
|
|
1
|
+
import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerGetAccountByAddressAction, AccountsControllerAccountRenamedEvent, AccountsControllerAccountAddedEvent } from '@metamask/accounts-controller';
|
|
2
2
|
import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
3
3
|
import { BaseController } from '@metamask/base-controller';
|
|
4
4
|
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent, KeyringControllerAddNewAccountAction } from '@metamask/keyring-controller';
|
|
@@ -13,6 +13,7 @@ export declare type NotificationServicesControllerSelectIsNotificationServicesEn
|
|
|
13
13
|
type: `NotificationServicesController:selectIsNotificationServicesEnabled`;
|
|
14
14
|
handler: () => boolean;
|
|
15
15
|
};
|
|
16
|
+
export declare type NativeScrypt = (passwd: string, salt: Uint8Array, N: number, r: number, p: number, size: number) => Promise<Uint8Array>;
|
|
16
17
|
declare const controllerName = "UserStorageController";
|
|
17
18
|
export type UserStorageControllerState = {
|
|
18
19
|
/**
|
|
@@ -54,7 +55,7 @@ export type UserStorageControllerAccountSyncingComplete = {
|
|
|
54
55
|
type: `${typeof controllerName}:accountSyncingComplete`;
|
|
55
56
|
payload: [boolean];
|
|
56
57
|
};
|
|
57
|
-
export type AllowedEvents = UserStorageControllerChangeEvent | UserStorageControllerAccountSyncingInProgress | UserStorageControllerAccountSyncingComplete | KeyringControllerLockEvent | KeyringControllerUnlockEvent;
|
|
58
|
+
export type AllowedEvents = UserStorageControllerChangeEvent | UserStorageControllerAccountSyncingInProgress | UserStorageControllerAccountSyncingComplete | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AccountsControllerAccountAddedEvent | AccountsControllerAccountRenamedEvent;
|
|
58
59
|
export type UserStorageControllerMessenger = RestrictedControllerMessenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
59
60
|
/**
|
|
60
61
|
* Reusable controller that allows any team to store synchronized data for a given user.
|
|
@@ -67,13 +68,14 @@ export type UserStorageControllerMessenger = RestrictedControllerMessenger<typeo
|
|
|
67
68
|
export default class UserStorageController extends BaseController<typeof controllerName, UserStorageControllerState, UserStorageControllerMessenger> {
|
|
68
69
|
#private;
|
|
69
70
|
getMetaMetricsState: () => boolean;
|
|
70
|
-
constructor(
|
|
71
|
+
constructor({ messenger, state, env, getMetaMetricsState, nativeScryptCrypto, }: {
|
|
71
72
|
messenger: UserStorageControllerMessenger;
|
|
72
73
|
state?: UserStorageControllerState;
|
|
73
74
|
env?: {
|
|
74
75
|
isAccountSyncingEnabled?: boolean;
|
|
75
76
|
};
|
|
76
77
|
getMetaMetricsState: () => boolean;
|
|
78
|
+
nativeScryptCrypto?: NativeScrypt;
|
|
77
79
|
});
|
|
78
80
|
enableProfileSyncing(): Promise<void>;
|
|
79
81
|
setIsProfileSyncingEnabled(isProfileSyncingEnabled: boolean): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.d.ts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,2CAA2C,
|
|
1
|
+
{"version":3,"file":"UserStorageController.d.ts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,2CAA2C,EAC3C,qCAAqC,EACrC,mCAAmC,EACpC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAE9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACrC,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAA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CAC5B,IAAI,EAAE,gCAAgC,GACrC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAgBzB;;;;;;OAMG;IACU,kCAAkC,CAC7C,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAgB3B;;;;;;;OAOG;IACU,iBAAiB,CAC5B,IAAI,EAAE,gCAAgC,EACtC,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC;IAchB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAmF7C;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IAwI1D;;;OAGG;IACG,gCAAgC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAgBvE"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly } from '../schema';
|
|
2
2
|
import type { GetUserStorageAllFeatureEntriesResponse, GetUserStorageResponse } from '../services';
|
|
3
3
|
export declare const getMockUserStorageEndpoint: (path: UserStoragePathWithFeatureAndKey | UserStoragePathWithFeatureOnly) => string;
|
|
4
|
-
export declare const getMockUserStorageGetResponse: (path?: UserStoragePathWithFeatureAndKey) => {
|
|
4
|
+
export declare const getMockUserStorageGetResponse: (path?: UserStoragePathWithFeatureAndKey) => Promise<{
|
|
5
5
|
url: string;
|
|
6
6
|
requestMethod: "GET";
|
|
7
7
|
response: GetUserStorageResponse;
|
|
8
|
-
}
|
|
9
|
-
export declare const getMockUserStorageAllFeatureEntriesResponse: (path?: UserStoragePathWithFeatureOnly) => {
|
|
8
|
+
}>;
|
|
9
|
+
export declare const getMockUserStorageAllFeatureEntriesResponse: (path?: UserStoragePathWithFeatureOnly) => Promise<{
|
|
10
10
|
url: string;
|
|
11
11
|
requestMethod: "GET";
|
|
12
12
|
response: GetUserStorageAllFeatureEntriesResponse;
|
|
13
|
-
}
|
|
13
|
+
}>;
|
|
14
14
|
export declare const getMockUserStoragePutResponse: (path?: UserStoragePathWithFeatureAndKey) => {
|
|
15
15
|
url: string;
|
|
16
16
|
requestMethod: "PUT";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockResponses.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockResponses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,WAAW,CAAC;AAEnB,OAAO,KAAK,EACV,uCAAuC,EACvC,sBAAsB,EACvB,MAAM,aAAa,CAAC;AAUrB,eAAO,MAAM,0BAA0B,SAC/B,gCAAgC,GAAG,8BAA8B,WAUxE,CAAC;
|
|
1
|
+
{"version":3,"file":"mockResponses.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockResponses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,WAAW,CAAC;AAEnB,OAAO,KAAK,EACV,uCAAuC,EACvC,sBAAsB,EACvB,MAAM,aAAa,CAAC;AAUrB,eAAO,MAAM,0BAA0B,SAC/B,gCAAgC,GAAG,8BAA8B,WAUxE,CAAC;AAgBF,eAAO,MAAM,6BAA6B,UAClC,gCAAgC;;;;EAOvC,CAAC;AAEF,eAAO,MAAM,2CAA2C,UAChD,8BAA8B;;;;EAOrC,CAAC;AAEF,eAAO,MAAM,6BAA6B,UAClC,gCAAgC;;;;CAOvC,CAAC"}
|
|
@@ -4,8 +4,8 @@ type MockReply = {
|
|
|
4
4
|
status: nock.StatusCode;
|
|
5
5
|
body?: nock.Body;
|
|
6
6
|
};
|
|
7
|
-
export declare const mockEndpointGetUserStorageAllFeatureEntries: (path?: UserStoragePathWithFeatureOnly, mockReply?: MockReply) => nock.Scope
|
|
8
|
-
export declare const mockEndpointGetUserStorage: (path?: UserStoragePathWithFeatureAndKey, mockReply?: MockReply) => nock.Scope
|
|
7
|
+
export declare const mockEndpointGetUserStorageAllFeatureEntries: (path?: UserStoragePathWithFeatureOnly, mockReply?: MockReply) => Promise<nock.Scope>;
|
|
8
|
+
export declare const mockEndpointGetUserStorage: (path?: UserStoragePathWithFeatureAndKey, mockReply?: MockReply) => Promise<nock.Scope>;
|
|
9
9
|
export declare const mockEndpointUpsertUserStorage: (path?: UserStoragePathWithFeatureAndKey, mockReply?: Pick<MockReply, 'status'>) => nock.Scope;
|
|
10
10
|
export {};
|
|
11
11
|
//# sourceMappingURL=mockServices.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockServices.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockServices.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,WAAW,CAAC;AAOnB,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC;IACxB,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC;CAClB,CAAC;AAEF,eAAO,MAAM,2CAA2C,UAChD,8BAA8B,cACxB,SAAS,
|
|
1
|
+
{"version":3,"file":"mockServices.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockServices.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,WAAW,CAAC;AAOnB,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC;IACxB,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC;CAClB,CAAC;AAEF,eAAO,MAAM,2CAA2C,UAChD,8BAA8B,cACxB,SAAS,wBAatB,CAAC;AAEF,eAAO,MAAM,0BAA0B,UAC/B,gCAAgC,cAC1B,SAAS,wBAatB,CAAC;AAEF,eAAO,MAAM,6BAA6B,UAClC,gCAAgC,cAC1B,KAAK,SAAS,EAAE,QAAQ,CAAC,eAOtC,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
|
|
2
2
|
export declare const MOCK_STORAGE_KEY: string;
|
|
3
3
|
export declare const MOCK_STORAGE_DATA: string;
|
|
4
|
-
export declare const MOCK_ENCRYPTED_STORAGE_DATA: () => string
|
|
4
|
+
export declare const MOCK_ENCRYPTED_STORAGE_DATA: () => Promise<string>;
|
|
5
5
|
//# sourceMappingURL=mockStorage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockStorage.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"mockStorage.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/__fixtures__/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;AAKpE,eAAO,MAAM,2BAA2B,uBAIpC,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { NativeScrypt } from '../UserStorageController';
|
|
1
2
|
export type EncryptedPayload = {
|
|
2
3
|
v: '1';
|
|
3
4
|
t: 'scrypt';
|
|
@@ -12,8 +13,8 @@ export type EncryptedPayload = {
|
|
|
12
13
|
};
|
|
13
14
|
declare class EncryptorDecryptor {
|
|
14
15
|
#private;
|
|
15
|
-
encryptString(plaintext: string, password: string): string
|
|
16
|
-
decryptString(encryptedDataStr: string, password: string): string
|
|
16
|
+
encryptString(plaintext: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
17
|
+
decryptString(encryptedDataStr: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
17
18
|
}
|
|
18
19
|
declare const encryption: EncryptorDecryptor;
|
|
19
20
|
export default encryption;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/encryption/encryption.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/encryption/encryption.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAI7D,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,CAAC;IAGP,CAAC,EAAE,QAAQ,CAAC;IAGZ,CAAC,EAAE,MAAM,CAAC;IAGV,CAAC,EAAE;QAED,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;IAGF,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAeF,cAAM,kBAAkB;;IAChB,aAAa,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IAaZ,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;CAuKnB;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly } from './schema';
|
|
2
|
+
import type { NativeScrypt } from './UserStorageController';
|
|
2
3
|
export declare const USER_STORAGE_API: string;
|
|
3
4
|
export declare const USER_STORAGE_ENDPOINT: string;
|
|
4
5
|
/**
|
|
@@ -18,9 +19,11 @@ export type UserStorageBaseOptions = {
|
|
|
18
19
|
};
|
|
19
20
|
export type UserStorageOptions = UserStorageBaseOptions & {
|
|
20
21
|
path: UserStoragePathWithFeatureAndKey;
|
|
22
|
+
nativeScryptCrypto?: NativeScrypt;
|
|
21
23
|
};
|
|
22
24
|
export type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {
|
|
23
25
|
path: UserStoragePathWithFeatureOnly;
|
|
26
|
+
nativeScryptCrypto?: NativeScrypt;
|
|
24
27
|
};
|
|
25
28
|
/**
|
|
26
29
|
* User Storage Service - Get Storage Entry.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.ts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/services.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"services.d.ts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/services.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC/B,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAI5D,eAAO,MAAM,gBAAgB,EAAE,MAAmC,CAAC;AACnE,eAAO,MAAM,qBAAqB,QAA2C,CAAC;AAE9E;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IAEnC,SAAS,EAAE,MAAM,CAAC;IAElB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,uCAAuC,GAAG;IAEpD,SAAS,EAAE,MAAM,CAAC;IAElB,IAAI,EAAE,MAAM,CAAC;CACd,EAAE,CAAC;AAEJ,MAAM,MAAM,sBAAsB,GAAG;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,sBAAsB,GAAG;IACxD,IAAI,EAAE,gCAAgC,CAAC;IACvC,kBAAkB,CAAC,EAAE,YAAY,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,mCAAmC,GAAG,sBAAsB,GAAG;IACzE,IAAI,EAAE,8BAA8B,CAAC;IACrC,kBAAkB,CAAC,EAAE,YAAY,CAAC;CACnC,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA0CxB;AAED;;;;;GAKG;AACH,wBAAsB,+BAA+B,CACnD,IAAI,EAAE,mCAAmC,GACxC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CA+C1B;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,IAAI,CAAC,CAuBf"}
|
|
@@ -7,13 +7,13 @@ export declare const MOCK_STORAGE_KEY = "MOCK_STORAGE_KEY";
|
|
|
7
7
|
export declare const MOCK_NOTIFICATIONS_DATA: {
|
|
8
8
|
is_compact: boolean;
|
|
9
9
|
};
|
|
10
|
-
export declare const MOCK_NOTIFICATIONS_DATA_ENCRYPTED: string
|
|
11
|
-
export declare const MOCK_STORAGE_RESPONSE: {
|
|
10
|
+
export declare const MOCK_NOTIFICATIONS_DATA_ENCRYPTED: () => Promise<string>;
|
|
11
|
+
export declare const MOCK_STORAGE_RESPONSE: () => Promise<{
|
|
12
12
|
HashedKey: string;
|
|
13
13
|
Data: string;
|
|
14
|
-
}
|
|
15
|
-
export declare const handleMockUserStorageGet: (mockReply?: MockReply) => nock.Scope
|
|
16
|
-
export declare const handleMockUserStorageGetAllFeatureEntries: (mockReply?: MockReply) => nock.Scope
|
|
14
|
+
}>;
|
|
15
|
+
export declare const handleMockUserStorageGet: (mockReply?: MockReply) => Promise<nock.Scope>;
|
|
16
|
+
export declare const handleMockUserStorageGetAllFeatureEntries: (mockReply?: MockReply) => Promise<nock.Scope>;
|
|
17
17
|
export declare const handleMockUserStoragePut: (mockReply?: MockReply) => nock.Scope;
|
|
18
18
|
export {};
|
|
19
19
|
//# sourceMappingURL=mock-userstorage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock-userstorage.d.ts","sourceRoot":"","sources":["../../../../src/sdk/__fixtures__/mock-userstorage.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAMxB,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC;IACxB,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC;CAClB,CAAC;AAYF,eAAO,MAAM,gBAAgB,qBAAqB,CAAC;AAGnD,eAAO,MAAM,uBAAuB;;CAAwB,CAAC;AAC7D,eAAO,MAAM,iCAAiC,
|
|
1
|
+
{"version":3,"file":"mock-userstorage.d.ts","sourceRoot":"","sources":["../../../../src/sdk/__fixtures__/mock-userstorage.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAMxB,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC;IACxB,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC;CAClB,CAAC;AAYF,eAAO,MAAM,gBAAgB,qBAAqB,CAAC;AAGnD,eAAO,MAAM,uBAAuB;;CAAwB,CAAC;AAC7D,eAAO,MAAM,iCAAiC,uBAI3C,CAAC;AAEJ,eAAO,MAAM,qBAAqB;;;EAGhC,CAAC;AAEH,eAAO,MAAM,wBAAwB,eAAsB,SAAS,wBAWnE,CAAC;AAEF,eAAO,MAAM,yCAAyC,eACxC,SAAS,wBAYtB,CAAC;AAEF,eAAO,MAAM,wBAAwB,eAAgB,SAAS,eAQ7D,CAAC"}
|
|
@@ -14,6 +14,7 @@ export declare class JwtBearerAuth implements SIWEInterface, SRPInterface {
|
|
|
14
14
|
constructor(...args: JwtBearerAuthParams);
|
|
15
15
|
getAccessToken(): Promise<string>;
|
|
16
16
|
connectSnap(): Promise<string>;
|
|
17
|
+
isSnapConnected(): Promise<boolean>;
|
|
17
18
|
getUserProfile(): Promise<UserProfile>;
|
|
18
19
|
getIdentifier(): Promise<string>;
|
|
19
20
|
signMessage(message: string): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authentication.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAKxE,OAAO,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"authentication.d.ts","sourceRoot":"","sources":["../../../src/sdk/authentication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAKxE,OAAO,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AAa3E,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,KAAK,CAAC;AACvE,KAAK,aAAa,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAChD,KAAK,YAAY,GAAG,OAAO,CAAC,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
|
|
23
23
|
export declare function getSnaps(provider: Eip1193Provider): Promise<GetSnapsResponse>;
|
|
24
|
+
/**
|
|
25
|
+
* Check if snap is connected
|
|
26
|
+
*
|
|
27
|
+
* @param provider - MetaMask Wallet Provider
|
|
28
|
+
* @returns if snap is connected
|
|
29
|
+
*/
|
|
30
|
+
export declare function isSnapConnected(provider: Eip1193Provider): Promise<boolean>;
|
|
24
31
|
/**
|
|
25
32
|
* Will return the message signing snap if installed
|
|
26
33
|
* @param provider - MetaMask Wallet Provider
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messaging-signing-snap-requests.d.ts","sourceRoot":"","sources":["../../../../src/sdk/utils/messaging-signing-snap-requests.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,MAAM,MAAM,IAAI,GAAG;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC7C,CAAC;AACF,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEpD,eAAO,MAAM,WAAW,uCAAuC,CAAC;AAIhE;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAS5E;AAED;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAM3B;AAED;;;GAGG;AACH,wBAAsB,OAAO,CAC3B,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAQ3B;AAED,eAAO,MAAM,oBAAoB;2BACF,eAAe;0BAShB,eAAe,WAAW,YAAY,MAAM,EAAE;CAW3E,CAAC"}
|
|
1
|
+
{"version":3,"file":"messaging-signing-snap-requests.d.ts","sourceRoot":"","sources":["../../../../src/sdk/utils/messaging-signing-snap-requests.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAE9C,MAAM,MAAM,IAAI,GAAG;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC7C,CAAC;AACF,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEpD,eAAO,MAAM,WAAW,uCAAuC,CAAC;AAIhE;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAS5E;AAED;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAM3B;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,OAAO,CAAC,CAWlB;AAED;;;GAGG;AACH,wBAAsB,OAAO,CAC3B,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAQ3B;AAED,eAAO,MAAM,oBAAoB;2BACF,eAAe;0BAShB,eAAe,WAAW,YAAY,MAAM,EAAE;CAW3E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/profile-sync-controller",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "The profile sync helps developers synchronize data across multiple clients and devices in a privacy-preserving way. All data saved in the user storage database is encrypted client-side to preserve privacy. The user storage provides a modular design, giving developers the flexibility to construct and manage their storage spaces in a way that best suits their needs",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/utils/messaging-signing-snap-requests.ts"],"sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nexport type Snap = {\n permissionName: string;\n id: string;\n version: string;\n initialPermissions: Record<string, unknown>;\n};\nexport type GetSnapsResponse = Record<string, Snap>;\n\nexport const SNAP_ORIGIN = 'npm:@metamask/message-signing-snap';\n\nconst foundSnap = (snap: Snap) => snap.id === SNAP_ORIGIN;\n\n/**\n * Requests Connection to the Message Signing Snap\n *\n * @param provider - MetaMask Wallet Provider\n * @returns snap connect result\n */\nexport async function connectSnap(provider: Eip1193Provider): Promise<string> {\n const result: string = await provider.request({\n method: 'wallet_requestSnaps',\n params: {\n [SNAP_ORIGIN]: {},\n },\n });\n\n return result;\n}\n\n/**\n * Gets Snaps from a MetaMask Wallet\n *\n * @param provider - MetaMask Wallet Provider\n * @returns All currently installed snaps.\n */\nexport async function getSnaps(\n provider: Eip1193Provider,\n): Promise<GetSnapsResponse> {\n const result: GetSnapsResponse = await provider.request({\n method: 'wallet_getSnaps',\n });\n\n return result;\n}\n\n/**\n * Will return the message signing snap if installed\n * @param provider - MetaMask Wallet Provider\n */\nexport async function getSnap(\n provider: Eip1193Provider,\n): Promise<Snap | undefined> {\n try {\n const snaps = await getSnaps(provider);\n return Object.values(snaps ?? {}).find((snap) => foundSnap(snap));\n } catch (e) {\n console.error('Failed to obtain installed snap', e);\n return undefined;\n }\n}\n\nexport const MESSAGE_SIGNING_SNAP = {\n async getPublicKey(provider: Eip1193Provider) {\n const publicKey: string = await provider.request({\n method: 'wallet_invokeSnap',\n params: { snapId: SNAP_ORIGIN, request: { method: 'getPublicKey' } },\n });\n\n return publicKey;\n },\n\n async signMessage(provider: Eip1193Provider, message: `metamask:${string}`) {\n const signedMessage: string = await provider?.request({\n method: 'wallet_invokeSnap',\n params: {\n snapId: SNAP_ORIGIN,\n request: { method: 'signMessage', params: { message } },\n },\n });\n\n return signedMessage;\n },\n};\n"],"mappings":";AAUO,IAAM,cAAc;AAE3B,IAAM,YAAY,CAAC,SAAe,KAAK,OAAO;AAQ9C,eAAsB,YAAY,UAA4C;AAC5E,QAAM,SAAiB,MAAM,SAAS,QAAQ;AAAA,IAC5C,QAAQ;AAAA,IACR,QAAQ;AAAA,MACN,CAAC,WAAW,GAAG,CAAC;AAAA,IAClB;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAQA,eAAsB,SACpB,UAC2B;AAC3B,QAAM,SAA2B,MAAM,SAAS,QAAQ;AAAA,IACtD,QAAQ;AAAA,EACV,CAAC;AAED,SAAO;AACT;AAMA,eAAsB,QACpB,UAC2B;AAC3B,MAAI;AACF,UAAM,QAAQ,MAAM,SAAS,QAAQ;AACrC,WAAO,OAAO,OAAO,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,SAAS,UAAU,IAAI,CAAC;AAAA,EAClE,SAAS,GAAG;AACV,YAAQ,MAAM,mCAAmC,CAAC;AAClD,WAAO;AAAA,EACT;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,MAAM,aAAa,UAA2B;AAC5C,UAAM,YAAoB,MAAM,SAAS,QAAQ;AAAA,MAC/C,QAAQ;AAAA,MACR,QAAQ,EAAE,QAAQ,aAAa,SAAS,EAAE,QAAQ,eAAe,EAAE;AAAA,IACrE,CAAC;AAED,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,YAAY,UAA2B,SAA+B;AAC1E,UAAM,gBAAwB,MAAM,UAAU,QAAQ;AAAA,MACpD,QAAQ;AAAA,MACR,QAAQ;AAAA,QACN,QAAQ;AAAA,QACR,SAAS,EAAE,QAAQ,eAAe,QAAQ,EAAE,QAAQ,EAAE;AAAA,MACxD;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/services.ts"],"names":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AI,oBAAoB,WAAW,KAAK;AACtC,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,UAAM,cACJ,MAAM,oBAAoB,KAAK;AAEjC,QAAI,CAAC,MAAM,QAAQ,WAAW,GAAG;AAC/B,aAAO;AAAA,IACT;AAEA,UAAM,gBAAgB,aAAa,QAAQ,CAAC,UAAU;AACpD,UAAI,CAAC,MAAM,MAAM;AACf,eAAO,CAAC;AAAA,MACV;AAEA,aAAO,mBAAW,cAAc,MAAM,MAAM,KAAK,UAAU;AAAA,IAC7D,CAAC;AAED,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,MAAM,8BAA8B,CAAC;AACzC,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,kBACpB,MACA,MACe;AACf,QAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,QAAM,gBAAgB,mBAAW,cAAc,MAAM,KAAK,UAAU;AACpE,QAAM,gBAAgB,gBAAgB,MAAM,UAAU;AACtD,QAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,GAAG,aAAa,EAAE;AAE9D,QAAM,MAAM,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,IACtC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,WAAW;AAAA,IACtC;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAAA,EAC9C,CAAC;AAED,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACF","sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk/env';\nimport encryption from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport { createEntryPath } from './schema';\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 // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n};\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 } = 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('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = encryption.decryptString(\n encryptedData,\n opts.storageKey,\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 } = 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('Unable to get User Storage');\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 = userStorage?.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, opts.storageKey);\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 } = opts;\n\n const encryptedData = encryption.encryptString(data, opts.storageKey);\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('user-storage - unable to upsert data');\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["export * from './authentication';\nexport * from './user-storage';\nexport * from './env';\nexport * from './errors';\nexport * from './encryption';\nexport * from './utils/messaging-signing-snap-requests';\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/encryption/encryption.ts"],"sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scrypt } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport { getAnyCachedKey, getCachedKeyBySalt, setCachedKey } from './cache';\nimport { base64ToByteArray, byteArrayToBase64, bytesToUtf8 } from './utils';\n\nexport type EncryptedPayload = {\n // version\n v: '1';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\n// Nonce/Key Sizes\nconst ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nconst ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nconst SCRYPT_SALT_SIZE = 16; // 16 bytes\nconst SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_r = 8; // Block size parameter\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_p = 1; // Parallelization parameter\n\nclass EncryptorDecryptor {\n encryptString(plaintext: string, password: string): string {\n try {\n return this.#encryptStringV1(plaintext, password);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n decryptString(encryptedDataStr: string, password: string): string {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return this.#decryptStringV1(encryptedData, password);\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n #encryptStringV1(plaintext: string, password: string): string {\n const { key, salt } = this.#getOrGenerateScryptKey(password, {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n });\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n #decryptStringV1(data: EncryptedPayload, password: string): string {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getAnyCachedKey(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? randomBytes(SCRYPT_SALT_SIZE);\n const newKey = scrypt(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n setCachedKey(hashedPassword, newSalt, newKey);\n\n return {\n key: newKey,\n salt: newSalt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,WAAW;AACpB,SAAS,mBAAmB;AAC5B,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,aAAa,aAAa,kBAAkB;AA6BrD,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB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AAU;AAAA,MACf,MAAM,UAAU;AAAA,IAClB;AAAA,EACF;AAEA,QAAM,UAAU,QAAQ,YAAY,gBAAgB;AACpD,QAAM,SAAS,OAAO,UAAU,SAAS;AAAA,IACvC,GAAG,EAAE;AAAA,IACL,GAAG,EAAE;AAAA,IACL,GAAG,EAAE;AAAA,IACL,OAAO,EAAE;AAAA,EACX,CAAC;AACD,eAAa,gBAAgB,SAAS,MAAM;AAE5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AACF;AAGF,IAAM,aAAa,IAAI,mBAAmB;AAC1C,IAAO,qBAAQ;AAOR,SAAS,iBAAiB,MAAsB;AACrD,QAAM,aAAa,OAAO,IAAI;AAC9B,SAAO,WAAW,UAAU;AAC9B;","names":[]}
|
package/dist/chunk-LDYHGAP4.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
-
|
|
3
|
-
var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
|
|
4
|
-
|
|
5
|
-
// src/sdk/encryption.ts
|
|
6
|
-
var encryption_default2 = _chunkT3FNDVE3js.encryption_default;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
exports.encryption_default = encryption_default2;
|
|
11
|
-
//# sourceMappingURL=chunk-LDYHGAP4.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,sBAAsB;AA+C/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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AO,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","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\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 type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { createSHA256Hash } from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} 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 | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Events = UserStorageControllerStateChangeEvent;\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 // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\n\nexport type AllowedEvents =\n | UserStorageControllerChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | 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 #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n getInternalAccountByAddress: async (address: string) => {\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (address: string) => {\n const internalAccount = await this.#accounts.getInternalAccountByAddress(\n address,\n );\n\n if (!internalAccount) {\n return;\n }\n\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\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(\n 'KeyringController:unlock',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n this.#isUnlocked = true;\n\n await this.syncInternalAccountsWithUserStorage();\n },\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 env?: {\n isAccountSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n params.env?.isAccountSyncingEnabled,\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:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.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 this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.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: UserStoragePathWithFeatureAndKey,\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 retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\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: UserStoragePathWithFeatureAndKey,\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 /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n this.#assertProfileSyncingEnabled();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n });\n\n await Promise.all(addNewAccountsPromises);\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param address - The address of the internal account to save\n */\n async saveInternalAccountToUserStorage(address: string): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(address);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/services.ts"],"sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk/env';\nimport encryption from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport { createEntryPath } from './schema';\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 // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n};\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 } = 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('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = encryption.decryptString(\n encryptedData,\n opts.storageKey,\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 } = 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('Unable to get User Storage');\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 = userStorage?.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, opts.storageKey);\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 } = opts;\n\n const encryptedData = encryption.encryptString(data, opts.storageKey);\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('user-storage - unable to upsert data');\n }\n}\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AAI,oBAAoB,WAAW,KAAK;AACtC,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,UAAM,cACJ,MAAM,oBAAoB,KAAK;AAEjC,QAAI,CAAC,MAAM,QAAQ,WAAW,GAAG;AAC/B,aAAO;AAAA,IACT;AAEA,UAAM,gBAAgB,aAAa,QAAQ,CAAC,UAAU;AACpD,UAAI,CAAC,MAAM,MAAM;AACf,eAAO,CAAC;AAAA,MACV;AAEA,aAAO,mBAAW,cAAc,MAAM,MAAM,KAAK,UAAU;AAAA,IAC7D,CAAC;AAED,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,MAAM,8BAA8B,CAAC;AACzC,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,kBACpB,MACA,MACe;AACf,QAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,QAAM,gBAAgB,mBAAW,cAAc,MAAM,KAAK,UAAU;AACpE,QAAM,gBAAgB,gBAAgB,MAAM,UAAU;AACtD,QAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,GAAG,aAAa,EAAE;AAE9D,QAAM,MAAM,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,IACtC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,WAAW;AAAA,IACtC;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAAA,EAC9C,CAAC;AAED,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\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 type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { createSHA256Hash } from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} 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 | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Events = UserStorageControllerStateChangeEvent;\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 // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\n\nexport type AllowedEvents =\n | UserStorageControllerChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | 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 #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n getInternalAccountByAddress: async (address: string) => {\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (address: string) => {\n const internalAccount = await this.#accounts.getInternalAccountByAddress(\n address,\n );\n\n if (!internalAccount) {\n return;\n }\n\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\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(\n 'KeyringController:unlock',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n this.#isUnlocked = true;\n\n await this.syncInternalAccountsWithUserStorage();\n },\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 env?: {\n isAccountSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n params.env?.isAccountSyncingEnabled,\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:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.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 this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.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: UserStoragePathWithFeatureAndKey,\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 retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\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: UserStoragePathWithFeatureAndKey,\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 /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n this.#assertProfileSyncingEnabled();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n });\n\n await Promise.all(addNewAccountsPromises);\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param address - The address of the internal account to save\n */\n async saveInternalAccountToUserStorage(address: string): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(address);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,sBAAsB;AA+C/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;AAtFA;AAiMA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAqIA,YAAY,QAOT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC5C,CAAC;AAeH;AAAA;AAAA;AAAA;AAAA;AAgMA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;A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1193Provider } from 'ethers';\n\nexport type Snap = {\n permissionName: string;\n id: string;\n version: string;\n initialPermissions: Record<string, unknown>;\n};\nexport type GetSnapsResponse = Record<string, Snap>;\n\nexport const SNAP_ORIGIN = 'npm:@metamask/message-signing-snap';\n\nconst foundSnap = (snap: Snap) => snap.id === SNAP_ORIGIN;\n\n/**\n * Requests Connection to the Message Signing Snap\n *\n * @param provider - MetaMask Wallet Provider\n * @returns snap connect result\n */\nexport async function connectSnap(provider: Eip1193Provider): Promise<string> {\n const result: string = await provider.request({\n method: 'wallet_requestSnaps',\n params: {\n [SNAP_ORIGIN]: {},\n },\n });\n\n return result;\n}\n\n/**\n * Gets Snaps from a MetaMask Wallet\n *\n * @param provider - MetaMask Wallet Provider\n * @returns All currently installed snaps.\n */\nexport async function getSnaps(\n provider: Eip1193Provider,\n): Promise<GetSnapsResponse> {\n const result: GetSnapsResponse = await provider.request({\n method: 'wallet_getSnaps',\n });\n\n return result;\n}\n\n/**\n * Will return the message signing snap if installed\n * @param provider - MetaMask Wallet Provider\n */\nexport async function getSnap(\n provider: Eip1193Provider,\n): Promise<Snap | undefined> {\n try {\n const snaps = await getSnaps(provider);\n return Object.values(snaps ?? {}).find((snap) => foundSnap(snap));\n } catch (e) {\n console.error('Failed to obtain installed snap', e);\n return undefined;\n }\n}\n\nexport const MESSAGE_SIGNING_SNAP = {\n async getPublicKey(provider: Eip1193Provider) {\n const publicKey: string = await provider.request({\n method: 'wallet_invokeSnap',\n params: { snapId: SNAP_ORIGIN, request: { method: 'getPublicKey' } },\n });\n\n return publicKey;\n },\n\n async signMessage(provider: Eip1193Provider, message: `metamask:${string}`) {\n const signedMessage: string = await provider?.request({\n method: 'wallet_invokeSnap',\n params: {\n snapId: SNAP_ORIGIN,\n request: { method: 'signMessage', params: { message } },\n },\n });\n\n return signedMessage;\n },\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/authentication.ts"],"names":[],"mappings":";;;;;;;;;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IAAI,EAAE,UAAU;AAC/C,gBAAM,MAAM,MAAM,EAAE,YAAY,GAAG;AACnC,iBAAO;AAAA,YACL,WAAW;AAAA;AAAA;AAAA,YAGX,aAAa;AAAA;AAAA;AAAA,YAGb,uBAAuB,EAAE;AAAA;AAAA;AAAA,YAGzB,iBAAiB,EAAE;AAAA,UACrB;AAAA,QACF,SAAS,GAAG;AAEV,gBAAM,eACJ,aAAa,QAAQ,EAAE,UAAU,KAAK,UAAU,KAAK,EAAE;AACzD,gBAAM,IAAI;AAAA,YACR,mCAAmC,YAAY;AAAA,UACjD;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAEA,UAAM,cAAc,MAAM,KAAK,eAAe;AAC9C,UAAM,gBAAgB,EAAE,OAAO,QAAQ,aAAa,mBAAK,KAAI;AAAA,EAC/D;AAAA,EAEA,QAAQ,QAKC;AACP,0BAAK,4BAAL,WAAiB,mBAAK,QAAO,mBAAK;AAClC,uBAAK,MAAK,QAAQ,MAAM;AAAA,EAC1B;AAcF;AA1GE;AAEA;AAEA;AA0FA;AAAA,gBAAW,SACT,MACA,KACkC;AAClC,MAAI,4BAAwB;AAC1B;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF","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 './authentication-jwt-bearer/types';\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/encryption/encryption.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,WAAW;AACpB,SAAS,mBAAmB;AAC5B,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,aAAa,aAAa,kBAAkB;AA6BrD,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB;AAI3B,IAAM,mBAAmB;AACzB,IAAM,WAAW,KAAK;AAEtB,IAAM,WAAW;AAEjB,IAAM,WAAW;AA3CjB;AA6CA,IAAM,qBAAN,MAAyB;AAAA,EAAzB;AA2BE;AAkCA;AA+BA;AASA;AAYA;AAAA;AAAA,EAhHA,cAAc,WAAm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AAA,IACL,OAAO,EAAE;AAAA,EACX,CAAC;AACD,eAAa,gBAAgB,SAAS,MAAM;AAE5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AACF;AAGF,IAAM,aAAa,IAAI,mBAAmB;AAC1C,IAAO,qBAAQ;AAOR,SAAS,iBAAiB,MAAsB;AACrD,QAAM,aAAa,OAAO,IAAI;AAC9B,SAAO,WAAW,UAAU;AAC9B","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scrypt } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport { getAnyCachedKey, getCachedKeyBySalt, setCachedKey } from './cache';\nimport { base64ToByteArray, byteArrayToBase64, bytesToUtf8 } from './utils';\n\nexport type EncryptedPayload = {\n // version\n v: '1';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\n// Nonce/Key Sizes\nconst ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nconst ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nconst SCRYPT_SALT_SIZE = 16; // 16 bytes\nconst SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_r = 8; // Block size parameter\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_p = 1; // Parallelization parameter\n\nclass EncryptorDecryptor {\n encryptString(plaintext: string, password: string): string {\n try {\n return this.#encryptStringV1(plaintext, password);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n decryptString(encryptedDataStr: string, password: string): string {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return this.#decryptStringV1(encryptedData, password);\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n #encryptStringV1(plaintext: string, password: string): string {\n const { key, salt } = this.#getOrGenerateScryptKey(password, {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n });\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n #decryptStringV1(data: EncryptedPayload, password: string): string {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getAnyCachedKey(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? randomBytes(SCRYPT_SALT_SIZE);\n const newKey = scrypt(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n setCachedKey(hashedPassword, newSalt, newKey);\n\n return {\n key: newKey,\n salt: newSalt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controllers/user-storage/index.ts","../src/controllers/user-storage/__fixtures__/index.ts","../src/controllers/user-storage/__fixtures__/mockStorage.ts","../src/controllers/user-storage/__fixtures__/mockResponses.ts"],"names":["encryption_default","UserStorageController"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,6BAA6B;AACnC,IAAM,mBAAmB,iBAAiB,0BAA0B;AACpE,IAAM,oBAAoB,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC;AAI3D,IAAM,8BAA8B,MACzCA,oBAAW,cAAc,mBAAmB,gBAAgB;;;ACSvD,IAAM,6BAA6B,CACxC,SACG;AACH,MAAI,KAAK,MAAM,GAAG,EAAE,WAAW,GAAG;AAChC,WAAO,GAAG,qBAAqB,IAAI,IAAI;AAAA,EACzC;AAEA,SAAO,GAAG,qBAAqB,GAAG;AAAA,IAChC;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAEA,IAAM,iCAAiC,OAA+B;AAAA,EACpE,WAAW;AAAA,EACX,MAAM,4BAA4B;AACpC;AAEA,IAAM,qDACJ,MAA+C;AAAA,EAC7C;AAAA,IACE,WAAW;AAAA,IACX,MAAM,4BAA4B;AAAA,EACpC;AACF;AAEK,IAAM,gCAAgC,CAC3C,OAAyC,yCACtC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU,+BAA+B;AAAA,EAC3C;AACF;AAEO,IAAM,8CAA8C,CACzD,OAAuC,oBACpC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU,mDAAmD;AAAA,EAC/D;AACF;AAEO,IAAM,gCAAgC,CAC3C,OAAyC,yCACtC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;;;AHtEA,IAAMC,yBAAwB;AAE9B,IAAO,uBAAQA","sourcesContent":["import Controller from './UserStorageController';\n\nconst UserStorageController = Controller;\nexport { Controller };\nexport default UserStorageController;\nexport * from './UserStorageController';\nexport * from './encryption';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\nexport * from './mockStorage';\n","import encryption, { createSHA256Hash } from '../encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\n\n// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.\n// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports\nexport const MOCK_ENCRYPTED_STORAGE_DATA = () =>\n encryption.encryptString(MOCK_STORAGE_DATA, MOCK_STORAGE_KEY);\n","import type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../schema';\nimport { createEntryPath } from '../schema';\nimport type {\n GetUserStorageAllFeatureEntriesResponse,\n GetUserStorageResponse,\n} from '../services';\nimport { USER_STORAGE_ENDPOINT } from '../services';\nimport { MOCK_ENCRYPTED_STORAGE_DATA, MOCK_STORAGE_KEY } from './mockStorage';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const getMockUserStorageEndpoint = (\n path: UserStoragePathWithFeatureAndKey | UserStoragePathWithFeatureOnly,\n) => {\n if (path.split('.').length === 1) {\n return `${USER_STORAGE_ENDPOINT}/${path}`;\n }\n\n return `${USER_STORAGE_ENDPOINT}${createEntryPath(\n path as UserStoragePathWithFeatureAndKey,\n MOCK_STORAGE_KEY,\n )}`;\n};\n\nconst MOCK_GET_USER_STORAGE_RESPONSE = (): GetUserStorageResponse => ({\n HashedKey: 'HASHED_KEY',\n Data: MOCK_ENCRYPTED_STORAGE_DATA(),\n});\n\nconst MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE =\n (): GetUserStorageAllFeatureEntriesResponse => [\n {\n HashedKey: 'HASHED_KEY',\n Data: MOCK_ENCRYPTED_STORAGE_DATA(),\n },\n ];\n\nexport const getMockUserStorageGetResponse = (\n path: UserStoragePathWithFeatureAndKey = 'notifications.notificationSettings',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'GET',\n response: MOCK_GET_USER_STORAGE_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStorageAllFeatureEntriesResponse = (\n path: UserStoragePathWithFeatureOnly = 'notifications',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'GET',\n response: MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStoragePutResponse = (\n path: UserStoragePathWithFeatureAndKey = 'notifications.notificationSettings',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'PUT',\n response: null,\n } satisfies MockResponse;\n};\n"]}
|