@metamask-previews/profile-sync-controller 20.0.0-preview-2bb8758e → 21.0.0-preview-c10fdda1

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 CHANGED
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [21.0.0]
11
+
10
12
  ### Added
11
13
 
12
14
  - Add performance tracing to user storage syncing operations (contacts and accounts) ([#6050](https://github.com/MetaMask/core/pull/6050))
@@ -665,7 +667,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
665
667
 
666
668
  - Initial release
667
669
 
668
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@20.0.0...HEAD
670
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@21.0.0...HEAD
671
+ [21.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@20.0.0...@metamask/profile-sync-controller@21.0.0
669
672
  [20.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@19.0.0...@metamask/profile-sync-controller@20.0.0
670
673
  [19.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@18.0.0...@metamask/profile-sync-controller@19.0.0
671
674
  [18.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@17.1.0...@metamask/profile-sync-controller@18.0.0
@@ -32,6 +32,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
32
32
  exports.UserStorage = exports.STORAGE_URL = void 0;
33
33
  const errors_1 = require("./errors.cjs");
34
34
  const encryption_1 = __importStar(require("../shared/encryption/index.cjs"));
35
+ const constants_1 = require("../shared/encryption/constants.cjs");
35
36
  const env_1 = require("../shared/env.cjs");
36
37
  const storage_schema_1 = require("../shared/storage-schema.cjs");
37
38
  const STORAGE_URL = (env, encryptedPath) => `${(0, env_1.getEnvUrls)(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;
@@ -196,10 +197,10 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
196
197
  return null;
197
198
  }
198
199
  const decryptedData = await encryption_1.default.decryptString(encryptedData, storageKey, options?.nativeScryptCrypto);
199
- // Migrate data from v1 to v2 encryption
200
- if (JSON.parse(encryptedData).v === '1') {
201
- const reEncryptedData = await encryption_1.default.encryptString(decryptedData, storageKey);
202
- await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_upsertUserStorage).call(this, path, reEncryptedData, options);
200
+ // Re-encrypt the entry if it was encrypted with a random salt
201
+ const salt = encryption_1.default.getSalt(encryptedData);
202
+ if (salt.toString() !== constants_1.SHARED_SALT.toString()) {
203
+ await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_upsertUserStorage).call(this, path, decryptedData, options);
203
204
  }
204
205
  return decryptedData;
205
206
  }
@@ -240,10 +241,13 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
240
241
  try {
241
242
  const data = await encryption_1.default.decryptString(entry.Data, storageKey, options?.nativeScryptCrypto);
242
243
  decryptedData.push(data);
243
- // Migrate data from v1 to v2 encryption
244
- if (JSON.parse(entry.Data).v === '1') {
245
- const reEncryptedData = await encryption_1.default.encryptString(data, storageKey);
246
- reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);
244
+ // Re-encrypt the entry was encrypted with a random salt
245
+ const salt = encryption_1.default.getSalt(entry.Data);
246
+ if (salt.toString() !== constants_1.SHARED_SALT.toString()) {
247
+ reEncryptedEntries.push([
248
+ entry.HashedKey,
249
+ await encryption_1.default.encryptString(data, storageKey, options?.nativeScryptCrypto),
250
+ ]);
247
251
  }
248
252
  }
249
253
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCA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wt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(encryptedData).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n decryptedData,\n storageKey,\n );\n await this.#upsertUserStorage(path, reEncryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(entry.Data).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n data,\n storageKey,\n );\n reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
1
+ {"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAA2D;AAC3D,6EAAoE;AACpE,kEAA6D;AAE7D,2CAA2C;AAO3C,iEAA2D;AAGpD,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,aAAqB,EAAE,EAAE,CAC7D,GAAG,IAAA,gBAAU,EAAC,GAAG,CAAC,CAAC,iBAAiB,uBAAuB,aAAa,EAAE,CAAC;AADhE,QAAA,WAAW,eACqD;AAgC7E,MAAa,WAAW;IAOtB,YAAY,MAAyB,EAAE,OAA2B;;QAChE,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;QACtB,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;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,MAAM,YAAY,GAAiB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;gBACpE,OAAO,EAAE,SAAS;gBAClB,KAAK,EAAE,SAAS;aACjB,CAAC,CAAC,CAAC;YACJ,MAAM,IAAI,KAAK,CACb,uBAAuB,YAAY,CAAC,OAAO,YAAY,YAAY,CAAC,KAAK,EAAE,CAC5E,CAAC;SACH;KACF;IAAC,OAAO,CAAC,EAAE;QACV,0BAA0B;QAC1B,MAAM,YAAY,GAChB,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,MAAM,IAAI,yBAAgB,CACxB,iDAAiD,IAAI,MAAM,YAAY,EAAE,CAC1E,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,OAAO,IAAA,6BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;AAC5C,CAAC,wCAED,KAAK,8CACH,eAAwB;IAExB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;IAC3E,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport { SHARED_SALT } from '../shared/encryption/constants';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Re-encrypt the entry if it was encrypted with a random salt\n const salt = encryption.getSalt(encryptedData);\n if (salt.toString() !== SHARED_SALT.toString()) {\n await this.#upsertUserStorage(path, decryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Re-encrypt the entry was encrypted with a random salt\n const salt = encryption.getSalt(entry.Data);\n if (salt.toString() !== SHARED_SALT.toString()) {\n reEncryptedEntries.push([\n entry.HashedKey,\n await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"user-storage.d.cts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,8CAA0C;AAGnE,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,4BAA4B,EAC5B,6BAA6B,EAC7B,uCAAuC,EAExC,qCAAiC;AAElC,OAAO,KAAK,EAAE,YAAY,EAAE,uCAAmC;AAE/D,eAAO,MAAM,WAAW,QAAS,GAAG,iBAAiB,MAAM,WACiB,CAAC;AAE7E,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,aAAa,CAAC,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,aAAa,EAAE,CAAC,OAAO,EAAE,YAAY,MAAM,EAAE,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzE,aAAa,EAAE,CAAC,OAAO,EAAE,YAAY,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9B,OAAO,CACX,IAAI,EAAE,uCAAuC,EAC7C,OAAO,CAAC,EAAE,wBAAwB,GACjC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAInB,kBAAkB,CACtB,IAAI,EAAE,6BAA6B,EACnC,OAAO,CAAC,EAAE,wBAAwB,GACjC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAIrB,UAAU,CACd,IAAI,EAAE,uCAAuC,EAC7C,OAAO,CAAC,EAAE,wBAAwB,GACjC,OAAO,CAAC,IAAI,CAAC;IAIV,qBAAqB,CACzB,IAAI,EAAE,6BAA6B,EACnC,OAAO,CAAC,EAAE,wBAAwB,GACjC,OAAO,CAAC,IAAI,CAAC;IAIV,gBAAgB,CACpB,IAAI,EAAE,6BAA6B,EACnC,MAAM,EAAE,4BAA4B,EAAE,EACtC,OAAO,CAAC,EAAE,wBAAwB;IAK9B,aAAa,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAgd/D"}
@@ -6,6 +6,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
6
6
  var _UserStorage_instances, _UserStorage_upsertUserStorage, _UserStorage_batchUpsertUserStorage, _UserStorage_batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries, _UserStorage_getUserStorage, _UserStorage_getUserStorageAllFeatureEntries, _UserStorage_deleteUserStorage, _UserStorage_deleteUserStorageAllFeatureEntries, _UserStorage_batchDeleteUserStorage, _UserStorage_createEntryKey, _UserStorage_getAuthorizationHeader;
7
7
  import { NotFoundError, UserStorageError } from "./errors.mjs";
8
8
  import encryption, { createSHA256Hash } from "../shared/encryption/index.mjs";
9
+ import { SHARED_SALT } from "../shared/encryption/constants.mjs";
9
10
  import { getEnvUrls } from "../shared/env.mjs";
10
11
  import { createEntryPath } from "../shared/storage-schema.mjs";
11
12
  export const STORAGE_URL = (env, encryptedPath) => `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;
@@ -168,10 +169,10 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
168
169
  return null;
169
170
  }
170
171
  const decryptedData = await encryption.decryptString(encryptedData, storageKey, options?.nativeScryptCrypto);
171
- // Migrate data from v1 to v2 encryption
172
- if (JSON.parse(encryptedData).v === '1') {
173
- const reEncryptedData = await encryption.encryptString(decryptedData, storageKey);
174
- await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_upsertUserStorage).call(this, path, reEncryptedData, options);
172
+ // Re-encrypt the entry if it was encrypted with a random salt
173
+ const salt = encryption.getSalt(encryptedData);
174
+ if (salt.toString() !== SHARED_SALT.toString()) {
175
+ await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_upsertUserStorage).call(this, path, decryptedData, options);
175
176
  }
176
177
  return decryptedData;
177
178
  }
@@ -212,10 +213,13 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
212
213
  try {
213
214
  const data = await encryption.decryptString(entry.Data, storageKey, options?.nativeScryptCrypto);
214
215
  decryptedData.push(data);
215
- // Migrate data from v1 to v2 encryption
216
- if (JSON.parse(entry.Data).v === '1') {
217
- const reEncryptedData = await encryption.encryptString(data, storageKey);
218
- reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);
216
+ // Re-encrypt the entry was encrypted with a random salt
217
+ const salt = encryption.getSalt(entry.Data);
218
+ if (salt.toString() !== SHARED_SALT.toString()) {
219
+ reEncryptedEntries.push([
220
+ entry.HashedKey,
221
+ await encryption.encryptString(data, storageKey, options?.nativeScryptCrypto),
222
+ ]);
219
223
  }
220
224
  }
221
225
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAiB;AAC3D,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,uCAA6B;AAEpE,OAAO,EAAE,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EAAE,KAAK;YACb,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YAED,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC;SACrD,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,MAAM,YAAY,GAAiB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;gBACpE,OAAO,EAAE,SAAS;gBAClB,KAAK,EAAE,SAAS;aACjB,CAAC,CAAC,CAAC;YACJ,MAAM,IAAI,KAAK,CACb,uBAAuB,YAAY,CAAC,OAAO,YAAY,YAAY,CAAC,KAAK,EAAE,CAC5E,CAAC;SACH;KACF;IAAC,OAAO,CAAC,EAAE;QACV,0BAA0B;QAC1B,MAAM,YAAY,GAChB,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,MAAM,IAAI,gBAAgB,CACxB,iDAAiD,IAAI,MAAM,YAAY,EAAE,CAC1E,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,OAAO,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;AAC5C,CAAC,wCAED,KAAK,8CACH,eAAwB;IAExB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;IAC3E,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(encryptedData).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n decryptedData,\n storageKey,\n );\n await this.#upsertUserStorage(path, reEncryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(entry.Data).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n data,\n storageKey,\n );\n reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
1
+ {"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAiB;AAC3D,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,uCAA6B;AACpE,OAAO,EAAE,WAAW,EAAE,2CAAuC;AAE7D,OAAO,EAAE,UAAU,EAAE,0BAAsB;AAO3C,OAAO,EAAE,eAAe,EAAE,qCAAiC;AAG3D,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,aAAqB,EAAE,EAAE,CAC7D,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,iBAAiB,uBAAuB,aAAa,EAAE,CAAC;AAgC7E,MAAM,OAAO,WAAW;IAOtB,YAAY,MAAyB,EAAE,OAA2B;;QAChE,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;QACtB,IAAI,CAAC,MAAM,GA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AAC;gBACpE,OAAO,EAAE,SAAS;gBAClB,KAAK,EAAE,SAAS;aACjB,CAAC,CAAC,CAAC;YACJ,MAAM,IAAI,KAAK,CACb,uBAAuB,YAAY,CAAC,OAAO,YAAY,YAAY,CAAC,KAAK,EAAE,CAC5E,CAAC;SACH;KACF;IAAC,OAAO,CAAC,EAAE;QACV,0BAA0B;QAC1B,MAAM,YAAY,GAChB,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,MAAM,IAAI,gBAAgB,CACxB,iDAAiD,IAAI,MAAM,YAAY,EAAE,CAC1E,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,OAAO,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;AAC5C,CAAC,wCAED,KAAK,8CACH,eAAwB;IAExB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;IAC3E,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport { SHARED_SALT } from '../shared/encryption/constants';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Re-encrypt the entry if it was encrypted with a random salt\n const salt = encryption.getSalt(encryptedData);\n if (salt.toString() !== SHARED_SALT.toString()) {\n await this.#upsertUserStorage(path, decryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Re-encrypt the entry was encrypted with a random salt\n const salt = encryption.getSalt(entry.Data);\n if (salt.toString() !== SHARED_SALT.toString()) {\n reEncryptedEntries.push([\n entry.HashedKey,\n await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SHARED_SALT = exports.SCRYPT_p = exports.SCRYPT_r = exports.SCRYPT_N_V2 = exports.SCRYPT_N = exports.SCRYPT_SALT_SIZE = exports.ALGORITHM_KEY_SIZE = exports.ALGORITHM_NONCE_SIZE = void 0;
3
+ exports.SHARED_SALT = exports.SCRYPT_p = exports.SCRYPT_r = exports.SCRYPT_N = exports.SCRYPT_SALT_SIZE = exports.ALGORITHM_KEY_SIZE = exports.ALGORITHM_NONCE_SIZE = void 0;
4
4
  // Nonce/Key Sizes
5
5
  exports.ALGORITHM_NONCE_SIZE = 12; // 12 bytes
6
6
  exports.ALGORITHM_KEY_SIZE = 16; // 16 bytes
@@ -8,7 +8,6 @@ exports.ALGORITHM_KEY_SIZE = 16; // 16 bytes
8
8
  // see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt
9
9
  exports.SCRYPT_SALT_SIZE = 16; // 16 bytes
10
10
  exports.SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)
11
- exports.SCRYPT_N_V2 = 2;
12
11
  exports.SCRYPT_r = 8; // Block size parameter
13
12
  exports.SCRYPT_p = 1; // Parallelization parameter
14
13
  exports.SHARED_SALT = new Uint8Array([
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":";;;AAAA,kBAAkB;AACL,QAAA,oBAAoB,GAAG,EAAE,CAAC,CAAC,WAAW;AACtC,QAAA,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAClF,QAAA,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAClC,QAAA,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AAC5E,QAAA,WAAW,GAAG,CAAC,CAAC;AAChB,QAAA,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AACrC,QAAA,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAE1C,QAAA,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC","sourcesContent":["// Nonce/Key Sizes\nexport const ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nexport const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_N_V2 = 2;\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n"]}
1
+ {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":";;;AAAA,kBAAkB;AACL,QAAA,oBAAoB,GAAG,EAAE,CAAC,CAAC,WAAW;AACtC,QAAA,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAClF,QAAA,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAClC,QAAA,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AAC5E,QAAA,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AACrC,QAAA,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAE1C,QAAA,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC","sourcesContent":["// Nonce/Key Sizes\nexport const ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nexport const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n"]}
@@ -2,7 +2,6 @@ export declare const ALGORITHM_NONCE_SIZE = 12;
2
2
  export declare const ALGORITHM_KEY_SIZE = 16;
3
3
  export declare const SCRYPT_SALT_SIZE = 16;
4
4
  export declare const SCRYPT_N: number;
5
- export declare const SCRYPT_N_V2 = 2;
6
5
  export declare const SCRYPT_r = 8;
7
6
  export declare const SCRYPT_p = 1;
8
7
  export declare const SHARED_SALT: Uint8Array;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
1
+ {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
@@ -2,7 +2,6 @@ export declare const ALGORITHM_NONCE_SIZE = 12;
2
2
  export declare const ALGORITHM_KEY_SIZE = 16;
3
3
  export declare const SCRYPT_SALT_SIZE = 16;
4
4
  export declare const SCRYPT_N: number;
5
- export declare const SCRYPT_N_V2 = 2;
6
5
  export declare const SCRYPT_r = 8;
7
6
  export declare const SCRYPT_p = 1;
8
7
  export declare const SHARED_SALT: Uint8Array;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
1
+ {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAIrC,eAAO,MAAM,gBAAgB,KAAK,CAAC;AACnC,eAAO,MAAM,QAAQ,QAAU,CAAC;AAChC,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
@@ -5,7 +5,6 @@ export const ALGORITHM_KEY_SIZE = 16; // 16 bytes
5
5
  // see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt
6
6
  export const SCRYPT_SALT_SIZE = 16; // 16 bytes
7
7
  export const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)
8
- export const SCRYPT_N_V2 = 2;
9
8
  export const SCRYPT_r = 8; // Block size parameter
10
9
  export const SCRYPT_p = 1; // Parallelization parameter
11
10
  export const SHARED_SALT = new Uint8Array([
@@ -1 +1 @@
1
- {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC,CAAC,WAAW;AACnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAC/C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AACzF,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAC7B,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAEvD,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC","sourcesContent":["// Nonce/Key Sizes\nexport const ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nexport const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_N_V2 = 2;\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n"]}
1
+ {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC,CAAC,WAAW;AACnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC,CAAC,WAAW;AAEjD,kBAAkB;AAClB,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC,CAAC,WAAW;AAC/C,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,wDAAwD;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,uBAAuB;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,4BAA4B;AAEvD,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC;IACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACrD,CAAC,CAAC","sourcesContent":["// Nonce/Key Sizes\nexport const ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nexport const ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nexport const SCRYPT_SALT_SIZE = 16; // 16 bytes\nexport const SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\nexport const SCRYPT_r = 8; // Block size parameter\nexport const SCRYPT_p = 1; // Parallelization parameter\n\nexport const SHARED_SALT = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n]);\n"]}
@@ -21,13 +21,7 @@ class EncryptorDecryptor {
21
21
  }
22
22
  async encryptString(plaintext, password, nativeScryptCrypto) {
23
23
  try {
24
- const startTimestamp = Date.now();
25
- console.warn(`Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
26
- const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto, {
27
- N: constants_1.SCRYPT_N_V2,
28
- });
29
- console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
30
- return encryptedData;
24
+ return await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto);
31
25
  }
32
26
  catch (e) {
33
27
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
@@ -36,14 +30,10 @@ class EncryptorDecryptor {
36
30
  }
37
31
  async decryptString(encryptedDataStr, password, nativeScryptCrypto) {
38
32
  try {
39
- const startTimestamp = Date.now();
40
- console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
41
33
  const encryptedData = JSON.parse(encryptedDataStr);
42
- if (['1', '2'].includes(encryptedData.v)) {
34
+ if (encryptedData.v === '1') {
43
35
  if (encryptedData.t === 'scrypt') {
44
- const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
45
- console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`);
46
- return decryptedData;
36
+ return await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
47
37
  }
48
38
  }
49
39
  throw new Error(`Unsupported encrypted data payload - ${encryptedDataStr}`);
@@ -88,11 +78,9 @@ class EncryptorDecryptor {
88
78
  return strSet.size === salts.length;
89
79
  }
90
80
  }
91
- _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto, scryptOverrides = {
92
- N: constants_1.SCRYPT_N,
93
- }) {
81
+ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto) {
94
82
  const { key, salt } = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_getOrGenerateScryptKey).call(this, password, {
95
- N: scryptOverrides.N,
83
+ N: constants_1.SCRYPT_N,
96
84
  r: constants_1.SCRYPT_r,
97
85
  p: constants_1.SCRYPT_p,
98
86
  dkLen: constants_1.ALGORITHM_KEY_SIZE,
@@ -103,11 +91,11 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
103
91
  // Convert to Base64
104
92
  const encryptedData = (0, utils_2.byteArrayToBase64)(ciphertextAndNonceAndSalt);
105
93
  const encryptedPayload = {
106
- v: '2',
94
+ v: '1',
107
95
  t: 'scrypt',
108
96
  d: encryptedData,
109
97
  o: {
110
- N: scryptOverrides.N,
98
+ N: constants_1.SCRYPT_N,
111
99
  r: constants_1.SCRYPT_r,
112
100
  p: constants_1.SCRYPT_p,
113
101
  dkLen: constants_1.ALGORITHM_KEY_SIZE,
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.cjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;;;;AAAA,4CAAyC;AACzC,wDAAuD;AACvD,iDAAmD;AACnD,iDAA8C;AAC9C,+CAA2E;AAE3E,uCAIiB;AACjB,+CASqB;AACrB,uCAKiB;AAyBjB,MAAM,kBAAkB;IAAxB;;IAgQA,CAAC;IA/PC,KAAK,CAAC,aAAa,CACjB,SAAiB,EACjB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;YACF,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAClC,OAAO,CAAC,IAAI,CACV,oDAAoD,QAAQ,OAAO,IAAI,IAAI,CAAC,cAAc,CAAC,CAAC,WAAW,EAAE,EAAE,CAC5G,CAAC;YACF,MAAM,aAAa,GAAG,MAAM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,EAAE,CAAC,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,KAAK,EAAE,CAAC,CAAC,KAAK;SACf,CAAC,CAAC;KACJ;IAED,IAAA,oBAAY,EAAC,cAAc,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE9C,OAAO;QACL,GAAG,EAAE,MAAM;QACX,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAGH,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,kBAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,IAAA,eAAM,EAAC,IAAI,CAAC,CAAC;IAChC,OAAO,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;AAChC,CAAC;AAHD,4CAGC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_N_V2,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\n\nexport type EncryptedPayload = {\n // version\n v: '1' | '2';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData = await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n {\n N: SCRYPT_N_V2,\n },\n );\n console.warn(\n `Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`,\n );\n\n return encryptedData;\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 async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n\n if (['1', '2'].includes(encryptedData.v)) {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`,\n );\n return decryptedData;\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 async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n scryptOverrides = {\n N: SCRYPT_N,\n },\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\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: '2',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: scryptOverrides.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 async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<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 } = await 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 nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\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 return salt;\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 get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\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 async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\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 *\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
+ {"version":3,"file":"encryption.cjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;;;;AAAA,4CAAyC;AACzC,wDAAuD;AACvD,iDAAmD;AACnD,iDAA8C;AAC9C,+CAA2E;AAE3E,uCAIiB;AACjB,+CAQqB;AACrB,uCAKiB;AAyBjB,MAAM,kBAAkB;IAAxB;;IAuOA,CAAC;IAtOC,KAAK,CAAC,aAAa,CACjB,SAAiB,EACjB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;YACF,OAAO,MAAM,uBAAA,IAAI,0EAAiB,MAArB,IAAI,EACf,SAAS,EACT,QAAQ,EACR,kBAAkB,CACnB,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YACxE,MAAM,IAAI,KAAK,CAAC,8BAA8B,YAAY,EAAE,CAAC,CAAC;SAC/D;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,gBAAwB,EACxB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;YACF,MAAM,aAAa,GAAqB,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;YACrE,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;gBAC3B,IAAI,aAAa,CAAC,CAAC,KAAK,QAAQ,EAAE;oBAChC,OAAO,MAAM,uBAAA,IAAI,0EAAiB,MAArB,IAAI,EACf,aAAa,EACb,QAAQ,EACR,kBAAkB,CACnB,CAAC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AAE,CAAC,CAAC,CAAC;YACN,KAAK,EAAE,CAAC,CAAC,KAAK;SACf,CAAC,CAAC;KACJ;IAED,IAAA,oBAAY,EAAC,cAAc,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE9C,OAAO;QACL,GAAG,EAAE,MAAM;QACX,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAGH,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,kBAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,IAAA,eAAM,EAAC,IAAI,CAAC,CAAC;IAChC,OAAO,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;AAChC,CAAC;AAHD,4CAGC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\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 N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n return await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n );\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 async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\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 async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\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 async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<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 } = await 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 nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\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 return salt;\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 get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\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 async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\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 *\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,6 +1,6 @@
1
1
  import type { NativeScrypt } from "../types/encryption.cjs";
2
2
  export type EncryptedPayload = {
3
- v: '1' | '2';
3
+ v: '1';
4
4
  t: 'scrypt';
5
5
  d: string;
6
6
  o: {
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.d.cts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,YA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ACV,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;IAoGlB,OAAO,CAAC,gBAAgB,EAAE,MAAM;IA0BhC,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO;CAmF3D;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
@@ -1,6 +1,6 @@
1
1
  import type { NativeScrypt } from "../types/encryption.mjs";
2
2
  export type EncryptedPayload = {
3
- v: '1' | '2';
3
+ v: '1';
4
4
  t: 'scrypt';
5
5
  d: string;
6
6
  o: {
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.d.mts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,YAAY,EAAE,gCAA4B;AAExD,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC;IAGb,CAAC,EAAE,QAAQ,CAAC;IAGZ,CAAC,EAAE,MAAM,CAAC;IAGV,CAAC,EAAE;QACD,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,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AoGlB,OAAO,CAAC,gBAAgB,EAAE,MAAM;IA0BhC,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO;CAmF3D;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
@@ -10,7 +10,7 @@ import { scryptAsync } from "@noble/hashes/scrypt";
10
10
  import { sha256 } from "@noble/hashes/sha256";
11
11
  import { utf8ToBytes, concatBytes, bytesToHex } from "@noble/hashes/utils";
12
12
  import { getCachedKeyBySalt, getCachedKeyGeneratedWithSharedSalt, setCachedKey } from "./cache.mjs";
13
- import { ALGORITHM_KEY_SIZE, ALGORITHM_NONCE_SIZE, SCRYPT_N, SCRYPT_N_V2, SCRYPT_p, SCRYPT_r, SCRYPT_SALT_SIZE, SHARED_SALT } from "./constants.mjs";
13
+ import { ALGORITHM_KEY_SIZE, ALGORITHM_NONCE_SIZE, SCRYPT_N, SCRYPT_p, SCRYPT_r, SCRYPT_SALT_SIZE, SHARED_SALT } from "./constants.mjs";
14
14
  import { base64ToByteArray, byteArrayToBase64, bytesToUtf8, stringToByteArray } from "./utils.mjs";
15
15
  class EncryptorDecryptor {
16
16
  constructor() {
@@ -18,13 +18,7 @@ class EncryptorDecryptor {
18
18
  }
19
19
  async encryptString(plaintext, password, nativeScryptCrypto) {
20
20
  try {
21
- const startTimestamp = Date.now();
22
- console.warn(`Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
23
- const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto, {
24
- N: SCRYPT_N_V2,
25
- });
26
- console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
27
- return encryptedData;
21
+ return await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto);
28
22
  }
29
23
  catch (e) {
30
24
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
@@ -33,14 +27,10 @@ class EncryptorDecryptor {
33
27
  }
34
28
  async decryptString(encryptedDataStr, password, nativeScryptCrypto) {
35
29
  try {
36
- const startTimestamp = Date.now();
37
- console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
38
30
  const encryptedData = JSON.parse(encryptedDataStr);
39
- if (['1', '2'].includes(encryptedData.v)) {
31
+ if (encryptedData.v === '1') {
40
32
  if (encryptedData.t === 'scrypt') {
41
- const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
42
- console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`);
43
- return decryptedData;
33
+ return await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
44
34
  }
45
35
  }
46
36
  throw new Error(`Unsupported encrypted data payload - ${encryptedDataStr}`);
@@ -85,11 +75,9 @@ class EncryptorDecryptor {
85
75
  return strSet.size === salts.length;
86
76
  }
87
77
  }
88
- _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto, scryptOverrides = {
89
- N: SCRYPT_N,
90
- }) {
78
+ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto) {
91
79
  const { key, salt } = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_getOrGenerateScryptKey).call(this, password, {
92
- N: scryptOverrides.N,
80
+ N: SCRYPT_N,
93
81
  r: SCRYPT_r,
94
82
  p: SCRYPT_p,
95
83
  dkLen: ALGORITHM_KEY_SIZE,
@@ -100,11 +88,11 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
100
88
  // Convert to Base64
101
89
  const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
102
90
  const encryptedPayload = {
103
- v: '2',
91
+ v: '1',
104
92
  t: 'scrypt',
105
93
  d: encryptedData,
106
94
  o: {
107
- N: scryptOverrides.N,
95
+ N: SCRYPT_N,
108
96
  r: SCRYPT_r,
109
97
  p: SCRYPT_p,
110
98
  dkLen: ALGORITHM_KEY_SIZE,
@@ -1 +1 @@
1
- {"version":3,"file":"encryption.mjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,GAAG,EAAE,2BAA2B;AACzC,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,WAAW,EAAE,6BAA6B;AACnD,OAAO,EAAE,MAAM,EAAE,6BAA6B;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B;AAE3E,OAAO,EACL,kBAAkB,EAClB,mCAAmC,EACnC,YAAY,EACb,oBAAgB;AACjB,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,QAAQ,EACR,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,gBAAgB,EAChB,WAAW,EACZ,wBAAoB;AACrB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EAClB,oBAAgB;AAyBjB,MAAM,kBAAkB;IAAxB;;IAgQA,CAAC;IA/PC,KAAK,CAAC,aAAa,CACjB,SAAiB,EACjB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;YACF,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAClC,OAAO,CAAC,IAAI,CACV,oDAAoD,QAAQ,OAAO,IAAI,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C,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,KAAK,EAAE,CAAC,CAAC,KAAK;SACf,CAAC,CAAC;KACJ;IAED,YAAY,CAAC,cAAc,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE9C,OAAO;QACL,GAAG,EAAE,MAAM;QACX,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAGH,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,UAAU,CAAC,UAAU,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_N_V2,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\n\nexport type EncryptedPayload = {\n // version\n v: '1' | '2';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData = await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n {\n N: SCRYPT_N_V2,\n },\n );\n console.warn(\n `Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`,\n );\n\n return encryptedData;\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 async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n\n if (['1', '2'].includes(encryptedData.v)) {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`,\n );\n return decryptedData;\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 async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n scryptOverrides = {\n N: SCRYPT_N,\n },\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\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: '2',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: scryptOverrides.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 async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<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 } = await 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 nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\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 return salt;\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 get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\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 async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\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 *\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
+ {"version":3,"file":"encryption.mjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,GAAG,EAAE,2BAA2B;AACzC,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,WAAW,EAAE,6BAA6B;AACnD,OAAO,EAAE,MAAM,EAAE,6BAA6B;AAC9C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B;AAE3E,OAAO,EACL,kBAAkB,EAClB,mCAAmC,EACnC,YAAY,EACb,oBAAgB;AACjB,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,gBAAgB,EAChB,WAAW,EACZ,wBAAoB;AACrB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EAClB,oBAAgB;AAyBjB,MAAM,kBAAkB;IAAxB;;IAuOA,CAAC;IAtOC,KAAK,CAAC,aAAa,CACjB,SAAiB,EACjB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;YACF,OAAO,MAAM,uBAAA,IAAI,0EAAiB,MAArB,IAAI,EACf,SAAS,EACT,QAAQ,EACR,kBAAkB,CACnB,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YACxE,MAAM,IAAI,KAAK,CAAC,8BAA8B,YAAY,EAAE,CAAC,CAAC;SAC/D;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,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CAAC,EACH,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,KAAK,CACR,CAAC;KACH;SAAM;QACL,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,OAAO,EAAE;YAC5C,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,KAAK,EAAE,CAAC,CAAC,KAAK;SACf,CAAC,CAAC;KACJ;IAED,YAAY,CAAC,cAAc,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE9C,OAAO;QACL,GAAG,EAAE,MAAM;QACX,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAGH,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,UAAU,CAAC,UAAU,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\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 N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n return await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n );\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 async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\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 async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\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 async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<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 } = await 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 nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\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 return salt;\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 get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\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 async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\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 *\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/profile-sync-controller",
3
- "version": "20.0.0-preview-2bb8758e",
3
+ "version": "21.0.0-preview-c10fdda1",
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",