@metamask/profile-sync-controller 0.8.1 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +55 -14
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +12 -3
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +12 -3
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +57 -15
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs +38 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts +26 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts +26 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs +39 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs +9 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts +5 -0
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts +5 -0
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs +7 -0
- package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.cjs +15 -3
- package/dist/controllers/user-storage/__fixtures__/mockServices.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts +2 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts +2 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.mjs +14 -3
- package/dist/controllers/user-storage/__fixtures__/mockServices.mjs.map +1 -1
- package/dist/controllers/user-storage/services.cjs +58 -2
- package/dist/controllers/user-storage/services.cjs.map +1 -1
- package/dist/controllers/user-storage/services.d.cts +10 -1
- package/dist/controllers/user-storage/services.d.cts.map +1 -1
- package/dist/controllers/user-storage/services.d.mts +10 -1
- package/dist/controllers/user-storage/services.d.mts.map +1 -1
- package/dist/controllers/user-storage/services.mjs +33 -1
- package/dist/controllers/user-storage/services.mjs.map +1 -1
- package/dist/controllers/user-storage/utils.cjs +27 -1
- package/dist/controllers/user-storage/utils.cjs.map +1 -1
- package/dist/controllers/user-storage/utils.d.cts +11 -0
- package/dist/controllers/user-storage/utils.d.cts.map +1 -1
- package/dist/controllers/user-storage/utils.d.mts +11 -0
- package/dist/controllers/user-storage/utils.d.mts.map +1 -1
- package/dist/controllers/user-storage/utils.mjs +25 -0
- package/dist/controllers/user-storage/utils.mjs.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.cjs +4 -2
- package/dist/sdk/__fixtures__/mock-userstorage.cjs.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.cts +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.cts.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.mts +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.mts.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.mjs +4 -2
- package/dist/sdk/__fixtures__/mock-userstorage.mjs.map +1 -1
- package/dist/sdk/user-storage.cjs +39 -1
- package/dist/sdk/user-storage.cjs.map +1 -1
- package/dist/sdk/user-storage.d.cts +2 -1
- package/dist/sdk/user-storage.d.cts.map +1 -1
- package/dist/sdk/user-storage.d.mts +2 -1
- package/dist/sdk/user-storage.d.mts.map +1 -1
- package/dist/sdk/user-storage.mjs +39 -1
- package/dist/sdk/user-storage.mjs.map +1 -1
- package/dist/shared/storage-schema.cjs.map +1 -1
- package/dist/shared/storage-schema.d.cts +5 -2
- package/dist/shared/storage-schema.d.cts.map +1 -1
- package/dist/shared/storage-schema.d.mts +5 -2
- package/dist/shared/storage-schema.d.mts.map +1 -1
- package/dist/shared/storage-schema.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6EAAoE;AAEpE,2CAA2C;AAK3C,iEAA2D;AAE3D,yCAA2D;AAEpD,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;AA4B7E,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,IAAsC,EACtC,KAAa;QAEb,MAAM,uBAAA,IAAI,8DAAmB,MAAvB,IAAI,EAAoB,IAAI,EAAE,KAAK,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,IAAsC;QAClD,OAAO,uBAAA,IAAI,2DAAgB,MAApB,IAA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C;KAChD;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,CAAC,YAAY,sBAAa,EAAE;YAC9B,MAAM,CAAC,CAAC;SACT;QAED,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;QAE3D,MAAM,IAAI,yBAAgB,CACxB,wCAAwC,IAAI,MAAM,YAAY,EAAE,CACjE,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,MAAM,SAAS,GAAG,IAAA,6BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IACrD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,gFAAgF;AAChF,gEAAgE;AAChE,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;IAC5D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async getItem(path: UserStoragePathWithFeatureAndKey): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getAllFeatureItems(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n data: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 #getUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 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\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, storageKey);\n });\n\n return (await Promise.allSettled(decryptedData))\n .map((d) => (d.status === 'fulfilled' ? d.value : undefined))\n .filter((d): d is string => d !== undefined);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6EAAoE;AAEpE,2CAA2C;AAM3C,iEAA2D;AAE3D,yCAA2D;AAEpD,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;AA4B7E,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,IAAsC,EACtC,KAAa;QAEb,MAAM,uBAAA,I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AAC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;IAC5D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async batchSetItems(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ) {\n await this.#batchUpsertUserStorage(path, values);\n }\n\n async getItem(path: UserStoragePathWithFeatureAndKey): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getAllFeatureItems(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n data: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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: UserStoragePathWithFeatureOnly,\n data: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 #getUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 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\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, storageKey);\n });\n\n return (await Promise.allSettled(decryptedData))\n .map((d) => (d.status === 'fulfilled' ? d.value : undefined))\n .filter((d): d is string => d !== undefined);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Env } from "../shared/env.cjs";
|
|
2
|
-
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly } from "../shared/storage-schema.cjs";
|
|
2
|
+
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly, UserStoragePathWithKeyOnly } from "../shared/storage-schema.cjs";
|
|
3
3
|
import type { IBaseAuth } from "./authentication-jwt-bearer/types.cjs";
|
|
4
4
|
export declare const STORAGE_URL: (env: Env, encryptedPath: string) => string;
|
|
5
5
|
export type UserStorageConfig = {
|
|
@@ -20,6 +20,7 @@ export declare class UserStorage {
|
|
|
20
20
|
protected env: Env;
|
|
21
21
|
constructor(config: UserStorageConfig, options: UserStorageOptions);
|
|
22
22
|
setItem(path: UserStoragePathWithFeatureAndKey, value: string): Promise<void>;
|
|
23
|
+
batchSetItems(path: UserStoragePathWithFeatureOnly, values: [UserStoragePathWithKeyOnly, string][]): Promise<void>;
|
|
23
24
|
getItem(path: UserStoragePathWithFeatureAndKey): Promise<string>;
|
|
24
25
|
getAllFeatureItems(path: UserStoragePathWithFeatureOnly): Promise<string[] | null>;
|
|
25
26
|
getStorageKey(): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.d.cts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,
|
|
1
|
+
{"version":3,"file":"user-storage.d.cts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,0BAA0B,EAC3B,qCAAiC;AAElC,OAAO,KAAK,EAAE,SAAS,EAAE,8CAA0C;AAGnE,eAAO,MAAM,WAAW,QAAS,GAAG,iBAAiB,MAAM,WACiB,CAAC;AAE7E,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,aAAa,CAAC,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,aAAa,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC5C,aAAa,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B,CAAC;AAcF,qBAAa,WAAW;;IACtB,SAAS,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAEpC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC;IAEtC,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC;gBAEP,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,kBAAkB;IAM5D,OAAO,CACX,IAAI,EAAE,gCAAgC,EACtC,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC;IAIV,aAAa,CACjB,IAAI,EAAE,8BAA8B,EACpC,MAAM,EAAE,CAAC,0BAA0B,EAAE,MAAM,CAAC,EAAE;IAK1C,OAAO,CAAC,IAAI,EAAE,gCAAgC,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhE,kBAAkB,CACtB,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAIrB,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;CAgOvC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Env } from "../shared/env.mjs";
|
|
2
|
-
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly } from "../shared/storage-schema.mjs";
|
|
2
|
+
import type { UserStoragePathWithFeatureAndKey, UserStoragePathWithFeatureOnly, UserStoragePathWithKeyOnly } from "../shared/storage-schema.mjs";
|
|
3
3
|
import type { IBaseAuth } from "./authentication-jwt-bearer/types.mjs";
|
|
4
4
|
export declare const STORAGE_URL: (env: Env, encryptedPath: string) => string;
|
|
5
5
|
export type UserStorageConfig = {
|
|
@@ -20,6 +20,7 @@ export declare class UserStorage {
|
|
|
20
20
|
protected env: Env;
|
|
21
21
|
constructor(config: UserStorageConfig, options: UserStorageOptions);
|
|
22
22
|
setItem(path: UserStoragePathWithFeatureAndKey, value: string): Promise<void>;
|
|
23
|
+
batchSetItems(path: UserStoragePathWithFeatureOnly, values: [UserStoragePathWithKeyOnly, string][]): Promise<void>;
|
|
23
24
|
getItem(path: UserStoragePathWithFeatureAndKey): Promise<string>;
|
|
24
25
|
getAllFeatureItems(path: UserStoragePathWithFeatureOnly): Promise<string[] | null>;
|
|
25
26
|
getStorageKey(): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.d.mts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,
|
|
1
|
+
{"version":3,"file":"user-storage.d.mts","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,0BAAsB;AAEzC,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,0BAA0B,EAC3B,qCAAiC;AAElC,OAAO,KAAK,EAAE,SAAS,EAAE,8CAA0C;AAGnE,eAAO,MAAM,WAAW,QAAS,GAAG,iBAAiB,MAAM,WACiB,CAAC;AAE7E,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,aAAa,CAAC,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,aAAa,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC5C,aAAa,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B,CAAC;AAcF,qBAAa,WAAW;;IACtB,SAAS,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAEpC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC;IAEtC,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC;gBAEP,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,kBAAkB;IAM5D,OAAO,CACX,IAAI,EAAE,gCAAgC,EACtC,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC;IAIV,aAAa,CACjB,IAAI,EAAE,8BAA8B,EACpC,MAAM,EAAE,CAAC,0BAA0B,EAAE,MAAM,CAAC,EAAE;IAK1C,OAAO,CAAC,IAAI,EAAE,gCAAgC,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhE,kBAAkB,CACtB,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAIrB,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;CAgOvC"}
|
|
@@ -3,7 +3,7 @@ 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 _UserStorage_instances, _UserStorage_upsertUserStorage, _UserStorage_getUserStorage, _UserStorage_getUserStorageAllFeatureEntries, _UserStorage_createEntryKey, _UserStorage_getAuthorizationHeader;
|
|
6
|
+
var _UserStorage_instances, _UserStorage_upsertUserStorage, _UserStorage_batchUpsertUserStorage, _UserStorage_getUserStorage, _UserStorage_getUserStorageAllFeatureEntries, _UserStorage_createEntryKey, _UserStorage_getAuthorizationHeader;
|
|
7
7
|
import encryption, { createSHA256Hash } from "../shared/encryption/index.mjs";
|
|
8
8
|
import { getEnvUrls } from "../shared/env.mjs";
|
|
9
9
|
import { createEntryPath } from "../shared/storage-schema.mjs";
|
|
@@ -19,6 +19,9 @@ export class UserStorage {
|
|
|
19
19
|
async setItem(path, value) {
|
|
20
20
|
await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_upsertUserStorage).call(this, path, value);
|
|
21
21
|
}
|
|
22
|
+
async batchSetItems(path, values) {
|
|
23
|
+
await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_batchUpsertUserStorage).call(this, path, values);
|
|
24
|
+
}
|
|
22
25
|
async getItem(path) {
|
|
23
26
|
return __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_getUserStorage).call(this, path);
|
|
24
27
|
}
|
|
@@ -65,6 +68,41 @@ _UserStorage_instances = new WeakSet(), _UserStorage_upsertUserStorage = async f
|
|
|
65
68
|
const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? '');
|
|
66
69
|
throw new UserStorageError(`failed to upsert user storage for path '${path}'. ${errorMessage}`);
|
|
67
70
|
}
|
|
71
|
+
}, _UserStorage_batchUpsertUserStorage = async function _UserStorage_batchUpsertUserStorage(path, data) {
|
|
72
|
+
try {
|
|
73
|
+
if (!data.length) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const headers = await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_getAuthorizationHeader).call(this);
|
|
77
|
+
const storageKey = await this.getStorageKey();
|
|
78
|
+
const encryptedData = await Promise.all(data.map(async (d) => {
|
|
79
|
+
return [
|
|
80
|
+
__classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_createEntryKey).call(this, d[0], storageKey),
|
|
81
|
+
await encryption.encryptString(d[1], storageKey),
|
|
82
|
+
];
|
|
83
|
+
}));
|
|
84
|
+
const url = new URL(STORAGE_URL(this.env, path));
|
|
85
|
+
const response = await fetch(url.toString(), {
|
|
86
|
+
method: 'PUT',
|
|
87
|
+
headers: {
|
|
88
|
+
'Content-Type': 'application/json',
|
|
89
|
+
...headers,
|
|
90
|
+
},
|
|
91
|
+
body: JSON.stringify({ data: Object.fromEntries(encryptedData) }),
|
|
92
|
+
});
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
const responseBody = await response.json().catch(() => ({
|
|
95
|
+
message: 'unknown',
|
|
96
|
+
error: 'unknown',
|
|
97
|
+
}));
|
|
98
|
+
throw new Error(`HTTP error message: ${responseBody.message}, error: ${responseBody.error}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
/* istanbul ignore next */
|
|
103
|
+
const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? '');
|
|
104
|
+
throw new UserStorageError(`failed to batch upsert user storage for path '${path}'. ${errorMessage}`);
|
|
105
|
+
}
|
|
68
106
|
}, _UserStorage_getUserStorage = async function _UserStorage_getUserStorage(path) {
|
|
69
107
|
try {
|
|
70
108
|
const headers = await __classPrivateFieldGet(this, _UserStorage_instances, "m", _UserStorage_getAuthorizationHeader).call(this);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,uCAA6B;AAEpE,OAAO,EAAE,UAAU,EAAE,0BAAsB;AAK3C,OAAO,EAAE,eAAe,EAAE,qCAAiC;AAE3D,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAiB;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,aAAqB,EAAE,EAAE,CAC7D,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,iBAAiB,uBAAuB,aAAa,EAAE,CAAC;AA4B7E,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,IAAsC,EACt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,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;aAC5D,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;KAChD;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,CAAC,YAAY,aAAa,EAAE;YAC9B,MAAM,CAAC,CAAC;SACT;QAED,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;QAE3D,MAAM,IAAI,gBAAgB,CACxB,wCAAwC,IAAI,MAAM,YAAY,EAAE,CACjE,CAAC;KACH;AACH,CAAC,qEAEe,GAAW,EAAE,UAAkB;IAC7C,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IACrD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,gFAAgF;AAChF,gEAAgE;AAChE,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;IAC5D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async getItem(path: UserStoragePathWithFeatureAndKey): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getAllFeatureItems(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n data: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 #getUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 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\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, storageKey);\n });\n\n return (await Promise.allSettled(decryptedData))\n .map((d) => (d.status === 'fulfilled' ? d.value : undefined))\n .filter((d): d is string => d !== undefined);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,uCAA6B;AAEpE,OAAO,EAAE,UAAU,EAAE,0BAAsB;AAM3C,OAAO,EAAE,eAAe,EAAE,qCAAiC;AAE3D,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAiB;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,aAAqB,EAAE,EAAE,CAC7D,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,iBAAiB,uBAAuB,aAAa,EAAE,CAAC;AA4B7E,MAAM,OAAO,WAAW;IAOtB,YAAY,MAAyB,EAAE,OAA2B;;QAChE,IAAI,CAAC,GAAG,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C;IACrD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,gFAAgF;AAChF,gEAAgE;AAChE,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;IAC5D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import encryption, { createSHA256Hash } from '../shared/encryption';\nimport type { Env } from '../shared/env';\nimport { getEnvUrls } from '../shared/env';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\n} from '../shared/storage-schema';\nimport { createEntryPath } from '../shared/storage-schema';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async batchSetItems(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ) {\n await this.#batchUpsertUserStorage(path, values);\n }\n\n async getItem(path: UserStoragePathWithFeatureAndKey): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getAllFeatureItems(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n data: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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: UserStoragePathWithFeatureOnly,\n data: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n try {\n if (!data.length) {\n return;\n }\n\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 #getUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\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 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\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, storageKey);\n });\n\n return (await Promise.allSettled(decryptedData))\n .map((d) => (d.status === 'fulfilled' ? d.value : undefined))\n .filter((d): d is string => d !== undefined);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-schema.cjs","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":";;;AAAA,uDAAgD;AAEhD;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG,sBAA+B,CAAC;AAEhD,QAAA,mBAAmB,GAAG;IACjC,aAAa,EAAE,CAAC,uBAAuB,CAAC;IACxC,QAAQ,EAAE,CAAC,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AAC,CAAC;AAlCW,QAAA,wBAAwB,4BAkCnC;AAEK,MAAM,uBAAuB,GAAG,CACrC,IAAY,EAC8B,EAAE;IAC5C,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC,CAAC;AANW,QAAA,uBAAuB,2BAMlC;AAEF;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAC7B,IAAsC,EACtC,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,IAAA,gCAAwB,EAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,IAAA,6BAAgB,EAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC;AARD,0CAQC","sourcesContent":["import { createSHA256Hash } from './encryption';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Developers can provide additional features and keys by extending these types below.\n *\n * Adding ALLOW_ARBITRARY_KEYS as the first key in the array allows for any key to be used for this feature.\n * This can be useful for features where keys are not deterministic (eg. accounts addresses).\n */\nconst ALLOW_ARBITRARY_KEYS = 'ALLOW_ARBITRARY_KEYS' as const;\n\nexport const USER_STORAGE_SCHEMA = {\n notifications: ['notification_settings'],\n accounts: [ALLOW_ARBITRARY_KEYS], // keyed by account addresses\n networks: [ALLOW_ARBITRARY_KEYS], // keyed by chains/networks\n} as const;\n\ntype UserStorageSchema = typeof USER_STORAGE_SCHEMA;\n\nexport type UserStorageFeatures = keyof UserStorageSchema;\nexport type UserStorageFeatureKeys<Feature extends UserStorageFeatures> =\n UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS\n ? string\n : UserStorageSchema[Feature][number];\n\ntype UserStorageFeatureAndKey = {\n feature: UserStorageFeatures;\n key: UserStorageFeatureKeys<UserStorageFeatures>;\n};\n\nexport type UserStoragePathWithFeatureOnly = keyof UserStorageSchema;\nexport type UserStoragePathWithKeyOnly = {\n [K in UserStorageFeatures]: `${UserStorageFeatureKeys<K>}`;\n}[UserStoragePathWithFeatureOnly];\nexport type UserStoragePathWithFeatureAndKey = {\n [K in UserStorageFeatures]: `${K}.${UserStorageFeatureKeys<K>}`;\n}[UserStoragePathWithFeatureOnly];\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStoragePathWithFeatureAndKey,\n): UserStorageFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.') as [\n UserStorageFeatures,\n UserStorageFeatureKeys<UserStorageFeatures>,\n ];\n\n if (!(feature in USER_STORAGE_SCHEMA)) {\n throw new Error(`user-storage - invalid feature provided: ${feature}`);\n }\n\n const validFeature = USER_STORAGE_SCHEMA[feature] as readonly string[];\n\n if (\n !validFeature.includes(key) &&\n !validFeature.includes(ALLOW_ARBITRARY_KEYS)\n ) {\n const validKeys = USER_STORAGE_SCHEMA[feature].join(', ');\n\n throw new Error(\n `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`,\n );\n }\n\n return { feature, key };\n};\n\nexport const isPathWithFeatureAndKey = (\n path: string,\n): path is UserStoragePathWithFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n return pathRegex.test(path);\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStoragePathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
|
|
@@ -12,13 +12,16 @@ export declare const USER_STORAGE_SCHEMA: {
|
|
|
12
12
|
readonly networks: readonly ["ALLOW_ARBITRARY_KEYS"];
|
|
13
13
|
};
|
|
14
14
|
type UserStorageSchema = typeof USER_STORAGE_SCHEMA;
|
|
15
|
-
type UserStorageFeatures = keyof UserStorageSchema;
|
|
16
|
-
type UserStorageFeatureKeys<Feature extends UserStorageFeatures> = UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS ? string : UserStorageSchema[Feature][number];
|
|
15
|
+
export type UserStorageFeatures = keyof UserStorageSchema;
|
|
16
|
+
export type UserStorageFeatureKeys<Feature extends UserStorageFeatures> = UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS ? string : UserStorageSchema[Feature][number];
|
|
17
17
|
type UserStorageFeatureAndKey = {
|
|
18
18
|
feature: UserStorageFeatures;
|
|
19
19
|
key: UserStorageFeatureKeys<UserStorageFeatures>;
|
|
20
20
|
};
|
|
21
21
|
export type UserStoragePathWithFeatureOnly = keyof UserStorageSchema;
|
|
22
|
+
export type UserStoragePathWithKeyOnly = {
|
|
23
|
+
[K in UserStorageFeatures]: `${UserStorageFeatureKeys<K>}`;
|
|
24
|
+
}[UserStoragePathWithFeatureOnly];
|
|
22
25
|
export type UserStoragePathWithFeatureAndKey = {
|
|
23
26
|
[K in UserStorageFeatures]: `${K}.${UserStorageFeatureKeys<K>}`;
|
|
24
27
|
}[UserStoragePathWithFeatureOnly];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-schema.d.cts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,QAAA,MAAM,oBAAoB,wBAAkC,CAAC;AAE7D,eAAO,MAAM,mBAAmB;;;;CAItB,CAAC;AAEX,KAAK,iBAAiB,GAAG,OAAO,mBAAmB,CAAC;AAEpD,
|
|
1
|
+
{"version":3,"file":"storage-schema.d.cts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":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= typeof USER_STORAGE_SCHEMA;
|
|
15
|
-
type UserStorageFeatures = keyof UserStorageSchema;
|
|
16
|
-
type UserStorageFeatureKeys<Feature extends UserStorageFeatures> = UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS ? string : UserStorageSchema[Feature][number];
|
|
15
|
+
export type UserStorageFeatures = keyof UserStorageSchema;
|
|
16
|
+
export type UserStorageFeatureKeys<Feature extends UserStorageFeatures> = UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS ? string : UserStorageSchema[Feature][number];
|
|
17
17
|
type UserStorageFeatureAndKey = {
|
|
18
18
|
feature: UserStorageFeatures;
|
|
19
19
|
key: UserStorageFeatureKeys<UserStorageFeatures>;
|
|
20
20
|
};
|
|
21
21
|
export type UserStoragePathWithFeatureOnly = keyof UserStorageSchema;
|
|
22
|
+
export type UserStoragePathWithKeyOnly = {
|
|
23
|
+
[K in UserStorageFeatures]: `${UserStorageFeatureKeys<K>}`;
|
|
24
|
+
}[UserStoragePathWithFeatureOnly];
|
|
22
25
|
export type UserStoragePathWithFeatureAndKey = {
|
|
23
26
|
[K in UserStorageFeatures]: `${K}.${UserStorageFeatureKeys<K>}`;
|
|
24
27
|
}[UserStoragePathWithFeatureOnly];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-schema.d.mts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,QAAA,MAAM,oBAAoB,wBAAkC,CAAC;AAE7D,eAAO,MAAM,mBAAmB;;;;CAItB,CAAC;AAEX,KAAK,iBAAiB,GAAG,OAAO,mBAAmB,CAAC;AAEpD,
|
|
1
|
+
{"version":3,"file":"storage-schema.d.mts","sourceRoot":"","sources":["../../src/shared/storage-schema.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,QAAA,MAAM,oBAAoB,wBAAkC,CAAC;AAE7D,eAAO,MAAM,mBAAmB;;;;CAItB,CAAC;AAE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ACb,yDAAyD,GAAG,iBAAiB,SAAS,EAAE,CACzF,CAAC;KACH;IAED,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC1B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,CACrC,IAAY,EAC8B,EAAE;IAC5C,MAAM,SAAS,GAAG,aAAa,CAAC;IAEhC,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,IAAsC,EACtC,UAAkB;IAElB,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,wBAAwB,CAAC,IAAI,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,GAAG,UAAU,CAAC,CAAC;IAErD,OAAO,GAAG,OAAO,IAAI,SAAS,EAAE,CAAC;AACnC,CAAC","sourcesContent":["import { createSHA256Hash } from './encryption';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Developers can provide additional features and keys by extending these types below.\n *\n * Adding ALLOW_ARBITRARY_KEYS as the first key in the array allows for any key to be used for this feature.\n * This can be useful for features where keys are not deterministic (eg. accounts addresses).\n */\nconst ALLOW_ARBITRARY_KEYS = 'ALLOW_ARBITRARY_KEYS' as const;\n\nexport const USER_STORAGE_SCHEMA = {\n notifications: ['notification_settings'],\n accounts: [ALLOW_ARBITRARY_KEYS], // keyed by account addresses\n networks: [ALLOW_ARBITRARY_KEYS], // keyed by chains/networks\n} as const;\n\ntype UserStorageSchema = typeof USER_STORAGE_SCHEMA;\n\nexport type UserStorageFeatures = keyof UserStorageSchema;\nexport type UserStorageFeatureKeys<Feature extends UserStorageFeatures> =\n UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS\n ? string\n : UserStorageSchema[Feature][number];\n\ntype UserStorageFeatureAndKey = {\n feature: UserStorageFeatures;\n key: UserStorageFeatureKeys<UserStorageFeatures>;\n};\n\nexport type UserStoragePathWithFeatureOnly = keyof UserStorageSchema;\nexport type UserStoragePathWithKeyOnly = {\n [K in UserStorageFeatures]: `${UserStorageFeatureKeys<K>}`;\n}[UserStoragePathWithFeatureOnly];\nexport type UserStoragePathWithFeatureAndKey = {\n [K in UserStorageFeatures]: `${K}.${UserStorageFeatureKeys<K>}`;\n}[UserStoragePathWithFeatureOnly];\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStoragePathWithFeatureAndKey,\n): UserStorageFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.') as [\n UserStorageFeatures,\n UserStorageFeatureKeys<UserStorageFeatures>,\n ];\n\n if (!(feature in USER_STORAGE_SCHEMA)) {\n throw new Error(`user-storage - invalid feature provided: ${feature}`);\n }\n\n const validFeature = USER_STORAGE_SCHEMA[feature] as readonly string[];\n\n if (\n !validFeature.includes(key) &&\n !validFeature.includes(ALLOW_ARBITRARY_KEYS)\n ) {\n const validKeys = USER_STORAGE_SCHEMA[feature].join(', ');\n\n throw new Error(\n `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`,\n );\n }\n\n return { feature, key };\n};\n\nexport const isPathWithFeatureAndKey = (\n path: string,\n): path is UserStoragePathWithFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n return pathRegex.test(path);\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStoragePathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `${feature}/${hashedKey}`;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/profile-sync-controller",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
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",
|
|
@@ -101,6 +101,8 @@
|
|
|
101
101
|
},
|
|
102
102
|
"dependencies": {
|
|
103
103
|
"@metamask/base-controller": "^7.0.1",
|
|
104
|
+
"@metamask/keyring-api": "^8.1.2",
|
|
105
|
+
"@metamask/keyring-controller": "^17.2.1",
|
|
104
106
|
"@metamask/snaps-sdk": "^6.5.0",
|
|
105
107
|
"@metamask/snaps-utils": "^8.1.1",
|
|
106
108
|
"@noble/ciphers": "^0.5.2",
|
|
@@ -113,8 +115,6 @@
|
|
|
113
115
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
114
116
|
"@metamask/accounts-controller": "^18.2.1",
|
|
115
117
|
"@metamask/auto-changelog": "^3.4.4",
|
|
116
|
-
"@metamask/keyring-api": "^8.1.0",
|
|
117
|
-
"@metamask/keyring-controller": "^17.2.1",
|
|
118
118
|
"@metamask/network-controller": "^21.0.1",
|
|
119
119
|
"@metamask/snaps-controllers": "^9.7.0",
|
|
120
120
|
"@types/jest": "^27.4.1",
|