@metamask-previews/profile-sync-controller 20.0.0-preview-fb4d0ad1 → 20.0.0-preview-38b0103c
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 +1 -9
- package/dist/shared/encryption/constants.cjs.map +1 -1
- package/dist/shared/encryption/constants.d.cts +0 -6
- package/dist/shared/encryption/constants.d.cts.map +1 -1
- package/dist/shared/encryption/constants.d.mts +0 -6
- package/dist/shared/encryption/constants.d.mts.map +1 -1
- package/dist/shared/encryption/constants.mjs +0 -8
- package/dist/shared/encryption/constants.mjs.map +1 -1
- package/dist/shared/encryption/encryption.cjs +28 -31
- package/dist/shared/encryption/encryption.cjs.map +1 -1
- package/dist/shared/encryption/encryption.d.cts +8 -3
- package/dist/shared/encryption/encryption.d.cts.map +1 -1
- package/dist/shared/encryption/encryption.d.mts +8 -3
- package/dist/shared/encryption/encryption.d.mts.map +1 -1
- package/dist/shared/encryption/encryption.mjs +30 -33
- 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);
|
|
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),
|
|
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,KAAK,CAAC,aAAa,CACjB,IAAmC,EACnC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E;QACV,0BAA0B;QAC1B,MAAM,YAAY,GAChB,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,MAAM,IAAI,yBAAgB,CACxB,iDAAiD,IAAI,MAAM,YAAY,EAAE,CAC1E,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,OAAO,IAAA,6BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;AAC5C,CAAC,wCAED,KAAK,8CACH,eAAwB;IAExB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;IAC3E,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(encryptedData).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n decryptedData,\n storageKey,\n );\n await this.#upsertUserStorage(path, reEncryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(entry.Data).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n data,\n storageKey,\n );\n reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAA2D;AAC3D,6EAAoE;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,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AM,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.d.cts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,8CAA0C;AAGnE,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,4BAA4B,EAC5B,6BAA6B,EAC7B,uCAAuC,EAExC,qCAAiC;AAElC,OAAO,KAAK,EAAE,YAAY,EAAE,uCAAmC;AAE/D,eAAO,MAAM,WA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iB,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;CAuc/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);
|
|
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),
|
|
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;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAA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OAAO,YAAY,YAAY,CAAC,KAAK,EAAE,CAC5E,CAAC;SACH;KACF;IAAC,OAAO,CAAC,EAAE;QACV,0BAA0B;QAC1B,MAAM,YAAY,GAChB,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,MAAM,IAAI,gBAAgB,CACxB,iDAAiD,IAAI,MAAM,YAAY,EAAE,CAC1E,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,OAAO,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;AAC5C,CAAC,wCAED,KAAK,8CACH,eAAwB;IAExB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;IAC3E,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\nimport encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericFeatureName,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { NativeScrypt } from '../shared/types/encryption';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: (message: `metamask:${string}`) => Promise<string | null>;\n setStorageKey: (message: `metamask:${string}`, val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n HashedKey: string;\n\n Data: string;\n}[];\n\nexport type UserStorageMethodOptions = {\n nativeScryptCrypto?: NativeScrypt;\n entropySourceId?: string;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n public options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value, options);\n }\n\n async batchSetItems(\n path: UserStorageGenericFeatureName,\n values: [UserStorageGenericFeatureKey, string][],\n options?: UserStorageMethodOptions,\n ) {\n await this.#batchUpsertUserStorage(path, values, options);\n }\n\n async getItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n return this.#getUserStorage(path, options);\n }\n\n async getAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path, options);\n }\n\n async deleteItem(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorage(path, options);\n }\n\n async deleteAllFeatureItems(\n path: UserStorageGenericFeatureName,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n return this.#deleteUserStorageAllFeatureEntries(path, options);\n }\n\n async batchDeleteItems(\n path: UserStorageGenericFeatureName,\n values: UserStorageGenericFeatureKey[],\n options?: UserStorageMethodOptions,\n ) {\n return this.#batchDeleteUserStorage(path, values, options);\n }\n\n async getStorageKey(entropySourceId?: string): Promise<string> {\n const userProfile = await this.config.auth.getUserProfile(entropySourceId);\n const message = `metamask:${userProfile.profileId}` as const;\n\n const storageKey = await this.options.storage?.getStorageKey(message);\n if (storageKey) {\n return storageKey;\n }\n\n const storageKeySignature = await this.config.auth.signMessage(\n message,\n entropySourceId,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(\n message,\n hashedStorageKeySignature,\n );\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n data: string,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedData = await encryption.encryptString(\n data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n data: [string, string][],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const encryptedData = await Promise.all(\n data.map(async (d) => {\n return [\n this.#createEntryKey(d[0], storageKey),\n await encryption.encryptString(\n d[1],\n storageKey,\n options?.nativeScryptCrypto,\n ),\n ];\n }),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n encryptedData: [string, string][],\n entropySourceId?: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),\n });\n\n // istanbul ignore next\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n // istanbul ignore next\n throw new UserStorageError(\n `failed to batch upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<string | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage = await response.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n storageKey,\n options?.nativeScryptCrypto,\n );\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(encryptedData).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n decryptedData,\n storageKey,\n );\n await this.#upsertUserStorage(path, reEncryptedData, options);\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<string[] | null> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData: string[] = [];\n const reEncryptedEntries: [string, string][] = [];\n\n for (const entry of userStorage) {\n if (!entry.Data) {\n continue;\n }\n\n try {\n const data = await encryption.decryptString(\n entry.Data,\n storageKey,\n options?.nativeScryptCrypto,\n );\n decryptedData.push(data);\n\n // Migrate data from v1 to v2 encryption\n if (JSON.parse(entry.Data).v === '1') {\n const reEncryptedData = await encryption.encryptString(\n data,\n storageKey,\n );\n reEncryptedEntries.push([entry.HashedKey, reEncryptedData]);\n }\n } catch {\n // do nothing\n }\n }\n\n // Re-upload the re-encrypted entries\n if (reEncryptedEntries.length) {\n await this.#batchUpsertUserStorageWithAlreadyHashedAndEncryptedEntries(\n path,\n reEncryptedEntries,\n entropySourceId,\n );\n }\n\n return decryptedData;\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n const entropySourceId = options?.entropySourceId;\n try {\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #deleteUserStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #batchDeleteUserStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n keysToDelete: string[],\n options?: UserStorageMethodOptions,\n ): Promise<void> {\n try {\n if (!keysToDelete.length) {\n return;\n }\n\n const entropySourceId = options?.entropySourceId;\n const headers = await this.#getAuthorizationHeader(entropySourceId);\n const storageKey = await this.getStorageKey(entropySourceId);\n\n const rawEntryKeys = keysToDelete.map((d) =>\n this.#createEntryKey(d, storageKey),\n );\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n\n body: JSON.stringify({ batch_delete: rawEntryKeys }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to batch delete user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n return createSHA256Hash(key + storageKey);\n }\n\n async #getAuthorizationHeader(\n entropySourceId?: string,\n ): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken(entropySourceId);\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAiB;AAC3D,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,uCAA6B;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,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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,16 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SHARED_SALT = exports.
|
|
3
|
+
exports.SHARED_SALT = 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
|
|
14
6
|
exports.SHARED_SALT = new Uint8Array([
|
|
15
7
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
16
8
|
]);
|
|
@@ -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;AAEtC,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\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,9 +1,3 @@
|
|
|
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;
|
|
8
2
|
export declare const SHARED_SALT: Uint8Array;
|
|
9
3
|
//# 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;AAEvC,eAAO,MAAM,WAAW,YAEtB,CAAC"}
|
|
@@ -1,9 +1,3 @@
|
|
|
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;
|
|
8
2
|
export declare const SHARED_SALT: Uint8Array;
|
|
9
3
|
//# 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;AAEvC,eAAO,MAAM,WAAW,YAEtB,CAAC"}
|
|
@@ -1,13 +1,5 @@
|
|
|
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
|
|
11
3
|
export const SHARED_SALT = new Uint8Array([
|
|
12
4
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
13
5
|
]);
|
|
@@ -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;AAEnD,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\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_encryptStringV2, _EncryptorDecryptor_decryptStringV1, _EncryptorDecryptor_decryptStringV2, _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,13 +19,11 @@ class EncryptorDecryptor {
|
|
|
19
19
|
constructor() {
|
|
20
20
|
_EncryptorDecryptor_instances.add(this);
|
|
21
21
|
}
|
|
22
|
-
async encryptString(plaintext, password
|
|
22
|
+
async encryptString(plaintext, password) {
|
|
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",
|
|
27
|
-
N: constants_1.SCRYPT_N_V2,
|
|
28
|
-
});
|
|
26
|
+
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV2).call(this, plaintext, password);
|
|
29
27
|
console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
|
|
30
28
|
return encryptedData;
|
|
31
29
|
}
|
|
@@ -39,10 +37,17 @@ class EncryptorDecryptor {
|
|
|
39
37
|
const startTimestamp = Date.now();
|
|
40
38
|
console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
41
39
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
42
|
-
if (
|
|
40
|
+
if (encryptedData.v === '2') {
|
|
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') {
|
|
43
48
|
if (encryptedData.t === 'scrypt') {
|
|
44
49
|
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
|
|
45
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using
|
|
50
|
+
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V1 encryption)`);
|
|
46
51
|
return decryptedData;
|
|
47
52
|
}
|
|
48
53
|
}
|
|
@@ -56,6 +61,10 @@ class EncryptorDecryptor {
|
|
|
56
61
|
getSalt(encryptedDataStr) {
|
|
57
62
|
try {
|
|
58
63
|
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
|
+
}
|
|
59
68
|
if (encryptedData.v === '1') {
|
|
60
69
|
if (encryptedData.t === 'scrypt') {
|
|
61
70
|
const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;
|
|
@@ -84,35 +93,19 @@ class EncryptorDecryptor {
|
|
|
84
93
|
}
|
|
85
94
|
})
|
|
86
95
|
.filter((s) => s !== undefined);
|
|
87
|
-
|
|
96
|
+
// Convert to strings for comparison, using 'null' for null values
|
|
97
|
+
const strSet = new Set(salts.map((salt) => (salt ? salt.toString() : 'null')));
|
|
88
98
|
return strSet.size === salts.length;
|
|
89
99
|
}
|
|
90
100
|
}
|
|
91
|
-
_EncryptorDecryptor_instances = new WeakSet(),
|
|
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.
|
|
101
|
+
_EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV2 = async function _EncryptorDecryptor_encryptStringV2(plaintext, password) {
|
|
101
102
|
const plaintextRaw = (0, utils_1.utf8ToBytes)(plaintext);
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const encryptedData = (0, utils_2.byteArrayToBase64)(ciphertextAndNonceAndSalt);
|
|
103
|
+
const passwordRaw = (0, utils_1.hexToBytes)(password);
|
|
104
|
+
const cipherTextAndNonce = __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encrypt).call(this, plaintextRaw, passwordRaw);
|
|
105
105
|
const encryptedPayload = {
|
|
106
106
|
v: '2',
|
|
107
|
-
t: '
|
|
108
|
-
d:
|
|
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,
|
|
107
|
+
t: 'gcm',
|
|
108
|
+
d: (0, utils_2.byteArrayToBase64)(cipherTextAndNonce),
|
|
116
109
|
};
|
|
117
110
|
return JSON.stringify(encryptedPayload);
|
|
118
111
|
}, _EncryptorDecryptor_decryptStringV1 = async function _EncryptorDecryptor_decryptStringV1(data, password, nativeScryptCrypto) {
|
|
@@ -131,9 +124,13 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
|
|
|
131
124
|
}, salt, nativeScryptCrypto);
|
|
132
125
|
// Decrypt and return result.
|
|
133
126
|
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));
|
|
134
132
|
}, _EncryptorDecryptor_encrypt = function _EncryptorDecryptor_encrypt(plaintext, key) {
|
|
135
133
|
const nonce = (0, webcrypto_1.randomBytes)(constants_1.ALGORITHM_NONCE_SIZE);
|
|
136
|
-
// Encrypt and prepend nonce.
|
|
137
134
|
const ciphertext = (0, aes_1.gcm)(key, nonce).encrypt(plaintext);
|
|
138
135
|
return (0, utils_1.concatBytes)(nonce, ciphertext);
|
|
139
136
|
}, _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,+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,kBAAkB,EAClB;gBACE,CAAC,EAAE,uBAAW;aACf,CACF,CAAC;YACF,OAAO,CAAC,IAAI,CACV,2CAA2C,IAAI,CAAC,GAAG,EAAE,GAAG,cAAc,KAAK,CAC5E,CAAC;YAEF,OAAO,aAAa,CAAC;SACtB;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YACxE,MAAM,IAAI,KAAK,CAAC,8BAA8B,YAAY,EAAE,CAAC,CAAC;SAC/D;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,gBAAwB,EACxB,QAAgB,EAChB,kBAAiC;QAEjC,IAAI;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';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_N_V2,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\n\nexport type EncryptedPayload = {\n // version\n v: '1' | '2';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData = await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n {\n N: SCRYPT_N_V2,\n },\n );\n console.warn(\n `Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`,\n );\n\n return encryptedData;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n\n if (['1', '2'].includes(encryptedData.v)) {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`,\n );\n return decryptedData;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n scryptOverrides = {\n N: SCRYPT_N,\n },\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\n );\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '2',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n return salt;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\n\n setCachedKey(hashedPassword, newSalt, newKey);\n\n return {\n key: newKey,\n salt: newSalt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n *\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"encryption.cjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;;;;AAAA,4CAAyC;AACzC,wDAAuD;AACvD,iDAAmD;AACnD,iDAA8C;AAC9C,+CAK6B;AAE7B,uCAIiB;AACjB,+CAAgE;AAChE,uCAKiB;AAoCjB,MAAM,kBAAkB;IAAxB;;IAuPA,CAAC;IAtPC,KAAK,CAAC,aAAa,CAAC,SAAiB,EAAE,QAAgB;QACrD,IAAI;YACF,MAAM,cAAc,GAAG,IAAI,C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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,6 +1,6 @@
|
|
|
1
1
|
import type { NativeScrypt } from "../types/encryption.cjs";
|
|
2
2
|
export type EncryptedPayload = {
|
|
3
|
-
v: '1'
|
|
3
|
+
v: '1';
|
|
4
4
|
t: 'scrypt';
|
|
5
5
|
d: string;
|
|
6
6
|
o: {
|
|
@@ -11,11 +11,16 @@ 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
|
+
};
|
|
14
19
|
declare class EncryptorDecryptor {
|
|
15
20
|
#private;
|
|
16
|
-
encryptString(plaintext: string, password: string
|
|
21
|
+
encryptString(plaintext: string, password: string): Promise<string>;
|
|
17
22
|
decryptString(encryptedDataStr: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
18
|
-
getSalt(encryptedDataStr: string): Uint8Array;
|
|
23
|
+
getSalt(encryptedDataStr: string): Uint8Array | null;
|
|
19
24
|
getIfEntriesHaveDifferentSalts(entries: string[]): boolean;
|
|
20
25
|
}
|
|
21
26
|
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":"AAuBA,OAAO,KAAK,EAAE,YAAY,EAAE,gCAA4B;AAExD,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,CAAC;IAGP,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,MAAM,MAAM,kBAAkB,GAAG;IAE/B,CAAC,EAAE,GAAG,CAAC;IAGP,CAAC,EAAE,KAAK,CAAC;IAGT,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AAEF,cAAM,kBAAkB;;IAChB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkBnE,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IA2GlB,OAAO,CAAC,gBAAgB,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI;IAiCpD,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO;CAoF3D;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';
|
|
4
4
|
t: 'scrypt';
|
|
5
5
|
d: string;
|
|
6
6
|
o: {
|
|
@@ -11,11 +11,16 @@ 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
|
+
};
|
|
14
19
|
declare class EncryptorDecryptor {
|
|
15
20
|
#private;
|
|
16
|
-
encryptString(plaintext: string, password: string
|
|
21
|
+
encryptString(plaintext: string, password: string): Promise<string>;
|
|
17
22
|
decryptString(encryptedDataStr: string, password: string, nativeScryptCrypto?: NativeScrypt): Promise<string>;
|
|
18
|
-
getSalt(encryptedDataStr: string): Uint8Array;
|
|
23
|
+
getSalt(encryptedDataStr: string): Uint8Array | null;
|
|
19
24
|
getIfEntriesHaveDifferentSalts(entries: string[]): boolean;
|
|
20
25
|
}
|
|
21
26
|
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":"AAuBA,OAAO,KAAK,EAAE,YAAY,EAAE,gCAA4B;AAExD,MAAM,MAAM,gBAAgB,GAAG;IAE7B,CAAC,EAAE,GAAG,CAAC;IAGP,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,MAAM,MAAM,kBAAkB,GAAG;IAE/B,CAAC,EAAE,GAAG,CAAC;IAGP,CAAC,EAAE,KAAK,CAAC;IAGT,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AAEF,cAAM,kBAAkB;;IAChB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkBnE,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,CAAC,EAAE,YAAY,GAChC,OAAO,CAAC,MAAM,CAAC;IA2GlB,OAAO,CAAC,gBAAgB,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI;IAiCpD,8BAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO;CAoF3D;AAED,QAAA,MAAM,UAAU,oBAA2B,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD"}
|
|
@@ -3,26 +3,24 @@ 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_encryptStringV2, _EncryptorDecryptor_decryptStringV1, _EncryptorDecryptor_decryptStringV2, _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 } from "@noble/hashes/utils";
|
|
11
|
+
import { utf8ToBytes, concatBytes, bytesToHex, hexToBytes } from "@noble/hashes/utils";
|
|
12
12
|
import { getCachedKeyBySalt, getCachedKeyGeneratedWithSharedSalt, setCachedKey } from "./cache.mjs";
|
|
13
|
-
import {
|
|
13
|
+
import { ALGORITHM_NONCE_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) {
|
|
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",
|
|
24
|
-
N: SCRYPT_N_V2,
|
|
25
|
-
});
|
|
23
|
+
const encryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encryptStringV2).call(this, plaintext, password);
|
|
26
24
|
console.warn(`Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`);
|
|
27
25
|
return encryptedData;
|
|
28
26
|
}
|
|
@@ -36,10 +34,17 @@ class EncryptorDecryptor {
|
|
|
36
34
|
const startTimestamp = Date.now();
|
|
37
35
|
console.warn(`Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`);
|
|
38
36
|
const encryptedData = JSON.parse(encryptedDataStr);
|
|
39
|
-
if (
|
|
37
|
+
if (encryptedData.v === '2') {
|
|
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') {
|
|
40
45
|
if (encryptedData.t === 'scrypt') {
|
|
41
46
|
const decryptedData = await __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_decryptStringV1).call(this, encryptedData, password, nativeScryptCrypto);
|
|
42
|
-
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using
|
|
47
|
+
console.warn(`Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V1 encryption)`);
|
|
43
48
|
return decryptedData;
|
|
44
49
|
}
|
|
45
50
|
}
|
|
@@ -53,6 +58,10 @@ class EncryptorDecryptor {
|
|
|
53
58
|
getSalt(encryptedDataStr) {
|
|
54
59
|
try {
|
|
55
60
|
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
|
+
}
|
|
56
65
|
if (encryptedData.v === '1') {
|
|
57
66
|
if (encryptedData.t === 'scrypt') {
|
|
58
67
|
const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;
|
|
@@ -81,35 +90,19 @@ class EncryptorDecryptor {
|
|
|
81
90
|
}
|
|
82
91
|
})
|
|
83
92
|
.filter((s) => s !== undefined);
|
|
84
|
-
|
|
93
|
+
// Convert to strings for comparison, using 'null' for null values
|
|
94
|
+
const strSet = new Set(salts.map((salt) => (salt ? salt.toString() : 'null')));
|
|
85
95
|
return strSet.size === salts.length;
|
|
86
96
|
}
|
|
87
97
|
}
|
|
88
|
-
_EncryptorDecryptor_instances = new WeakSet(),
|
|
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.
|
|
98
|
+
_EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptStringV2 = async function _EncryptorDecryptor_encryptStringV2(plaintext, password) {
|
|
98
99
|
const plaintextRaw = utf8ToBytes(plaintext);
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
|
|
100
|
+
const passwordRaw = hexToBytes(password);
|
|
101
|
+
const cipherTextAndNonce = __classPrivateFieldGet(this, _EncryptorDecryptor_instances, "m", _EncryptorDecryptor_encrypt).call(this, plaintextRaw, passwordRaw);
|
|
102
102
|
const encryptedPayload = {
|
|
103
103
|
v: '2',
|
|
104
|
-
t: '
|
|
105
|
-
d:
|
|
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,
|
|
104
|
+
t: 'gcm',
|
|
105
|
+
d: byteArrayToBase64(cipherTextAndNonce),
|
|
113
106
|
};
|
|
114
107
|
return JSON.stringify(encryptedPayload);
|
|
115
108
|
}, _EncryptorDecryptor_decryptStringV1 = async function _EncryptorDecryptor_decryptStringV1(data, password, nativeScryptCrypto) {
|
|
@@ -128,9 +121,13 @@ _EncryptorDecryptor_instances = new WeakSet(), _EncryptorDecryptor_encryptString
|
|
|
128
121
|
}, salt, nativeScryptCrypto);
|
|
129
122
|
// Decrypt and return result.
|
|
130
123
|
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));
|
|
131
129
|
}, _EncryptorDecryptor_encrypt = function _EncryptorDecryptor_encrypt(plaintext, key) {
|
|
132
130
|
const nonce = randomBytes(ALGORITHM_NONCE_SIZE);
|
|
133
|
-
// Encrypt and prepend nonce.
|
|
134
131
|
const ciphertext = gcm(key, nonce).encrypt(plaintext);
|
|
135
132
|
return concatBytes(nonce, ciphertext);
|
|
136
133
|
}, _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,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AC,cAAc,CAAC,CAAC;IAExD,IAAI,SAAS,EAAE;QACb,OAAO;YACL,GAAG,EAAE,SAAS,CAAC,GAAG;YAClB,IAAI,EAAE,SAAS,CAAC,IAAI;SACrB,CAAC;KACH;IAED,MAAM,OAAO,GAAG,IAAI,IAAI,WAAW,CAAC;IAEpC,IAAI,MAAkB,CAAC;IAEvB,IAAI,kBAAkB,EAAE;QACtB,MAAM,GAAG,MAAM,kBAAkB,CAC/B,iBAAiB,CAAC,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,WAAW,CAAC,QAAQ,EAAE,OAAO,EAAE;YAC5C,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;YACN,KAAK,EAAE,CAAC,CAAC,KAAK;SACf,CAAC,CAAC;KACJ;IAED,YAAY,CAAC,cAAc,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE9C,OAAO;QACL,GAAG,EAAE,MAAM;QACX,IAAI,EAAE,OAAO;KACd,CAAC;AACJ,CAAC;AAGH,MAAM,UAAU,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAC5C,eAAe,UAAU,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,UAAU,CAAC,UAAU,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scryptAsync } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport {\n getCachedKeyBySalt,\n getCachedKeyGeneratedWithSharedSalt,\n setCachedKey,\n} from './cache';\nimport {\n ALGORITHM_KEY_SIZE,\n ALGORITHM_NONCE_SIZE,\n SCRYPT_N,\n SCRYPT_N_V2,\n SCRYPT_p,\n SCRYPT_r,\n SCRYPT_SALT_SIZE,\n SHARED_SALT,\n} from './constants';\nimport {\n base64ToByteArray,\n byteArrayToBase64,\n bytesToUtf8,\n stringToByteArray,\n} from './utils';\nimport type { NativeScrypt } from '../types/encryption';\n\nexport type EncryptedPayload = {\n // version\n v: '1' | '2';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\nclass EncryptorDecryptor {\n async encryptString(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Encrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData = await this.#encryptStringV1(\n plaintext,\n password,\n nativeScryptCrypto,\n {\n N: SCRYPT_N_V2,\n },\n );\n console.warn(\n `Scrypt removal: Encryption completed in ${Date.now() - startTimestamp} ms`,\n );\n\n return encryptedData;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n async decryptString(\n encryptedDataStr: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n try {\n const startTimestamp = Date.now();\n console.warn(\n `Scrypt removal: Decrypting string with password: ${password} at ${new Date(startTimestamp).toISOString()}`,\n );\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n\n if (['1', '2'].includes(encryptedData.v)) {\n if (encryptedData.t === 'scrypt') {\n const decryptedData = await this.#decryptStringV1(\n encryptedData,\n password,\n nativeScryptCrypto,\n );\n\n console.warn(\n `Scrypt removal: Decryption completed in ${Date.now() - startTimestamp} ms (using V${encryptedData.v} encryption)`,\n );\n return decryptedData;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n async #encryptStringV1(\n plaintext: string,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n scryptOverrides = {\n N: SCRYPT_N,\n },\n ): Promise<string> {\n const { key, salt } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n undefined,\n nativeScryptCrypto,\n );\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '2',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: scryptOverrides.N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n async #decryptStringV1(\n data: EncryptedPayload,\n password: string,\n nativeScryptCrypto?: NativeScrypt,\n ): Promise<string> {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = await this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n nativeScryptCrypto,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n getSalt(encryptedDataStr: string) {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n const { d: base64CiphertextAndNonceAndSalt, saltLen } = encryptedData;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n return salt;\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to get salt - ${errorMessage}`);\n }\n }\n\n getIfEntriesHaveDifferentSalts(entries: string[]): boolean {\n const salts = entries\n .map((e) => {\n try {\n return this.getSalt(e);\n } catch {\n return undefined;\n }\n })\n .filter((s): s is Uint8Array => s !== undefined);\n\n const strSet = new Set(salts.map((arr) => arr.toString()));\n return strSet.size === salts.length;\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n async #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n nativeScryptCrypto?: NativeScrypt,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getCachedKeyGeneratedWithSharedSalt(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? SHARED_SALT;\n\n let newKey: Uint8Array;\n\n if (nativeScryptCrypto) {\n newKey = await nativeScryptCrypto(\n stringToByteArray(password),\n newSalt,\n o.N,\n o.r,\n o.p,\n o.dkLen,\n );\n } else {\n newKey = await scryptAsync(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n }\n\n setCachedKey(hashedPassword, newSalt, newKey);\n\n return {\n key: newKey,\n salt: newSalt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n *\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"encryption.mjs","sourceRoot":"","sources":["../../../src/shared/encryption/encryption.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,GAAG,EAAE,2BAA2B;AACzC,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,WAAW,EAAE,6BAA6B;AACnD,OAAO,EAAE,MAAM,EAAE,6BAA6B;AAC9C,OAAO,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,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AM,OAAO,GAAG,IAAI,IAAI,WAAW,CAAC;IAEpC,IAAI,MAAkB,CAAC;IAEvB,IAAI,kBAAkB,EAAE;QACtB,MAAM,GAAG,MAAM,kBAAkB,CAC/B,iBAAiB,CAAC,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,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"]}
|
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-38b0103c",
|
|
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",
|