@metamask/snaps-execution-environments 0.38.1-flask.1 → 0.38.3-flask.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../node_modules/ses/types.d.ts" />
3
3
  "use strict";
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","constructedError","constructError","serializedError","serializeError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","isJsonRpcRequest","Error","id","respond","result","EEOpenRPCDocument","hasProperty","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","assertSnapOutboundRequest","sanitizedArgs","getSafeJson","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAuGnDA;;;eAAAA;;;2BAtGkB;4BAYxB;uBAcA;8BAC+C;+BACd;6BAEf;yBAEL;oEACU;0BAEkB;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,wBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAG,WAAW;QACTL,QAAQM,2CAA+B;QACvCJ,QAAQ,EAAE;IACZ;IACAK,SAAS;QACPP,QAAQQ,yCAA6B;QACrCN,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIO,MAAMX;IAwEHkB,aAAaC,KAAc,EAAEC,IAA0B,EAAE;QAC/D,MAAMC,mBAAmBC,IAAAA,sBAAc,EAACH;QACxC,MAAMI,kBAAkBC,IAAAA,4BAAc,EAACH,kBAAkB;YACvDp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,CAAC1F,SAAS,CAAC0D,IAAI,CAAC,IAAI,GACxB,OAAOiC,QAAQC,aAAajC;YAC1B,MAAM7F,OAAO,IAAI,CAAC4D,QAAQ,CAACsB,GAAG,CAAC2C;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAU/H,MAAMuD,OAAO,CAACuE,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGvC,wBAAY,CAACqC,YAAY;YAE9CG,IAAAA,aAAM,EACJ,CAACD,YAAYD,YAAYvB,WACzB,CAAC,GAAG,EAAEsB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAG1D,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACE,SAAS;gBACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAIhH,SAAS,MAAM,IAAI,CAAC0D,oBAAoB,CAACoD,QAAQ,IACnDE,QAAQlC;YAGV,0EAA0E;YAC1E,IAAI9E,WAAWyF,WAAW;gBACxBzF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOiF,IAAAA,kBAAW,EAACjF;YACrB,EAAE,OAAOhB,OAAO;gBACd,MAAM,IAAImI,UACR,CAAC,sCAAsC,EAAEnI,MAAMb,OAAO,CAACiJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACtD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","constructedError","constructError","serializedError","serializeError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","isJsonRpcRequest","Error","id","respond","result","EEOpenRPCDocument","hasProperty","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","assertSnapOutboundRequest","sanitizedArgs","getSafeJson","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAuGnDA;;;eAAAA;;;2BAtGkB;4BAYxB;uBAcA;8BAC+C;+BACd;6BAEf;yBAEL;oEACU;0BAEkB;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,wBA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AO;gBACd,MAAM,IAAImI,UACR,CAAC,sCAAsC,EAAEnI,MAAMb,OAAO,CAACiJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACtD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
@@ -192,12 +192,22 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
192
192
  };
193
193
  return {
194
194
  fetch: harden(_fetch),
195
+ // Request, Headers and Response are the endowments injected alongside fetch
196
+ // only when 'endowment:network-access' permission is requested,
197
+ // therefore these are hardened as part of fetch dependency injection within its factory.
198
+ // These endowments are not (and should never be) available by default.
199
+ Request: harden(Request),
200
+ Headers: harden(Headers),
201
+ Response: harden(Response),
195
202
  teardownFunction
196
203
  };
197
204
  };
198
205
  const endowmentModule = {
199
206
  names: [
200
- 'fetch'
207
+ 'fetch',
208
+ 'Request',
209
+ 'Headers',
210
+ 'Response'
201
211
  ],
202
212
  factory: createNetwork
203
213
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","withTeardown","arrayBuffer","blob","clone","newResponse","teardownRef","formData","json","constructor","createNetwork","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","endowmentModule","names","factory"],"mappings":";;;;+BAmMA;;;eAAA;;;uBAnM6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOlB,4CAET;AAPF;;;CAGC,GACD,MAAMA;IAUJ,IAAIC,OAA0C;QAC5C,OAAO,yBAAA,IAAI,EAAEC,aAAWD,IAAI;IAC9B;IAEA,IAAIE,WAAW;QACb,OAAO,yBAAA,IAAI,EAA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,IAAIL;oBACtB,EAAE,OAAM;oBACN,cAAc,GAChB;gBACF;YACJ;YACAtB,gBAAgBuB,GAAG,CAACG;YACpBvB,QAAQyB,QAAQ,CACdV,IAAIvC,IAAI,EACR,yFAAyF,GACzF,IAAMqB,gBAAgBwB,MAAM,CAACE;QAEjC;QACA,OAAOG,OAAOX;IAChB;IAEA,MAAMY,mBAAmB;QACvBnC,YAAYO,YAAY,IAAI;QAC5B,MAAM6B,WAA4B,EAAE;QACpC/B,gBAAgBgC,OAAO,CAAC,CAAC,EAAEV,MAAM,EAAE,GAAKS,SAASE,IAAI,CAACX;QACtDtB,gBAAgBkC,KAAK;QACrB,MAAMC,QAAQC,GAAG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAOvB;QACdwB;IACF;AACF;AAEA,MAAMO,kBAAkB;IACtBC,OAAO;QAAC;KAAQ;IAChBC,SAASxC;AACX;MACA,WAAesC"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","withTeardown","arrayBuffer","blob","clone","newResponse","teardownRef","formData","json","constructor","createNetwork","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","Request","Headers","Response","endowmentModule","names","factory"],"mappings":";;;;+BA0MA;;;eAAA;;;uBA1M6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOlB,4CAET;AAPF;;;CAGC,GACD,MAAMA;IAUJ,I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AwBP,IAAIvC,IAAI;YAEjD,MAAM+C,qBAAqB;gBACzBJ,QACE,+EAA+E,GAC/E;oBACE,IAAI;wBACF,MAAM3C,KAAKgD,KAAK,IAAIL;oBACtB,EAAE,OAAM;oBACN,cAAc,GAChB;gBACF;YACJ;YACAtB,gBAAgBuB,GAAG,CAACG;YACpBvB,QAAQyB,QAAQ,CACdV,IAAIvC,IAAI,EACR,yFAAyF,GACzF,IAAMqB,gBAAgBwB,MAAM,CAACE;QAEjC;QACA,OAAOG,OAAOX;IAChB;IAEA,MAAMY,mBAAmB;QACvBnC,YAAYO,YAAY,IAAI;QAC5B,MAAM6B,WAA4B,EAAE;QACpC/B,gBAAgBgC,OAAO,CAAC,CAAC,EAAEV,MAAM,EAAE,GAAKS,SAASE,IAAI,CAACX;QACtDtB,gBAAgBkC,KAAK;QACrB,MAAMC,QAAQC,GAAG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAOvB;QACd,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE+B,SAASR,OAAOQ;QAChBC,SAAST,OAAOS;QAChBC,UAAUV,OAAOU;QACjBT;IACF;AACF;AAEA,MAAMU,kBAAkB;IACtBC,OAAO;QAAC;QAAS;QAAW;QAAW;KAAW;IAClDC,SAAS3C;AACX;MACA,WAAeyC"}
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../../node_modules/ses/types.d.ts" />
3
3
  "use strict";
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/lockdown/lockdown-more.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n logError('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"],"names":["executeLockdownMore","namedIntrinsics","Reflect","ownKeys","Compartment","globalThis","shouldHardenManually","Set","globalProperties","forEach","propertyName","descriptor","getOwnPropertyDescriptor","configurable","hasAccessor","Object","defineProperty","writable","has","harden","error","logError"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;;;;;+BAwBnDA;;;eAAAA;;;4BAtBS;AAsBlB,SAASA;IACd,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAMC,kBAAkBC,QAAQC,OAAO,CAAC,IAAIC,cAAcC,UAAU;QAEpE,sEAAsE;QACtE,MAAMC,uBAAuB,IAAIC,IAAqB;YAAC;YAAQ;SAAW;QAE1E,MAAMC,mBAAmB,IAAID,IAAI;YAC/B,yEAAyE;YACzE,oEAAoE;YACpE,8CAA8C;eAC3CN;SAKJ;QAEDO,iBAAiBC,OAAO,CAAC,CAACC;YACxB,MAAMC,aAAaT,QAAQU,wBAAwB,CACjDP,YACAK;YAGF,IAAIC,YAAY;gBACd,IAAIA,WAAWE,YAAY,EAAE;oBAC3B,yDAAyD;oBACzD,mEAAmE;oBACnE,gBAAgB;oBAChB,IAAIC,YAAYH,aAAa;wBAC3BI,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;wBAChB;oBACF,OAAO;wBACLE,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;4BACdI,UAAU;wBACZ;oBACF;gBACF;gBAEA,IAAIX,qBAAqBY,GAAG,CAACR,eAAe;oBAC1CS,OAAO,AAACd,UAAkB,CAACK,aAAa;gBAC1C;YACF;QACF;IACF,EAAE,OAAOU,OAAO;QACdC,IAAAA,oBAAQ,EAAC,iCAAiCD;QAC1C,MAAMA;IACR;AACF;AAEA;;;;;;;;;CASC,GACD,SAASN,YAAYH,UAAe;IAClC,OAAO,SAASA,cAAc,SAASA;AACzC"}
1
+ {"version":3,"sources":["../../../../src/common/lockdown/lockdown-more.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/types.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n logError('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"],"names":["executeLockdownMore","namedIntrinsics","Reflect","ownKeys","Compartment","globalThis","shouldHardenManually","Set","globalProperties","forEach","propertyName","descriptor","getOwnPropertyDescriptor","configurable","hasAccessor","Object","defineProperty","writable","has","harden","error","logError"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;;;;;+BAwBnDA;;;eAAAA;;;4BAtBS;AAsBlB,SAASA;IACd,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAMC,kBAAkBC,QAAQC,OAAO,CAAC,IAAIC,cAAcC,UAAU;QAEpE,sEAAsE;QACtE,MAAMC,uBAAuB,IAAIC,IAAqB;YAAC;YAAQ;SAAW;QAE1E,MAAMC,mBAAmB,IAAID,IAAI;YAC/B,yEAAyE;YACzE,oEAAoE;YACpE,8CAA8C;eAC3CN;SAKJ;QAEDO,iBAAiBC,OAAO,CAAC,CAACC;YACxB,MAAMC,aAAaT,QAAQU,wBAAwB,CACjDP,YACAK;YAGF,IAAIC,YAAY;gBACd,IAAIA,WAAWE,YAAY,EAAE;oBAC3B,yDAAyD;oBACzD,mEAAmE;oBACnE,gBAAgB;oBAChB,IAAIC,YAAYH,aAAa;wBAC3BI,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;wBAChB;oBACF,OAAO;wBACLE,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;4BACdI,UAAU;wBACZ;oBACF;gBACF;gBAEA,IAAIX,qBAAqBY,GAAG,CAACR,eAAe;oBAC1CS,OAAO,AAACd,UAAkB,CAACK,aAAa;gBAC1C;YACF;QACF;IACF,EAAE,OAAOU,OAAO;QACdC,IAAAA,oBAAQ,EAAC,iCAAiCD;QAC1C,MAAMA;IACR;AACF;AAEA;;;;;;;;;CASC,GACD,SAASN,YAAYH,UAAe;IAClC,OAAO,SAASA,cAAc,SAASA;AACzC"}
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../../node_modules/ses/types.d.ts" />
3
3
  "use strict";
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/lockdown/lockdown.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n logError('Lockdown failed:', error);\n throw error;\n }\n}\n"],"names":["executeLockdown","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","error","logError"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;;;;;+BASnDA;;;eAAAA;;;4BAPS;AAOlB,SAASA;IACd,IAAI;QACFC,SAAS;YACPC,eAAe;YACfC,aAAa;YACbC,YAAY;YACZC,YAAY;YACZC,gBAAgB;QAClB;IACF,EAAE,OAAOC,OAAO;QACd,gFAAgF;QAChFC,IAAAA,oBAAQ,EAAC,oBAAoBD;QAC7B,MAAMA;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../src/common/lockdown/lockdown.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/types.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n logError('Lockdown failed:', error);\n throw error;\n }\n}\n"],"names":["executeLockdown","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","error","logError"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;;;;;+BASnDA;;;eAAAA;;;4BAPS;AAOlB,SAASA;IACd,IAAI;QACFC,SAAS;YACPC,eAAe;YACfC,aAAa;YACbC,YAAY;YACZC,YAAY;YACZC,gBAAgB;QAClB;IACF,EAAE,OAAOC,OAAO;QACd,gFAAgF;QAChFC,IAAAA,oBAAQ,EAAC,oBAAoBD;QAC7B,MAAMA;IACR;AACF"}
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../node_modules/ses/types.d.ts" />
3
3
  function _define_property(obj, key, value) {
4
4
  if (key in obj) {
5
5
  Object.defineProperty(obj, key, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["StreamProvider","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","errorCodes","ethErrors","serializeError","createIdRemapMiddleware","validate","log","EEOpenRPCDocument","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","constructError","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","constructedError","serializedError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","Error","id","respond","result","methodNotFound","serialize","methodObject","paramsAsArray","invalidParams","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,cAAc,QAAQ,sBAAsB;AAQrD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AACzB,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,iBAAiB;AACvE,SAASC,uBAAuB,QAAQ,kBAAkB;AAE1D,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AACjC,OAAOC,uBAAuB,kBAAkB;AAEhD,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,cAAc,EACdC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAMtB,WAAWuB,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQV;QACRW,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXF,QAAQX;QACRY,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAE,WAAW;QACTH,QAAQR;QACRS,QAAQ,EAAE;IACZ;IACAG,SAAS;QACPJ,QAAQT;QACRU,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIA,OAAO,MAAMI;IAwEHC,aAAaC,KAAc,EA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AE,GAAGlJ,YAAY,CAACgJ,YAAY;YAE9C7I,OACE,CAAC+I,YAAYD,YAAYnB,WACzB,CAAC,GAAG,EAAEkB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAG1D,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACE,SAAS;gBACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAI1F,SAAS,MAAM,IAAI,CAAC6C,oBAAoB,CAAC2C,QAAQ,IACnDE,QAAQ3B;YAGV,0EAA0E;YAC1E,IAAI/D,WAAWuE,WAAW;gBACxBvE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOjD,YAAYiD;YACrB,EAAE,OAAOb,OAAO;gBACd,MAAM,IAAIyG,UACR,CAAC,sCAAsC,EAAEzG,MAAMV,OAAO,CAACoH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["StreamProvider","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","errorCodes","ethErrors","serializeError","createIdRemapMiddleware","validate","log","EEOpenRPCDocument","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","constructError","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","constructedError","serializedError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","Error","id","respond","result","methodNotFound","serialize","methodObject","paramsAsArray","invalidParams","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,cAAc,QAAQ,sBAAsB;AAQrD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AACzB,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,iBAAiB;AACvE,SAASC,uBAAuB,QAAQ,kBAAkB;AAE1D,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AACjC,OAAOC,uBAAuB,kBAAkB;AAEhD,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,Q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A,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
@@ -182,12 +182,22 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
182
182
  };
183
183
  return {
184
184
  fetch: harden(_fetch),
185
+ // Request, Headers and Response are the endowments injected alongside fetch
186
+ // only when 'endowment:network-access' permission is requested,
187
+ // therefore these are hardened as part of fetch dependency injection within its factory.
188
+ // These endowments are not (and should never be) available by default.
189
+ Request: harden(Request),
190
+ Headers: harden(Headers),
191
+ Response: harden(Response),
185
192
  teardownFunction
186
193
  };
187
194
  };
188
195
  const endowmentModule = {
189
196
  names: [
190
- 'fetch'
197
+ 'fetch',
198
+ 'Request',
199
+ 'Headers',
200
+ 'Response'
191
201
  ],
192
202
  factory: createNetwork
193
203
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["withTeardown","ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","arrayBuffer","blob","clone","newResponse","teardownRef","formData","json","constructor","createNetwork","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,YAAY,QAAQ,WAAW;IAO7B,4CAET;AAPF;;;CAGC,GACD,MAAMC;IAUJ,IAAIC,OAA0C;QAC5C,OAAO,yBAAA,IAAI,EAAEC,aAAWD,IAAI;IAC9B;IAEA,IAAIE,WAAW;QACb,OAAO,yBAAA,IAAI,EAAED,aAAWC,QAAQ;IAClC;IAEA,IAAIC,UAAU;QACZ,OAAO,yBAAA,IAAI,EAAEF,aAAWE,OAAO;IACjC;IAEA,IAAIC,KAAK;QACP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OAAOX;IAChB;IAEA,MAAMY,mBAAmB;QACvBnC,YAAYO,YAAY,IAAI;QAC5B,MAAM6B,WAA4B,EAAE;QACpC/B,gBAAgBgC,OAAO,CAAC,CAAC,EAAEV,MAAM,EAAE,GAAKS,SAASE,IAAI,CAACX;QACtDtB,gBAAgBkC,KAAK;QACrB,MAAMC,QAAQC,GAAG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAOvB;QACdwB;IACF;AACF;AAEA,MAAMO,kBAAkB;IACtBC,OAAO;QAAC;KAAQ;IAChBC,SAASxC;AACX;AACA,eAAesC,gBAAgB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["withTeardown","ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","arrayBuffer","blob","clone","newResponse","teardownRef","formData","json","constructor","createNetwork","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","Request","Headers","Response","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,YAAY,QAAQ,WAAW;IAO7B,4CAET;AAPF;;;CAGC,GACD,MAAMC;IAUJ,IAAIC,OAA0C;QAC5C,OAAO,yBAAA,IAAI,EAAEC,aAAWD,IAAI;IAC9B;IAEA,IAAIE,WAAW;QACb,OAAO,yBAAA,IAAI,EAAED,aAAWC,QAAQ;IAClC;IAEA,IAAIC,UAAU;QACZ,OAAO,yBAAA,IAAI,EAAEF,aAAWE,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wB,MAAM,CAACE;QAEjC;QACA,OAAOG,OAAOX;IAChB;IAEA,MAAMY,mBAAmB;QACvBnC,YAAYO,YAAY,IAAI;QAC5B,MAAM6B,WAA4B,EAAE;QACpC/B,gBAAgBgC,OAAO,CAAC,CAAC,EAAEV,MAAM,EAAE,GAAKS,SAASE,IAAI,CAACX;QACtDtB,gBAAgBkC,KAAK;QACrB,MAAMC,QAAQC,GAAG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAOvB;QACd,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE+B,SAASR,OAAOQ;QAChBC,SAAST,OAAOS;QAChBC,UAAUV,OAAOU;QACjBT;IACF;AACF;AAEA,MAAMU,kBAAkB;IACtBC,OAAO;QAAC;QAAS;QAAW;QAAW;KAAW;IAClDC,SAAS3C;AACX;AACA,eAAeyC,gBAAgB"}
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../../node_modules/ses/types.d.ts" />
3
3
  import { logError } from '@metamask/snaps-utils';
4
4
  /**
5
5
  * The SES `lockdown` function only hardens the properties enumerated by the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/lockdown/lockdown-more.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n logError('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"],"names":["logError","executeLockdownMore","namedIntrinsics","Reflect","ownKeys","Compartment","globalThis","shouldHardenManually","Set","globalProperties","forEach","propertyName","descriptor","getOwnPropertyDescriptor","configurable","hasAccessor","Object","defineProperty","writable","has","harden","error"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;AAEnE,SAASA,QAAQ,QAAQ,wBAAwB;AAEjD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASC;IACd,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAMC,kBAAkBC,QAAQC,OAAO,CAAC,IAAIC,cAAcC,UAAU;QAEpE,sEAAsE;QACtE,MAAMC,uBAAuB,IAAIC,IAAqB;YAAC;YAAQ;SAAW;QAE1E,MAAMC,mBAAmB,IAAID,IAAI;YAC/B,yEAAyE;YACzE,oEAAoE;YACpE,8CAA8C;eAC3CN;SAKJ;QAEDO,iBAAiBC,OAAO,CAAC,CAACC;YACxB,MAAMC,aAAaT,QAAQU,wBAAwB,CACjDP,YACAK;YAGF,IAAIC,YAAY;gBACd,IAAIA,WAAWE,YAAY,EAAE;oBAC3B,yDAAyD;oBACzD,mEAAmE;oBACnE,gBAAgB;oBAChB,IAAIC,YAAYH,aAAa;wBAC3BI,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;wBAChB;oBACF,OAAO;wBACLE,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;4BACdI,UAAU;wBACZ;oBACF;gBACF;gBAEA,IAAIX,qBAAqBY,GAAG,CAACR,eAAe;oBAC1CS,OAAO,AAACd,UAAkB,CAACK,aAAa;gBAC1C;YACF;QACF;IACF,EAAE,OAAOU,OAAO;QACdrB,SAAS,iCAAiCqB;QAC1C,MAAMA;IACR;AACF;AAEA;;;;;;;;;CASC,GACD,SAASN,YAAYH,UAAe;IAClC,OAAO,SAASA,cAAc,SAASA;AACzC"}
1
+ {"version":3,"sources":["../../../../src/common/lockdown/lockdown-more.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/types.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n logError('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"],"names":["logError","executeLockdownMore","namedIntrinsics","Reflect","ownKeys","Compartment","globalThis","shouldHardenManually","Set","globalProperties","forEach","propertyName","descriptor","getOwnPropertyDescriptor","configurable","hasAccessor","Object","defineProperty","writable","has","harden","error"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;AAEnE,SAASA,QAAQ,QAAQ,wBAAwB;AAEjD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASC;IACd,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAMC,kBAAkBC,QAAQC,OAAO,CAAC,IAAIC,cAAcC,UAAU;QAEpE,sEAAsE;QACtE,MAAMC,uBAAuB,IAAIC,IAAqB;YAAC;YAAQ;SAAW;QAE1E,MAAMC,mBAAmB,IAAID,IAAI;YAC/B,yEAAyE;YACzE,oEAAoE;YACpE,8CAA8C;eAC3CN;SAKJ;QAEDO,iBAAiBC,OAAO,CAAC,CAACC;YACxB,MAAMC,aAAaT,QAAQU,wBAAwB,CACjDP,YACAK;YAGF,IAAIC,YAAY;gBACd,IAAIA,WAAWE,YAAY,EAAE;oBAC3B,yDAAyD;oBACzD,mEAAmE;oBACnE,gBAAgB;oBAChB,IAAIC,YAAYH,aAAa;wBAC3BI,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;wBAChB;oBACF,OAAO;wBACLE,OAAOC,cAAc,CAACX,YAAYK,cAAc;4BAC9CG,cAAc;4BACdI,UAAU;wBACZ;oBACF;gBACF;gBAEA,IAAIX,qBAAqBY,GAAG,CAACR,eAAe;oBAC1CS,OAAO,AAACd,UAAkB,CAACK,aAAa;gBAC1C;YACF;QACF;IACF,EAAE,OAAOU,OAAO;QACdrB,SAAS,iCAAiCqB;QAC1C,MAAMA;IACR;AACF;AAEA;;;;;;;;;CASC,GACD,SAASN,YAAYH,UAAe;IAClC,OAAO,SAASA,cAAc,SAASA;AACzC"}
@@ -1,5 +1,5 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
- /// <reference path="../../../../../node_modules/ses/index.d.ts" />
2
+ /// <reference path="../../../../../node_modules/ses/types.d.ts" />
3
3
  import { logError } from '@metamask/snaps-utils';
4
4
  /**
5
5
  * Execute SES lockdown in the current context, i.e., the current iframe.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/lockdown/lockdown.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n logError('Lockdown failed:', error);\n throw error;\n }\n}\n"],"names":["logError","executeLockdown","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","error"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;AAEnE,SAASA,QAAQ,QAAQ,wBAAwB;AAEjD;;;;CAIC,GACD,OAAO,SAASC;IACd,IAAI;QACFC,SAAS;YACPC,eAAe;YACfC,aAAa;YACbC,YAAY;YACZC,YAAY;YACZC,gBAAgB;QAClB;IACF,EAAE,OAAOC,OAAO;QACd,gFAAgF;QAChFR,SAAS,oBAAoBQ;QAC7B,MAAMA;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../src/common/lockdown/lockdown.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/types.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n logError('Lockdown failed:', error);\n throw error;\n }\n}\n"],"names":["logError","executeLockdown","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","error"],"mappings":"AAAA,qFAAqF;AACrF,mEAAmE;AAEnE,SAASA,QAAQ,QAAQ,wBAAwB;AAEjD;;;;CAIC,GACD,OAAO,SAASC;IACd,IAAI;QACFC,SAAS;YACPC,eAAe;YACfC,aAAa;YACbC,YAAY;YACZC,YAAY;YACZC,gBAAgB;QAClB;IACF,EAAE,OAAOC,OAAO;QACd,gFAAgF;QAChFR,SAAS,oBAAoBQ;QAC7B,MAAMA;IACR;AACF"}
@@ -1,7 +1,21 @@
1
1
  declare const endowmentModule: {
2
- names: readonly ["fetch"];
2
+ names: readonly ["fetch", "Request", "Headers", "Response"];
3
3
  factory: () => {
4
4
  fetch: typeof fetch;
5
+ Request: {
6
+ new (input: URL | RequestInfo, init?: RequestInit | undefined): Request;
7
+ prototype: Request;
8
+ };
9
+ Headers: {
10
+ new (init?: HeadersInit | undefined): Headers;
11
+ prototype: Headers;
12
+ };
13
+ Response: {
14
+ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response;
15
+ prototype: Response;
16
+ error(): Response;
17
+ redirect(url: string | URL, status?: number | undefined): Response;
18
+ };
5
19
  teardownFunction: () => Promise<void>;
6
20
  };
7
21
  };