@metamask/snaps-rpc-methods 3.3.0 → 4.0.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 +18 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/permitted/common/snapInstallation.js.map +1 -1
- package/dist/cjs/permitted/getFile.js +5 -5
- package/dist/cjs/permitted/getFile.js.map +1 -1
- package/dist/cjs/permitted/getSnaps.js.map +1 -1
- package/dist/cjs/permitted/invokeKeyring.js.map +1 -1
- package/dist/cjs/permitted/invokeSnapSugar.js.map +1 -1
- package/dist/cjs/permitted/requestSnaps.js.map +1 -1
- package/dist/cjs/restricted/caveats/permittedCoinTypes.js.map +1 -1
- package/dist/cjs/restricted/dialog.js +16 -25
- package/dist/cjs/restricted/dialog.js.map +1 -1
- package/dist/cjs/restricted/getBip32Entropy.js.map +1 -1
- package/dist/cjs/restricted/getBip32PublicKey.js.map +1 -1
- package/dist/cjs/restricted/getBip44Entropy.js +0 -1
- package/dist/cjs/restricted/getBip44Entropy.js.map +1 -1
- package/dist/cjs/restricted/getEntropy.js.map +1 -1
- package/dist/cjs/restricted/getLocale.js.map +1 -1
- package/dist/cjs/restricted/index.js +0 -9
- package/dist/cjs/restricted/index.js.map +1 -1
- package/dist/cjs/restricted/invokeSnap.js.map +1 -1
- package/dist/cjs/restricted/manageAccounts.js.map +1 -1
- package/dist/cjs/restricted/manageState.js +13 -22
- package/dist/cjs/restricted/manageState.js.map +1 -1
- package/dist/cjs/restricted/notify.js +6 -13
- package/dist/cjs/restricted/notify.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/permitted/common/snapInstallation.js.map +1 -1
- package/dist/esm/permitted/getFile.js +1 -1
- package/dist/esm/permitted/getFile.js.map +1 -1
- package/dist/esm/permitted/getSnaps.js.map +1 -1
- package/dist/esm/permitted/invokeKeyring.js.map +1 -1
- package/dist/esm/permitted/invokeSnapSugar.js.map +1 -1
- package/dist/esm/permitted/requestSnaps.js.map +1 -1
- package/dist/esm/restricted/caveats/permittedCoinTypes.js.map +1 -1
- package/dist/esm/restricted/dialog.js +3 -9
- package/dist/esm/restricted/dialog.js.map +1 -1
- package/dist/esm/restricted/getBip32Entropy.js.map +1 -1
- package/dist/esm/restricted/getBip32PublicKey.js.map +1 -1
- package/dist/esm/restricted/getBip44Entropy.js +0 -1
- package/dist/esm/restricted/getBip44Entropy.js.map +1 -1
- package/dist/esm/restricted/getEntropy.js.map +1 -1
- package/dist/esm/restricted/getLocale.js.map +1 -1
- package/dist/esm/restricted/index.js +0 -3
- package/dist/esm/restricted/index.js.map +1 -1
- package/dist/esm/restricted/invokeSnap.js.map +1 -1
- package/dist/esm/restricted/manageAccounts.js.map +1 -1
- package/dist/esm/restricted/manageState.js +8 -14
- package/dist/esm/restricted/manageState.js.map +1 -1
- package/dist/esm/restricted/notify.js +3 -7
- package/dist/esm/restricted/notify.js.map +1 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/permitted/common/snapInstallation.d.ts +3 -5
- package/dist/types/permitted/getFile.d.ts +5 -4
- package/dist/types/permitted/getSnaps.d.ts +3 -3
- package/dist/types/permitted/handlers.d.ts +6 -12
- package/dist/types/permitted/invokeKeyring.d.ts +5 -7
- package/dist/types/permitted/invokeSnapSugar.d.ts +5 -8
- package/dist/types/permitted/requestSnaps.d.ts +3 -2
- package/dist/types/restricted/caveats/permittedCoinTypes.d.ts +1 -1
- package/dist/types/restricted/dialog.d.ts +82 -29
- package/dist/types/restricted/getBip32Entropy.d.ts +2 -3
- package/dist/types/restricted/getBip32PublicKey.d.ts +2 -6
- package/dist/types/restricted/getBip44Entropy.d.ts +2 -5
- package/dist/types/restricted/getEntropy.d.ts +3 -2
- package/dist/types/restricted/getLocale.d.ts +2 -1
- package/dist/types/restricted/index.d.ts +9 -90
- package/dist/types/restricted/invokeSnap.d.ts +8 -7
- package/dist/types/restricted/manageAccounts.d.ts +5 -4
- package/dist/types/restricted/manageState.d.ts +3 -13
- package/dist/types/restricted/notify.d.ts +4 -7
- package/package.json +7 -8
- package/dist/cjs/request.js +0 -6
- package/dist/cjs/request.js.map +0 -1
- package/dist/esm/request.js +0 -3
- package/dist/esm/request.js.map +0 -1
- package/dist/types/request.d.ts +0 -99
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/restricted/caveats/permittedCoinTypes.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n RestrictedMethodCaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isPlainObject } from '@metamask/utils';\n\
|
|
1
|
+
{"version":3,"sources":["../../../../src/restricted/caveats/permittedCoinTypes.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n RestrictedMethodCaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { GetBip44EntropyParams } from '@metamask/snaps-sdk';\nimport { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isPlainObject } from '@metamask/utils';\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function permittedCoinTypesCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n return {\n caveats: [\n {\n type: SnapCaveatType.PermittedCoinTypes,\n value,\n },\n ],\n };\n}\n\n/**\n * Validate the params for `snap_getBip44Entropy`.\n *\n * @param value - The params to validate.\n * @throws If the params are invalid.\n */\nexport function validateBIP44Params(\n value: unknown,\n): asserts value is GetBip44EntropyParams {\n if (!isPlainObject(value) || !hasProperty(value, 'coinType')) {\n throw rpcErrors.invalidParams({\n message: 'Expected a plain object containing a coin type.',\n });\n }\n\n if (\n typeof value.coinType !== 'number' ||\n !Number.isInteger(value.coinType) ||\n value.coinType < 0 ||\n value.coinType > 0x7fffffff\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid \"coinType\" parameter. Coin type must be a non-negative integer.',\n });\n }\n\n if (FORBIDDEN_COIN_TYPES.includes(value.coinType)) {\n throw rpcErrors.invalidParams({\n message: `Coin type ${value.coinType} is forbidden.`,\n });\n }\n}\n\n/**\n * Validate the coin types values associated with a caveat. This checks if the\n * values are non-negative integers (>= 0).\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat is invalid.\n */\nexport function validateBIP44Caveat(caveat: Caveat<string, any>) {\n if (\n !hasProperty(caveat, 'value') ||\n !Array.isArray(caveat.value) ||\n caveat.value.length === 0\n ) {\n throw rpcErrors.invalidParams({\n message: 'Expected non-empty array of coin types.',\n });\n }\n\n caveat.value.forEach(validateBIP44Params);\n}\n\nexport const PermittedCoinTypesCaveatSpecification: Record<\n SnapCaveatType.PermittedCoinTypes,\n RestrictedMethodCaveatSpecificationConstraint\n> = {\n [SnapCaveatType.PermittedCoinTypes]: Object.freeze({\n type: SnapCaveatType.PermittedCoinTypes,\n decorator: (\n method,\n caveat: Caveat<\n SnapCaveatType.PermittedCoinTypes,\n GetBip44EntropyParams[]\n >,\n ) => {\n return async (args) => {\n const { params } = args;\n validateBIP44Params(params);\n\n const coinType = caveat.value.find(\n (caveatValue) => caveatValue.coinType === params.coinType,\n );\n\n if (!coinType) {\n throw providerErrors.unauthorized({\n message:\n 'The requested coin type is not permitted. Allowed coin types must be specified in the snap manifest.',\n });\n }\n\n return await method(args);\n };\n },\n validator: (caveat) => validateBIP44Caveat(caveat),\n }),\n};\n"],"names":["providerErrors","rpcErrors","FORBIDDEN_COIN_TYPES","SnapCaveatType","hasProperty","isPlainObject","permittedCoinTypesCaveatMapper","value","caveats","type","PermittedCoinTypes","validateBIP44Params","invalidParams","message","coinType","Number","isInteger","includes","validateBIP44Caveat","caveat","Array","isArray","length","forEach","PermittedCoinTypesCaveatSpecification","Object","freeze","decorator","method","args","params","find","caveatValue","unauthorized","validator"],"mappings":"AAKA,SAASA,cAAc,EAAEC,SAAS,QAAQ,uBAAuB;AAEjE,SAASC,oBAAoB,EAAEC,cAAc,QAAQ,wBAAwB;AAE7E,SAASC,WAAW,EAAEC,aAAa,QAAQ,kBAAkB;AAE7D;;;;;;;CAOC,GACD,OAAO,SAASC,+BACdC,KAAW;IAEX,OAAO;QACLC,SAAS;YACP;gBACEC,MAAMN,eAAeO,kBAAkB;gBACvCH;YACF;SACD;IACH;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASI,oBACdJ,KAAc;IAEd,IAAI,CAACF,cAAcE,UAAU,CAACH,YAAYG,OAAO,aAAa;QAC5D,MAAMN,UAAUW,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,IACE,OAAON,MAAMO,QAAQ,KAAK,YAC1B,CAACC,OAAOC,SAAS,CAACT,MAAMO,QAAQ,KAChCP,MAAMO,QAAQ,GAAG,KACjBP,MAAMO,QAAQ,GAAG,YACjB;QACA,MAAMb,UAAUW,aAAa,CAAC;YAC5BC,SACE;QACJ;IACF;IAEA,IAAIX,qBAAqBe,QAAQ,CAACV,MAAMO,QAAQ,GAAG;QACjD,MAAMb,UAAUW,aAAa,CAAC;YAC5BC,SAAS,CAAC,UAAU,EAAEN,MAAMO,QAAQ,CAAC,cAAc,CAAC;QACtD;IACF;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASI,oBAAoBC,MAA2B;IAC7D,IACE,CAACf,YAAYe,QAAQ,YACrB,CAACC,MAAMC,OAAO,CAACF,OAAOZ,KAAK,KAC3BY,OAAOZ,KAAK,CAACe,MAAM,KAAK,GACxB;QACA,MAAMrB,UAAUW,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEAM,OAAOZ,KAAK,CAACgB,OAAO,CAACZ;AACvB;AAEA,OAAO,MAAMa,wCAGT;IACF,CAACrB,eAAeO,kBAAkB,CAAC,EAAEe,OAAOC,MAAM,CAAC;QACjDjB,MAAMN,eAAeO,kBAAkB;QACvCiB,WAAW,CACTC,QACAT;YAKA,OAAO,OAAOU;gBACZ,MAAM,EAAEC,MAAM,EAAE,GAAGD;gBACnBlB,oBAAoBmB;gBAEpB,MAAMhB,WAAWK,OAAOZ,KAAK,CAACwB,IAAI,CAChC,CAACC,cAAgBA,YAAYlB,QAAQ,KAAKgB,OAAOhB,QAAQ;gBAG3D,IAAI,CAACA,UAAU;oBACb,MAAMd,eAAeiC,YAAY,CAAC;wBAChCpB,SACE;oBACJ;gBACF;gBAEA,OAAO,MAAMe,OAAOC;YACtB;QACF;QACAK,WAAW,CAACf,SAAWD,oBAAoBC;IAC7C;AACF,EAAE"}
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
-
import { ComponentStruct,
|
|
4
|
-
import {
|
|
3
|
+
import { DialogType, ComponentStruct, enumValue } from '@metamask/snaps-sdk';
|
|
4
|
+
import { validateComponentLinks } from '@metamask/snaps-utils';
|
|
5
5
|
import { create, enums, object, optional, size, string, StructError, type, union } from 'superstruct';
|
|
6
6
|
const methodName = 'snap_dialog';
|
|
7
|
-
export var DialogType;
|
|
8
|
-
(function(DialogType) {
|
|
9
|
-
DialogType["Alert"] = 'alert';
|
|
10
|
-
DialogType["Confirmation"] = 'confirmation';
|
|
11
|
-
DialogType["Prompt"] = 'prompt';
|
|
12
|
-
})(DialogType || (DialogType = {}));
|
|
13
7
|
const PlaceholderStruct = optional(size(string(), 1, 40));
|
|
14
8
|
/**
|
|
15
9
|
* The specification builder for the `snap_dialog` permission. `snap_dialog`
|
|
@@ -95,7 +89,7 @@ const structs = {
|
|
|
95
89
|
const validatedParams = getValidatedParams(params, structs[validatedType]);
|
|
96
90
|
const { content } = validatedParams;
|
|
97
91
|
await maybeUpdatePhishingList();
|
|
98
|
-
|
|
92
|
+
validateComponentLinks(content, isOnPhishingList);
|
|
99
93
|
const placeholder = validatedParams.type === DialogType.Prompt ? validatedParams.placeholder : undefined;
|
|
100
94
|
return showDialog(origin, validatedType, content, placeholder);
|
|
101
95
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/dialog.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Component } from '@metamask/snaps-ui';\nimport { ComponentStruct, assertUILinksAreSafe } from '@metamask/snaps-ui';\nimport type { EnumToUnion } from '@metamask/snaps-utils';\nimport { enumValue } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n create,\n enums,\n object,\n optional,\n size,\n string,\n StructError,\n type,\n union,\n} from 'superstruct';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_dialog';\n\nexport enum DialogType {\n Alert = 'alert',\n Confirmation = 'confirmation',\n Prompt = 'prompt',\n}\n\nconst PlaceholderStruct = optional(size(string(), 1, 40));\n\nexport type Placeholder = Infer<typeof PlaceholderStruct>;\n\ntype ShowDialog = (\n snapId: string,\n type: EnumToUnion<DialogType>,\n content: Component,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype MaybeUpdatePhisingList = () => Promise<void>;\ntype IsOnPhishingList = (url: string) => boolean;\n\nexport type DialogMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the alert.\n * @param type - The dialog type.\n * @param content - The dialog custom UI.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n maybeUpdatePhishingList: MaybeUpdatePhisingList;\n\n /**\n * @param url - The URL to check against the phishing list.\n */\n isOnPhishingList: IsOnPhishingList;\n};\n\ntype DialogSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: DialogMethodHooks;\n};\n\ntype DialogSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getDialogImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_dialog` permission. `snap_dialog`\n * lets the Snap display one of the following dialogs to the user:\n * - An alert, for displaying information.\n * - A confirmation, for accepting or rejecting some action.\n * - A prompt, for inputting some information.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the\n * permission.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_dialog` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n DialogSpecificationBuilderOptions,\n DialogSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: DialogSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getDialogImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<DialogMethodHooks> = {\n showDialog: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const dialogBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n// Note: We use `type` here instead of `object` because `type` does not validate\n// the keys of the object, which is what we want.\nconst BaseParamsStruct = type({\n type: enums([DialogType.Alert, DialogType.Confirmation, DialogType.Prompt]),\n});\n\nconst AlertParametersStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst PromptParametersStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst DialogParametersStruct = union([\n AlertParametersStruct,\n ConfirmationParametersStruct,\n PromptParametersStruct,\n]);\n\nexport type DialogParameters = Infer<typeof DialogParametersStruct>;\n\nconst structs = {\n [DialogType.Alert]: AlertParametersStruct,\n [DialogType.Confirmation]: ConfirmationParametersStruct,\n [DialogType.Prompt]: PromptParametersStruct,\n};\n\n/**\n * Builds the method implementation for `snap_dialog`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showDialog - A function that shows the specified dialog in the\n * MetaMask UI and returns the appropriate value for the dialog type.\n * @param hooks.isOnPhishingList - A function that checks a link against the\n * phishing list and return true if it's in, otherwise false.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which return value depends on the dialog\n * type, valid return types are: string, boolean, null.\n */\nexport function getDialogImplementation({\n showDialog,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: DialogMethodHooks) {\n return async function dialogImplementation(\n args: RestrictedMethodOptions<DialogParameters>,\n ): Promise<boolean | null | string> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedType = getValidatedType(params);\n const validatedParams = getValidatedParams(params, structs[validatedType]);\n\n const { content } = validatedParams;\n\n await maybeUpdatePhishingList();\n\n assertUILinksAreSafe(content, isOnPhishingList);\n\n const placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n return showDialog(origin, validatedType, content, placeholder);\n };\n}\n\n/**\n * Get the validated type of the dialog parameters. Throws an error if the type\n * is invalid.\n *\n * @param params - The parameters to validate.\n * @returns The validated type of the dialog parameters.\n */\nfunction getValidatedType(params: unknown): DialogType {\n try {\n return create(params, BaseParamsStruct).type;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `The \"type\" property must be one of: ${Object.values(\n DialogType,\n ).join(', ')}.`,\n });\n }\n}\n\n/**\n * Validates the confirm method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param struct - The struct to validate the params against.\n * @returns The validated confirm method parameter object.\n */\nfunction getValidatedParams(\n params: unknown,\n struct: Struct<any>,\n): DialogParameters {\n try {\n return create(params, struct);\n } catch (error) {\n if (error instanceof StructError) {\n const { key, type: errorType } = error;\n\n if (key === 'placeholder' && errorType === 'never') {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid params: Alerts or confirmations may not specify a \"placeholder\" field.',\n });\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","ComponentStruct","assertUILinksAreSafe","enumValue","create","enums","object","optional","size","string","StructError","type","union","methodName","DialogType","Alert","Confirmation","Prompt","PlaceholderStruct","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getDialogImplementation","subjectTypes","Snap","showDialog","isOnPhishingList","maybeUpdatePhishingList","dialogBuilder","Object","freeze","BaseParamsStruct","AlertParametersStruct","content","ConfirmationParametersStruct","PromptParametersStruct","placeholder","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","error","invalidParams","message","values","join","struct","key","errorType","internal"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,eAAe,EAAEC,oBAAoB,QAAQ,qBAAqB;AAE3E,SAASC,SAAS,QAAQ,wBAAwB;AAGlD,SACEC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,WAAW,EACXC,IAAI,EACJC,KAAK,QACA,cAAc;AAIrB,MAAMC,aAAa;WAEZ;UAAKC,UAAU;IAAVA,WACVC,WAAQ;IADED,WAEVE,kBAAe;IAFLF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\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { DialogType, ComponentStruct, enumValue } from '@metamask/snaps-sdk';\nimport type { DialogParams, EnumToUnion, Component } from '@metamask/snaps-sdk';\nimport { validateComponentLinks } from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n create,\n enums,\n object,\n optional,\n size,\n string,\n StructError,\n type,\n union,\n} from 'superstruct';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_dialog';\n\nconst PlaceholderStruct = optional(size(string(), 1, 40));\n\nexport type Placeholder = Infer<typeof PlaceholderStruct>;\n\ntype ShowDialog = (\n snapId: string,\n type: EnumToUnion<DialogType>,\n content: Component,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype MaybeUpdatePhisingList = () => Promise<void>;\ntype IsOnPhishingList = (url: string) => boolean;\n\nexport type DialogMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the alert.\n * @param type - The dialog type.\n * @param content - The dialog custom UI.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n maybeUpdatePhishingList: MaybeUpdatePhisingList;\n\n /**\n * @param url - The URL to check against the phishing list.\n */\n isOnPhishingList: IsOnPhishingList;\n};\n\ntype DialogSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: DialogMethodHooks;\n};\n\ntype DialogSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getDialogImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_dialog` permission. `snap_dialog`\n * lets the Snap display one of the following dialogs to the user:\n * - An alert, for displaying information.\n * - A confirmation, for accepting or rejecting some action.\n * - A prompt, for inputting some information.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the\n * permission.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_dialog` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n DialogSpecificationBuilderOptions,\n DialogSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: DialogSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getDialogImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<DialogMethodHooks> = {\n showDialog: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const dialogBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n// Note: We use `type` here instead of `object` because `type` does not validate\n// the keys of the object, which is what we want.\nconst BaseParamsStruct = type({\n type: enums([DialogType.Alert, DialogType.Confirmation, DialogType.Prompt]),\n});\n\nconst AlertParametersStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst PromptParametersStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst DialogParametersStruct = union([\n AlertParametersStruct,\n ConfirmationParametersStruct,\n PromptParametersStruct,\n]);\n\nexport type DialogParameters = InferMatching<\n typeof DialogParametersStruct,\n DialogParams\n>;\n\nconst structs = {\n [DialogType.Alert]: AlertParametersStruct,\n [DialogType.Confirmation]: ConfirmationParametersStruct,\n [DialogType.Prompt]: PromptParametersStruct,\n};\n\n/**\n * Builds the method implementation for `snap_dialog`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showDialog - A function that shows the specified dialog in the\n * MetaMask UI and returns the appropriate value for the dialog type.\n * @param hooks.isOnPhishingList - A function that checks a link against the\n * phishing list and return true if it's in, otherwise false.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which return value depends on the dialog\n * type, valid return types are: string, boolean, null.\n */\nexport function getDialogImplementation({\n showDialog,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: DialogMethodHooks) {\n return async function dialogImplementation(\n args: RestrictedMethodOptions<DialogParameters>,\n ): Promise<boolean | null | string> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedType = getValidatedType(params);\n const validatedParams = getValidatedParams(params, structs[validatedType]);\n\n const { content } = validatedParams;\n\n await maybeUpdatePhishingList();\n\n validateComponentLinks(content, isOnPhishingList);\n\n const placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n return showDialog(origin, validatedType, content, placeholder);\n };\n}\n\n/**\n * Get the validated type of the dialog parameters. Throws an error if the type\n * is invalid.\n *\n * @param params - The parameters to validate.\n * @returns The validated type of the dialog parameters.\n */\nfunction getValidatedType(params: unknown): DialogType {\n try {\n return create(params, BaseParamsStruct).type;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `The \"type\" property must be one of: ${Object.values(\n DialogType,\n ).join(', ')}.`,\n });\n }\n}\n\n/**\n * Validates the confirm method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param struct - The struct to validate the params against.\n * @returns The validated confirm method parameter object.\n */\nfunction getValidatedParams(\n params: unknown,\n struct: Struct<any>,\n): DialogParameters {\n try {\n return create(params, struct);\n } catch (error) {\n if (error instanceof StructError) {\n const { key, type: errorType } = error;\n\n if (key === 'placeholder' && errorType === 'never') {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid params: Alerts or confirmations may not specify a \"placeholder\" field.',\n });\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","DialogType","ComponentStruct","enumValue","validateComponentLinks","create","enums","object","optional","size","string","StructError","type","union","methodName","PlaceholderStruct","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getDialogImplementation","subjectTypes","Snap","showDialog","isOnPhishingList","maybeUpdatePhishingList","dialogBuilder","Object","freeze","BaseParamsStruct","Alert","Confirmation","Prompt","AlertParametersStruct","content","ConfirmationParametersStruct","PromptParametersStruct","placeholder","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","error","invalidParams","message","values","join","struct","key","errorType","internal"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AACjD,SAASC,UAAU,EAAEC,eAAe,EAAEC,SAAS,QAAQ,sBAAsB;AAE7E,SAASC,sBAAsB,QAAQ,wBAAwB;AAI/D,SACEC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,WAAW,EACXC,IAAI,EACJC,KAAK,QACA,cAAc;AAIrB,MAAMC,aAAa;AAEnB,MAAMC,oBAAoBP,SAASC,KAAKC,UAAU,GAAG;AA2CrD;;;;;;;;;;;;;CAaC,GACD,MAAMM,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EACuB;IAClC,OAAO;QACLC,gBAAgBrB,eAAesB,gBAAgB;QAC/CC,YAAYP;QACZG;QACAK,sBAAsBC,wBAAwBL;QAC9CM,cAAc;YAACzB,YAAY0B,IAAI;SAAC;IAClC;AACF;AAEA,MAAMP,cAAoD;IACxDQ,YAAY;IACZC,kBAAkB;IAClBC,yBAAyB;AAC3B;AAEA,OAAO,MAAMC,gBAAgBC,OAAO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,SAASS,iBAAiBJ,MAAe;IACvC,IAAI;QACF,OAAOxC,OAAOwC,QAAQb,kBAAkBpB,IAAI;IAC9C,EAAE,OAAOyC,OAAO;QACd,MAAMrD,UAAUsD,aAAa,CAAC;YAC5BC,SAAS,CAAC,oCAAoC,EAAEzB,OAAO0B,MAAM,CAC3DvD,YACAwD,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAASN,mBACPN,MAAe,EACfa,MAAmB;IAEnB,IAAI;QACF,OAAOrD,OAAOwC,QAAQa;IACxB,EAAE,OAAOL,OAAO;QACd,IAAIA,iBAAiB1C,aAAa;YAChC,MAAM,EAAEgD,GAAG,EAAE/C,MAAMgD,SAAS,EAAE,GAAGP;YAEjC,IAAIM,QAAQ,iBAAiBC,cAAc,SAAS;gBAClD,MAAM5D,UAAUsD,aAAa,CAAC;oBAC5BC,SACE;gBACJ;YACF;YAEA,MAAMvD,UAAUsD,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QAEA,wBAAwB,GACxB,MAAMvD,UAAU6D,QAAQ;IAC1B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip32Entropy.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip32Entropy.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32EntropyParams,\n GetBip32EntropyResult,\n} from '@metamask/snaps-sdk';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32Entropy';\n\nexport type GetBip32EntropyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip32EntropySpecificationBuilderOptions = {\n methodHooks: GetBip32EntropyMethodHooks;\n};\n\ntype GetBip32EntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32EntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * The specification builder for the `snap_getBip32Entropy` permission.\n * `snap_getBip32Entropy` lets the Snap control private keys for a particular\n * BIP-32 node.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getBip32Entropy` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32EntropySpecificationBuilderOptions,\n GetBip32EntropySpecification\n> = ({ methodHooks }: GetBip32EntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32EntropyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32EntropyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32EntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32Entropy`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a `JsonSLIP10Node`.\n * @throws If the params are invalid.\n */\nexport function getBip32EntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32EntropyMethodHooks) {\n return async function getBip32Entropy(\n args: RestrictedMethodOptions<GetBip32EntropyParams>,\n ): Promise<GetBip32EntropyResult> {\n await getUnlockPromise(true);\n\n const { params } = args;\n assert(params);\n\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n return node.toJSON();\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","SnapCaveatType","assert","getNode","targetName","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedDerivationPaths","methodImplementation","getBip32EntropyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip32EntropyBuilder","Object","freeze","getBip32Entropy","args","params","node","curve","path","secretRecoveryPhrase","toJSON"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,SAASC,MAAM,QAAQ,kBAAkB;AAGzC,SAASC,OAAO,QAAQ,WAAW;AAEnC,MAAMC,aAAa;AA4BnB;;;;;;;;CAQC,GACD,MAAMC,uBAIF,CAAC,EAAEC,WAAW,EAA8C;IAC9D,OAAO;QACLC,gBAAgBT,eAAeU,gBAAgB;QAC/CJ;QACAK,gBAAgB;YAACR,eAAeS,wBAAwB;SAAC;QACzDC,sBAAsBC,8BAA8BN;QACpDO,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKf,eAAeS,wBAAwB,EAC3D;gBACA,MAAMV,UAAUiB,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEjB,eAAeS,wBAAwB,CAAC,SAAS,CAAC;gBACnF;YACF;QACF;QACAS,cAAc;YAACpB,YAAYqB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMd,cAA6D;IACjEe,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,yBAAyBC,OAAOC,MAAM,CAAC;IAClDrB;IACAC;IACAC;AACF,GAAY;AAEZ;;;;;;;;;CASC,GACD,OAAO,SAASM,8BAA8B,EAC5CS,WAAW,EACXC,gBAAgB,EACW;IAC3B,OAAO,eAAeI,gBACpBC,IAAoD;QAEpD,MAAML,iBAAiB;QAEvB,MAAM,EAAEM,MAAM,EAAE,GAAGD;QACnBzB,OAAO0B;QAEP,MAAMC,OAAO,MAAM1B,QAAQ;YACzB2B,OAAOF,OAAOE,KAAK;YACnBC,MAAMH,OAAOG,IAAI;YACjBC,sBAAsB,MAAMX;QAC9B;QAEA,OAAOQ,KAAKI,MAAM;IACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip32PublicKey.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip32PublicKey.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32PublicKeyParams,\n GetBip32PublicKeyResult,\n} from '@metamask/snaps-sdk';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\nexport const Bip32PublicKeyArgsStruct = bip32entropy(\n object({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n compressed: optional(boolean()),\n }),\n);\n\n/**\n * The specification builder for the `snap_getBip32PublicKey` permission.\n * `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular\n * BIP-32 node.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getBip32PublicKey` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32PublicKeySpecificationBuilderOptions,\n GetBip32PublicKeySpecification\n> = ({ methodHooks }: GetBip32PublicKeySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32PublicKeyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32PublicKeyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32PublicKeyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32PublicKey`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a public key.\n * @throws If the params are invalid.\n */\nexport function getBip32PublicKeyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32PublicKeyMethodHooks) {\n return async function getBip32PublicKey(\n args: RestrictedMethodOptions<GetBip32PublicKeyParams>,\n ): Promise<GetBip32PublicKeyResult> {\n await getUnlockPromise(true);\n\n assertStruct(\n args.params,\n Bip32PublicKeyArgsStruct,\n 'Invalid BIP-32 public key params',\n rpcErrors.invalidParams,\n );\n\n const { params } = args;\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n if (params.compressed) {\n return node.compressedPublicKey;\n }\n\n return node.publicKey;\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","bip32entropy","Bip32PathStruct","SnapCaveatType","assertStruct","boolean","enums","object","optional","getNode","targetName","Bip32PublicKeyArgsStruct","path","curve","compressed","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedDerivationPaths","methodImplementation","getBip32PublicKeyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip32PublicKeyBuilder","Object","freeze","getBip32PublicKey","args","params","node","secretRecoveryPhrase","compressedPublicKey","publicKey"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SACEC,YAAY,EACZC,eAAe,EACfC,cAAc,QACT,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,kBAAkB;AAC/C,SAASC,OAAO,EAAEC,KAAK,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,cAAc;AAG/D,SAASC,OAAO,QAAQ,WAAW;AAEnC,MAAMC,aAAa;AA4BnB,OAAO,MAAMC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 +56,6 @@ export const getBip44EntropyBuilder = Object.freeze({
|
|
|
56
56
|
return async function getBip44Entropy(args) {
|
|
57
57
|
await getUnlockPromise(true);
|
|
58
58
|
// `args.params` is validated by the decorator, so it's safe to assert here.
|
|
59
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
60
59
|
const params = args.params;
|
|
61
60
|
const node = await BIP44CoinTypeNode.fromDerivationPath([
|
|
62
61
|
await getMnemonic(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip44Entropy.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip44Entropy.ts"],"sourcesContent":["import { BIP44CoinTypeNode } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip44EntropyParams,\n GetBip44EntropyResult,\n} from '@metamask/snaps-sdk';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst targetName = 'snap_getBip44Entropy';\n\nexport type GetBip44EntropyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip44EntropySpecificationBuilderOptions = {\n methodHooks: GetBip44EntropyMethodHooks;\n};\n\ntype GetBip44EntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip44EntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * The specification builder for the `snap_getBip44Entropy` permission.\n * `snap_getBip44Entropy_*` lets the Snap control private keys for a particular\n * BIP-32 coin type.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_getBip44Entropy` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip44EntropySpecificationBuilderOptions,\n GetBip44EntropySpecification\n> = ({ methodHooks }: GetBip44EntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedCoinTypes],\n methodImplementation: getBip44EntropyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedCoinTypes\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedCoinTypes}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip44EntropyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip44EntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip44Entropy`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @returns The method implementation which returns a `BIP44CoinTypeNode`.\n * @throws If the params are invalid.\n */\nexport function getBip44EntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip44EntropyMethodHooks) {\n return async function getBip44Entropy(\n args: RestrictedMethodOptions<GetBip44EntropyParams>,\n ): Promise<GetBip44EntropyResult> {\n await getUnlockPromise(true);\n\n // `args.params` is validated by the decorator, so it's safe to assert here.\n const params = args.params as GetBip44EntropyParams;\n\n const node = await BIP44CoinTypeNode.fromDerivationPath([\n await getMnemonic(),\n `bip32:44'`,\n `bip32:${params.coinType}'`,\n ]);\n\n return node.toJSON();\n };\n}\n"],"names":["BIP44CoinTypeNode","PermissionType","SubjectType","rpcErrors","SnapCaveatType","targetName","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedCoinTypes","methodImplementation","getBip44EntropyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip44EntropyBuilder","Object","freeze","getBip44Entropy","args","params","node","fromDerivationPath","coinType","toJSON"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AAOvD,SAASC,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SAASC,cAAc,QAAQ,wBAAwB;AAKvD,MAAMC,aAAa;AA4BnB;;;;;;;;;CASC,GACD,MAAMC,uBAIF,CAAC,EAAEC,WAAW,EAA8C;IAC9D,OAAO;QACLC,gBAAgBP,eAAeQ,gBAAgB;QAC/CJ;QACAK,gBAAgB;YAACN,eAAeO,kBAAkB;SAAC;QACnDC,sBAAsBC,8BAA8BN;QACpDO,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKb,eAAeO,kBAAkB,EACrD;gBACA,MAAMR,UAAUe,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEf,eAAeO,kBAAkB,CAAC,SAAS,CAAC;gBAC7E;YACF;QACF;QACAS,cAAc;YAAClB,YAAYmB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMd,cAA6D;IACjEe,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,yBAAyBC,OAAOC,MAAM,CAAC;IAClDrB;IACAC;IACAC;AACF,GAAY;AAEZ;;;;;;;;;;;CAWC,GACD,OAAO,SAASM,8BAA8B,EAC5CS,WAAW,EACXC,gBAAgB,EACW;IAC3B,OAAO,eAAeI,gBACpBC,IAAoD;QAEpD,MAAML,iBAAiB;QAEvB,4EAA4E;QAC5E,MAAMM,SAASD,KAAKC,MAAM;QAE1B,MAAMC,OAAO,MAAM9B,kBAAkB+B,kBAAkB,CAAC;YACtD,MAAMT;YACN,CAAC,SAAS,CAAC;YACX,CAAC,MAAM,EAAEO,OAAOG,QAAQ,CAAC,CAAC,CAAC;SAC5B;QAED,OAAOF,KAAKG,MAAM;IACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getEntropy.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { SIP_6_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getEntropy.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { GetEntropyParams, GetEntropyResult } from '@metamask/snaps-sdk';\nimport { SIP_6_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\nconst targetName = 'snap_getEntropy';\n\ntype GetEntropySpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetEntropyHooks;\n};\n\ntype GetEntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getEntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\nexport const GetEntropyArgsStruct = object({\n version: literal(1),\n salt: optional(string()),\n});\n\n/**\n * @property version - The version of the `snap_getEntropy` method. This must be\n * the numeric literal `1`.\n * @property salt - A string to use as the salt when deriving the entropy. If\n * omitted, the salt will be an empty string.\n */\nexport type GetEntropyArgs = Infer<typeof GetEntropyArgsStruct>;\n\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetEntropySpecificationBuilderOptions,\n GetEntropySpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: GetEntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats,\n methodImplementation: getEntropyImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetEntropyHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getEntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport type GetEntropyHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\n/**\n * Builds the method implementation for `snap_getEntropy`. The implementation\n * is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - The method to get the mnemonic of the user's\n * primary keyring.\n * @param hooks.getUnlockPromise - The method to get a promise that resolves\n * once the extension is unlocked.\n * @returns The method implementation.\n */\nfunction getEntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetEntropyHooks) {\n return async function getEntropy(\n options: RestrictedMethodOptions<GetEntropyParams>,\n ): Promise<GetEntropyResult> {\n const {\n params,\n context: { origin },\n } = options;\n\n assertStruct(\n params,\n GetEntropyArgsStruct,\n 'Invalid \"snap_getEntropy\" parameters',\n rpcErrors.invalidParams,\n );\n\n await getUnlockPromise(true);\n const mnemonicPhrase = await getMnemonic();\n\n return deriveEntropy({\n input: origin,\n salt: params.salt,\n mnemonicPhrase,\n magic: SIP_6_MAGIC_VALUE,\n });\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","SIP_6_MAGIC_VALUE","assertStruct","literal","object","optional","string","deriveEntropy","targetName","GetEntropyArgsStruct","version","salt","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","methodImplementation","getEntropyImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","getEntropyBuilder","Object","freeze","getEntropy","options","params","context","origin","invalidParams","mnemonicPhrase","input","magic"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,iBAAiB,QAAQ,wBAAwB;AAE1D,SAASC,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,cAAc;AAGhE,SAASC,aAAa,QAAQ,WAAW;AAEzC,MAAMC,aAAa;AAcnB,OAAO,MAAMC,uBAAuBL,OAAO;IACzCM,SAASP,QAAQ;IACjBQ,MAAMN,SAASC;AACjB,GAAG;AAUH,MAAMM,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EAC2B;IACtC,OAAO;QACLC,gBAAgBjB,eAAekB,gBAAgB;QAC/CR;QACAK;QACAI,sBAAsBC,yBAAyBJ;QAC/CK,cAAc;YAACpB,YAAYqB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMN,cAAkD;IACtDO,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,oBAAoBC,OAAOC,MAAM,CAAC;IAC7CjB;IACAI;IACAE;AACF,GAAY;AAgBZ;;;;;;;;;;;CAWC,GACD,SAASI,yBAAyB,EAChCG,WAAW,EACXC,gBAAgB,EACA;IAChB,OAAO,eAAeI,WACpBC,OAAkD;QAElD,MAAM,EACJC,MAAM,EACNC,SAAS,EAAEC,MAAM,EAAE,EACpB,GAAGH;QAEJzB,aACE0B,QACAnB,sBACA,wCACAT,UAAU+B,aAAa;QAGzB,MAAMT,iBAAiB;QACvB,MAAMU,iBAAiB,MAAMX;QAE7B,OAAOd,cAAc;YACnB0B,OAAOH;YACPnB,MAAMiB,OAAOjB,IAAI;YACjBqB;YACAE,OAAOjC;QACT;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getLocale.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n ValidPermissionSpecification,\n RestrictedMethodOptions,\n RestrictedMethodParameters,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_getLocale';\n\nexport type GetLocaleMethodHooks = {\n getLocale: () => Promise<string>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetLocaleMethodHooks;\n};\n\ntype Specification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_getLocale` permission.\n * `snap_getLocale` allows snaps to get the user selected locale.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getLocale` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n SpecificationBuilderOptions,\n Specification\n> = ({ allowedCaveats = null, methodHooks }: SpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetLocaleMethodHooks> = {\n getLocale: true,\n};\n\nexport const getLocaleBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getLocale`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getLocale - A function that returns the user selected locale.\n * @returns The user selected locale.\n */\nexport function getImplementation({ getLocale }: GetLocaleMethodHooks) {\n return async function implementation(\n _args: RestrictedMethodOptions<RestrictedMethodParameters>,\n ): Promise<
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getLocale.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n ValidPermissionSpecification,\n RestrictedMethodOptions,\n RestrictedMethodParameters,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { GetLocaleResult } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_getLocale';\n\nexport type GetLocaleMethodHooks = {\n getLocale: () => Promise<string>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetLocaleMethodHooks;\n};\n\ntype Specification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_getLocale` permission.\n * `snap_getLocale` allows snaps to get the user selected locale.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getLocale` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n SpecificationBuilderOptions,\n Specification\n> = ({ allowedCaveats = null, methodHooks }: SpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetLocaleMethodHooks> = {\n getLocale: true,\n};\n\nexport const getLocaleBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getLocale`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getLocale - A function that returns the user selected locale.\n * @returns The user selected locale.\n */\nexport function getImplementation({ getLocale }: GetLocaleMethodHooks) {\n return async function implementation(\n _args: RestrictedMethodOptions<RestrictedMethodParameters>,\n ): Promise<GetLocaleResult> {\n return getLocale();\n };\n}\n"],"names":["PermissionType","SubjectType","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getImplementation","subjectTypes","Snap","getLocale","getLocaleBuilder","Object","freeze","implementation","_args"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAM9E,MAAMC,aAAa;AAkBnB;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAIT,CAAC,EAAEC,iBAAiB,IAAI,EAAEC,WAAW,EAA+B;IACtE,OAAO;QACLC,gBAAgBN,eAAeO,gBAAgB;QAC/CC,YAAYN;QACZE;QACAK,sBAAsBC,kBAAkBL;QACxCM,cAAc;YAACV,YAAYW,IAAI;SAAC;IAClC;AACF,EAAE;AAEF,MAAMP,cAAuD;IAC3DQ,WAAW;AACb;AAEA,OAAO,MAAMC,mBAAmBC,OAAOC,MAAM,CAAC;IAC5CR,YAAYN;IACZC;IACAE;AACF,GAAY;AAEZ;;;;;;CAMC,GACD,OAAO,SAASK,kBAAkB,EAAEG,SAAS,EAAwB;IACnE,OAAO,eAAeI,eACpBC,KAA0D;QAE1D,OAAOL;IACT;AACF"}
|
|
@@ -8,10 +8,7 @@ import { invokeSnapBuilder } from './invokeSnap';
|
|
|
8
8
|
import { manageAccountsBuilder } from './manageAccounts';
|
|
9
9
|
import { manageStateBuilder } from './manageState';
|
|
10
10
|
import { notifyBuilder } from './notify';
|
|
11
|
-
export { DialogType } from './dialog';
|
|
12
|
-
export { ManageStateOperation } from './manageState';
|
|
13
11
|
export { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';
|
|
14
|
-
export { NotificationType } from './notify';
|
|
15
12
|
export const restrictedMethodPermissionBuilders = {
|
|
16
13
|
[dialogBuilder.targetName]: dialogBuilder,
|
|
17
14
|
[getBip32EntropyBuilder.targetName]: getBip32EntropyBuilder,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/index.ts"],"sourcesContent":["import type { DialogMethodHooks } from './dialog';\nimport { dialogBuilder } from './dialog';\nimport type { GetBip32EntropyMethodHooks } from './getBip32Entropy';\nimport { getBip32EntropyBuilder } from './getBip32Entropy';\nimport type { GetBip32PublicKeyMethodHooks } from './getBip32PublicKey';\nimport { getBip32PublicKeyBuilder } from './getBip32PublicKey';\nimport type { GetBip44EntropyMethodHooks } from './getBip44Entropy';\nimport { getBip44EntropyBuilder } from './getBip44Entropy';\nimport type { GetEntropyHooks } from './getEntropy';\nimport { getEntropyBuilder } from './getEntropy';\nimport type { GetLocaleMethodHooks } from './getLocale';\nimport { getLocaleBuilder } from './getLocale';\nimport type { InvokeSnapMethodHooks } from './invokeSnap';\nimport { invokeSnapBuilder } from './invokeSnap';\nimport type { ManageAccountsMethodHooks } from './manageAccounts';\nimport { manageAccountsBuilder } from './manageAccounts';\nimport type { ManageStateMethodHooks } from './manageState';\nimport { manageStateBuilder } from './manageState';\nimport type { NotifyMethodHooks } from './notify';\nimport { notifyBuilder } from './notify';\n\nexport
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/index.ts"],"sourcesContent":["import type { DialogMethodHooks } from './dialog';\nimport { dialogBuilder } from './dialog';\nimport type { GetBip32EntropyMethodHooks } from './getBip32Entropy';\nimport { getBip32EntropyBuilder } from './getBip32Entropy';\nimport type { GetBip32PublicKeyMethodHooks } from './getBip32PublicKey';\nimport { getBip32PublicKeyBuilder } from './getBip32PublicKey';\nimport type { GetBip44EntropyMethodHooks } from './getBip44Entropy';\nimport { getBip44EntropyBuilder } from './getBip44Entropy';\nimport type { GetEntropyHooks } from './getEntropy';\nimport { getEntropyBuilder } from './getEntropy';\nimport type { GetLocaleMethodHooks } from './getLocale';\nimport { getLocaleBuilder } from './getLocale';\nimport type { InvokeSnapMethodHooks } from './invokeSnap';\nimport { invokeSnapBuilder } from './invokeSnap';\nimport type { ManageAccountsMethodHooks } from './manageAccounts';\nimport { manageAccountsBuilder } from './manageAccounts';\nimport type { ManageStateMethodHooks } from './manageState';\nimport { manageStateBuilder } from './manageState';\nimport type { NotifyMethodHooks } from './notify';\nimport { notifyBuilder } from './notify';\n\nexport { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';\n\nexport type RestrictedMethodHooks = DialogMethodHooks &\n GetBip32EntropyMethodHooks &\n GetBip32PublicKeyMethodHooks &\n GetBip44EntropyMethodHooks &\n GetEntropyHooks &\n InvokeSnapMethodHooks &\n ManageStateMethodHooks &\n NotifyMethodHooks &\n ManageAccountsMethodHooks &\n GetLocaleMethodHooks;\n\nexport const restrictedMethodPermissionBuilders = {\n [dialogBuilder.targetName]: dialogBuilder,\n [getBip32EntropyBuilder.targetName]: getBip32EntropyBuilder,\n [getBip32PublicKeyBuilder.targetName]: getBip32PublicKeyBuilder,\n [getBip44EntropyBuilder.targetName]: getBip44EntropyBuilder,\n [getEntropyBuilder.targetName]: getEntropyBuilder,\n [invokeSnapBuilder.targetName]: invokeSnapBuilder,\n [manageStateBuilder.targetName]: manageStateBuilder,\n [notifyBuilder.targetName]: notifyBuilder,\n [manageAccountsBuilder.targetName]: manageAccountsBuilder,\n [getLocaleBuilder.targetName]: getLocaleBuilder,\n} as const;\n\nexport * from './caveats';\n"],"names":["dialogBuilder","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","getLocaleBuilder","invokeSnapBuilder","manageAccountsBuilder","manageStateBuilder","notifyBuilder","WALLET_SNAP_PERMISSION_KEY","restrictedMethodPermissionBuilders","targetName"],"mappings":"AACA,SAASA,aAAa,QAAQ,WAAW;AAEzC,SAASC,sBAAsB,QAAQ,oBAAoB;AAE3D,SAASC,wBAAwB,QAAQ,sBAAsB;AAE/D,SAASC,sBAAsB,QAAQ,oBAAoB;AAE3D,SAASC,iBAAiB,QAAQ,eAAe;AAEjD,SAASC,gBAAgB,QAAQ,cAAc;AAE/C,SAASC,iBAAiB,QAAQ,eAAe;AAEjD,SAASC,qBAAqB,QAAQ,mBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,gBAAgB;AAEnD,SAASC,aAAa,QAAQ,WAAW;AAEzC,SAASC,0BAA0B,QAAQ,eAAe;AAa1D,OAAO,MAAMC,qCAAqC;IAChD,CAACX,cAAcY,UAAU,CAAC,EAAEZ;IAC5B,CAACC,uBAAuBW,UAAU,CAAC,EAAEX;IACrC,CAACC,yBAAyBU,UAAU,CAAC,EAAEV;IACvC,CAACC,uBAAuBS,UAAU,CAAC,EAAET;IACrC,CAACC,kBAAkBQ,UAAU,CAAC,EAAER;IAChC,CAACE,kBAAkBM,UAAU,CAAC,EAAEN;IAChC,CAACE,mBAAmBI,UAAU,CAAC,EAAEJ;IACjC,CAACC,cAAcG,UAAU,CAAC,EAAEH;IAC5B,CAACF,sBAAsBK,UAAU,CAAC,EAAEL;IACpC,CAACF,iBAAiBO,UAAU,CAAC,EAAEP;AACjC,EAAW;AAEX,cAAc,YAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/invokeSnap.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionSideEffect,\n} from '@metamask/permission-controller';\nimport { PermissionType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/invokeSnap.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionSideEffect,\n} from '@metamask/permission-controller';\nimport { PermissionType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeSnapResult,\n RequestSnapsParams,\n RequestSnapsResult,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\n// Redeclare installSnaps action type to avoid circular dependencies\nexport type InstallSnaps = {\n type: `SnapController:install`;\n handler: (\n origin: string,\n requestedSnaps: RequestSnapsParams,\n ) => Promise<RequestSnapsResult>;\n};\n\nexport type GetPermittedSnaps = {\n type: `SnapController:getPermitted`;\n handler: (origin: string) => RequestSnapsResult;\n};\n\ntype AllowedActions = InstallSnaps | GetPermittedSnaps;\n\nexport type InvokeSnapMethodHooks = {\n getSnap: (snapId: string) => Snap | undefined;\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: string }) => Promise<unknown>;\n};\n\ntype InvokeSnapSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: InvokeSnapMethodHooks;\n};\n\ntype InvokeSnapSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof WALLET_SNAP_PERMISSION_KEY;\n methodImplementation: ReturnType<typeof getInvokeSnapImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n sideEffect: {\n onPermitted: PermissionSideEffect<AllowedActions, never>['onPermitted'];\n };\n}>;\n\nexport type InvokeSnapParams = {\n snapId: string;\n request: Record<string, Json>;\n};\n\n/**\n * The side-effect method to handle the snap install.\n *\n * @param params - The side-effect params.\n * @param params.requestData - The request data associated to the requested permission.\n * @param params.messagingSystem - The messenger to call an action.\n */\nexport const handleSnapInstall: PermissionSideEffect<\n AllowedActions,\n never\n>['onPermitted'] = async ({ requestData, messagingSystem }) => {\n const snaps = requestData.permissions[WALLET_SNAP_PERMISSION_KEY].caveats?.[0]\n .value as RequestSnapsParams;\n\n const permittedSnaps = messagingSystem.call(\n `SnapController:getPermitted`,\n requestData.metadata.origin,\n );\n\n const dedupedSnaps = Object.keys(snaps).reduce<RequestSnapsParams>(\n (filteredSnaps, snap) => {\n if (!permittedSnaps[snap]) {\n filteredSnaps[snap] = snaps[snap];\n }\n return filteredSnaps;\n },\n {},\n );\n\n return messagingSystem.call(\n `SnapController:install`,\n requestData.metadata.origin,\n dedupedSnaps,\n );\n};\n/**\n * The specification builder for the `wallet_snap_*` permission.\n *\n * `wallet_snap_*` attempts to invoke an RPC method of the specified Snap.\n *\n * Requesting its corresponding permission will attempt to connect to the Snap,\n * and install it if it's not available yet.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `wallet_snap_*` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n InvokeSnapSpecificationBuilderOptions,\n InvokeSnapSpecification\n> = ({ methodHooks }: InvokeSnapSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: WALLET_SNAP_PERMISSION_KEY,\n allowedCaveats: [SnapCaveatType.SnapIds],\n methodImplementation: getInvokeSnapImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (caveats?.length !== 1 || caveats[0].type !== SnapCaveatType.SnapIds) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.SnapIds}\" caveat.`,\n });\n }\n },\n sideEffect: {\n onPermitted: handleSnapInstall,\n },\n };\n};\n\nconst methodHooks: MethodHooksObject<InvokeSnapMethodHooks> = {\n getSnap: true,\n handleSnapRpcRequest: true,\n};\n\nexport const invokeSnapBuilder = Object.freeze({\n targetName: WALLET_SNAP_PERMISSION_KEY,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `wallet_snap_*`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnap - A function that retrieves all information stored about a snap.\n * @param hooks.handleSnapRpcRequest - A function that sends an RPC request to a snap's RPC handler or throws if that fails.\n * @returns The method implementation which returns the result of `handleSnapRpcRequest`.\n * @throws If the params are invalid.\n */\nexport function getInvokeSnapImplementation({\n getSnap,\n handleSnapRpcRequest,\n}: InvokeSnapMethodHooks) {\n return async function invokeSnap(\n options: RestrictedMethodOptions<InvokeSnapParams>,\n ): Promise<InvokeSnapResult> {\n const { params = {}, context } = options;\n\n const { snapId, request } = params as InvokeSnapParams;\n\n if (!getSnap(snapId)) {\n throw rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n });\n }\n\n const { origin } = context;\n\n return (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnRpcRequest,\n })) as Json;\n };\n}\n"],"names":["PermissionType","rpcErrors","HandlerType","SnapCaveatType","WALLET_SNAP_PERMISSION_KEY","handleSnapInstall","requestData","messagingSystem","snaps","permissions","caveats","value","permittedSnaps","call","metadata","origin","dedupedSnaps","Object","keys","reduce","filteredSnaps","snap","specificationBuilder","methodHooks","permissionType","RestrictedMethod","targetName","allowedCaveats","SnapIds","methodImplementation","getInvokeSnapImplementation","validator","length","type","invalidParams","message","sideEffect","onPermitted","getSnap","handleSnapRpcRequest","invokeSnapBuilder","freeze","invokeSnap","options","params","context","snapId","request","invalidRequest","handler","OnRpcRequest"],"mappings":"AAOA,SAASA,cAAc,QAAQ,kCAAkC;AACjE,SAASC,SAAS,QAAQ,uBAAuB;AAOjD,SAASC,WAAW,EAAEC,cAAc,QAAQ,wBAAwB;AAKpE,OAAO,MAAMC,6BAA6B,cAAc;AAiDxD;;;;;;CAMC,GACD,OAAO,MAAMC,oBAGM,OAAO,EAAEC,WAAW,EAAEC,eAAe,EAAE;IACxD,MAAMC,QAAQF,YAAYG,WAAW,CAACL,2BAA2B,CAACM,OAAO,EAAE,CAAC,EAAE,CAC3EC;IAEH,MAAMC,iBAAiBL,gBAAgBM,IAAI,CACzC,CAAC,2BAA2B,CAAC,EAC7BP,YAAYQ,QAAQ,CAACC,MAAM;IAG7B,MAAMC,eAAeC,OAAOC,IAAI,CAACV,OAAOW,MAAM,CAC5C,CAACC,eAAeC;QACd,IAAI,CAACT,cAAc,CAACS,KAAK,EAAE;YACzBD,aAAa,CAACC,KAAK,GAAGb,KAAK,CAACa,KAAK;QACnC;QACA,OAAOD;IACT,GACA,CAAC;IAGH,OAAOb,gBAAgBM,IAAI,CACzB,CAAC,sBAAsB,CAAC,EACxBP,YAAYQ,QAAQ,CAACC,MAAM,EAC3BC;AAEJ,EAAE;AACF;;;;;;;;;;;CAWC,GACD,MAAMM,uBAIF,CAAC,EAAEC,WAAW,EAAyC;IACzD,OAAO;QACLC,gBAAgBxB,eAAeyB,gBAAgB;QAC/CC,YAAYtB;QACZuB,gBAAgB;YAACxB,eAAeyB,OAAO;SAAC;QACxCC,sBAAsBC,4BAA4BP;QAClDQ,WAAW,CAAC,EAAErB,OAAO,EAAE;YACrB,IAAIA,SAASsB,WAAW,KAAKtB,OAAO,CAAC,EAAE,CAACuB,IAAI,KAAK9B,eAAeyB,OAAO,EAAE;gBACvE,MAAM3B,UAAUiC,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEhC,eAAeyB,OAAO,CAAC,SAAS,CAAC;gBAClE;YACF;QACF;QACAQ,YAAY;YACVC,aAAahC;QACf;IACF;AACF;AAEA,MAAMkB,cAAwD;IAC5De,SAAS;IACTC,sBAAsB;AACxB;AAEA,OAAO,MAAMC,oBAAoBvB,OAAOwB,MAAM,CAAC;IAC7Cf,YAAYtB;IACZkB;IACAC;AACF,GAAY;AAEZ;;;;;;;;CAQC,GACD,OAAO,SAASO,4BAA4B,EAC1CQ,OAAO,EACPC,oBAAoB,EACE;IACtB,OAAO,eAAeG,WACpBC,OAAkD;QAElD,MAAM,EAAEC,SAAS,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAGF;QAEjC,MAAM,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAAGH;QAE5B,IAAI,CAACN,QAAQQ,SAAS;YACpB,MAAM7C,UAAU+C,cAAc,CAAC;gBAC7Bb,SAAS,CAAC,UAAU,EAAEW,OAAO,sEAAsE,CAAC;YACtG;QACF;QAEA,MAAM,EAAE/B,MAAM,EAAE,GAAG8B;QAEnB,OAAQ,MAAMN,qBAAqB;YACjCO;YACA/B;YACAgC;YACAE,SAAS/C,YAAYgD,YAAY;QACnC;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/manageAccounts.ts"],"sourcesContent":["import type {\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionSpecificationBuilder,\n} from '@metamask/permission-controller';\nimport { SubjectType, PermissionType } from '@metamask/permission-controller';\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/manageAccounts.ts"],"sourcesContent":["import type {\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionSpecificationBuilder,\n} from '@metamask/permission-controller';\nimport { SubjectType, PermissionType } from '@metamask/permission-controller';\nimport type {\n ManageAccountsParams,\n ManageAccountsResult,\n} from '@metamask/snaps-sdk';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { JsonStruct } from '@metamask/utils';\nimport { assert, string, object, union, array, record } from 'superstruct';\n\nconst SnapMessageStruct = union([\n object({\n method: string(),\n }),\n object({\n method: string(),\n params: union([array(JsonStruct), record(string(), JsonStruct)]),\n }),\n]);\n\ntype Message = InferMatching<typeof SnapMessageStruct, ManageAccountsParams>;\n\nexport const methodName = 'snap_manageAccounts';\n\nexport type ManageAccountsMethodHooks = {\n /**\n * Gets the snap keyring implementation.\n */\n getSnapKeyring: (snapOrigin: string) => Promise<{\n handleKeyringSnapMessage: (\n snapId: string,\n message: Message,\n ) => Promise<Json>;\n }>;\n};\n\ntype ManageAccountsSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageAccountsMethodHooks;\n};\n\ntype ManageAccountsSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof manageAccountsImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageAccounts` permission.\n * `snap_manageAccounts` lets the Snap manage a set of accounts via a custom keyring.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageAccounts` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageAccountsSpecificationBuilderOptions,\n ManageAccountsSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageAccountsSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: manageAccountsImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\n/**\n * Builds the method implementation for `snap_manageAccounts`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapKeyring - A function to get the snap keyring.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function manageAccountsImplementation({\n getSnapKeyring,\n}: ManageAccountsMethodHooks) {\n return async function manageAccounts(\n options: RestrictedMethodOptions<ManageAccountsParams>,\n ): Promise<ManageAccountsResult> {\n const {\n context: { origin },\n params,\n } = options;\n\n assert(params, SnapMessageStruct);\n const keyring = await getSnapKeyring(origin);\n return await keyring.handleKeyringSnapMessage(origin, params);\n };\n}\n\nexport const manageAccountsBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks: {\n getSnapKeyring: true,\n },\n} as const);\n"],"names":["SubjectType","PermissionType","JsonStruct","assert","string","object","union","array","record","SnapMessageStruct","method","params","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","manageAccountsImplementation","subjectTypes","Snap","getSnapKeyring","manageAccounts","options","context","origin","keyring","handleKeyringSnapMessage","manageAccountsBuilder","Object","freeze"],"mappings":"AAKA,SAASA,WAAW,EAAEC,cAAc,QAAQ,kCAAkC;AAO9E,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,QAAQ,cAAc;AAE3E,MAAMC,oBAAoBH,MAAM;IAC9BD,OAAO;QACLK,QAAQN;IACV;IACAC,OAAO;QACLK,QAAQN;QACRO,QAAQL,MAAM;YAACC,MAAML;YAAaM,OAAOJ,UAAUF;SAAY;IACjE;CACD;AAID,OAAO,MAAMU,aAAa,sBAAsB;AA0BhD;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAIT,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EAC+B;IAC1C,OAAO;QACLC,gBAAgBf,eAAegB,gBAAgB;QAC/CC,YAAYN;QACZE;QACAK,sBAAsBC,6BAA6BL;QACnDM,cAAc;YAACrB,YAAYsB,IAAI;SAAC;IAClC;AACF,EAAE;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASF,6BAA6B,EAC3CG,cAAc,EACY;IAC1B,OAAO,eAAeC,eACpBC,OAAsD;QAEtD,MAAM,EACJC,SAAS,EAAEC,MAAM,EAAE,EACnBhB,MAAM,EACP,GAAGc;QAEJtB,OAAOQ,QAAQF;QACf,MAAMmB,UAAU,MAAML,eAAeI;QACrC,OAAO,MAAMC,QAAQC,wBAAwB,CAACF,QAAQhB;IACxD;AACF;AAEA,OAAO,MAAMmB,wBAAwBC,OAAOC,MAAM,CAAC;IACjDd,YAAYN;IACZC;IACAE,aAAa;QACXQ,gBAAgB;IAClB;AACF,GAAY"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
+
import { ManageStateOperation } from '@metamask/snaps-sdk';
|
|
3
4
|
import { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';
|
|
4
5
|
import { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';
|
|
5
6
|
import { deriveEntropy } from '../utils';
|
|
@@ -40,12 +41,6 @@ export const manageStateBuilder = Object.freeze({
|
|
|
40
41
|
specificationBuilder,
|
|
41
42
|
methodHooks
|
|
42
43
|
});
|
|
43
|
-
export var ManageStateOperation;
|
|
44
|
-
(function(ManageStateOperation) {
|
|
45
|
-
ManageStateOperation["ClearState"] = 'clear';
|
|
46
|
-
ManageStateOperation["GetState"] = 'get';
|
|
47
|
-
ManageStateOperation["UpdateState"] = 'update';
|
|
48
|
-
})(ManageStateOperation || (ManageStateOperation = {}));
|
|
49
44
|
export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
50
45
|
/**
|
|
51
46
|
* Get a deterministic encryption key to use for encrypting and decrypting the
|
|
@@ -128,15 +123,15 @@ export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
|
128
123
|
*/ export function getManageStateImplementation({ getMnemonic, getUnlockPromise, clearSnapState, getSnapState, updateSnapState, encrypt, decrypt }) {
|
|
129
124
|
return async function manageState(options) {
|
|
130
125
|
const { params = {}, method, context: { origin } } = options;
|
|
131
|
-
const
|
|
126
|
+
const validatedParams = getValidatedParams(params, method);
|
|
132
127
|
// If the encrypted param is undefined or null we default to true.
|
|
133
|
-
const shouldEncrypt = encrypted ?? true;
|
|
128
|
+
const shouldEncrypt = validatedParams.encrypted ?? true;
|
|
134
129
|
// We only need to prompt the user when the mnemonic is needed
|
|
135
130
|
// which it isn't for the clear operation or unencrypted storage.
|
|
136
|
-
if (shouldEncrypt && operation !== ManageStateOperation.ClearState) {
|
|
131
|
+
if (shouldEncrypt && validatedParams.operation !== ManageStateOperation.ClearState) {
|
|
137
132
|
await getUnlockPromise(true);
|
|
138
133
|
}
|
|
139
|
-
switch(operation){
|
|
134
|
+
switch(validatedParams.operation){
|
|
140
135
|
case ManageStateOperation.ClearState:
|
|
141
136
|
clearSnapState(origin, shouldEncrypt);
|
|
142
137
|
return null;
|
|
@@ -155,18 +150,17 @@ export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
|
155
150
|
}
|
|
156
151
|
case ManageStateOperation.UpdateState:
|
|
157
152
|
{
|
|
158
|
-
assert(newState);
|
|
159
153
|
const finalizedState = shouldEncrypt ? await encryptState({
|
|
160
|
-
state: newState,
|
|
154
|
+
state: validatedParams.newState,
|
|
161
155
|
encryptFunction: encrypt,
|
|
162
156
|
mnemonicPhrase: await getMnemonic(),
|
|
163
157
|
snapId: origin
|
|
164
|
-
}) : JSON.stringify(newState);
|
|
158
|
+
}) : JSON.stringify(validatedParams.newState);
|
|
165
159
|
updateSnapState(origin, finalizedState, shouldEncrypt);
|
|
166
160
|
return null;
|
|
167
161
|
}
|
|
168
162
|
default:
|
|
169
|
-
throw rpcErrors.invalidParams(`Invalid ${method} operation: "${operation}"`);
|
|
163
|
+
throw rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
|
|
170
164
|
}
|
|
171
165
|
};
|
|
172
166
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { EnumToUnion } from '@metamask/snaps-utils';\nimport { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string, encrypted: boolean) => string;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: string,\n encrypted: boolean,\n ) => void;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport enum ManageStateOperation {\n ClearState = 'clear',\n GetState = 'get',\n UpdateState = 'update',\n}\n\nexport type ManageStateArgs = {\n operation: EnumToUnion<ManageStateOperation>;\n newState?: Record<string, Json>;\n encrypted?: boolean;\n};\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nasync function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateArgs>,\n ): Promise<null | Record<string, Json>> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const { operation, newState, encrypted } = getValidatedParams(\n params,\n method,\n );\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (shouldEncrypt && operation !== ManageStateOperation.ClearState) {\n await getUnlockPromise(true);\n }\n\n switch (operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = getSnapState(origin, shouldEncrypt);\n if (state === null) {\n return state;\n }\n return shouldEncrypt\n ? await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : parseJson<Record<string, Json>>(state);\n }\n\n case ManageStateOperation.UpdateState: {\n assert(newState);\n\n const finalizedState = shouldEncrypt\n ? await encryptState({\n state: newState,\n encryptFunction: encrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : JSON.stringify(newState);\n\n updateSnapState(origin, finalizedState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${operation as string}\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateArgs {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !(Object.values(ManageStateOperation) as string[]).includes(operation)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateArgs;\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","STATE_ENCRYPTION_MAGIC_VALUE","parseJson","isObject","getJsonSize","assert","isValidJson","deriveEntropy","STATE_ENCRYPTION_SALT","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getManageStateImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","manageStateBuilder","Object","freeze","ManageStateOperation","ClearState","GetState","UpdateState","STORAGE_SIZE_LIMIT","getEncryptionKey","mnemonicPhrase","snapId","input","salt","magic","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","internal","message","manageState","options","params","method","context","origin","operation","newState","encrypted","getValidatedParams","shouldEncrypt","finalizedState","JSON","stringify","invalidParams","storageSizeLimit","values","includes","undefined","data","receivedNewState","size"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,4BAA4B,EAAEC,SAAS,QAAQ,wBAAwB;AAEhF,SAASC,QAAQ,EAAEC,WAAW,EAAEC,MAAM,EAAEC,WAAW,QAAQ,kBAAkB;AAG7E,SAASC,aAAa,QAAQ,WAAW;AAEzC,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AiB,eAAe,CAAC;gBACtHI,MAAM;oBACJC,kBACE,OAAOb,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;IACF;IAEA,OAAOL;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string, encrypted: boolean) => string;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: string,\n encrypted: boolean,\n ) => void;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nasync function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = getSnapState(origin, shouldEncrypt);\n if (state === null) {\n return state;\n }\n return shouldEncrypt\n ? await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : parseJson<Record<string, Json>>(state);\n }\n\n case ManageStateOperation.UpdateState: {\n const finalizedState = shouldEncrypt\n ? await encryptState({\n state: validatedParams.newState,\n encryptFunction: encrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : JSON.stringify(validatedParams.newState);\n\n updateSnapState(origin, finalizedState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","ManageStateOperation","STATE_ENCRYPTION_MAGIC_VALUE","parseJson","isObject","getJsonSize","assert","isValidJson","deriveEntropy","STATE_ENCRYPTION_SALT","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getManageStateImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","manageStateBuilder","Object","freeze","STORAGE_SIZE_LIMIT","getEncryptionKey","mnemonicPhrase","snapId","input","salt","magic","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","internal","message","manageState","options","params","method","context","origin","validatedParams","getValidatedParams","shouldEncrypt","encrypted","operation","ClearState","GetState","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","values","includes","undefined","data","receivedNewState","size"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,oBAAoB,QAAQ,sBAAsB;AAC3D,SAASC,4BAA4B,EAAEC,SAAS,QAAQ,wBAAwB;AAEhF,SAASC,QAAQ,EAAEC,WAAW,EAAEC,MAAM,EAAEC,WAAW,QAAQ,kBAAkB;AAG7E,SAASC,aAAa,QAAQ,WAAW;AAEzC,oDAAoD;AACpD,OAAO,MAAMC,wBAAwB,8BAA8B;AAEnE,MAAMC,aAAa;AAuEnB;;;;;;;;;CASC,GACD,OAAO,MAAMC,uBAIT,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@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
-
import {
|
|
3
|
+
import { NotificationType } from '@metamask/snaps-sdk';
|
|
4
|
+
import { validateTextLinks } from '@metamask/snaps-utils';
|
|
4
5
|
import { isObject } from '@metamask/utils';
|
|
5
6
|
const methodName = 'snap_notify';
|
|
6
|
-
export var NotificationType;
|
|
7
|
-
(function(NotificationType) {
|
|
8
|
-
NotificationType["InApp"] = 'inApp';
|
|
9
|
-
NotificationType["Native"] = 'native';
|
|
10
|
-
})(NotificationType || (NotificationType = {}));
|
|
11
7
|
/**
|
|
12
8
|
* The specification builder for the `snap_notify` permission.
|
|
13
9
|
* `snap_notify` allows snaps to send multiple types of notifications to its users.
|
|
@@ -53,7 +49,7 @@ export const notifyBuilder = Object.freeze({
|
|
|
53
49
|
const { params, context: { origin } } = args;
|
|
54
50
|
const validatedParams = getValidatedParams(params);
|
|
55
51
|
await maybeUpdatePhishingList();
|
|
56
|
-
|
|
52
|
+
validateTextLinks(validatedParams.message, isOnPhishingList);
|
|
57
53
|
switch(validatedParams.type){
|
|
58
54
|
case NotificationType.Native:
|
|
59
55
|
return await showNativeNotification(origin, validatedParams);
|