UNPKG

@metamask/snaps-rpc-methods

Version:
1 lines 2.85 kB
{"version":3,"file":"middleware.mjs","sourceRoot":"","sources":["../../src/permitted/middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EAAE,QAAQ,EAAE,8BAA8B;AAGjD,OAAO,EAAE,cAAc,EAAE,uBAAmB;AAC5C,OAAO,EAAE,WAAW,EAAE,qBAAiB;AAEvC;;;;;;GAMG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAAe,EACf,KAA8B;IAE9B,iEAAiE;IACjE,kEAAkE;IAClE,OAAO,KAAK,UAAU,gBAAgB,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG;QACjE,MAAM,OAAO,GACX,cAAc,CAAC,OAAO,CAAC,MAAqC,CAAC,CAAC;QAChE,IAAI,OAAO,EAAE,CAAC;YACZ,IACE,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC;gBACzD,CAAC,MAAM,EACP,CAAC;gBACD,OAAO,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC,CAAC;YACzC,CAAC;YAED,iFAAiF;YACjF,MAAM,EAAE,cAAc,EAAE,SAAS,EAAE,GAAG,OAAc,CAAC;YACrD,IAAI,CAAC;gBACH,kEAAkE;gBAClE,OAAO,MAAM,cAAc,CACzB,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,GAAG,EACH,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAC9B,CAAC;YACJ,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAChB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { methodHandlers } from './handlers';\nimport { selectHooks } from '../utils';\n\n/**\n * Creates a middleware that handles permitted snap RPC methods.\n *\n * @param isSnap - A flag that should indicate whether the requesting origin is a snap or not.\n * @param hooks - An object containing the hooks made available to the permitted RPC methods.\n * @returns The middleware.\n */\nexport function createSnapsMethodMiddleware(\n isSnap: boolean,\n hooks: Record<string, unknown>,\n): JsonRpcMiddleware<JsonRpcParams, Json> {\n // This is not actually a misused promise, the type is just wrong\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async function methodMiddleware(request, response, next, end) {\n const handler =\n methodHandlers[request.method as keyof typeof methodHandlers];\n if (handler) {\n if (\n String.prototype.startsWith.call(request.method, 'snap_') &&\n !isSnap\n ) {\n return end(rpcErrors.methodNotFound());\n }\n\n // TODO: Once json-rpc-engine types are up to date, we should type this correctly\n const { implementation, hookNames } = handler as any;\n try {\n // Implementations may or may not be async, so we must await them.\n return await implementation(\n request,\n response,\n next,\n end,\n selectHooks(hooks, hookNames),\n );\n } catch (error) {\n logError(error);\n return end(error);\n }\n }\n\n return next();\n };\n}\n"]}