@metamask/snaps-rpc-methods 8.0.0 → 9.0.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 +15 -1
- package/dist/{chunk-MXCJWR45.mjs → chunk-2CTOCP34.mjs} +8 -8
- package/dist/chunk-2CTOCP34.mjs.map +1 -0
- package/dist/{chunk-TKXU7ZXP.mjs → chunk-2L2ATCIK.mjs} +2 -2
- package/dist/{chunk-YG7W4CDT.js → chunk-33MTKZ4H.js} +11 -4
- package/dist/chunk-33MTKZ4H.js.map +1 -0
- package/dist/{chunk-LGUJMQC7.js → chunk-4BPNRCZJ.js} +5 -4
- package/dist/chunk-4BPNRCZJ.js.map +1 -0
- package/dist/{chunk-WLDEPJGG.mjs → chunk-634BK2VP.mjs} +3 -3
- package/dist/chunk-634BK2VP.mjs.map +1 -0
- package/dist/{chunk-7OMVZR5X.mjs → chunk-CJPFADO7.mjs} +3 -3
- package/dist/{chunk-GP5KW5FU.js → chunk-D5WQBUZB.js} +2 -2
- package/dist/chunk-D5WQBUZB.js.map +1 -0
- package/dist/{chunk-IDZGMGIB.js → chunk-DLVPMPRZ.js} +8 -8
- package/dist/chunk-DLVPMPRZ.js.map +1 -0
- package/dist/{chunk-AOWUGDER.js → chunk-E27BGHCR.js} +3 -3
- package/dist/{chunk-Y4LNTDZ2.mjs → chunk-FR26QD3N.mjs} +3 -3
- package/dist/{chunk-YS6TYXCP.mjs → chunk-GVJLWGSI.mjs} +3 -3
- package/dist/chunk-GVJLWGSI.mjs.map +1 -0
- package/dist/{chunk-SU6KOIVB.mjs → chunk-I3QG3QZL.mjs} +6 -6
- package/dist/{chunk-GYZV5UBD.js → chunk-I7DR6BFO.js} +4 -4
- package/dist/chunk-I7DR6BFO.js.map +1 -0
- package/dist/{chunk-S7AR3ROH.js → chunk-IE6EHYEG.js} +3 -3
- package/dist/{chunk-Q5W3YGEB.js → chunk-IVD2ORDS.js} +3 -3
- package/dist/{chunk-IBV23QOX.mjs → chunk-KIXPIIY5.mjs} +2 -2
- package/dist/{chunk-AYJK7MSH.js → chunk-LLH2T5NT.js} +5 -5
- package/dist/{chunk-TNRH2LRU.mjs → chunk-LXJBBRQ4.mjs} +2 -2
- package/dist/{chunk-R2M4YLJ7.js → chunk-M2JQCKR7.js} +3 -3
- package/dist/{chunk-RZXF4KSR.js → chunk-O2VSIMDY.js} +11 -11
- package/dist/{chunk-EGKFC56F.js → chunk-QAKSH24Z.js} +8 -8
- package/dist/{chunk-6WUIFFMQ.mjs → chunk-R3DRYUNH.mjs} +5 -4
- package/dist/chunk-R3DRYUNH.mjs.map +1 -0
- package/dist/{chunk-JQ456NCC.mjs → chunk-S46RTIDR.mjs} +5 -5
- package/dist/{chunk-NESDQ4PF.mjs → chunk-TE4W25CA.mjs} +2 -2
- package/dist/{chunk-AMBEX4N4.mjs → chunk-TUIJOZXZ.mjs} +4 -4
- package/dist/{chunk-3LPBU737.js → chunk-UDB4MUXI.js} +2 -2
- package/dist/chunk-UDB4MUXI.js.map +1 -0
- package/dist/{chunk-6UY23OOZ.js → chunk-VBCE6VHM.js} +5 -5
- package/dist/{chunk-SGQXD5K7.mjs → chunk-W33UWNA2.mjs} +11 -4
- package/dist/chunk-W33UWNA2.mjs.map +1 -0
- package/dist/{chunk-4SQWLI2S.mjs → chunk-X247BMMW.mjs} +6 -6
- package/dist/chunk-X247BMMW.mjs.map +1 -0
- package/dist/{chunk-D6MUXDVI.js → chunk-XXSAESE7.js} +9 -9
- package/dist/index.js +16 -16
- package/dist/index.mjs +15 -15
- package/dist/permissions.js +10 -10
- package/dist/permissions.mjs +9 -9
- package/dist/permitted/createInterface.js +2 -2
- package/dist/permitted/createInterface.mjs +1 -1
- package/dist/permitted/handlers.js +6 -6
- package/dist/permitted/handlers.mjs +5 -5
- package/dist/permitted/index.js +8 -8
- package/dist/permitted/index.mjs +7 -7
- package/dist/permitted/invokeKeyring.js +3 -3
- package/dist/permitted/invokeKeyring.mjs +2 -2
- package/dist/permitted/invokeSnapSugar.js +2 -2
- package/dist/permitted/invokeSnapSugar.mjs +1 -1
- package/dist/permitted/middleware.js +8 -8
- package/dist/permitted/middleware.mjs +7 -7
- package/dist/permitted/updateInterface.js +2 -2
- package/dist/permitted/updateInterface.mjs +1 -1
- package/dist/restricted/caveats/index.js +5 -5
- package/dist/restricted/caveats/index.mjs +4 -4
- package/dist/restricted/dialog.js +2 -2
- package/dist/restricted/dialog.mjs +1 -1
- package/dist/restricted/getBip32Entropy.js +3 -3
- package/dist/restricted/getBip32Entropy.mjs +2 -2
- package/dist/restricted/getBip32PublicKey.js +3 -3
- package/dist/restricted/getBip32PublicKey.mjs +2 -2
- package/dist/restricted/getEntropy.js +3 -3
- package/dist/restricted/getEntropy.mjs +2 -2
- package/dist/restricted/index.js +9 -9
- package/dist/restricted/index.mjs +8 -8
- package/dist/restricted/manageState.js +3 -3
- package/dist/restricted/manageState.mjs +2 -2
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/permitted/createInterface.d.ts +41 -41
- package/dist/types/permitted/handlers.d.ts +2 -2
- package/dist/types/permitted/invokeSnapSugar.d.ts +12 -7
- package/dist/types/permitted/updateInterface.d.ts +42 -42
- package/dist/types/restricted/dialog.d.ts +316 -148
- package/dist/types/restricted/getBip32PublicKey.d.ts +2 -5
- package/dist/types/restricted/manageAccounts.d.ts +1 -1
- package/dist/types/utils.d.ts +7 -5
- package/dist/utils.js +2 -2
- package/dist/utils.mjs +1 -1
- package/package.json +4 -4
- package/dist/chunk-3LPBU737.js.map +0 -1
- package/dist/chunk-4SQWLI2S.mjs.map +0 -1
- package/dist/chunk-6WUIFFMQ.mjs.map +0 -1
- package/dist/chunk-GP5KW5FU.js.map +0 -1
- package/dist/chunk-GYZV5UBD.js.map +0 -1
- package/dist/chunk-IDZGMGIB.js.map +0 -1
- package/dist/chunk-LGUJMQC7.js.map +0 -1
- package/dist/chunk-MXCJWR45.mjs.map +0 -1
- package/dist/chunk-SGQXD5K7.mjs.map +0 -1
- package/dist/chunk-WLDEPJGG.mjs.map +0 -1
- package/dist/chunk-YG7W4CDT.js.map +0 -1
- package/dist/chunk-YS6TYXCP.mjs.map +0 -1
- /package/dist/{chunk-TKXU7ZXP.mjs.map → chunk-2L2ATCIK.mjs.map} +0 -0
- /package/dist/{chunk-7OMVZR5X.mjs.map → chunk-CJPFADO7.mjs.map} +0 -0
- /package/dist/{chunk-AOWUGDER.js.map → chunk-E27BGHCR.js.map} +0 -0
- /package/dist/{chunk-Y4LNTDZ2.mjs.map → chunk-FR26QD3N.mjs.map} +0 -0
- /package/dist/{chunk-SU6KOIVB.mjs.map → chunk-I3QG3QZL.mjs.map} +0 -0
- /package/dist/{chunk-S7AR3ROH.js.map → chunk-IE6EHYEG.js.map} +0 -0
- /package/dist/{chunk-Q5W3YGEB.js.map → chunk-IVD2ORDS.js.map} +0 -0
- /package/dist/{chunk-IBV23QOX.mjs.map → chunk-KIXPIIY5.mjs.map} +0 -0
- /package/dist/{chunk-AYJK7MSH.js.map → chunk-LLH2T5NT.js.map} +0 -0
- /package/dist/{chunk-TNRH2LRU.mjs.map → chunk-LXJBBRQ4.mjs.map} +0 -0
- /package/dist/{chunk-R2M4YLJ7.js.map → chunk-M2JQCKR7.js.map} +0 -0
- /package/dist/{chunk-RZXF4KSR.js.map → chunk-O2VSIMDY.js.map} +0 -0
- /package/dist/{chunk-EGKFC56F.js.map → chunk-QAKSH24Z.js.map} +0 -0
- /package/dist/{chunk-JQ456NCC.mjs.map → chunk-S46RTIDR.mjs.map} +0 -0
- /package/dist/{chunk-NESDQ4PF.mjs.map → chunk-TE4W25CA.mjs.map} +0 -0
- /package/dist/{chunk-AMBEX4N4.mjs.map → chunk-TUIJOZXZ.mjs.map} +0 -0
- /package/dist/{chunk-6UY23OOZ.js.map → chunk-VBCE6VHM.js.map} +0 -0
- /package/dist/{chunk-D6MUXDVI.js.map → chunk-XXSAESE7.js.map} +0 -0
|
@@ -21,14 +21,11 @@ declare type GetBip32PublicKeySpecificationBuilderOptions = {
|
|
|
21
21
|
};
|
|
22
22
|
export declare const Bip32PublicKeyArgsStruct: import("superstruct").Struct<{
|
|
23
23
|
path: string[];
|
|
24
|
-
curve: "ed25519" | "secp256k1";
|
|
24
|
+
curve: "ed25519" | "ed25519Bip32" | "secp256k1";
|
|
25
25
|
compressed?: boolean | undefined;
|
|
26
26
|
}, {
|
|
27
27
|
path: import("superstruct").Struct<string[], import("superstruct").Struct<string, null>>;
|
|
28
|
-
curve: import("superstruct").
|
|
29
|
-
ed25519: "ed25519";
|
|
30
|
-
secp256k1: "secp256k1";
|
|
31
|
-
}>;
|
|
28
|
+
curve: import("superstruct").Describe<"ed25519" | "ed25519Bip32" | "secp256k1">;
|
|
32
29
|
compressed: import("superstruct").Struct<boolean | undefined, null>;
|
|
33
30
|
}>;
|
|
34
31
|
export declare const getBip32PublicKeyBuilder: Readonly<{
|
|
@@ -6,8 +6,8 @@ import type { Json, NonEmptyArray } from '@metamask/utils';
|
|
|
6
6
|
declare const SnapMessageStruct: import("superstruct").Struct<{
|
|
7
7
|
method: string;
|
|
8
8
|
} | {
|
|
9
|
-
method: string;
|
|
10
9
|
params: Record<string, Json> | Json[];
|
|
10
|
+
method: string;
|
|
11
11
|
}, null>;
|
|
12
12
|
declare type Message = InferMatching<typeof SnapMessageStruct, ManageAccountsParams>;
|
|
13
13
|
export declare const methodName = "snap_manageAccounts";
|
package/dist/types/utils.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SupportedCurve } from '@metamask/key-tree';
|
|
1
2
|
import { SLIP10Node } from '@metamask/key-tree';
|
|
2
3
|
import type { MagicValue } from '@metamask/snaps-utils';
|
|
3
4
|
import type { Hex } from '@metamask/utils';
|
|
@@ -61,19 +62,20 @@ export declare function deriveEntropy({ input, salt, mnemonicPhrase, magic, }: D
|
|
|
61
62
|
* Get the path prefix to use for key derivation in `key-tree`. This assumes the
|
|
62
63
|
* following:
|
|
63
64
|
*
|
|
64
|
-
* - The Secp256k1 curve always
|
|
65
|
-
* - The Ed25519 curve always
|
|
65
|
+
* - The Secp256k1 curve always uses the BIP-32 specification.
|
|
66
|
+
* - The Ed25519 curve always uses the SLIP-10 specification.
|
|
67
|
+
* - The BIP-32-Ed25519 curve always uses the CIP-3 specification.
|
|
66
68
|
*
|
|
67
69
|
* While this does not matter in most situations (no known case at the time of
|
|
68
70
|
* writing), `key-tree` requires a specific specification to be used.
|
|
69
71
|
*
|
|
70
72
|
* @param curve - The curve to get the path prefix for. The curve is NOT
|
|
71
73
|
* validated by this function.
|
|
72
|
-
* @returns The path prefix, i.e., `
|
|
74
|
+
* @returns The path prefix, i.e., `bip32` or `slip10`.
|
|
73
75
|
*/
|
|
74
|
-
export declare function getPathPrefix(curve:
|
|
76
|
+
export declare function getPathPrefix(curve: SupportedCurve): 'bip32' | 'slip10' | 'cip3';
|
|
75
77
|
declare type GetNodeArgs = {
|
|
76
|
-
curve:
|
|
78
|
+
curve: SupportedCurve;
|
|
77
79
|
secretRecoveryPhrase: Uint8Array;
|
|
78
80
|
path: string[];
|
|
79
81
|
};
|
package/dist/utils.js
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk33MTKZ4Hjs = require('./chunk-33MTKZ4H.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
exports.deriveEntropy =
|
|
12
|
+
exports.deriveEntropy = _chunk33MTKZ4Hjs.deriveEntropy; exports.getNode = _chunk33MTKZ4Hjs.getNode; exports.getPathPrefix = _chunk33MTKZ4Hjs.getPathPrefix; exports.selectHooks = _chunk33MTKZ4Hjs.selectHooks;
|
|
13
13
|
//# sourceMappingURL=utils.js.map
|
package/dist/utils.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-rpc-methods",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "9.0.0",
|
|
4
4
|
"description": "MetaMask Snaps JSON-RPC method implementations.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -39,11 +39,11 @@
|
|
|
39
39
|
"build:ci": "tsup --clean"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@metamask/key-tree": "^9.
|
|
42
|
+
"@metamask/key-tree": "^9.1.0",
|
|
43
43
|
"@metamask/permission-controller": "^9.0.2",
|
|
44
44
|
"@metamask/rpc-errors": "^6.2.1",
|
|
45
|
-
"@metamask/snaps-sdk": "^4.
|
|
46
|
-
"@metamask/snaps-utils": "^7.
|
|
45
|
+
"@metamask/snaps-sdk": "^4.2.0",
|
|
46
|
+
"@metamask/snaps-utils": "^7.4.0",
|
|
47
47
|
"@metamask/utils": "^8.3.0",
|
|
48
48
|
"@noble/hashes": "^1.3.1",
|
|
49
49
|
"superstruct": "^1.0.3"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/createInterface.ts"],"names":[],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,cAAc;AAI5C,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,GAAG,IAAI;AAEf,QAAI,SAAS,MAAM,gBAAgB,EAAE;AAAA,EACvC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Component,\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { ComponentStruct } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (ui: Component) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentStruct,\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui } = validatedParams;\n\n res.result = await createInterface(ui);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface 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 * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
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 {\n DialogType,\n ComponentStruct,\n enumValue,\n union,\n} from '@metamask/snaps-sdk';\nimport type {\n DialogParams,\n EnumToUnion,\n Component,\n InterfaceState,\n SnapId,\n} from '@metamask/snaps-sdk';\nimport { createUnion } from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport { hasProperty, 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 type,\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 id: string,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype CreateInterface = (snapId: string, content: Component) => Promise<string>;\ntype GetInterface = (\n snapId: string,\n id: string,\n) => { content: Component; snapId: SnapId; state: InterfaceState };\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 id - The interface ID.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n /**\n * @param snapId - The Snap ID creating the interface.\n * @param content - The content of the interface.\n */\n createInterface: CreateInterface;\n /**\n * @param snapId - The SnapId requesting the interface.\n * @param id - The interface ID.\n */\n getInterface: GetInterface;\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 createInterface: true,\n getInterface: 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 AlertParametersWithContentStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\nconst AlertParametersWithIdStruct = object({\n type: enumValue(DialogType.Alert),\n id: string(),\n});\n\nconst AlertParametersStruct = union([\n AlertParametersWithContentStruct,\n AlertParametersWithIdStruct,\n]);\n\nconst ConfirmationParametersWithContentStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersWithIdStruct = object({\n type: enumValue(DialogType.Confirmation),\n id: string(),\n});\n\nconst ConfirmationParametersStruct = union([\n ConfirmationParametersWithContentStruct,\n ConfirmationParametersWithIdStruct,\n]);\n\nconst PromptParametersWithContentStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersWithIdStruct = object({\n type: enumValue(DialogType.Prompt),\n id: string(),\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersStruct = union([\n PromptParametersWithContentStruct,\n PromptParametersWithIdStruct,\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.createInterface - A function that creates the interface in SnapInterfaceController.\n * @param hooks.getInterface - A function that gets an interface from SnapInterfaceController.\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 createInterface,\n getInterface,\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 placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n if (hasProperty(validatedParams, 'content')) {\n const id = await createInterface(\n origin,\n validatedParams.content as Component,\n );\n return showDialog(origin, validatedType, id, placeholder);\n }\n\n // Verify that the passed interface ID is valid.\n // This will throw if the interface ID is invalid (not created by the snap or doesn't exist)\n try {\n getInterface(origin, validatedParams.id);\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}`,\n });\n }\n\n return showDialog(origin, validatedType, validatedParams.id, 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, any>,\n): DialogParameters {\n try {\n return createUnion(params, struct, 'type');\n } catch (error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AA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,WAAO,WAAW,QAAQ,eAAe,gBAAgB,IAAI,WAAW;AAAA,EAC1E;AACF;AASA,SAAS,iBAAiB,QAA6B;AACrD,MAAI;AACF,WAAO,OAAO,QAAQ,gBAAgB,EAAE;AAAA,EAC1C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,uCAAuC,OAAO;AAAA,QACrD;AAAA,MACF,EAAE,KAAK,IAAI,CAAC;AAAA,IACd,CAAC;AAAA,EACH;AACF;AAUA,SAAS,mBACP,QACA,QACkB;AAClB,MAAI;AACF,WAAO,YAAY,QAAQ,QAAQ,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,IAC3C,CAAC;AAAA,EACH;AACF;","names":["methodHooks"]}
|
|
@@ -1 +0,0 @@
|
|
|
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"],"mappings":";;;;;AAMA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAK1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS,OAAO,QAAQ,gBAAgB;AAKjD,IAAM,aAAa;AA4BZ,IAAM,2BAA2B;AAAA,EACtC,OAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MAAM,CAAC,WAAW,WAAW,CAAC;AAAA,IACrC,YAAY,SAAS,QAAQ,CAAC;AAAA,EAChC,CAAC;AACH;AAWA,IAAM,uBAIF,CAAC,EAAE,aAAAA,aAAY,MAAoD;AACrE,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B;AAAA,IACA,gBAAgB,CAAC,eAAe,wBAAwB;AAAA,IACxD,sBAAsB,gCAAgCA,YAAW;AAAA,IACjE,WAAW,CAA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ACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,IAAI,GAAG,IAAI;AAEnB,UAAM,gBAAgB,IAAI,EAAE;AAC5B,QAAI,SAAS;AAAA,EACf,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Component,\n UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { ComponentStruct } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<UpdateInterfaceMethodHooks> = {\n updateInterface: true,\n};\n\nexport type UpdateInterfaceMethodHooks = {\n /**\n * @param id - The interface ID.\n * @param ui - The UI components.\n */\n updateInterface: (id: string, ui: Component) => Promise<void>;\n};\n\nexport const updateInterfaceHandler: PermittedHandlerExport<\n UpdateInterfaceMethodHooks,\n UpdateInterfaceParameters,\n UpdateInterfaceResult\n> = {\n methodNames: ['snap_updateInterface'],\n implementation: getUpdateInterfaceImplementation,\n hookNames,\n};\n\nconst UpdateInterfaceParametersStruct = object({\n id: string(),\n ui: ComponentStruct,\n});\n\nexport type UpdateInterfaceParameters = InferMatching<\n typeof UpdateInterfaceParametersStruct,\n UpdateInterfaceParams\n>;\n\n/**\n * The `snap_updateInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.updateInterface - The function to update the interface.\n * @returns Nothing.\n */\nasync function getUpdateInterfaceImplementation(\n req: JsonRpcRequest<UpdateInterfaceParameters>,\n res: PendingJsonRpcResponse<UpdateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { updateInterface }: UpdateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id, ui } = validatedParams;\n\n await updateInterface(id, ui);\n res.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the updateInterface 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 * @returns The validated updateInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): UpdateInterfaceParameters {\n try {\n return create(params, UpdateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/restricted/dialog.ts"],"names":["methodHooks"],"mappings":";AAKA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQP,SAAS,mBAAmB;AAE5B,SAAS,mBAAuC;AAEhD;AAAA,EACE;AAAA,EACA;AAAA,EACA;A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AAA,MAC5B,SAAS,uCAAuC,OAAO;AAAA,QACrD;AAAA,MACF,EAAE,KAAK,IAAI,CAAC;AAAA,IACd,CAAC;AAAA,EACH;AACF;AAUA,SAAS,mBACP,QACA,QACkB;AAClB,MAAI;AACF,WAAO,YAAY,QAAQ,QAAQ,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,IAC3C,CAAC;AAAA,EACH;AACF","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 {\n DialogType,\n ComponentStruct,\n enumValue,\n union,\n} from '@metamask/snaps-sdk';\nimport type {\n DialogParams,\n EnumToUnion,\n Component,\n InterfaceState,\n SnapId,\n} from '@metamask/snaps-sdk';\nimport { createUnion } from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport { hasProperty, 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 type,\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 id: string,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype CreateInterface = (snapId: string, content: Component) => Promise<string>;\ntype GetInterface = (\n snapId: string,\n id: string,\n) => { content: Component; snapId: SnapId; state: InterfaceState };\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 id - The interface ID.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n /**\n * @param snapId - The Snap ID creating the interface.\n * @param content - The content of the interface.\n */\n createInterface: CreateInterface;\n /**\n * @param snapId - The SnapId requesting the interface.\n * @param id - The interface ID.\n */\n getInterface: GetInterface;\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 createInterface: true,\n getInterface: 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 AlertParametersWithContentStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\nconst AlertParametersWithIdStruct = object({\n type: enumValue(DialogType.Alert),\n id: string(),\n});\n\nconst AlertParametersStruct = union([\n AlertParametersWithContentStruct,\n AlertParametersWithIdStruct,\n]);\n\nconst ConfirmationParametersWithContentStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersWithIdStruct = object({\n type: enumValue(DialogType.Confirmation),\n id: string(),\n});\n\nconst ConfirmationParametersStruct = union([\n ConfirmationParametersWithContentStruct,\n ConfirmationParametersWithIdStruct,\n]);\n\nconst PromptParametersWithContentStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersWithIdStruct = object({\n type: enumValue(DialogType.Prompt),\n id: string(),\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersStruct = union([\n PromptParametersWithContentStruct,\n PromptParametersWithIdStruct,\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.createInterface - A function that creates the interface in SnapInterfaceController.\n * @param hooks.getInterface - A function that gets an interface from SnapInterfaceController.\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 createInterface,\n getInterface,\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 placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n if (hasProperty(validatedParams, 'content')) {\n const id = await createInterface(\n origin,\n validatedParams.content as Component,\n );\n return showDialog(origin, validatedType, id, placeholder);\n }\n\n // Verify that the passed interface ID is valid.\n // This will throw if the interface ID is invalid (not created by the snap or doesn't exist)\n try {\n getInterface(origin, validatedParams.id);\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}`,\n });\n }\n\n return showDialog(origin, validatedType, validatedParams.id, 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, any>,\n): DialogParameters {\n try {\n return createUnion(params, struct, 'type');\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}`,\n });\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/invokeSnapSugar.ts"],"names":[],"mappings":";AAKA,SAAS,iBAAiB;AAG1B,SAAS,gBAAgB;AAKlB,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,mBAAmB;AAAA,EACjC,gBAAgB;AAAA,EAChB,WAAW;AACb;AAcO,SAAS,gBACd,KACA,MACA,MACA,KACM;AACN,MAAI;AACJ,MAAI;AACF,aAAS,mBAAmB,IAAI,MAAM;AAAA,EACxC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,SAAO,KAAK;AACd;AASO,SAAS,mBAAmB,QAAmC;AACpE,MAAI,CAAC,SAAS,MAAM,GAAG;AACrB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI;AAE5B,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,WAAW,IAAI;AAC1D,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,CAAC,SAAS,OAAO,GAAG;AACtB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO;AACT","sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapParams,\n InvokeSnapResult\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapParams>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap 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 * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapParams;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/restricted/getBip32PublicKey.ts"],"names":["methodHooks"],"mappings":";;;;;AAMA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAK1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS,OAAO,QAAQ,gBAAgB;AAKjD,IAAM,aAAa;AA4BZ,IAAM,2BAA2B;AAAA,EACtC,OAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MAAM,CAAC,WAAW,WAAW,CAAC;AAAA,IACrC,YAAY,SAAS,QAAQ,CAAC;AAAA,EAChC,CAAC;AACH;AAWA,IAAM,uBAIF,CAAC,EAAE,aAAAA,aAAY,MAAoD;AACrE,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B;AAAA,IACA,gBAAgB,CAAC,eAAe,wBAAwB;AAAA,IACxD,sBAAsB,gCAAgCA,YAAW;AAAA,IACjE,WAAW,CAAC,EAAE,QAAQ,MAAM;AAC1B,UACE,SAAS,WAAW,KACpB,QAAQ,CAAC,EAAE,SAAS,eAAe,0BACnC;AACA,cAAM,UAAU,cAAc;AAAA,UAC5B,SAAS,sBAAsB,eAAe,wBAAwB;AAAA,QACxE,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAA+D;AAAA,EACnE,aAAa;AAAA,EACb,kBAAkB;AACpB;AAEO,IAAM,2BAA2B,OAAO,OAAO;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAYH,SAAS,gCAAgC;AAAA,EAC9C;AAAA,EACA;AACF,GAAiC;AAC/B,SAAO,eAAe,kBACpB,MACkC;AAClC,UAAM,iBAAiB,IAAI;AAE3B;AAAA,MACE,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU;AAAA,IACZ;AAEA,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,OAAO,MAAM,QAAQ;AAAA,MACzB,OAAO,OAAO;AAAA,MACd,MAAM,OAAO;AAAA,MACb,sBAAsB,MAAM,YAAY;AAAA,IAC1C,CAAC;AAED,QAAI,OAAO,YAAY;AACrB,aAAO,KAAK;AAAA,IACd;AAEA,WAAO,KAAK;AAAA,EACd;AACF","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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/invokeSnapSugar.ts"],"sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapParams,\n InvokeSnapResult\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapParams>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap 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 * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapParams;\n}\n"],"mappings":";AAKA,SAAS,iBAAiB;AAG1B,SAAS,gBAAgB;AAKlB,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,mBAAmB;AAAA,EACjC,gBAAgB;AAAA,EAChB,WAAW;AACb;AAcO,SAAS,gBACd,KACA,MACA,MACA,KACM;AACN,MAAI;AACJ,MAAI;AACF,aAAS,mBAAmB,IAAI,MAAM;AAAA,EACxC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,SAAO,KAAK;AACd;AASO,SAAS,mBAAmB,QAAmC;AACpE,MAAI,CAAC,SAAS,MAAM,GAAG;AACrB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI;AAE5B,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,WAAW,IAAI;AAC1D,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,CAAC,SAAS,OAAO,GAAG;AACtB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\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\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/**\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 * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\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 derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\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 use the BIP-32 specification.\n * - The Ed25519 curve always use the SLIP-10 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., `secp256k1` or `ed25519`.\n */\nexport function getPathPrefix(\n curve: 'secp256k1' | 'ed25519',\n): 'bip32' | 'slip10' {\n if (curve === 'secp256k1') {\n return 'bip32';\n }\n\n return 'slip10';\n}\n\ntype GetNodeArgs = {\n curve: 'secp256k1' | 'ed25519';\n secretRecoveryPhrase: Uint8Array;\n path: string[];\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 */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n return await SLIP10Node.fromDerivationPath({\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n });\n}\n"],"mappings":";AAKA,SAAS,kBAAkB;AAG3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc,iBAAiB;AAExC,IAAM,iBAAiB;AAuBhB,SAAS,YAId,OACA,WACmC;AACnC,MAAI,WAAW;AACb,WAAO,OAAO,KAAK,SAAS,EAAE;AAAA,MAC5B,CAAC,YAAY,cAAc;AACzB,cAAM,WAAW;AACjB,mBAAW,QAAQ,IAAI,MAAM,QAAQ;AACrC,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AASA,SAAS,uBAAuB,MAAuC;AACrE,QAAM,QAA6B,CAAC;AACpC,QAAM,OAAO,eAAe,IAAI;AAEhC,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AACtC,UAAM,SAAS,KAAK,UAAU,QAAQ,CAAC;AAMvC,UAAM,aAAa,SAAS,oBAAoB;AAChD,UAAM,KAAK,SAAS,YAAY,cAAc,GAAY;AAAA,EAC5D;AAEA,SAAO;AACT;AAwCA,eAAsB,cAAc;AAAA,EAClC;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AACF,GAAuC;AACrC,QAAM,aAAa,cAAc,KAAK;AACtC,QAAM,YAAY,cAAc,IAAI;AAGpC,QAAM,OAAO,UAAU,YAAY,CAAC,YAAY,UAAU,SAAS,CAAC,CAAC,CAAC;AACtE,QAAM,yBAAyB,uBAAuB,IAAI;AAG1D,QAAM,EAAE,WAAW,IAAI,MAAM,WAAW,mBAAmB;AAAA,IACzD,gBAAgB;AAAA,MACd;AAAA,MACA,SAAS,KAAK;AAAA,MACd,GAAG;AAAA,IACL;AAAA,IACA,OAAO;AAAA,EACT,CAAC;AAGD,SAAO,YAAY,+BAA+B;AAElD,SAAO,MAAM,UAAU;AACzB;AAgBO,SAAS,cACd,OACoB;AACpB,MAAI,UAAU,aAAa;AACzB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAqBA,eAAsB,QAAQ;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAgB;AACd,QAAM,SAAS,cAAc,KAAK;AAClC,SAAO,MAAM,WAAW,mBAAmB;AAAA,IACzC;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA,GAAI,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,KAAK,EAAE;AAAA,IAGvD;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/createInterface.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Component,\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { ComponentStruct } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (ui: Component) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentStruct,\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui } = validatedParams;\n\n res.result = await createInterface(ui);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface 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 * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,cAAc;AAI5C,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KAC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5D;AAEA,SAAO;AACT;AAwCA,eAAsB,cAAc;AAAA,EAClC;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AACF,GAAuC;AACrC,QAAM,aAAa,cAAc,KAAK;AACtC,QAAM,YAAY,cAAc,IAAI;AAGpC,QAAM,OAAO,UAAU,YAAY,CAAC,YAAY,UAAU,SAAS,CAAC,CAAC,CAAC;AACtE,QAAM,yBAAyB,uBAAuB,IAAI;AAG1D,QAAM,EAAE,WAAW,IAAI,MAAM,WAAW,mBAAmB;AAAA,IACzD,gBAAgB;AAAA,MACd;AAAA,MACA,SAAS,KAAK;AAAA,MACd,GAAG;AAAA,IACL;AAAA,IACA,OAAO;AAAA,EACT,CAAC;AAGD,SAAO,YAAY,+BAA+B;AAElD,SAAO,MAAM,UAAU;AACzB;AAgBO,SAAS,cACd,OACoB;AACpB,MAAI,UAAU,aAAa;AACzB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAqBA,eAAsB,QAAQ;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAgB;AACd,QAAM,SAAS,cAAc,KAAK;AAClC,SAAO,MAAM,WAAW,mBAAmB;AAAA,IACzC;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA,GAAI,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,KAAK,EAAE;AAAA,IAGvD;AAAA,EACF,CAAC;AACH","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\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\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/**\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 * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\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 derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\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 use the BIP-32 specification.\n * - The Ed25519 curve always use the SLIP-10 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., `secp256k1` or `ed25519`.\n */\nexport function getPathPrefix(\n curve: 'secp256k1' | 'ed25519',\n): 'bip32' | 'slip10' {\n if (curve === 'secp256k1') {\n return 'bip32';\n }\n\n return 'slip10';\n}\n\ntype GetNodeArgs = {\n curve: 'secp256k1' | 'ed25519';\n secretRecoveryPhrase: Uint8Array;\n path: string[];\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 */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n return await SLIP10Node.fromDerivationPath({\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/updateInterface.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Component,\n UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { ComponentStruct } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<UpdateInterfaceMethodHooks> = {\n updateInterface: true,\n};\n\nexport type UpdateInterfaceMethodHooks = {\n /**\n * @param id - The interface ID.\n * @param ui - The UI components.\n */\n updateInterface: (id: string, ui: Component) => Promise<void>;\n};\n\nexport const updateInterfaceHandler: PermittedHandlerExport<\n UpdateInterfaceMethodHooks,\n UpdateInterfaceParameters,\n UpdateInterfaceResult\n> = {\n methodNames: ['snap_updateInterface'],\n implementation: getUpdateInterfaceImplementation,\n hookNames,\n};\n\nconst UpdateInterfaceParametersStruct = object({\n id: string(),\n ui: ComponentStruct,\n});\n\nexport type UpdateInterfaceParameters = InferMatching<\n typeof UpdateInterfaceParametersStruct,\n UpdateInterfaceParams\n>;\n\n/**\n * The `snap_updateInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.updateInterface - The function to update the interface.\n * @returns Nothing.\n */\nasync function getUpdateInterfaceImplementation(\n req: JsonRpcRequest<UpdateInterfaceParameters>,\n res: PendingJsonRpcResponse<UpdateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { updateInterface }: UpdateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id, ui } = validatedParams;\n\n await updateInterface(id, ui);\n res.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the updateInterface 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 * @returns The validated updateInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): UpdateInterfaceParameters {\n try {\n return create(params, UpdateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,QAAQ,cAAc;AAIpD,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI,OAAO;AAAA,EACX,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,IAAI,GAAG,IAAI;AAEnB,UAAM,gBAAgB,IAAI,EAAE;AAC5B,QAAI,SAAS;AAAA,EACf,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|