@metamask/snaps-rpc-methods 11.12.0 → 11.13.0
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 +12 -1
- package/dist/endowments/caveats/requestTime.cjs +1 -2
- package/dist/endowments/caveats/requestTime.cjs.map +1 -1
- package/dist/endowments/caveats/requestTime.mjs +1 -2
- package/dist/endowments/caveats/requestTime.mjs.map +1 -1
- package/dist/endowments/rpc.cjs.map +1 -1
- package/dist/endowments/rpc.d.cts.map +1 -1
- package/dist/endowments/rpc.d.mts.map +1 -1
- package/dist/endowments/rpc.mjs.map +1 -1
- package/dist/permitted/getState.cjs.map +1 -1
- package/dist/permitted/getState.d.cts +1 -1
- package/dist/permitted/getState.d.cts.map +1 -1
- package/dist/permitted/getState.d.mts +1 -1
- package/dist/permitted/getState.d.mts.map +1 -1
- package/dist/permitted/getState.mjs.map +1 -1
- package/dist/permitted/handlers.cjs +2 -0
- package/dist/permitted/handlers.cjs.map +1 -1
- package/dist/permitted/handlers.d.cts +2 -1
- package/dist/permitted/handlers.d.cts.map +1 -1
- package/dist/permitted/handlers.d.mts +2 -1
- package/dist/permitted/handlers.d.mts.map +1 -1
- package/dist/permitted/handlers.mjs +2 -0
- package/dist/permitted/handlers.mjs.map +1 -1
- package/dist/permitted/index.cjs.map +1 -1
- package/dist/permitted/index.d.cts +2 -1
- package/dist/permitted/index.d.cts.map +1 -1
- package/dist/permitted/index.d.mts +2 -1
- package/dist/permitted/index.d.mts.map +1 -1
- package/dist/permitted/index.mjs.map +1 -1
- package/dist/permitted/invokeKeyring.cjs.map +1 -1
- package/dist/permitted/invokeKeyring.d.cts.map +1 -1
- package/dist/permitted/invokeKeyring.d.mts.map +1 -1
- package/dist/permitted/invokeKeyring.mjs.map +1 -1
- package/dist/permitted/listEntropySources.cjs +50 -0
- package/dist/permitted/listEntropySources.cjs.map +1 -0
- package/dist/permitted/listEntropySources.d.cts +19 -0
- package/dist/permitted/listEntropySources.d.cts.map +1 -0
- package/dist/permitted/listEntropySources.d.mts +19 -0
- package/dist/permitted/listEntropySources.d.mts.map +1 -0
- package/dist/permitted/listEntropySources.mjs +47 -0
- package/dist/permitted/listEntropySources.mjs.map +1 -0
- package/dist/permitted/middleware.cjs +1 -1
- package/dist/permitted/middleware.cjs.map +1 -1
- package/dist/permitted/middleware.mjs +1 -1
- package/dist/permitted/middleware.mjs.map +1 -1
- package/dist/permitted/resolveInterface.cjs.map +1 -1
- package/dist/permitted/resolveInterface.d.cts +1 -1
- package/dist/permitted/resolveInterface.d.cts.map +1 -1
- package/dist/permitted/resolveInterface.d.mts +1 -1
- package/dist/permitted/resolveInterface.d.mts.map +1 -1
- package/dist/permitted/resolveInterface.mjs.map +1 -1
- package/dist/permitted/scheduleBackgroundEvent.cjs.map +1 -1
- package/dist/permitted/scheduleBackgroundEvent.d.cts +1 -2
- package/dist/permitted/scheduleBackgroundEvent.d.cts.map +1 -1
- package/dist/permitted/scheduleBackgroundEvent.d.mts +1 -2
- package/dist/permitted/scheduleBackgroundEvent.d.mts.map +1 -1
- package/dist/permitted/scheduleBackgroundEvent.mjs.map +1 -1
- package/dist/permitted/setState.cjs +1 -3
- package/dist/permitted/setState.cjs.map +1 -1
- package/dist/permitted/setState.d.cts +1 -1
- package/dist/permitted/setState.d.cts.map +1 -1
- package/dist/permitted/setState.d.mts +1 -1
- package/dist/permitted/setState.d.mts.map +1 -1
- package/dist/permitted/setState.mjs +1 -3
- package/dist/permitted/setState.mjs.map +1 -1
- package/dist/restricted/caveats/index.cjs +3 -3
- package/dist/restricted/caveats/index.cjs.map +1 -1
- package/dist/restricted/caveats/index.mjs +3 -3
- package/dist/restricted/caveats/index.mjs.map +1 -1
- package/dist/restricted/caveats/permittedCoinTypes.cjs +7 -0
- package/dist/restricted/caveats/permittedCoinTypes.cjs.map +1 -1
- package/dist/restricted/caveats/permittedCoinTypes.d.cts.map +1 -1
- package/dist/restricted/caveats/permittedCoinTypes.d.mts.map +1 -1
- package/dist/restricted/caveats/permittedCoinTypes.mjs +7 -0
- package/dist/restricted/caveats/permittedCoinTypes.mjs.map +1 -1
- package/dist/restricted/getBip32Entropy.cjs +2 -1
- package/dist/restricted/getBip32Entropy.cjs.map +1 -1
- package/dist/restricted/getBip32Entropy.d.cts +7 -2
- package/dist/restricted/getBip32Entropy.d.cts.map +1 -1
- package/dist/restricted/getBip32Entropy.d.mts +7 -2
- package/dist/restricted/getBip32Entropy.d.mts.map +1 -1
- package/dist/restricted/getBip32Entropy.mjs +3 -2
- package/dist/restricted/getBip32Entropy.mjs.map +1 -1
- package/dist/restricted/getBip32PublicKey.cjs +3 -1
- package/dist/restricted/getBip32PublicKey.cjs.map +1 -1
- package/dist/restricted/getBip32PublicKey.d.cts +9 -2
- package/dist/restricted/getBip32PublicKey.d.cts.map +1 -1
- package/dist/restricted/getBip32PublicKey.d.mts +9 -2
- package/dist/restricted/getBip32PublicKey.d.mts.map +1 -1
- package/dist/restricted/getBip32PublicKey.mjs +5 -3
- package/dist/restricted/getBip32PublicKey.mjs.map +1 -1
- package/dist/restricted/getBip44Entropy.cjs +3 -1
- package/dist/restricted/getBip44Entropy.cjs.map +1 -1
- package/dist/restricted/getBip44Entropy.d.cts +7 -2
- package/dist/restricted/getBip44Entropy.d.cts.map +1 -1
- package/dist/restricted/getBip44Entropy.d.mts +7 -2
- package/dist/restricted/getBip44Entropy.d.mts.map +1 -1
- package/dist/restricted/getBip44Entropy.mjs +3 -1
- package/dist/restricted/getBip44Entropy.mjs.map +1 -1
- package/dist/restricted/getEntropy.cjs +2 -1
- package/dist/restricted/getEntropy.cjs.map +1 -1
- package/dist/restricted/getEntropy.d.cts +9 -2
- package/dist/restricted/getEntropy.d.cts.map +1 -1
- package/dist/restricted/getEntropy.d.mts +9 -2
- package/dist/restricted/getEntropy.d.mts.map +1 -1
- package/dist/restricted/getEntropy.mjs +3 -2
- package/dist/restricted/getEntropy.mjs.map +1 -1
- package/dist/restricted/index.d.cts +2 -2
- package/dist/restricted/index.d.mts +2 -2
- package/dist/restricted/notify.cjs.map +1 -1
- package/dist/restricted/notify.d.cts +4 -14
- package/dist/restricted/notify.d.cts.map +1 -1
- package/dist/restricted/notify.d.mts +4 -14
- package/dist/restricted/notify.d.mts.map +1 -1
- package/dist/restricted/notify.mjs.map +1 -1
- package/dist/utils.cjs +29 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +9 -0
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +9 -0
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +27 -0
- package/dist/utils.mjs.map +1 -1
- package/package.json +8 -22
|
@@ -2,8 +2,7 @@ import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPerm
|
|
|
2
2
|
import { PermissionType } from "@metamask/permission-controller";
|
|
3
3
|
import type { NotifyParams, NotifyResult, InterfaceContext, ComponentOrElement } from "@metamask/snaps-sdk";
|
|
4
4
|
import { ContentType } from "@metamask/snaps-sdk";
|
|
5
|
-
import {
|
|
6
|
-
import type { InferMatching } from "@metamask/snaps-utils";
|
|
5
|
+
import type { InferMatching, Snap } from "@metamask/snaps-utils";
|
|
7
6
|
import type { NonEmptyArray } from "@metamask/utils";
|
|
8
7
|
import { type MethodHooksObject } from "../utils.mjs";
|
|
9
8
|
declare const methodName = "snap_notify";
|
|
@@ -23,10 +22,7 @@ declare const NotificationParametersStruct: import("@metamask/superstruct").Stru
|
|
|
23
22
|
} | {
|
|
24
23
|
type: import("@metamask/snaps-sdk").NodeType.Divider;
|
|
25
24
|
} | {
|
|
26
|
-
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
27
|
-
* @param snapId - The ID of the Snap that created the notification.
|
|
28
|
-
* @param args - The notification arguments.
|
|
29
|
-
*/
|
|
25
|
+
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
30
26
|
value: string;
|
|
31
27
|
} | {
|
|
32
28
|
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
@@ -125,10 +121,7 @@ declare const NotificationParametersStruct: import("@metamask/superstruct").Stru
|
|
|
125
121
|
} | {
|
|
126
122
|
type: import("@metamask/snaps-sdk").NodeType.Divider;
|
|
127
123
|
} | {
|
|
128
|
-
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
129
|
-
* @param snapId - The ID of the Snap that created the notification.
|
|
130
|
-
* @param args - The notification arguments.
|
|
131
|
-
*/
|
|
124
|
+
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
132
125
|
value: string;
|
|
133
126
|
} | {
|
|
134
127
|
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
@@ -221,10 +214,7 @@ declare const NotificationParametersStruct: import("@metamask/superstruct").Stru
|
|
|
221
214
|
} | {
|
|
222
215
|
type: import("@metamask/snaps-sdk").NodeType.Divider;
|
|
223
216
|
} | {
|
|
224
|
-
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
225
|
-
* @param snapId - The ID of the Snap that created the notification.
|
|
226
|
-
* @param args - The notification arguments.
|
|
227
|
-
*/
|
|
217
|
+
type: import("@metamask/snaps-sdk").NodeType.Heading;
|
|
228
218
|
value: string;
|
|
229
219
|
} | {
|
|
230
220
|
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notify.d.mts","sourceRoot":"","sources":["../../src/restricted/notify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,EAC7B,wCAAwC;AACzC,OAAO,EAAE,cAAc,EAAe,wCAAwC;AAE9E,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EACnB,4BAA4B;AAC7B,OAAO,EAIL,WAAW,EAGZ,4BAA4B;
|
|
1
|
+
{"version":3,"file":"notify.d.mts","sourceRoot":"","sources":["../../src/restricted/notify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,8BAA8B,EAC9B,uB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AChC,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,EACrC,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EACL,yEAAyE;SAC5E,CAAC,CAAC;IACL,CAAC;IAED,IACE,IAAI,KAAK,gBAAgB,CAAC,KAAK;QAC/B,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC,EACtC,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EACL,0EAA0E;SAC7E,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,WAAW,CACjC,MAAM,EACN,4BAA4B,EAC5B,MAAM,CACP,CAAC;QAEF,iBAAiB,CAAC,eAAe,CAAC,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAEtE,IAAI,WAAW,CAAC,eAAe,EAAE,YAAY,CAAC,EAAE,CAAC;YAC/C,YAAY,CAAC,eAAe,CAAC,UAAU,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAC3E,CAAC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,mBAAmB,eAAe,CAAC,KAAK,CAAC,EAAE;SACrD,CAAC,CAAC;IACL,CAAC;AACH,CAAC","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 {\n NotifyParams,\n NotifyResult,\n InterfaceContext,\n ComponentOrElement,\n} from '@metamask/snaps-sdk';\nimport {\n enumValue,\n NotificationType,\n union,\n ContentType,\n getErrorMessage,\n ComponentOrElementStruct,\n} from '@metamask/snaps-sdk';\nimport {\n createUnion,\n validateLink,\n validateTextLinks,\n type Snap,\n} from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport { object, string, optional } from '@metamask/superstruct';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_notify';\n\nconst NativeNotificationStruct = object({\n type: enumValue(NotificationType.Native),\n message: string(),\n});\n\nconst InAppNotificationStruct = object({\n type: enumValue(NotificationType.InApp),\n message: string(),\n});\n\nconst InAppNotificationWithDetailsStruct = object({\n type: enumValue(NotificationType.InApp),\n message: string(),\n content: ComponentOrElementStruct,\n title: string(),\n footerLink: optional(\n object({\n href: string(),\n text: string(),\n }),\n ),\n});\n\nconst NotificationParametersStruct = union([\n InAppNotificationStruct,\n InAppNotificationWithDetailsStruct,\n NativeNotificationStruct,\n]);\n\nexport type NotificationArgs = InferMatching<\n typeof NotificationParametersStruct,\n NotifyParams\n>;\n\nexport type NotifyMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showNativeNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showInAppNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n isOnPhishingList: (url: string) => boolean;\n\n maybeUpdatePhishingList: () => Promise<void>;\n\n createInterface: (\n origin: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => Promise<string>;\n getSnap: (snapId: string) => Snap | undefined;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: NotifyMethodHooks;\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_notify` permission.\n * `snap_notify` allows snaps to send multiple types of notifications to its users.\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_notify` 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<NotifyMethodHooks> = {\n showNativeNotification: true,\n showInAppNotification: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n createInterface: true,\n getSnap: true,\n};\n\nexport const notifyBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_notify`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showNativeNotification - A function that shows a native browser notification.\n * @param hooks.showInAppNotification - A function that shows a notification in the MetaMask UI.\n * @param hooks.isOnPhishingList - A function that checks for links against the phishing list.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @param hooks.createInterface - A function that creates the interface in SnapInterfaceController.\n * @param hooks.getSnap - A function that checks if a snap is installed.\n * @returns The method implementation which returns `null` on success.\n * @throws If the params are invalid.\n */\nexport function getImplementation({\n showNativeNotification,\n showInAppNotification,\n isOnPhishingList,\n maybeUpdatePhishingList,\n createInterface,\n getSnap,\n}: NotifyMethodHooks) {\n return async function implementation(\n args: RestrictedMethodOptions<NotifyParams>,\n ): Promise<NotifyResult> {\n const {\n params,\n context: { origin },\n } = args;\n\n await maybeUpdatePhishingList();\n\n const validatedParams = getValidatedParams(\n params,\n isOnPhishingList,\n getSnap,\n );\n\n if (hasProperty(validatedParams, 'content')) {\n const id = await createInterface(\n origin,\n validatedParams.content as ComponentOrElement,\n undefined,\n ContentType.Notification,\n );\n validatedParams.content = id;\n }\n\n switch (validatedParams.type) {\n case NotificationType.Native:\n return await showNativeNotification(origin, validatedParams);\n case NotificationType.InApp:\n return await showInAppNotification(origin, validatedParams);\n default:\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n };\n}\n\n/**\n * Validates the notify 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 isOnPhishingList - The function that checks for links against the phishing list.\n * @param getSnap - A function that checks if a snap is installed.\n * @returns The validated method parameter object.\n * @throws If the params are invalid.\n */\nexport function getValidatedParams(\n params: unknown,\n isOnPhishingList: NotifyMethodHooks['isOnPhishingList'],\n getSnap: NotifyMethodHooks['getSnap'],\n): NotifyParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { type, message } = params;\n\n if (\n !type ||\n typeof type !== 'string' ||\n !Object.values(NotificationType).includes(type as NotificationType)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n\n const isNotString = !message || typeof message !== 'string';\n // Set to the max message length on a Mac notification for now.\n if (\n type === NotificationType.Native &&\n (isNotString || message.length >= 50)\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 50 characters long.',\n });\n }\n\n if (\n type === NotificationType.InApp &&\n (isNotString || message.length >= 500)\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 500 characters long.',\n });\n }\n\n try {\n const validatedParams = createUnion(\n params,\n NotificationParametersStruct,\n 'type',\n );\n\n validateTextLinks(validatedParams.message, isOnPhishingList, getSnap);\n\n if (hasProperty(validatedParams, 'footerLink')) {\n validateLink(validatedParams.footerLink.href, isOnPhishingList, getSnap);\n }\n\n return validatedParams;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${getErrorMessage(error)}`,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"notify.mjs","sourceRoot":"","sources":["../../src/restricted/notify.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,wCAAwC;AAC9E,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAOjD,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,KAAK,EACL,WAAW,EACX,eAAe,EACf,wBAAwB,EACzB,4BAA4B;AAC7B,OAAO,EACL,WAAW,EACX,YAAY,EACZ,iBAAiB,EAClB,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;AAEjE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAIxD,MAAM,UAAU,GAAG,aAAa,CAAC;AAEjC,MAAM,wBAAwB,GAAG,MAAM,CAAC;IACtC,IAAI,EAAE,SAAS,CAAC,gBAAgB,CAAC,MAAM,CAAC;IACxC,OAAO,EAAE,MAAM,EAAE;CAClB,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,MAAM,CAAC;IACrC,IAAI,EAAE,SAAS,CAAC,gBAAgB,CAAC,KAAK,CAAC;IACvC,OAAO,EAAE,MAAM,EAAE;CAClB,CAAC,CAAC;AAEH,MAAM,kCAAkC,GAAG,MAAM,CAAC;IAChD,IAAI,EAAE,SAAS,CAAC,gBAAgB,CAAC,KAAK,CAAC;IACvC,OAAO,EAAE,MAAM,EAAE;IACjB,OAAO,EAAE,wBAAwB;IACjC,KAAK,EAAE,MAAM,EAAE;IACf,UAAU,EAAE,QAAQ,CAClB,MAAM,CAAC;QACL,IAAI,EAAE,MAAM,EAAE;QACd,IAAI,EAAE,MAAM,EAAE;KACf,CAAC,CACH;CACF,CAAC,CAAC;AAEH,MAAM,4BAA4B,GAAG,KAAK,CAAC;IACzC,uBAAuB;IACvB,kCAA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EACL,yEAAyE;SAC5E,CAAC,CAAC;IACL,CAAC;IAED,IACE,IAAI,KAAK,gBAAgB,CAAC,KAAK;QAC/B,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC,EACtC,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EACL,0EAA0E;SAC7E,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,WAAW,CACjC,MAAM,EACN,4BAA4B,EAC5B,MAAM,CACP,CAAC;QAEF,iBAAiB,CAAC,eAAe,CAAC,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAEtE,IAAI,WAAW,CAAC,eAAe,EAAE,YAAY,CAAC,EAAE,CAAC;YAC/C,YAAY,CAAC,eAAe,CAAC,UAAU,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAC3E,CAAC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,mBAAmB,eAAe,CAAC,KAAK,CAAC,EAAE;SACrD,CAAC,CAAC;IACL,CAAC;AACH,CAAC","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 {\n NotifyParams,\n NotifyResult,\n InterfaceContext,\n ComponentOrElement,\n} from '@metamask/snaps-sdk';\nimport {\n enumValue,\n NotificationType,\n union,\n ContentType,\n getErrorMessage,\n ComponentOrElementStruct,\n} from '@metamask/snaps-sdk';\nimport {\n createUnion,\n validateLink,\n validateTextLinks,\n} from '@metamask/snaps-utils';\nimport type { InferMatching, Snap } from '@metamask/snaps-utils';\nimport { object, string, optional } from '@metamask/superstruct';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_notify';\n\nconst NativeNotificationStruct = object({\n type: enumValue(NotificationType.Native),\n message: string(),\n});\n\nconst InAppNotificationStruct = object({\n type: enumValue(NotificationType.InApp),\n message: string(),\n});\n\nconst InAppNotificationWithDetailsStruct = object({\n type: enumValue(NotificationType.InApp),\n message: string(),\n content: ComponentOrElementStruct,\n title: string(),\n footerLink: optional(\n object({\n href: string(),\n text: string(),\n }),\n ),\n});\n\nconst NotificationParametersStruct = union([\n InAppNotificationStruct,\n InAppNotificationWithDetailsStruct,\n NativeNotificationStruct,\n]);\n\nexport type NotificationArgs = InferMatching<\n typeof NotificationParametersStruct,\n NotifyParams\n>;\n\nexport type NotifyMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showNativeNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showInAppNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n isOnPhishingList: (url: string) => boolean;\n\n maybeUpdatePhishingList: () => Promise<void>;\n\n createInterface: (\n origin: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => Promise<string>;\n getSnap: (snapId: string) => Snap | undefined;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: NotifyMethodHooks;\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_notify` permission.\n * `snap_notify` allows snaps to send multiple types of notifications to its users.\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_notify` 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<NotifyMethodHooks> = {\n showNativeNotification: true,\n showInAppNotification: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n createInterface: true,\n getSnap: true,\n};\n\nexport const notifyBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_notify`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showNativeNotification - A function that shows a native browser notification.\n * @param hooks.showInAppNotification - A function that shows a notification in the MetaMask UI.\n * @param hooks.isOnPhishingList - A function that checks for links against the phishing list.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @param hooks.createInterface - A function that creates the interface in SnapInterfaceController.\n * @param hooks.getSnap - A function that checks if a snap is installed.\n * @returns The method implementation which returns `null` on success.\n * @throws If the params are invalid.\n */\nexport function getImplementation({\n showNativeNotification,\n showInAppNotification,\n isOnPhishingList,\n maybeUpdatePhishingList,\n createInterface,\n getSnap,\n}: NotifyMethodHooks) {\n return async function implementation(\n args: RestrictedMethodOptions<NotifyParams>,\n ): Promise<NotifyResult> {\n const {\n params,\n context: { origin },\n } = args;\n\n await maybeUpdatePhishingList();\n\n const validatedParams = getValidatedParams(\n params,\n isOnPhishingList,\n getSnap,\n );\n\n if (hasProperty(validatedParams, 'content')) {\n const id = await createInterface(\n origin,\n validatedParams.content as ComponentOrElement,\n undefined,\n ContentType.Notification,\n );\n validatedParams.content = id;\n }\n\n switch (validatedParams.type) {\n case NotificationType.Native:\n return await showNativeNotification(origin, validatedParams);\n case NotificationType.InApp:\n return await showInAppNotification(origin, validatedParams);\n default:\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n };\n}\n\n/**\n * Validates the notify 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 isOnPhishingList - The function that checks for links against the phishing list.\n * @param getSnap - A function that checks if a snap is installed.\n * @returns The validated method parameter object.\n * @throws If the params are invalid.\n */\nexport function getValidatedParams(\n params: unknown,\n isOnPhishingList: NotifyMethodHooks['isOnPhishingList'],\n getSnap: NotifyMethodHooks['getSnap'],\n): NotifyParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { type, message } = params;\n\n if (\n !type ||\n typeof type !== 'string' ||\n !Object.values(NotificationType).includes(type as NotificationType)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n\n const isNotString = !message || typeof message !== 'string';\n // Set to the max message length on a Mac notification for now.\n if (\n type === NotificationType.Native &&\n (isNotString || message.length >= 50)\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 50 characters long.',\n });\n }\n\n if (\n type === NotificationType.InApp &&\n (isNotString || message.length >= 500)\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 500 characters long.',\n });\n }\n\n try {\n const validatedParams = createUnion(\n params,\n NotificationParametersStruct,\n 'type',\n );\n\n validateTextLinks(validatedParams.message, isOnPhishingList, getSnap);\n\n if (hasProperty(validatedParams, 'footerLink')) {\n validateLink(validatedParams.footerLink.href, isOnPhishingList, getSnap);\n }\n\n return validatedParams;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${getErrorMessage(error)}`,\n });\n }\n}\n"]}
|
package/dist/utils.cjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.StateKeyStruct = exports.isValidStateKey = exports.getNode = exports.getPathPrefix = exports.deriveEntropy = exports.selectHooks = exports.FORBIDDEN_KEYS = void 0;
|
|
3
|
+
exports.getSecretRecoveryPhrase = exports.StateKeyStruct = exports.isValidStateKey = exports.getNode = exports.getPathPrefix = exports.deriveEntropy = exports.selectHooks = exports.FORBIDDEN_KEYS = void 0;
|
|
4
4
|
const key_tree_1 = require("@metamask/key-tree");
|
|
5
|
+
const rpc_errors_1 = require("@metamask/rpc-errors");
|
|
5
6
|
const superstruct_1 = require("@metamask/superstruct");
|
|
6
7
|
const utils_1 = require("@metamask/utils");
|
|
7
8
|
const sha3_1 = require("@noble/hashes/sha3");
|
|
@@ -162,4 +163,31 @@ exports.StateKeyStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(),
|
|
|
162
163
|
}
|
|
163
164
|
return true;
|
|
164
165
|
});
|
|
166
|
+
/**
|
|
167
|
+
* Get the secret recovery phrase of the user. This calls the `getMnemonic` hook
|
|
168
|
+
* and handles any errors that occur, throwing formatted JSON-RPC errors.
|
|
169
|
+
*
|
|
170
|
+
* @param getMnemonic - The `getMnemonic` hook.
|
|
171
|
+
* @param source - The entropy source to use.
|
|
172
|
+
* @returns The secret recovery phrase.
|
|
173
|
+
*/
|
|
174
|
+
async function getSecretRecoveryPhrase(getMnemonic, source) {
|
|
175
|
+
try {
|
|
176
|
+
return await getMnemonic(source);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error instanceof Error) {
|
|
180
|
+
throw rpc_errors_1.rpcErrors.invalidParams({
|
|
181
|
+
message: error.message,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
throw rpc_errors_1.rpcErrors.internal({
|
|
185
|
+
message: 'An unknown error occurred.',
|
|
186
|
+
data: {
|
|
187
|
+
error: error.toString(),
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
exports.getSecretRecoveryPhrase = getSecretRecoveryPhrase;
|
|
165
193
|
//# sourceMappingURL=utils.cjs.map
|
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAOA,iDAAgD;AAEhD,uDAAuD;AAEvD,2CAOyB;AACzB,6CAA6D;AAE7D,MAAM,cAAc,GAAG,UAAU,CAAC;AAErB,QAAA,cAAc,GAAG,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AAWxE;;;;;;;;;;;GAWG;AACH,SAAgB,WAAW,CAIzB,KAAY,EACZ,SAAqC;IAErC,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAClC,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,SAAqB,CAAC;YACvC,UAAU,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,UAAU,CAAC;QACpB,CAAC,EACD,EAAE,CACsB,CAAC;IAC7B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAlBD,kCAkBC;AAED;;;;;;GAMG;AACH,SAAS,sBAAsB,CAAC,IAAgB;IAC9C,MAAM,KAAK,GAAwB,EAAE,CAAC;IACtC,MAAM,IAAI,GAAG,IAAA,sBAAc,EAAC,IAAI,CAAC,CAAC;IAElC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACvC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAEzC,2EAA2E;QAC3E,0EAA0E;QAC1E,mCAAmC;QACnC,sCAAsC;QACtC,MA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AAC;QAChB;YACE,OAAO,IAAA,wBAAgB,EAAC,KAAK,CAAC,CAAC;IACnC,CAAC;AACH,CAAC;AAbD,sCAaC;AASD;;;;;;;;;;;;;;;GAeG;AACI,KAAK,UAAU,OAAO,CAAC,EAC5B,KAAK,EACL,oBAAoB,EACpB,IAAI,EACJ,sBAAsB,GACV;IACZ,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAEpC,OAAO,MAAM,qBAAU,CAAC,kBAAkB,CACxC;QACE,KAAK;QACL,cAAc,EAAE;YACd,oBAAoB;YACpB,GAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,CAEhC;SACtB;KACF,EACD,sBAAsB,CACvB,CAAC;AACJ,CAAC;AApBD,0BAoBC;AAED;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,GAAuB;IACrD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACzD,CAAC;AAND,0CAMC;AAEY,QAAA,cAAc,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE;IACpE,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,4DAA4D,CAAC;IACtE,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n cryptographicFunctions,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath(\n {\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype GetNodeArgs = {\n curve: SupportedCurve;\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n"]}
|
|
1
|
+
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAOA,iDAAgD;AAChD,qDAAiD;AAEjD,uDAAuD;AAEvD,2CAOyB;AACzB,6CAA6D;AAE7D,MAAM,cAAc,GAAG,UAAU,CAAC;AAErB,QAAA,cAAc,GAAG,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AAWxE;;;;;;;;;;;GAWG;AACH,SAAgB,WAAW,CAIzB,KAAY,EACZ,SAAqC;IAErC,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAClC,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,SAAqB,CAAC;YACvC,UAAU,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,UAAU,CAAC;QACpB,CAAC,EACD,EAAE,CACsB,CAAC;IAC7B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAlBD,kCAkBC;AAED;;;;;;GAMG;AACH,SAAS,sBAAsB,CAAC,IAAgB;IAC9C,MAAM,KAAK,GAAwB,EAAE,CAAC;IACtC,MAAM,IAAI,GAAG,IAAA,sBAAc,EAAC,IAAI,CAAC,CAAC;IAElC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACvC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAEzC,2EAA2E;QAC3E,0EAA0E;QAC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,MAAM,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC3B,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;QACL,CAAC;QAED,MAAM,sBAAS,CAAC,QAAQ,CAAC;YACvB,OAAO,EAAE,4BAA4B;YACrC,IAAI,EAAE;gBACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;aACxB;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AApBD,0DAoBC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n cryptographicFunctions,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath(\n {\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype GetNodeArgs = {\n curve: SupportedCurve;\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n\n/**\n * Get the secret recovery phrase of the user. This calls the `getMnemonic` hook\n * and handles any errors that occur, throwing formatted JSON-RPC errors.\n *\n * @param getMnemonic - The `getMnemonic` hook.\n * @param source - The entropy source to use.\n * @returns The secret recovery phrase.\n */\nexport async function getSecretRecoveryPhrase(\n getMnemonic: (source?: string | undefined) => Promise<Uint8Array>,\n source?: string | undefined,\n): Promise<Uint8Array> {\n try {\n return await getMnemonic(source);\n } catch (error) {\n if (error instanceof Error) {\n throw rpcErrors.invalidParams({\n message: error.message,\n });\n }\n\n throw rpcErrors.internal({\n message: 'An unknown error occurred.',\n data: {\n error: error.toString(),\n },\n });\n }\n}\n"]}
|
package/dist/utils.d.cts
CHANGED
|
@@ -112,5 +112,14 @@ export declare function getNode({ curve, secretRecoveryPhrase, path, cryptograph
|
|
|
112
112
|
*/
|
|
113
113
|
export declare function isValidStateKey(key: string | undefined): boolean;
|
|
114
114
|
export declare const StateKeyStruct: import("@metamask/superstruct").Struct<string, null>;
|
|
115
|
+
/**
|
|
116
|
+
* Get the secret recovery phrase of the user. This calls the `getMnemonic` hook
|
|
117
|
+
* and handles any errors that occur, throwing formatted JSON-RPC errors.
|
|
118
|
+
*
|
|
119
|
+
* @param getMnemonic - The `getMnemonic` hook.
|
|
120
|
+
* @param source - The entropy source to use.
|
|
121
|
+
* @returns The secret recovery phrase.
|
|
122
|
+
*/
|
|
123
|
+
export declare function getSecretRecoveryPhrase(getMnemonic: (source?: string | undefined) => Promise<Uint8Array>, source?: string | undefined): Promise<Uint8Array>;
|
|
115
124
|
export {};
|
|
116
125
|
//# sourceMappingURL=utils.d.cts.map
|
package/dist/utils.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,cAAc,EACd,sBAAsB,EACvB,2BAA2B;AAC5B,OAAO,EAAE,UAAU,EAAE,2BAA2B;
|
|
1
|
+
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,cAAc,EACd,sBAAsB,EACvB,2BAA2B;AAC5B,OAAO,EAAE,UAAU,EAAE,2BAA2B;AAEhD,OAAO,KAAK,EAAE,UAAU,EAAE,8BAA8B;AAExD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAa3C,eAAO,MAAM,cAAc,UAA4C,CAAC;AAExE;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,SAAS,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;KACxE,GAAG,IAAI,MAAM,SAAS,GAAG,IAAI;CAC/B,CAAC;AAEF;;;;;;;;;;;GAWG;AAC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sDAMzB,CAAC;AAEH;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,EACjE,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,GAC1B,OAAO,CAAC,UAAU,CAAC,CAiBrB"}
|
package/dist/utils.d.mts
CHANGED
|
@@ -112,5 +112,14 @@ export declare function getNode({ curve, secretRecoveryPhrase, path, cryptograph
|
|
|
112
112
|
*/
|
|
113
113
|
export declare function isValidStateKey(key: string | undefined): boolean;
|
|
114
114
|
export declare const StateKeyStruct: import("@metamask/superstruct").Struct<string, null>;
|
|
115
|
+
/**
|
|
116
|
+
* Get the secret recovery phrase of the user. This calls the `getMnemonic` hook
|
|
117
|
+
* and handles any errors that occur, throwing formatted JSON-RPC errors.
|
|
118
|
+
*
|
|
119
|
+
* @param getMnemonic - The `getMnemonic` hook.
|
|
120
|
+
* @param source - The entropy source to use.
|
|
121
|
+
* @returns The secret recovery phrase.
|
|
122
|
+
*/
|
|
123
|
+
export declare function getSecretRecoveryPhrase(getMnemonic: (source?: string | undefined) => Promise<Uint8Array>, source?: string | undefined): Promise<Uint8Array>;
|
|
115
124
|
export {};
|
|
116
125
|
//# sourceMappingURL=utils.d.mts.map
|
package/dist/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,cAAc,EACd,sBAAsB,EACvB,2BAA2B;AAC5B,OAAO,EAAE,UAAU,EAAE,2BAA2B;
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,cAAc,EACd,sBAAsB,EACvB,2BAA2B;AAC5B,OAAO,EAAE,UAAU,EAAE,2BAA2B;AAEhD,OAAO,KAAK,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IACf,sBAAsB,EAAE,sBAAsB,GAAG,SAAS,CAAC;CAC5D,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,OAAO,CAAC,EAC5B,KAAK,EACL,oBAAoB,EACpB,IAAI,EACJ,sBAAsB,GACvB,EAAE,WAAW,uBAeb;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,WAMtD;AAED,eAAO,MAAM,cAAc,sDAMzB,CAAC;AAEH;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,EACjE,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,GAC1B,OAAO,CAAC,UAAU,CAAC,CAiBrB"}
|
package/dist/utils.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SLIP10Node } from "@metamask/key-tree";
|
|
2
|
+
import { rpcErrors } from "@metamask/rpc-errors";
|
|
2
3
|
import { refine, string } from "@metamask/superstruct";
|
|
3
4
|
import { assertExhaustive, add0x, assert, concatBytes, createDataView, stringToBytes } from "@metamask/utils";
|
|
4
5
|
import { keccak_256 as keccak256 } from "@noble/hashes/sha3";
|
|
@@ -154,4 +155,30 @@ export const StateKeyStruct = refine(string(), 'state key', (value) => {
|
|
|
154
155
|
}
|
|
155
156
|
return true;
|
|
156
157
|
});
|
|
158
|
+
/**
|
|
159
|
+
* Get the secret recovery phrase of the user. This calls the `getMnemonic` hook
|
|
160
|
+
* and handles any errors that occur, throwing formatted JSON-RPC errors.
|
|
161
|
+
*
|
|
162
|
+
* @param getMnemonic - The `getMnemonic` hook.
|
|
163
|
+
* @param source - The entropy source to use.
|
|
164
|
+
* @returns The secret recovery phrase.
|
|
165
|
+
*/
|
|
166
|
+
export async function getSecretRecoveryPhrase(getMnemonic, source) {
|
|
167
|
+
try {
|
|
168
|
+
return await getMnemonic(source);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (error instanceof Error) {
|
|
172
|
+
throw rpcErrors.invalidParams({
|
|
173
|
+
message: error.message,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
throw rpcErrors.internal({
|
|
177
|
+
message: 'An unknown error occurred.',
|
|
178
|
+
data: {
|
|
179
|
+
error: error.toString(),
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
157
184
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,2BAA2B;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,8BAA8B;AAEvD,OAAO,EACL,gBAAgB,EAChB,KAAK,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,aAAa,EACd,wBAAwB;AACzB,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,2BAA2B;AAE7D,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AAWxE;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW,CAIzB,KAAY,EACZ,SAAqC;IAErC,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAClC,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,SAAqB,CAAC;YACvC,UAAU,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,UAAU,CAAC;QACpB,CAAC,EACD,EAAE,CACsB,CAAC;IAC7B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAA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,EAAE;IACpE,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,4DAA4D,CAAC;IACtE,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n cryptographicFunctions,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath(\n {\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype GetNodeArgs = {\n curve: SupportedCurve;\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n"]}
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,2BAA2B;AAChD,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,8BAA8B;AAEvD,OAAO,EACL,gBAAgB,EAChB,KAAK,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,aAAa,EACd,wBAAwB;AACzB,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,2BAA2B;AAE7D,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;AAWxE;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW,CAIzB,KAAY,EACZ,SAAqC;IAErC,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAClC,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,SAAqB,CAAC;YACvC,UAAU,CAAC,QAAQ,CAA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I,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE;IACpE,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,4DAA4D,CAAC;IACtE,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC;AAEH;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,WAAiE,EACjE,MAA2B;IAE3B,IAAI,CAAC;QACH,OAAO,MAAM,WAAW,CAAC,MAAM,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC3B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;QACL,CAAC;QAED,MAAM,SAAS,CAAC,QAAQ,CAAC;YACvB,OAAO,EAAE,4BAA4B;YACrC,IAAI,EAAE;gBACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;aACxB;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n cryptographicFunctions,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath(\n {\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype GetNodeArgs = {\n curve: SupportedCurve;\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n\n/**\n * Get the secret recovery phrase of the user. This calls the `getMnemonic` hook\n * and handles any errors that occur, throwing formatted JSON-RPC errors.\n *\n * @param getMnemonic - The `getMnemonic` hook.\n * @param source - The entropy source to use.\n * @returns The secret recovery phrase.\n */\nexport async function getSecretRecoveryPhrase(\n getMnemonic: (source?: string | undefined) => Promise<Uint8Array>,\n source?: string | undefined,\n): Promise<Uint8Array> {\n try {\n return await getMnemonic(source);\n } catch (error) {\n if (error instanceof Error) {\n throw rpcErrors.invalidParams({\n message: error.message,\n });\n }\n\n throw rpcErrors.internal({\n message: 'An unknown error occurred.',\n data: {\n error: error.toString(),\n },\n });\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-rpc-methods",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.13.0",
|
|
4
4
|
"description": "MetaMask Snaps JSON-RPC method implementations",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -43,9 +43,9 @@
|
|
|
43
43
|
"lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies",
|
|
44
44
|
"lint:ci": "yarn lint",
|
|
45
45
|
"lint:dependencies": "depcheck",
|
|
46
|
-
"lint:eslint": "eslint . --cache
|
|
46
|
+
"lint:eslint": "eslint . --cache",
|
|
47
47
|
"lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
|
|
48
|
-
"lint:misc": "prettier --no-error-on-unmatched-pattern --
|
|
48
|
+
"lint:misc": "prettier --no-error-on-unmatched-pattern --log-level warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" --ignore-path ../../.gitignore",
|
|
49
49
|
"publish:preview": "yarn npm publish --tag preview",
|
|
50
50
|
"since-latest-release": "../../scripts/since-latest-release.sh",
|
|
51
51
|
"test": "jest --reporters=jest-silent-reporter",
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
"@metamask/key-tree": "^10.0.2",
|
|
59
59
|
"@metamask/permission-controller": "^11.0.6",
|
|
60
60
|
"@metamask/rpc-errors": "^7.0.2",
|
|
61
|
-
"@metamask/snaps-sdk": "^6.
|
|
62
|
-
"@metamask/snaps-utils": "^9.0.
|
|
61
|
+
"@metamask/snaps-sdk": "^6.19.0",
|
|
62
|
+
"@metamask/snaps-utils": "^9.0.1",
|
|
63
63
|
"@metamask/superstruct": "^3.1.0",
|
|
64
64
|
"@metamask/utils": "^11.2.0",
|
|
65
65
|
"@noble/hashes": "^1.3.1",
|
|
@@ -67,34 +67,20 @@
|
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
70
|
-
"@metamask/auto-changelog": "^
|
|
71
|
-
"@metamask/eslint-config": "^12.1.0",
|
|
72
|
-
"@metamask/eslint-config-jest": "^12.1.0",
|
|
73
|
-
"@metamask/eslint-config-nodejs": "^12.1.0",
|
|
74
|
-
"@metamask/eslint-config-typescript": "^12.1.0",
|
|
70
|
+
"@metamask/auto-changelog": "^4.1.0",
|
|
75
71
|
"@metamask/json-rpc-engine": "^10.0.2",
|
|
76
72
|
"@swc/core": "1.3.78",
|
|
77
73
|
"@swc/jest": "^0.2.26",
|
|
78
74
|
"@ts-bridge/cli": "^0.6.1",
|
|
79
75
|
"@types/luxon": "^3",
|
|
80
76
|
"@types/node": "18.14.2",
|
|
81
|
-
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
|
82
|
-
"@typescript-eslint/parser": "^6.21.0",
|
|
83
77
|
"deepmerge": "^4.2.2",
|
|
84
78
|
"depcheck": "^1.4.7",
|
|
85
|
-
"eslint": "^
|
|
86
|
-
"eslint-config-prettier": "^8.5.0",
|
|
87
|
-
"eslint-plugin-import": "^2.26.0",
|
|
88
|
-
"eslint-plugin-jest": "^27.1.5",
|
|
89
|
-
"eslint-plugin-jsdoc": "^41.1.2",
|
|
90
|
-
"eslint-plugin-n": "^15.7.0",
|
|
91
|
-
"eslint-plugin-prettier": "^4.2.1",
|
|
92
|
-
"eslint-plugin-promise": "^6.1.1",
|
|
79
|
+
"eslint": "^9.11.0",
|
|
93
80
|
"jest": "^29.0.2",
|
|
94
81
|
"jest-it-up": "^2.0.0",
|
|
95
82
|
"jest-silent-reporter": "^0.6.0",
|
|
96
|
-
"prettier": "^
|
|
97
|
-
"prettier-plugin-packagejson": "^2.5.2",
|
|
83
|
+
"prettier": "^3.3.3",
|
|
98
84
|
"typescript": "~5.3.3"
|
|
99
85
|
},
|
|
100
86
|
"engines": {
|