@metamask/snaps-execution-environments 3.3.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -1
- package/dist/browserify/iframe/bundle.js +1 -1
- package/dist/browserify/node-process/bundle.js +1 -1
- package/dist/browserify/node-thread/bundle.js +1 -1
- package/dist/browserify/offscreen/bundle.js +1 -1
- package/dist/browserify/worker-executor/bundle.js +1 -1
- package/dist/browserify/worker-pool/bundle.js +4 -4
- package/dist/cjs/common/BaseSnapExecutor.js +23 -5
- package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
- package/dist/cjs/common/endowments/commonEndowmentFactory.js.map +1 -1
- package/dist/cjs/common/endowments/index.js +3 -2
- package/dist/cjs/common/endowments/index.js.map +1 -1
- package/dist/cjs/common/endowments/network.js +130 -43
- package/dist/cjs/common/endowments/network.js.map +1 -1
- package/dist/cjs/common/validation.js +1 -1
- package/dist/cjs/common/validation.js.map +1 -1
- package/dist/esm/common/BaseSnapExecutor.js +23 -5
- package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
- package/dist/esm/common/endowments/commonEndowmentFactory.js.map +1 -1
- package/dist/esm/common/endowments/index.js +9 -6
- package/dist/esm/common/endowments/index.js.map +1 -1
- package/dist/esm/common/endowments/network.js +129 -42
- package/dist/esm/common/endowments/network.js.map +1 -1
- package/dist/esm/common/validation.js +1 -1
- package/dist/esm/common/validation.js.map +1 -1
- package/dist/types/common/BaseSnapExecutor.d.ts +3 -2
- package/dist/types/common/endowments/commonEndowmentFactory.d.ts +2 -0
- package/dist/types/common/endowments/index.d.ts +14 -5
- package/dist/types/common/endowments/network.d.ts +2 -1
- package/dist/types/common/validation.d.ts +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n
|
|
1
|
+
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAqBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;2BA3KU;4BACiB;uBAQpC;6BAgBA;AAEA,MAAMX,gCAAgCY,IAAAA,mBAAM,EACjDC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;CAAK,GACjCC,IAAAA,mBAAM,EAAC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oC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMC,qBAAqB;IAAEP,SAASC,yBAAa;AAAC;AACpD,MAAMO,sBAAsBhC,IAAAA,mBAAM,EAAC;IACjC,GAAG+B,kBAAkB;IACrBE,SAAS7B,IAAAA,mBAAM;AACjB;AACA,MAAM8B,uBAAuBlC,IAAAA,mBAAM,EAAC;IAClC,GAAG+B,kBAAkB;IACrBI,QAAQ/B,IAAAA,mBAAM;AAChB;AAEO,MAAMT,qCAAqCiB,IAAAA,kBAAK,EAAC;IACtDoB;IACAE;CACD;AAmBM,SAAStC,qCACdS,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAV,oCACA,0BACAkC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMM,mBAAmBvC,IAAAA,mBAAM,EAC7BwC,2BAAoB,EACpBrC,IAAAA,mBAAM,EAAC;IACLsC,QAAQ5B;AACV;AAGF,MAAM6B,kBAAkBF,2BAAoB"}
|
|
@@ -189,7 +189,13 @@ export class BaseSnapExecutor {
|
|
|
189
189
|
exports: {}
|
|
190
190
|
};
|
|
191
191
|
try {
|
|
192
|
-
const { endowments, teardown: endowmentTeardown } = createEndowments(
|
|
192
|
+
const { endowments, teardown: endowmentTeardown } = createEndowments({
|
|
193
|
+
snap,
|
|
194
|
+
ethereum,
|
|
195
|
+
snapId,
|
|
196
|
+
endowments: _endowments,
|
|
197
|
+
notify: _class_private_method_get(this, _notify, notify).bind(this)
|
|
198
|
+
});
|
|
193
199
|
// !!! Ensure that this is the only place the data is being set.
|
|
194
200
|
// Other methods access the object value and mutate its properties.
|
|
195
201
|
this.snapData.set(snapId, {
|
|
@@ -267,13 +273,19 @@ export class BaseSnapExecutor {
|
|
|
267
273
|
assertSnapOutboundRequest(sanitizedArgs);
|
|
268
274
|
return await withTeardown((async ()=>{
|
|
269
275
|
await _class_private_method_get(this, _notify, notify).call(this, {
|
|
270
|
-
method: 'OutboundRequest'
|
|
276
|
+
method: 'OutboundRequest',
|
|
277
|
+
params: {
|
|
278
|
+
source: 'snap.request'
|
|
279
|
+
}
|
|
271
280
|
});
|
|
272
281
|
try {
|
|
273
282
|
return await originalRequest(sanitizedArgs);
|
|
274
283
|
} finally{
|
|
275
284
|
await _class_private_method_get(this, _notify, notify).call(this, {
|
|
276
|
-
method: 'OutboundResponse'
|
|
285
|
+
method: 'OutboundResponse',
|
|
286
|
+
params: {
|
|
287
|
+
source: 'snap.request'
|
|
288
|
+
}
|
|
277
289
|
});
|
|
278
290
|
}
|
|
279
291
|
})(), this);
|
|
@@ -307,13 +319,19 @@ export class BaseSnapExecutor {
|
|
|
307
319
|
assertEthereumOutboundRequest(sanitizedArgs);
|
|
308
320
|
return await withTeardown((async ()=>{
|
|
309
321
|
await _class_private_method_get(this, _notify, notify).call(this, {
|
|
310
|
-
method: 'OutboundRequest'
|
|
322
|
+
method: 'OutboundRequest',
|
|
323
|
+
params: {
|
|
324
|
+
source: 'ethereum.request'
|
|
325
|
+
}
|
|
311
326
|
});
|
|
312
327
|
try {
|
|
313
328
|
return await originalRequest(sanitizedArgs);
|
|
314
329
|
} finally{
|
|
315
330
|
await _class_private_method_get(this, _notify, notify).call(this, {
|
|
316
|
-
method: 'OutboundResponse'
|
|
331
|
+
method: 'OutboundResponse',
|
|
332
|
+
params: {
|
|
333
|
+
source: 'ethereum.request'
|
|
334
|
+
}
|
|
317
335
|
});
|
|
318
336
|
}
|
|
319
337
|
})(), this);
|
|
@@ -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/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\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 type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\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 sanitizeRequestArguments,\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\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\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 rpcErrors.methodNotSupported,\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 let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\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 rpcErrors.internal(\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 serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\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 await this.#respond(id, {\n error: rpcErrors\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 await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#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\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\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\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): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\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 SnapsProvider;\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 const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\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 rpcErrors.internal(\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 rpcErrors.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 } catch (error) {\n throw new WrappedSnapError(error);\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":["createIdRemapMiddleware","StreamProvider","errorCodes","rpcErrors","serializeError","getErrorData","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","WrappedSnapError","unwrapError","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","unhandledError","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","serializedError","shouldIncludeStack","errorData","notify","method","catch","notifyError","onCommandRequest","invalidRequest","id","respond","methodNotFound","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","Error","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","cause","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","commandStream","Map","on","target","handlerType","handler","required","methodNotSupported","replace","chunk","resolve","write","requestObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAChE,SAASA,uBAAuB,QAAQ,4BAA4B;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,uBAAuB;AAE7E,SAASC,YAAY,QAAQ,sBAAsB;AAMnD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,gBAAgB,EAChBC,WAAW,QACN,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AAEzB,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,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,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAM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A,MAAagC,KAAW;IACtB,OAAO,IAAIjB,QAAc,CAACkB,SAAShB;QACjC,IAAI,CAACM,aAAa,CAACW,KAAK,CAACF,OAAO,CAACxG;YAC/B,IAAIA,OAAO;gBACTyF,OAAOzF;gBACP;YACF;YACAyG;QACF;IACF;AACF;AAEA,eAAA,OAAcE,aAAmD;IAC/D,IAAI,CAAChJ,YAAYgJ,kBAAkB,CAACjJ,SAASiJ,gBAAgB;QAC3D,MAAMzJ,UAAUiC,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEuH,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBC,SAAS;IACX;AACF;AAEA,eAAA,QAAejG,EAAa,EAAEgG,aAAsC;IAClE,IAAI,CAAChJ,YAAYgJ,kBAAkB,CAACjJ,SAASiJ,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;YAChB1G,OAAO7C,eACLD,UAAUiC,QAAQ,CAChB;YAGJwB;YACAiG,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAEF,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBhG;QACAiG,SAAS;IACX;AACF"}
|
|
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 { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\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 type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\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 sanitizeRequestArguments,\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\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\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 type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\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 rpcErrors.methodNotSupported,\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 let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\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 rpcErrors.internal(\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 serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\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 await this.#respond(id, {\n error: rpcErrors\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 await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#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: _endowments,\n notify: this.#notify.bind(this),\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\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\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\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): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\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 SnapsProvider;\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 const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\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 rpcErrors.internal(\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 rpcErrors.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 } catch (error) {\n throw new WrappedSnapError(error);\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":["createIdRemapMiddleware","StreamProvider","errorCodes","rpcErrors","serializeError","getErrorData","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","WrappedSnapError","unwrapError","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","unhandledError","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","serializedError","shouldIncludeStack","errorData","notify","method","catch","notifyError","onCommandRequest","invalidRequest","id","respond","methodNotFound","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","Error","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","bind","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","args","sanitizedArgs","source","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","commandStream","Map","on","target","handlerType","handler","required","methodNotSupported","replace","chunk","resolve","write","requestObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAChE,SAASA,uBAAuB,QAAQ,4BAA4B;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,uBAAuB;AAE7E,SAASC,YAAY,QAAQ,sBAAsB;AAMnD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,gBAAgB,EAChBC,WAAW,QACN,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AAEzB,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,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,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA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":["import { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["rootRealmGlobal","consoleEndowment","crypto","date","interval","math","network","textDecoder","textEncoder","timeout","commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","forEach","endowmentSpecification","names","factory","boundEndowment","harden","push"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["rootRealmGlobal","consoleEndowment","crypto","date","interval","math","network","textDecoder","textEncoder","timeout","commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEnd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C/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CjC;QACAE;QACAC;QACAC;QACAG;QACAF;QACAC;QACAL;QACAF;KACD;IAEDS,iBAAiB0B,OAAO,CAAC,CAACC;QACxB,MAAM1B,YAAY;YAChB2B,OAAO;gBAACD,uBAAuBxB,IAAI;aAAC;YACpC0B,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuB1B,SAAS,KAAK,cAC5C0B,uBAAuBpB,IAAI,GACvBoB,uBAAuB1B,SAAS,CAACM,IAAI,CAACjB,mBACtCqC,uBAAuB1B,SAAS;gBACtC,OAAO;oBACL,CAAC0B,uBAAuBxB,IAAI,CAAC,EAAE4B,OAAOD;gBACxC;YACF;QACF;QACAL,mBAAmBO,IAAI,CAAC/B;IAC1B;IAEA,OAAOwB;AACT;AAEA,eAAeD,sBAAsB"}
|
|
@@ -23,12 +23,14 @@ import buildCommonEndowments from './commonEndowmentFactory';
|
|
|
23
23
|
* such attenuated / modified endowments. Otherwise, the value that's on the
|
|
24
24
|
* root realm global will be used.
|
|
25
25
|
*
|
|
26
|
-
* @param
|
|
27
|
-
* @param
|
|
28
|
-
* @param
|
|
29
|
-
* @param
|
|
26
|
+
* @param options - An options bag.
|
|
27
|
+
* @param options.snap - The Snaps global API object.
|
|
28
|
+
* @param options.ethereum - The Snap's EIP-1193 provider object.
|
|
29
|
+
* @param options.snapId - The id of the snap that will use the created endowments.
|
|
30
|
+
* @param options.endowments - The list of endowments to provide to the snap.
|
|
31
|
+
* @param options.notify - A reference to the notify function of the snap executor.
|
|
30
32
|
* @returns An object containing the Snap's endowments.
|
|
31
|
-
*/ export function createEndowments(snap, ethereum, snapId, endowments
|
|
33
|
+
*/ export function createEndowments({ snap, ethereum, snapId, endowments, notify }) {
|
|
32
34
|
const attenuatedEndowments = {};
|
|
33
35
|
// TODO: All endowments should be hardened to prevent covert communication
|
|
34
36
|
// channels. Hardening the returned objects breaks tests elsewhere in the
|
|
@@ -45,7 +47,8 @@ import buildCommonEndowments from './commonEndowmentFactory';
|
|
|
45
47
|
// We just confirmed that endowmentFactories has the specified key.
|
|
46
48
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
47
49
|
const { teardownFunction, ...endowment } = endowmentFactories.get(endowmentName)({
|
|
48
|
-
snapId
|
|
50
|
+
snapId,
|
|
51
|
+
notify
|
|
49
52
|
});
|
|
50
53
|
Object.assign(attenuatedEndowments, endowment);
|
|
51
54
|
if (teardownFunction) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsProvider
|
|
1
|
+
{"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param options - An options bag.\n * @param options.snap - The Snaps global API object.\n * @param options.ethereum - The Snap's EIP-1193 provider object.\n * @param options.snapId - The id of the snap that will use the created endowments.\n * @param options.endowments - The list of endowments to provide to the snap.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments({\n snap,\n ethereum,\n snapId,\n endowments,\n notify,\n}: {\n snap: SnapsProvider;\n ethereum: StreamProvider;\n snapId: string;\n endowments: string[];\n notify: NotifyFunction;\n}): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId, notify });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["rpcErrors","logWarning","hasProperty","rootRealmGlobal","buildCommonEndowments","registeredEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","createEndowments","snap","ethereum","snapId","endowments","notify","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","teardownFunction","endowment","get","Object","assign","push","globalValue","internal","teardown","Promise","all","map"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,WAAW,QAAQ,kBAAkB;AAG9C,SAASC,eAAe,QAAQ,kBAAkB;AAElD,OAAOC,2BAA2B,2BAA2B;AAe7D;;CAEC,GACD,MAAMC,uBAAuBD;AAE7B;;;;CAIC,GACD,MAAME,qBAAqBD,qBAAqBE,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAEP;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,iBAAiB,EAC/BC,IAAI,EACJC,QAAQ,EACRC,MAAM,EACNC,UAAU,EACVC,MAAM,EAOP;IACC,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASH,WAAWb,MAAM,CAI9B,CAAC,EAAEiB,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIpB,mBAAmBqB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACxB,YAAYoB,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEE,gBAAgB,EAAE,GAAGC,WAAW,GAAGvB,mBAAmBwB,GAAG,CAC/DJ,eACC;oBAAEP;oBAAQE;gBAAO;gBACpBU,OAAOC,MAAM,CAACV,sBAAsBO;gBACpC,IAAID,kBAAkB;oBACpBH,UAAUQ,IAAI,CAACL;gBACjB;YACF;YACAJ,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGR;QACjC,OAAO,IAAIQ,iBAAiBvB,iBAAiB;YAC3CF,WAAW,CAAC,4BAA4B,EAAEyB,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMQ,cAAc,AAAC/B,eAA2C,CAC9DuB,cACD;YACDF,aAAa,CAACE,cAAc,GAAGQ;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAMlC,UAAUmC,QAAQ,CAAC,CAAC,oBAAoB,EAAET,cAAc,EAAE,CAAC;QACnE;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEP;QAAK;QACtBQ,WAAW,EAAE;IACf;IAGF,MAAMW,WAAW;QACf,MAAMC,QAAQC,GAAG,CACff,OAAOE,SAAS,CAACc,GAAG,CAAC,CAACX,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYG,OAAOC,aAAa;QAAEY;IAAS;AACtD"}
|
|
@@ -38,8 +38,9 @@ function _class_private_field_set(receiver, privateMap, value) {
|
|
|
38
38
|
_class_apply_descriptor_set(receiver, descriptor, value);
|
|
39
39
|
return value;
|
|
40
40
|
}
|
|
41
|
+
import { assert } from '@metamask/utils';
|
|
41
42
|
import { withTeardown } from '../utils';
|
|
42
|
-
var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new WeakMap();
|
|
43
|
+
var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new WeakMap(), _onStart = /*#__PURE__*/ new WeakMap(), _onFinish = /*#__PURE__*/ new WeakMap();
|
|
43
44
|
/**
|
|
44
45
|
* This class wraps a Response object.
|
|
45
46
|
* That way, a teardown process can stop any processes left.
|
|
@@ -72,25 +73,60 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
|
|
|
72
73
|
return _class_private_field_get(this, _ogResponse).url;
|
|
73
74
|
}
|
|
74
75
|
async text() {
|
|
75
|
-
return withTeardown(
|
|
76
|
+
return await withTeardown((async ()=>{
|
|
77
|
+
await _class_private_field_get(this, _onStart).call(this);
|
|
78
|
+
try {
|
|
79
|
+
return await _class_private_field_get(this, _ogResponse).text();
|
|
80
|
+
} finally{
|
|
81
|
+
await _class_private_field_get(this, _onFinish).call(this);
|
|
82
|
+
}
|
|
83
|
+
})(), _class_private_field_get(this, _teardownRef));
|
|
76
84
|
}
|
|
77
85
|
async arrayBuffer() {
|
|
78
|
-
return withTeardown(
|
|
86
|
+
return await withTeardown((async ()=>{
|
|
87
|
+
await _class_private_field_get(this, _onStart).call(this);
|
|
88
|
+
try {
|
|
89
|
+
return await _class_private_field_get(this, _ogResponse).arrayBuffer();
|
|
90
|
+
} finally{
|
|
91
|
+
await _class_private_field_get(this, _onFinish).call(this);
|
|
92
|
+
}
|
|
93
|
+
})(), _class_private_field_get(this, _teardownRef));
|
|
79
94
|
}
|
|
80
95
|
async blob() {
|
|
81
|
-
return withTeardown(
|
|
96
|
+
return await withTeardown((async ()=>{
|
|
97
|
+
await _class_private_field_get(this, _onStart).call(this);
|
|
98
|
+
try {
|
|
99
|
+
return await _class_private_field_get(this, _ogResponse).blob();
|
|
100
|
+
} finally{
|
|
101
|
+
await _class_private_field_get(this, _onFinish).call(this);
|
|
102
|
+
}
|
|
103
|
+
})(), _class_private_field_get(this, _teardownRef));
|
|
82
104
|
}
|
|
83
105
|
clone() {
|
|
84
106
|
const newResponse = _class_private_field_get(this, _ogResponse).clone();
|
|
85
|
-
return new ResponseWrapper(newResponse, _class_private_field_get(this, _teardownRef));
|
|
107
|
+
return new ResponseWrapper(newResponse, _class_private_field_get(this, _teardownRef), _class_private_field_get(this, _onStart), _class_private_field_get(this, _onFinish));
|
|
86
108
|
}
|
|
87
109
|
async formData() {
|
|
88
|
-
return withTeardown(
|
|
110
|
+
return await withTeardown((async ()=>{
|
|
111
|
+
await _class_private_field_get(this, _onStart).call(this);
|
|
112
|
+
try {
|
|
113
|
+
return await _class_private_field_get(this, _ogResponse).formData();
|
|
114
|
+
} finally{
|
|
115
|
+
await _class_private_field_get(this, _onFinish).call(this);
|
|
116
|
+
}
|
|
117
|
+
})(), _class_private_field_get(this, _teardownRef));
|
|
89
118
|
}
|
|
90
119
|
async json() {
|
|
91
|
-
return withTeardown(
|
|
120
|
+
return await withTeardown((async ()=>{
|
|
121
|
+
await _class_private_field_get(this, _onStart).call(this);
|
|
122
|
+
try {
|
|
123
|
+
return await _class_private_field_get(this, _ogResponse).json();
|
|
124
|
+
} finally{
|
|
125
|
+
await _class_private_field_get(this, _onFinish).call(this);
|
|
126
|
+
}
|
|
127
|
+
})(), _class_private_field_get(this, _teardownRef));
|
|
92
128
|
}
|
|
93
|
-
constructor(ogResponse, teardownRef){
|
|
129
|
+
constructor(ogResponse, teardownRef, onStart, onFinish){
|
|
94
130
|
_class_private_field_init(this, _teardownRef, {
|
|
95
131
|
writable: true,
|
|
96
132
|
value: void 0
|
|
@@ -99,8 +135,18 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
|
|
|
99
135
|
writable: true,
|
|
100
136
|
value: void 0
|
|
101
137
|
});
|
|
138
|
+
_class_private_field_init(this, _onStart, {
|
|
139
|
+
writable: true,
|
|
140
|
+
value: void 0
|
|
141
|
+
});
|
|
142
|
+
_class_private_field_init(this, _onFinish, {
|
|
143
|
+
writable: true,
|
|
144
|
+
value: void 0
|
|
145
|
+
});
|
|
102
146
|
_class_private_field_set(this, _ogResponse, ogResponse);
|
|
103
147
|
_class_private_field_set(this, _teardownRef, teardownRef);
|
|
148
|
+
_class_private_field_set(this, _onStart, onStart);
|
|
149
|
+
_class_private_field_set(this, _onFinish, onFinish);
|
|
104
150
|
}
|
|
105
151
|
}
|
|
106
152
|
/**
|
|
@@ -113,9 +159,12 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
|
|
|
113
159
|
* to ensure that a bad actor cannot get access to the original function, thus
|
|
114
160
|
* potentially preventing the network requests from being torn down.
|
|
115
161
|
*
|
|
162
|
+
* @param options - An options bag.
|
|
163
|
+
* @param options.notify - A reference to the notify function of the snap executor.
|
|
116
164
|
* @returns An object containing a wrapped `fetch`
|
|
117
165
|
* function, as well as a teardown function.
|
|
118
|
-
*/ const createNetwork = ()=>{
|
|
166
|
+
*/ const createNetwork = ({ notify } = {})=>{
|
|
167
|
+
assert(notify, 'Notify must be passed to network endowment factory');
|
|
119
168
|
// Open fetch calls or open body streams
|
|
120
169
|
const openConnections = new Set();
|
|
121
170
|
// Track last teardown count
|
|
@@ -135,43 +184,81 @@ var _teardownRef = /*#__PURE__*/ new WeakMap(), _ogResponse = /*#__PURE__*/ new
|
|
|
135
184
|
once: true
|
|
136
185
|
});
|
|
137
186
|
}
|
|
187
|
+
let started = false;
|
|
188
|
+
const onStart = async ()=>{
|
|
189
|
+
if (!started) {
|
|
190
|
+
started = true;
|
|
191
|
+
await notify({
|
|
192
|
+
method: 'OutboundRequest',
|
|
193
|
+
params: {
|
|
194
|
+
source: 'fetch'
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
let finished = false;
|
|
200
|
+
const onFinish = async ()=>{
|
|
201
|
+
if (!finished) {
|
|
202
|
+
finished = true;
|
|
203
|
+
await notify({
|
|
204
|
+
method: 'OutboundResponse',
|
|
205
|
+
params: {
|
|
206
|
+
source: 'fetch'
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
};
|
|
138
211
|
let res;
|
|
139
212
|
let openFetchConnection;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
213
|
+
return await withTeardown((async ()=>{
|
|
214
|
+
try {
|
|
215
|
+
await notify({
|
|
216
|
+
method: 'OutboundRequest',
|
|
217
|
+
params: {
|
|
218
|
+
source: 'fetch'
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
const fetchPromise = fetch(input, {
|
|
222
|
+
...init,
|
|
223
|
+
signal: abortController.signal
|
|
224
|
+
});
|
|
225
|
+
openFetchConnection = {
|
|
226
|
+
cancel: async ()=>{
|
|
227
|
+
abortController.abort();
|
|
228
|
+
try {
|
|
229
|
+
await fetchPromise;
|
|
230
|
+
} catch {
|
|
231
|
+
/* do nothing */ }
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
openConnections.add(openFetchConnection);
|
|
235
|
+
res = new ResponseWrapper(await fetchPromise, teardownRef, onStart, onFinish);
|
|
236
|
+
} finally{
|
|
237
|
+
if (openFetchConnection !== undefined) {
|
|
238
|
+
openConnections.delete(openFetchConnection);
|
|
152
239
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
240
|
+
await notify({
|
|
241
|
+
method: 'OutboundResponse',
|
|
242
|
+
params: {
|
|
243
|
+
source: 'fetch'
|
|
244
|
+
}
|
|
245
|
+
});
|
|
159
246
|
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
247
|
+
if (res.body !== null) {
|
|
248
|
+
const body = new WeakRef(res.body);
|
|
249
|
+
const openBodyConnection = {
|
|
250
|
+
cancel: /* istanbul ignore next: see it.todo('can be torn down during body read') test */ async ()=>{
|
|
251
|
+
try {
|
|
252
|
+
await body.deref()?.cancel();
|
|
253
|
+
} catch {
|
|
254
|
+
/* do nothing */ }
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
openConnections.add(openBodyConnection);
|
|
258
|
+
cleanup.register(res.body, /* istanbul ignore next: can't test garbage collection without modifying node parameters */ ()=>openConnections.delete(openBodyConnection));
|
|
259
|
+
}
|
|
260
|
+
return harden(res);
|
|
261
|
+
})(), teardownRef);
|
|
175
262
|
};
|
|
176
263
|
const teardownFunction = async ()=>{
|
|
177
264
|
teardownRef.lastTeardown += 1;
|