@metamask-previews/profile-sync-controller 20.0.0-preview-38b0103c → 20.0.0-preview-2bb8758e
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/dist/sdk/user-storage.cjs +2 -2
- package/dist/sdk/user-storage.cjs.map +1 -1
- package/dist/sdk/user-storage.d.cts.map +1 -1
- package/dist/sdk/user-storage.d.mts.map +1 -1
- package/dist/sdk/user-storage.mjs +2 -2
- package/dist/sdk/user-storage.mjs.map +1 -1
- package/dist/shared/encryption/constants.cjs +9 -1
- package/dist/shared/encryption/constants.cjs.map +1 -1
- package/dist/shared/encryption/constants.d.cts +6 -0
- package/dist/shared/encryption/constants.d.cts.map +1 -1
- package/dist/shared/encryption/constants.d.mts +6 -0
- package/dist/shared/encryption/constants.d.mts.map +1 -1
- package/dist/shared/encryption/constants.mjs +8 -0
- package/dist/shared/encryption/constants.mjs.map +1 -1
- package/dist/shared/encryption/encryption.cjs +31 -28
- package/dist/shared/encryption/encryption.cjs.map +1 -1
- package/dist/shared/encryption/encryption.d.cts +3 -8
- package/dist/shared/encryption/encryption.d.cts.map +1 -1
- package/dist/shared/encryption/encryption.d.mts +3 -8
- package/dist/shared/encryption/encryption.d.mts.map +1 -1
- package/dist/shared/encryption/encryption.mjs +33 -30
- package/dist/shared/encryption/encryption.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -83,7 +83,7 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
|
|
|
83
83
|
try {
|
|
84
84
|
const headers = await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_getAuthorizationHeader).call(this, entropySourceId);
|
|
85
85
|
const storageKey = await this.getStorageKey(entropySourceId);
|
|
86
|
-
const encryptedData = await encryption_1.default.encryptString(data, storageKey);
|
|
86
|
+
const encryptedData = await encryption_1.default.encryptString(data, storageKey, options?.nativeScryptCrypto);
|
|
87
87
|
const encryptedPath = (0, storage_schema_1.createEntryPath)(path, storageKey);
|
|
88
88
|
const url = new URL((0, exports.STORAGE_URL)(this.env, encryptedPath));
|
|
89
89
|
const response = await fetch(url.toString(), {
|
|
@@ -118,7 +118,7 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
|
|
|
118
118
|
const encryptedData = await Promise.all(data.map(async (d) => {
|
|
119
119
|
return [
|
|
120
120
|
__classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_createEntryKey).call(this, d[0], storageKey),
|
|
121
|
-
await encryption_1.default.encryptString(d[1], storageKey),
|
|
121
|
+
await encryption_1.default.encryptString(d[1], storageKey, options?.nativeScryptCrypto),
|
|
122
122
|
];
|
|
123
123
|
}));
|
|
124
124
|
const url = new URL((0, exports.STORAGE_URL)(this.env, path));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAA2D;AAC3D,6EAAoE;AAEpE,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,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,OAAO,CACX,IAA6C,EAC7C,KAAa,EACb,OAAkC;QAElC,MAAM,uBAAA,IAAI,8DAAmB,MAAvB,IAAI,EAAoB,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAA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1B,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 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(data, storageKey);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #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(d[1], storageKey),\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;AAEpE,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,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,OAAO,CACX,IAA6C,EAC7C,KAAa,EACb,OAAkC;QAElC,MAAM,uBAAA,IAAI,8DAAmB,MAAvB,IAAI,EAAoB,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,IAAmC,EACnC,MAAgD,EAChD,OAAkC;QAElC,MAAM,uBAAA,IAAI,mEAAwB,MAA5B,IAAI,EAAyB,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,OAAO,CACX,IAA6C,EAC7C,OAAkC;QAElC,OAAO,uBAAA,IAAI,2DAAgB,MAApB,IAAI,EAAiB,IAAI,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK,CAAC,kBAAkB,CACtB,IAAmC,EACnC,OAAkC;QAElC,OAAO,uBAAA,IAAI,4EAAiC,MAArC,IAAI,EAAkC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC9D,CAAC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AI,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 +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,EAA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tB,SAAS,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAE7B,OAAO,EAAE,kBAAkB,CAAC;IAEnC,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC;gBAEP,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,kBAAkB;IAM5D,OAAO,CACX,IAAI,EAAE,uCAAuC,EAC7C,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,wBAAwB,GACjC,OAAO,CAAC,IAAI,CAAC;IAIV,aAAa,CACjB,IAAI,EAAE,6BAA6B,EACnC,MAAM,EAAE,CAAC,4BAA4B,EAAE,MAAM,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE,wBAAwB;IAK9B,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;CA+c/D"}
|
|
@@ -55,7 +55,7 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
|
|
|
55
55
|
try {
|
|
56
56
|
const headers = await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_getAuthorizationHeader).call(this, entropySourceId);
|
|
57
57
|
const storageKey = await this.getStorageKey(entropySourceId);
|
|
58
|
-
const encryptedData = await encryption.encryptString(data, storageKey);
|
|
58
|
+
const encryptedData = await encryption.encryptString(data, storageKey, options?.nativeScryptCrypto);
|
|
59
59
|
const encryptedPath = createEntryPath(path, storageKey);
|
|
60
60
|
const url = new URL(STORAGE_URL(this.env, encryptedPath));
|
|
61
61
|
const response = await fetch(url.toString(), {
|
|
@@ -90,7 +90,7 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
|
|
|
90
90
|
const encryptedData = await Promise.all(data.map(async (d) => {
|
|
91
91
|
return [
|
|
92
92
|
__classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_createEntryKey).call(this, d[0], storageKey),
|
|
93
|
-
await encryption.encryptString(d[1], storageKey),
|
|
93
|
+
await encryption.encryptString(d[1], storageKey, options?.nativeScryptCrypto),
|
|
94
94
|
];
|
|
95
95
|
}));
|
|
96
96
|
const url = new URL(STORAGE_URL(this.env, path));
|
|
@@ -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,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,GAAG,MAAM,CAAC;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uB,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(data, storageKey);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #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(d[1], storageKey),\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;AAEpE,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,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,OAAO,CACX,IAA6C,EAC7C,KAAa,EACb,OAAkC;QAElC,MAAM,uBAAA,IAAI,8DAAmB,MAAvB,IAAI,EAAoB,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,IAAmC,EACnC,MAAgD,EAChD,OAAkC;QAElC,MAAM,uBAAA,IAAI,mEAAwB,MAA5B,IAAI,EAAyB,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,OAAO,CACX,IAA6C,EAC7C,OAAkC;QAElC,OAAO,uBAAA,IAAI,2DAAgB,MAApB,IAAI,EAAiB,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AC5C,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,8 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SHARED_SALT = exports.ALGORITHM_NONCE_SIZE = void 0;
|
|
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;
|
|
4
4
|
// Nonce/Key Sizes
|
|
5
5
|
exports.ALGORITHM_NONCE_SIZE = 12; // 12 bytes
|
|
6
|
+
exports.ALGORITHM_KEY_SIZE = 16; // 16 bytes
|
|
7
|
+
// Scrypt settings
|
|
8
|
+
// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt
|
|
9
|
+
exports.SCRYPT_SALT_SIZE = 16; // 16 bytes
|
|
10
|
+
exports.SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)
|
|
11
|
+
exports.SCRYPT_N_V2 = 2;
|
|
12
|
+
exports.SCRYPT_r = 8; // Block size parameter
|
|
13
|
+
exports.SCRYPT_p = 1; // Parallelization parameter
|
|
6
14
|
exports.SHARED_SALT = new Uint8Array([
|
|
7
15
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
8
16
|
]);
|
|
@@ -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;
|
|
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,3 +1,9 @@
|
|
|
1
1
|
export declare const ALGORITHM_NONCE_SIZE = 12;
|
|
2
|
+
export declare const ALGORITHM_KEY_SIZE = 16;
|
|
3
|
+
export declare const SCRYPT_SALT_SIZE = 16;
|
|
4
|
+
export declare const SCRYPT_N: number;
|
|
5
|
+
export declare const SCRYPT_N_V2 = 2;
|
|
6
|
+
export declare const SCRYPT_r = 8;
|
|
7
|
+
export declare const SCRYPT_p = 1;
|
|
2
8
|
export declare const SHARED_SALT: Uint8Array;
|
|
3
9
|
//# sourceMappingURL=constants.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,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,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
1
|
export declare const ALGORITHM_NONCE_SIZE = 12;
|
|
2
|
+
export declare const ALGORITHM_KEY_SIZE = 16;
|
|
3
|
+
export declare const SCRYPT_SALT_SIZE = 16;
|
|
4
|
+
export declare const SCRYPT_N: number;
|
|
5
|
+
export declare const SCRYPT_N_V2 = 2;
|
|
6
|
+
export declare const SCRYPT_r = 8;
|
|
7
|
+
export declare const SCRYPT_p = 1;
|
|
2
8
|
export declare const SHARED_SALT: Uint8Array;
|
|
3
9
|
//# sourceMappingURL=constants.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../src/shared/encryption/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,KAAK,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,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAC1B,eAAO,MAAM,QAAQ,IAAI,CAAC;AAE1B,eAAO,MAAM,WAAW,YAEtB,CAAC"}
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
// Nonce/Key Sizes
|
|
2
2
|
export const ALGORITHM_NONCE_SIZE = 12; // 12 bytes
|
|
3
|
+
export const ALGORITHM_KEY_SIZE = 16; // 16 bytes
|
|
4
|
+
// Scrypt settings
|
|
5
|
+
// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt
|
|
6
|
+
export const SCRYPT_SALT_SIZE = 16; // 16 bytes
|
|
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
|
+
export const SCRYPT_r = 8; // Block size parameter
|
|
10
|
+
export const SCRYPT_p = 1; // Parallelization parameter
|
|
3
11
|
export const SHARED_SALT = new Uint8Array([
|
|
4
12
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
5
13
|
]);
|
|
@@ -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;
|
|
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"]}
|
|
@@ -4,7 +4,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
4
4
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
5
5
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
6
|
};
|
|
7
|
-
var _EncryptorDecryptor_instances,
|
|
7
|
+
var _EncryptorDecryptor_instances, _EncryptorDecryptor_encryptStringV1, _EncryptorDecryptor_decryptStringV1, _EncryptorDecryptor_encrypt, _EncryptorDecryptor_decrypt, _EncryptorDecryptor_getOrGenerateScryptKey;
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
9
|
exports.createSHA256Hash = void 0;
|
|
10
10
|
const aes_1 = require("@noble/ciphers/aes");
|
|
@@ -19,11 +19,13 @@ class EncryptorDecryptor {
|
|
|
19
19
|
constructor() {
|
|
20
20
|
_EncryptorDecryptor_instances.add(this);
|
|
21
21
|
}
|
|
22
|
-
async encryptString(plaintext, password) {
|
|
22
|
+
async encryptString(plaintext, password, nativeScryptCrypto) {
|
|
23
23
|
try {
|
|
24
24
|
const startTimestamp = Date.now();
|
|
25
25
|
console.warn(`Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
26
|
-
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m",
|
|
26
|
+
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto, {
|
|
27
|
+
N: constants_1.SCRYPT_N_V2,
|
|
28
|
+
});
|
|
27
29
|
console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
|
|
28
30
|
return encryptedData;
|
|
29
31
|
}
|
|
@@ -37,17 +39,10 @@ class EncryptorDecryptor {
|
|
|
37
39
|
const startTimestamp = Date.now();
|
|
38
40
|
console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
39
41
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
40
|
-
if (
|
|
41
|
-
if (encryptedData.t === 'gcm') {
|
|
42
|
-
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV2).call(this, encryptedData, password);
|
|
43
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V2 encryption)`);
|
|
44
|
-
return decryptedData;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
if (encryptedData.v === '1') {
|
|
42
|
+
if (['1', '2'].includes(encryptedData.v)) {
|
|
48
43
|
if (encryptedData.t === 'scrypt') {
|
|
49
44
|
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
|
|
50
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using
|
|
45
|
+
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`);
|
|
51
46
|
return decryptedData;
|
|
52
47
|
}
|
|
53
48
|
}
|
|
@@ -61,10 +56,6 @@ class EncryptorDecryptor {
|
|
|
61
56
|
getSalt(encryptedDataStr) {
|
|
62
57
|
try {
|
|
63
58
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
64
|
-
if (encryptedData.v === '2') {
|
|
65
|
-
// V2 encryption doesn't use traditional salts, return null to indicate no salt
|
|
66
|
-
return null;
|
|
67
|
-
}
|
|
68
59
|
if (encryptedData.v === '1') {
|
|
69
60
|
if (encryptedData.t === 'scrypt') {
|
|
70
61
|
const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;
|
|
@@ -93,19 +84,35 @@ class EncryptorDecryptor {
|
|
|
93
84
|
}
|
|
94
85
|
})
|
|
95
86
|
.filter((s) => s !== undefined);
|
|
96
|
-
|
|
97
|
-
const strSet = new Set(salts.map((salt) => (salt ? salt.toString() : 'null')));
|
|
87
|
+
const strSet = new Set(salts.map((arr) => arr.toString()));
|
|
98
88
|
return strSet.size === salts.length;
|
|
99
89
|
}
|
|
100
90
|
}
|
|
101
|
-
_EncryptorDecryptor_instances = new WeakSet(),
|
|
91
|
+
_EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto, scryptOverrides = {
|
|
92
|
+
N: constants_1.SCRYPT_N,
|
|
93
|
+
}) {
|
|
94
|
+
const { key, salt } = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_getOrGenerateScryptKey).call(this, password, {
|
|
95
|
+
N: scryptOverrides.N,
|
|
96
|
+
r: constants_1.SCRYPT_r,
|
|
97
|
+
p: constants_1.SCRYPT_p,
|
|
98
|
+
dkLen: constants_1.ALGORITHM_KEY_SIZE,
|
|
99
|
+
}, undefined, nativeScryptCrypto);
|
|
100
|
+
// Encrypt and prepend salt.
|
|
102
101
|
const plaintextRaw = (0, utils_1.utf8ToBytes)(plaintext);
|
|
103
|
-
const
|
|
104
|
-
|
|
102
|
+
const ciphertextAndNonceAndSalt = (0, utils_1.concatBytes)(salt, __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encrypt).call(this, plaintextRaw, key));
|
|
103
|
+
// Convert to Base64
|
|
104
|
+
const encryptedData = (0, utils_2.byteArrayToBase64)(ciphertextAndNonceAndSalt);
|
|
105
105
|
const encryptedPayload = {
|
|
106
106
|
v: '2',
|
|
107
|
-
t: '
|
|
108
|
-
d:
|
|
107
|
+
t: 'scrypt',
|
|
108
|
+
d: encryptedData,
|
|
109
|
+
o: {
|
|
110
|
+
N: scryptOverrides.N,
|
|
111
|
+
r: constants_1.SCRYPT_r,
|
|
112
|
+
p: constants_1.SCRYPT_p,
|
|
113
|
+
dkLen: constants_1.ALGORITHM_KEY_SIZE,
|
|
114
|
+
},
|
|
115
|
+
saltLen: constants_1.SCRYPT_SALT_SIZE,
|
|
109
116
|
};
|
|
110
117
|
return JSON.stringify(encryptedPayload);
|
|
111
118
|
}, _EncryptorDecryptor_decryptStringV1 = async function _EncryptorDecryptor_decryptStringV1(data, password, nativeScryptCrypto) {
|
|
@@ -124,13 +131,9 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
|
|
|
124
131
|
}, salt, nativeScryptCrypto);
|
|
125
132
|
// Decrypt and return result.
|
|
126
133
|
return (0, utils_2.bytesToUtf8)(__classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decrypt).call(this, ciphertextAndNonce, key));
|
|
127
|
-
}, _EncryptorDecryptor_decryptStringV2 = async function _EncryptorDecryptor_decryptStringV2(data, password) {
|
|
128
|
-
const { d: base64CiphertextAndNonce } = data;
|
|
129
|
-
const ciphertextAndNonce = (0, utils_2.base64ToByteArray)(base64CiphertextAndNonce);
|
|
130
|
-
const passwordRaw = (0, utils_1.hexToBytes)(password);
|
|
131
|
-
return (0, utils_2.bytesToUtf8)(__classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decrypt).call(this, ciphertextAndNonce, passwordRaw));
|
|
132
134
|
}, _EncryptorDecryptor_encrypt = function _EncryptorDecryptor_encrypt(plaintext, key) {
|
|
133
135
|
const nonce = (0, webcrypto_1.randomBytes)(constants_1.ALGORITHM_NONCE_SIZE);
|
|
136
|
+
// Encrypt and prepend nonce.
|
|
134
137
|
const ciphertext = (0, aes_1.gcm)(key, nonce).encrypt(plaintext);
|
|
135
138
|
return (0, utils_1.concatBytes)(nonce, ciphertext);
|
|
136
139
|
}, _EncryptorDecryptor_decrypt = function _EncryptorDecryptor_decrypt(ciphertextAndNonce, key) {
|
|
@@ -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,+CAK6B;AAE7B,uCAIiB;AACjB,+CAAgE;AAChE,uCAKiB;AAoCjB,MAAM,kBAAkB;IAAxB;;IAuPA,CAAC;IAtPC,KAAK,CAAC,aAAa,CAAC,SAAiB,EAAE,QAA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,OAAO,GAAG,IAAI,IAAI,uBAAW,CAAC;IAEpC,IAAI,MAAkB,CAAC;IAEvB,IAAI,kBAAkB,EAAE;QACtB,MAAM,GAAG,MAAM,kBAAkB,CAC/B,IAAA,yBAAiB,EAAC,QAAQ,CAAC,EAC3B,OAAO,EACP,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,CAAC,EACH,CAAC,CAAC,KAAK,CACR,CAAC;KACH;SAAM;QACL,MAAM,GAAG,MAAM,IAAA,oBAAW,EAAC,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,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 {\n utf8ToBytes,\n concatBytes,\n bytesToHex,\n hexToBytes,\n} from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport { ALGORITHM_NONCE_SIZE, SHARED_SALT } 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\nexport type EncryptedPayloadV2 = {\n // version\n v: '2';\n\n // algorithm\n t: 'gcm';\n\n // data\n d: string;\n};\n\nclass EncryptorDecryptor {\n async encryptString(plaintext: string, password: string): 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.#encryptStringV2(plaintext, password);\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 | EncryptedPayloadV2 =\n JSON.parse(encryptedDataStr);\n\n if (encryptedData.v === '2') {\n if (encryptedData.t === 'gcm') {\n const decryptedData = await this.#decryptStringV2(\n encryptedData,\n password,\n );\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V2 encryption)`,\n );\n return decryptedData;\n }\n }\n\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V1 encryption)`,\n );\n return decryptedData;\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 #encryptStringV2(plaintext: string, password: string): Promise<string> {\n const plaintextRaw = utf8ToBytes(plaintext);\n const passwordRaw = hexToBytes(password);\n const cipherTextAndNonce = this.#encrypt(plaintextRaw, passwordRaw);\n\n const encryptedPayload: EncryptedPayloadV2 = {\n v: '2',\n t: 'gcm',\n d: byteArrayToBase64(cipherTextAndNonce),\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 async #decryptStringV2(\n data: EncryptedPayloadV2,\n password: string,\n ): Promise<string> {\n const { d: base64CiphertextAndNonce } = data;\n\n const ciphertextAndNonce = base64ToByteArray(base64CiphertextAndNonce);\n const passwordRaw = hexToBytes(password);\n\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, passwordRaw));\n }\n\n getSalt(encryptedDataStr: string): Uint8Array | null {\n try {\n const encryptedData: EncryptedPayload | EncryptedPayloadV2 =\n JSON.parse(encryptedDataStr);\n\n if (encryptedData.v === '2') {\n // V2 encryption doesn't use traditional salts, return null to indicate no salt\n return null;\n }\n\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 | null => s !== undefined);\n\n // Convert to strings for comparison, using 'null' for null values\n const strSet = new Set(\n salts.map((salt) => (salt ? salt.toString() : 'null')),\n );\n return strSet.size === salts.length;\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\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,+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,uBAAA,IAAI,0EAAiB,MAArB,IAAI,EAC9B,SAAS,EACT,QAAQ,EACR,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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,6 +1,6 @@
|
|
|
1
1
|
import type { NativeScrypt } from "../types/encryption.cjs";
|
|
2
2
|
export type EncryptedPayload = {
|
|
3
|
-
v: '1';
|
|
3
|
+
v: '1' | '2';
|
|
4
4
|
t: 'scrypt';
|
|
5
5
|
d: string;
|
|
6
6
|
o: {
|
|
@@ -11,16 +11,11 @@ export type EncryptedPayload = {
|
|
|
11
11
|
};
|
|
12
12
|
saltLen: number;
|
|
13
13
|
};
|
|
14
|
-
export type EncryptedPayloadV2 = {
|
|
15
|
-
v: '2';
|
|
16
|
-
t: 'gcm';
|
|
17
|
-
d: string;
|
|
18
|
-
};
|
|
19
14
|
declare class EncryptorDecryptor {
|
|
20
15
|
#private;
|
|
21
|
-
encryptString(plaintext: string, password: string): Promise<string>;
|
|
16
|
+
encryptString(plaintext: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
22
17
|
decryptString(encryptedDataStr: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
23
|
-
getSalt(encryptedDataStr: string): Uint8Array
|
|
18
|
+
getSalt(encryptedDataStr: string): Uint8Array;
|
|
24
19
|
getIfEntriesHaveDifferentSalts(entries: string[]): boolean;
|
|
25
20
|
}
|
|
26
21
|
declare const encryption: EncryptorDecryptor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryption.d.cts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"encryption.d.cts","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,kBAAkB;;IAChB,aAAa,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IAyBZ,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IAiHlB,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';
|
|
3
|
+
v: '1' | '2';
|
|
4
4
|
t: 'scrypt';
|
|
5
5
|
d: string;
|
|
6
6
|
o: {
|
|
@@ -11,16 +11,11 @@ export type EncryptedPayload = {
|
|
|
11
11
|
};
|
|
12
12
|
saltLen: number;
|
|
13
13
|
};
|
|
14
|
-
export type EncryptedPayloadV2 = {
|
|
15
|
-
v: '2';
|
|
16
|
-
t: 'gcm';
|
|
17
|
-
d: string;
|
|
18
|
-
};
|
|
19
14
|
declare class EncryptorDecryptor {
|
|
20
15
|
#private;
|
|
21
|
-
encryptString(plaintext: string, password: string): Promise<string>;
|
|
16
|
+
encryptString(plaintext: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
22
17
|
decryptString(encryptedDataStr: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
23
|
-
getSalt(encryptedDataStr: string): Uint8Array
|
|
18
|
+
getSalt(encryptedDataStr: string): Uint8Array;
|
|
24
19
|
getIfEntriesHaveDifferentSalts(entries: string[]): boolean;
|
|
25
20
|
}
|
|
26
21
|
declare const encryption: EncryptorDecryptor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryption.d.mts","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":"
|
|
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,kBAAkB;;IAChB,aAAa,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IAyBZ,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IAiHlB,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"}
|
|
@@ -3,24 +3,26 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
3
3
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
4
4
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
5
5
|
};
|
|
6
|
-
var _EncryptorDecryptor_instances,
|
|
6
|
+
var _EncryptorDecryptor_instances, _EncryptorDecryptor_encryptStringV1, _EncryptorDecryptor_decryptStringV1, _EncryptorDecryptor_encrypt, _EncryptorDecryptor_decrypt, _EncryptorDecryptor_getOrGenerateScryptKey;
|
|
7
7
|
import { gcm } from "@noble/ciphers/aes";
|
|
8
8
|
import { randomBytes } from "@noble/ciphers/webcrypto";
|
|
9
9
|
import { scryptAsync } from "@noble/hashes/scrypt";
|
|
10
10
|
import { sha256 } from "@noble/hashes/sha256";
|
|
11
|
-
import { utf8ToBytes, concatBytes, bytesToHex
|
|
11
|
+
import { utf8ToBytes, concatBytes, bytesToHex } from "@noble/hashes/utils";
|
|
12
12
|
import { getCachedKeyBySalt, getCachedKeyGeneratedWithSharedSalt, setCachedKey } from "./cache.mjs";
|
|
13
|
-
import { ALGORITHM_NONCE_SIZE, SHARED_SALT } from "./constants.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";
|
|
14
14
|
import { base64ToByteArray, byteArrayToBase64, bytesToUtf8, stringToByteArray } from "./utils.mjs";
|
|
15
15
|
class EncryptorDecryptor {
|
|
16
16
|
constructor() {
|
|
17
17
|
_EncryptorDecryptor_instances.add(this);
|
|
18
18
|
}
|
|
19
|
-
async encryptString(plaintext, password) {
|
|
19
|
+
async encryptString(plaintext, password, nativeScryptCrypto) {
|
|
20
20
|
try {
|
|
21
21
|
const startTimestamp = Date.now();
|
|
22
22
|
console.warn(`Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
23
|
-
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m",
|
|
23
|
+
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV1).call(this, plaintext, password, nativeScryptCrypto, {
|
|
24
|
+
N: SCRYPT_N_V2,
|
|
25
|
+
});
|
|
24
26
|
console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
|
|
25
27
|
return encryptedData;
|
|
26
28
|
}
|
|
@@ -34,17 +36,10 @@ class EncryptorDecryptor {
|
|
|
34
36
|
const startTimestamp = Date.now();
|
|
35
37
|
console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
36
38
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
37
|
-
if (
|
|
38
|
-
if (encryptedData.t === 'gcm') {
|
|
39
|
-
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV2).call(this, encryptedData, password);
|
|
40
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V2 encryption)`);
|
|
41
|
-
return decryptedData;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
if (encryptedData.v === '1') {
|
|
39
|
+
if (['1', '2'].includes(encryptedData.v)) {
|
|
45
40
|
if (encryptedData.t === 'scrypt') {
|
|
46
41
|
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
|
|
47
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using
|
|
42
|
+
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`);
|
|
48
43
|
return decryptedData;
|
|
49
44
|
}
|
|
50
45
|
}
|
|
@@ -58,10 +53,6 @@ class EncryptorDecryptor {
|
|
|
58
53
|
getSalt(encryptedDataStr) {
|
|
59
54
|
try {
|
|
60
55
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
61
|
-
if (encryptedData.v === '2') {
|
|
62
|
-
// V2 encryption doesn't use traditional salts, return null to indicate no salt
|
|
63
|
-
return null;
|
|
64
|
-
}
|
|
65
56
|
if (encryptedData.v === '1') {
|
|
66
57
|
if (encryptedData.t === 'scrypt') {
|
|
67
58
|
const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;
|
|
@@ -90,19 +81,35 @@ class EncryptorDecryptor {
|
|
|
90
81
|
}
|
|
91
82
|
})
|
|
92
83
|
.filter((s) => s !== undefined);
|
|
93
|
-
|
|
94
|
-
const strSet = new Set(salts.map((salt) => (salt ? salt.toString() : 'null')));
|
|
84
|
+
const strSet = new Set(salts.map((arr) => arr.toString()));
|
|
95
85
|
return strSet.size === salts.length;
|
|
96
86
|
}
|
|
97
87
|
}
|
|
98
|
-
_EncryptorDecryptor_instances = new WeakSet(),
|
|
88
|
+
_EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV1 = async function _EncryptorDecryptor_encryptStringV1(plaintext, password, nativeScryptCrypto, scryptOverrides = {
|
|
89
|
+
N: SCRYPT_N,
|
|
90
|
+
}) {
|
|
91
|
+
const { key, salt } = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_getOrGenerateScryptKey).call(this, password, {
|
|
92
|
+
N: scryptOverrides.N,
|
|
93
|
+
r: SCRYPT_r,
|
|
94
|
+
p: SCRYPT_p,
|
|
95
|
+
dkLen: ALGORITHM_KEY_SIZE,
|
|
96
|
+
}, undefined, nativeScryptCrypto);
|
|
97
|
+
// Encrypt and prepend salt.
|
|
99
98
|
const plaintextRaw = utf8ToBytes(plaintext);
|
|
100
|
-
const
|
|
101
|
-
|
|
99
|
+
const ciphertextAndNonceAndSalt = concatBytes(salt, __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encrypt).call(this, plaintextRaw, key));
|
|
100
|
+
// Convert to Base64
|
|
101
|
+
const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
|
|
102
102
|
const encryptedPayload = {
|
|
103
103
|
v: '2',
|
|
104
|
-
t: '
|
|
105
|
-
d:
|
|
104
|
+
t: 'scrypt',
|
|
105
|
+
d: encryptedData,
|
|
106
|
+
o: {
|
|
107
|
+
N: scryptOverrides.N,
|
|
108
|
+
r: SCRYPT_r,
|
|
109
|
+
p: SCRYPT_p,
|
|
110
|
+
dkLen: ALGORITHM_KEY_SIZE,
|
|
111
|
+
},
|
|
112
|
+
saltLen: SCRYPT_SALT_SIZE,
|
|
106
113
|
};
|
|
107
114
|
return JSON.stringify(encryptedPayload);
|
|
108
115
|
}, _EncryptorDecryptor_decryptStringV1 = async function _EncryptorDecryptor_decryptStringV1(data, password, nativeScryptCrypto) {
|
|
@@ -121,13 +128,9 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
|
|
|
121
128
|
}, salt, nativeScryptCrypto);
|
|
122
129
|
// Decrypt and return result.
|
|
123
130
|
return bytesToUtf8(__classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decrypt).call(this, ciphertextAndNonce, key));
|
|
124
|
-
}, _EncryptorDecryptor_decryptStringV2 = async function _EncryptorDecryptor_decryptStringV2(data, password) {
|
|
125
|
-
const { d: base64CiphertextAndNonce } = data;
|
|
126
|
-
const ciphertextAndNonce = base64ToByteArray(base64CiphertextAndNonce);
|
|
127
|
-
const passwordRaw = hexToBytes(password);
|
|
128
|
-
return bytesToUtf8(__classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decrypt).call(this, ciphertextAndNonce, passwordRaw));
|
|
129
131
|
}, _EncryptorDecryptor_encrypt = function _EncryptorDecryptor_encrypt(plaintext, key) {
|
|
130
132
|
const nonce = randomBytes(ALGORITHM_NONCE_SIZE);
|
|
133
|
+
// Encrypt and prepend nonce.
|
|
131
134
|
const ciphertext = gcm(key, nonce).encrypt(plaintext);
|
|
132
135
|
return concatBytes(nonce, ciphertext);
|
|
133
136
|
}, _EncryptorDecryptor_decrypt = function _EncryptorDecryptor_decrypt(ciphertextAndNonce, key) {
|
|
@@ -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,EACL,WAAW,EACX,WAAW,EACX,UAAU,EACV,UAAU,EACX,4BAA4B;AAE7B,OAAO,EACL,kBAAkB,EAClB,mCAAmC,EACnC,YAAY,EACb,oBAAgB;AACjB,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,wBAAoB;AAChE,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EAClB,oBAAgB;AAoCjB,MAAM,kBAAkB;IAAxB;;IAuPA,CAAC;IAtPC,KAAK,CAAC,aAAa,CAAC,SAAiB,EAAE,QAAgB;QACrD,IAAI;YACF,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAClC,OAAO,CAAC,IAAI,CACV,oDAAoD,QAAQ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C,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 {\n utf8ToBytes,\n concatBytes,\n bytesToHex,\n hexToBytes,\n} from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport { ALGORITHM_NONCE_SIZE, SHARED_SALT } 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\nexport type EncryptedPayloadV2 = {\n // version\n v: '2';\n\n // algorithm\n t: 'gcm';\n\n // data\n d: string;\n};\n\nclass EncryptorDecryptor {\n async encryptString(plaintext: string, password: string): 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.#encryptStringV2(plaintext, password);\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 | EncryptedPayloadV2 =\n JSON.parse(encryptedDataStr);\n\n if (encryptedData.v === '2') {\n if (encryptedData.t === 'gcm') {\n const decryptedData = await this.#decryptStringV2(\n encryptedData,\n password,\n );\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V2 encryption)`,\n );\n return decryptedData;\n }\n }\n\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V1 encryption)`,\n );\n return decryptedData;\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 #encryptStringV2(plaintext: string, password: string): Promise<string> {\n const plaintextRaw = utf8ToBytes(plaintext);\n const passwordRaw = hexToBytes(password);\n const cipherTextAndNonce = this.#encrypt(plaintextRaw, passwordRaw);\n\n const encryptedPayload: EncryptedPayloadV2 = {\n v: '2',\n t: 'gcm',\n d: byteArrayToBase64(cipherTextAndNonce),\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 async #decryptStringV2(\n data: EncryptedPayloadV2,\n password: string,\n ): Promise<string> {\n const { d: base64CiphertextAndNonce } = data;\n\n const ciphertextAndNonce = base64ToByteArray(base64CiphertextAndNonce);\n const passwordRaw = hexToBytes(password);\n\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, passwordRaw));\n }\n\n getSalt(encryptedDataStr: string): Uint8Array | null {\n try {\n const encryptedData: EncryptedPayload | EncryptedPayloadV2 =\n JSON.parse(encryptedDataStr);\n\n if (encryptedData.v === '2') {\n // V2 encryption doesn't use traditional salts, return null to indicate no salt\n return null;\n }\n\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 | null => s !== undefined);\n\n // Convert to strings for comparison, using 'null' for null values\n const strSet = new Set(\n salts.map((salt) => (salt ? salt.toString() : 'null')),\n );\n return strSet.size === salts.length;\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\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,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,IAAI,CAAC,cAAc,CAAC,CAAC,WAAW,E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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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/profile-sync-controller",
|
|
3
|
-
"version": "20.0.0-preview-
|
|
3
|
+
"version": "20.0.0-preview-2bb8758e",
|
|
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",
|