@metamask/snaps-execution-environments 0.28.0 → 0.29.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/dist/common/BaseSnapExecutor.js +4 -3
- package/dist/common/BaseSnapExecutor.js.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.d.ts +19 -0
- package/dist/common/endowments/commonEndowmentFactory.js +69 -0
- package/dist/common/endowments/commonEndowmentFactory.js.map +1 -0
- package/dist/common/endowments/crypto.js +4 -1
- package/dist/common/endowments/crypto.js.map +1 -1
- package/dist/common/endowments/date.d.ts +15 -0
- package/dist/common/endowments/date.js +39 -0
- package/dist/common/endowments/date.js.map +1 -0
- package/dist/common/endowments/index.d.ts +1 -1
- package/dist/common/endowments/index.js +6 -6
- package/dist/common/endowments/index.js.map +1 -1
- package/dist/common/endowments/interval.js +7 -4
- package/dist/common/endowments/interval.js.map +1 -1
- package/dist/common/endowments/math.js +2 -2
- package/dist/common/endowments/math.js.map +1 -1
- package/dist/common/endowments/network.js +2 -2
- package/dist/common/endowments/network.js.map +1 -1
- package/dist/common/endowments/textDecoder.d.ts +10 -0
- package/dist/common/endowments/textDecoder.js +18 -0
- package/dist/common/endowments/textDecoder.js.map +1 -0
- package/dist/common/endowments/textEncoder.d.ts +10 -0
- package/dist/common/endowments/textEncoder.js +18 -0
- package/dist/common/endowments/textEncoder.js.map +1 -0
- package/dist/common/endowments/timeout.js +6 -4
- package/dist/common/endowments/timeout.js.map +1 -1
- package/dist/common/lockdown/lockdown-more.js +2 -1
- package/dist/common/lockdown/lockdown-more.js.map +1 -1
- package/dist/common/lockdown/lockdown.js +2 -1
- package/dist/common/lockdown/lockdown.js.map +1 -1
- package/dist/common/utils.js +3 -2
- package/dist/common/utils.js.map +1 -1
- package/dist/iframe/IFrameSnapExecutor.js +3 -2
- package/dist/iframe/IFrameSnapExecutor.js.map +1 -1
- package/dist/logging.d.ts +8 -0
- package/dist/logging.js +13 -0
- package/dist/logging.js.map +1 -0
- package/dist/node-process/ChildProcessSnapExecutor.js +3 -2
- package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -1
- package/dist/node-thread/ThreadSnapExecutor.js +3 -2
- package/dist/node-thread/ThreadSnapExecutor.js.map +1 -1
- package/dist/offscreen/OffscreenSnapExecutor.js +1 -1
- package/dist/offscreen/OffscreenSnapExecutor.js.map +1 -1
- package/dist/webpack/iframe/bundle.js +2 -2
- package/dist/webpack/node-process/bundle.js +2 -2
- package/dist/webpack/node-thread/bundle.js +2 -2
- package/dist/webpack/offscreen/bundle.js +2 -2
- package/package.json +8 -6
|
@@ -12,6 +12,7 @@ const utils_1 = require("@metamask/utils");
|
|
|
12
12
|
const eth_rpc_errors_1 = require("eth-rpc-errors");
|
|
13
13
|
const json_rpc_engine_1 = require("json-rpc-engine");
|
|
14
14
|
const superstruct_1 = require("superstruct");
|
|
15
|
+
const logging_1 = require("../logging");
|
|
15
16
|
const openrpc_json_1 = __importDefault(require("../openrpc.json"));
|
|
16
17
|
const commands_1 = require("./commands");
|
|
17
18
|
const endowments_1 = require("./endowments");
|
|
@@ -55,7 +56,7 @@ class BaseSnapExecutor {
|
|
|
55
56
|
this.commandStream.on('data', (data) => {
|
|
56
57
|
this.onCommandRequest(data).catch((error) => {
|
|
57
58
|
// TODO: Decide how to handle errors.
|
|
58
|
-
|
|
59
|
+
(0, snaps_utils_1.logError)(error);
|
|
59
60
|
});
|
|
60
61
|
});
|
|
61
62
|
this.rpcStream = rpcStream;
|
|
@@ -166,7 +167,7 @@ class BaseSnapExecutor {
|
|
|
166
167
|
* @param _endowments - An array of the names of the endowments.
|
|
167
168
|
*/
|
|
168
169
|
async startSnap(snapName, sourceCode, _endowments) {
|
|
169
|
-
|
|
170
|
+
(0, logging_1.log)(`Starting snap '${snapName}' in worker.`);
|
|
170
171
|
if (this.snapPromiseErrorHandler) {
|
|
171
172
|
(0, globalEvents_1.removeEventListener)('unhandledrejection', this.snapPromiseErrorHandler);
|
|
172
173
|
}
|
|
@@ -255,7 +256,7 @@ class BaseSnapExecutor {
|
|
|
255
256
|
this.notify({ method: 'OutboundResponse' });
|
|
256
257
|
}
|
|
257
258
|
};
|
|
258
|
-
return { request };
|
|
259
|
+
return { request: request };
|
|
259
260
|
}
|
|
260
261
|
/**
|
|
261
262
|
* Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,mDAAqD;AAErD,uDAM+B;AAC/B,2CAUyB;AACzB,mDAAuE;AACvE,qDAA0D;AAE1D,6CAAuC;AAEvC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAAuD;AACvD,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EAAE,uCAA0B;QAClC,MAAM,EAAE,EAAE;KACX;IACD,WAAW,EAAE;QACX,MAAM,EAAE,8CAAiC;QACzC,MAAM,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC;KACjD;IACD,SAAS,EAAE;QACT,MAAM,EAAE,4CAA+B;QACvC,MAAM,EAAE,EAAE;KACX;IACD,OAAO,EAAE;QACP,MAAM,EAAE,0CAA6B;QACrC,MAAM,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,CAAC;KACnD;CACF,CAAC;AAEF,MAAa,gBAAgB;IAe3B,YAAsB,aAAqB,EAAE,SAAiB;QAFtD,iBAAY,GAAG,CAAC,CAAC;QAGvB,I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AAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;SACtD;gBAAS;YACR,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AAvZD,4CAuZC","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 { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport {\n SnapExports,\n SnapsGlobalObject,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\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\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\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: ['snapName', '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\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 console.error(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\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 assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\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 =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\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 snapName - The name 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 snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n console.log(`starting snap '${snapName}' 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, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\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 _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(snapName, {\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 window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(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(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\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 if (validateExport(exportName, 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 assert(\n args.method.startsWith('wallet_') || args.method.startsWith('snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return { request };\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 assert(\n !args.method.startsWith('snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // To harden and limit access to internals, we use a proxy.\n const proxy = new Proxy(provider, {\n get(target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return target[prop];\n }\n\n return undefined;\n },\n });\n\n return proxy;\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\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 snapName - The name 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 snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\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 \"${snapName}\" 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"]}
|
|
1
|
+
{"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,mDAAqD;AAGrD,uDAM+B;AAC/B,2CAUyB;AACzB,mDAAuE;AACvE,qDAA0D;AAE1D,6CAAuC;AAEvC,wCAAiC;AACjC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAAuD;AACvD,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EAAE,uCAA0B;QAClC,MAAM,EAAE,EAAE;KACX;IACD,WAAW,EAAE;QACX,MAAM,EAAE,8CAAiC;QACzC,MAAM,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC;KACjD;IACD,SAAS,EAAE;QACT,MAAM,EAAE,4CAA+B;QACvC,MAAM,EAAE,EAAE;KACX;IACD,OAAO,EAAE;QACP,MAAM,EAAE,0CAA6B;QACrC,MAAM,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,CAAC;KACnD;CACF,CAAC;AAEF,MAAa,gBAAgB;IAe3B,YAAsB,aAAqB,EAAE,SAAiB;QAFtD,iBAAY,GAAG,CAAC,CAAC;QAGvB,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,aAAa,CAAC,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cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AAvZD,4CAuZC","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 { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { RequestFunction, SnapsGlobalObject } from '@metamask/rpc-methods';\nimport {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\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\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\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: ['snapName', '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\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, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\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 assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\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 =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\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 snapName - The name 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 snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapName}' 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, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\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 _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(snapName, {\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 window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(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(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\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 if (validateExport(exportName, 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 assert(\n args.method.startsWith('wallet_') || args.method.startsWith('snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return { request: request as RequestFunction };\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 assert(\n !args.method.startsWith('snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // To harden and limit access to internals, we use a proxy.\n const proxy = new Proxy(provider, {\n get(target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return target[prop];\n }\n\n return undefined;\n },\n });\n\n return proxy;\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\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 snapName - The name 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 snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\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 \"${snapName}\" 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"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare type EndowmentFactory = {
|
|
2
|
+
names: readonly string[];
|
|
3
|
+
factory: () => {
|
|
4
|
+
[key: string]: unknown;
|
|
5
|
+
};
|
|
6
|
+
};
|
|
7
|
+
export declare type CommonEndowmentSpecification = {
|
|
8
|
+
endowment: unknown;
|
|
9
|
+
name: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Creates a consolidated collection of common endowments.
|
|
13
|
+
* This function will return factories for all common endowments including
|
|
14
|
+
* the additionally attenuated. All hardened with SES.
|
|
15
|
+
*
|
|
16
|
+
* @returns An object with common endowments.
|
|
17
|
+
*/
|
|
18
|
+
declare const buildCommonEndowments: () => EndowmentFactory[];
|
|
19
|
+
export default buildCommonEndowments;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const crypto_1 = __importDefault(require("./crypto"));
|
|
7
|
+
const date_1 = __importDefault(require("./date"));
|
|
8
|
+
const interval_1 = __importDefault(require("./interval"));
|
|
9
|
+
const math_1 = __importDefault(require("./math"));
|
|
10
|
+
const network_1 = __importDefault(require("./network"));
|
|
11
|
+
const textDecoder_1 = __importDefault(require("./textDecoder"));
|
|
12
|
+
const textEncoder_1 = __importDefault(require("./textEncoder"));
|
|
13
|
+
const timeout_1 = __importDefault(require("./timeout"));
|
|
14
|
+
// Array of common endowments
|
|
15
|
+
const commonEndowments = [
|
|
16
|
+
{ endowment: AbortController, name: 'AbortController' },
|
|
17
|
+
{ endowment: AbortSignal, name: 'AbortSignal' },
|
|
18
|
+
{ endowment: ArrayBuffer, name: 'ArrayBuffer' },
|
|
19
|
+
{ endowment: atob, name: 'atob' },
|
|
20
|
+
{ endowment: BigInt, name: 'BigInt' },
|
|
21
|
+
{ endowment: BigInt64Array, name: 'BigInt64Array' },
|
|
22
|
+
{ endowment: BigUint64Array, name: 'BigUint64Array' },
|
|
23
|
+
{ endowment: btoa, name: 'btoa' },
|
|
24
|
+
{ endowment: DataView, name: 'DataView' },
|
|
25
|
+
{ endowment: Float32Array, name: 'Float32Array' },
|
|
26
|
+
{ endowment: Float64Array, name: 'Float64Array' },
|
|
27
|
+
{ endowment: Int8Array, name: 'Int8Array' },
|
|
28
|
+
{ endowment: Int16Array, name: 'Int16Array' },
|
|
29
|
+
{ endowment: Int32Array, name: 'Int32Array' },
|
|
30
|
+
{ endowment: Uint8Array, name: 'Uint8Array' },
|
|
31
|
+
{ endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },
|
|
32
|
+
{ endowment: Uint16Array, name: 'Uint16Array' },
|
|
33
|
+
{ endowment: Uint32Array, name: 'Uint32Array' },
|
|
34
|
+
{ endowment: URL, name: 'URL' },
|
|
35
|
+
{ endowment: WebAssembly, name: 'WebAssembly' },
|
|
36
|
+
];
|
|
37
|
+
/**
|
|
38
|
+
* Creates a consolidated collection of common endowments.
|
|
39
|
+
* This function will return factories for all common endowments including
|
|
40
|
+
* the additionally attenuated. All hardened with SES.
|
|
41
|
+
*
|
|
42
|
+
* @returns An object with common endowments.
|
|
43
|
+
*/
|
|
44
|
+
const buildCommonEndowments = () => {
|
|
45
|
+
const endowmentFactories = [
|
|
46
|
+
crypto_1.default,
|
|
47
|
+
interval_1.default,
|
|
48
|
+
math_1.default,
|
|
49
|
+
network_1.default,
|
|
50
|
+
timeout_1.default,
|
|
51
|
+
textDecoder_1.default,
|
|
52
|
+
textEncoder_1.default,
|
|
53
|
+
date_1.default,
|
|
54
|
+
];
|
|
55
|
+
commonEndowments.forEach((endowmentSpecification) => {
|
|
56
|
+
const endowment = {
|
|
57
|
+
names: [endowmentSpecification.name],
|
|
58
|
+
factory: () => {
|
|
59
|
+
return {
|
|
60
|
+
[endowmentSpecification.name]: harden(endowmentSpecification.endowment),
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
endowmentFactories.push(endowment);
|
|
65
|
+
});
|
|
66
|
+
return endowmentFactories;
|
|
67
|
+
};
|
|
68
|
+
exports.default = buildCommonEndowments;
|
|
69
|
+
//# sourceMappingURL=commonEndowmentFactory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"commonEndowmentFactory.js","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AAAA,sDAA8B;AAC9B,kDAA0B;AAC1B,0DAAkC;AAClC,kDAA0B;AAC1B,wDAAgC;AAChC,gEAAwC;AACxC,gEAAwC;AACxC,wDAAgC;AAYhC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE;IACjC,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IACrC,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,EAAE;IACnD,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,EAAE,gBAAgB,EAAE;IACrD,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE;IACjC,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE;IACzC,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE;IACjD,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAE,cAAc,E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import 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 EndowmentFactory = {\n names: readonly string[];\n factory: () => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\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' },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa' },\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 ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n return {\n [endowmentSpecification.name]: harden(\n endowmentSpecification.endowment,\n ),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
|
|
@@ -15,7 +15,10 @@ const createCrypto = () => {
|
|
|
15
15
|
// TODO: Figure out if this is enough long-term or if we should use a polyfill.
|
|
16
16
|
/* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */
|
|
17
17
|
const crypto = require('crypto').webcrypto;
|
|
18
|
-
return {
|
|
18
|
+
return {
|
|
19
|
+
crypto: harden(crypto),
|
|
20
|
+
SubtleCrypto: harden(crypto.subtle.constructor),
|
|
21
|
+
};
|
|
19
22
|
};
|
|
20
23
|
const endowmentModule = {
|
|
21
24
|
names: ['crypto', 'SubtleCrypto'],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,8BAAe,CAAC,MAAM;YAC9B,YAAY,EAAE,8BAAe,CAAC,YAAY;SAC3C,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,8BAAe,CAAC,MAAM;YAC9B,YAAY,EAAE,8BAAe,CAAC,YAAY;SAC3C,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC;KACvC,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAU;IAC1C,OAAO,EAAE,YAAY;CACtB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nconst createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: rootRealmGlobal.crypto,\n SubtleCrypto: rootRealmGlobal.SubtleCrypto,\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a {@link Date} constructor, with most of the same properties as the global object.
|
|
3
|
+
* The Date.now() function has added noise as to limit its precision and prevent potential timing attacks.
|
|
4
|
+
* The Date constructor uses this now() function to seed itself if no arguments are given to the constructor.
|
|
5
|
+
*
|
|
6
|
+
* @returns A modified {@link Date} constructor with limited precision.
|
|
7
|
+
*/
|
|
8
|
+
declare function createDate(): {
|
|
9
|
+
Date: DateConstructor;
|
|
10
|
+
};
|
|
11
|
+
declare const endowmentModule: {
|
|
12
|
+
names: readonly ["Date"];
|
|
13
|
+
factory: typeof createDate;
|
|
14
|
+
};
|
|
15
|
+
export default endowmentModule;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const globalObject_1 = require("../globalObject");
|
|
4
|
+
/**
|
|
5
|
+
* Creates a {@link Date} constructor, with most of the same properties as the global object.
|
|
6
|
+
* The Date.now() function has added noise as to limit its precision and prevent potential timing attacks.
|
|
7
|
+
* The Date constructor uses this now() function to seed itself if no arguments are given to the constructor.
|
|
8
|
+
*
|
|
9
|
+
* @returns A modified {@link Date} constructor with limited precision.
|
|
10
|
+
*/
|
|
11
|
+
function createDate() {
|
|
12
|
+
const keys = Object.getOwnPropertyNames(globalObject_1.rootRealmGlobal.Date);
|
|
13
|
+
let currentTime = 0;
|
|
14
|
+
const now = () => {
|
|
15
|
+
const actual = globalObject_1.rootRealmGlobal.Date.now();
|
|
16
|
+
const newTime = Math.round(actual + Math.random());
|
|
17
|
+
if (newTime > currentTime) {
|
|
18
|
+
currentTime = newTime;
|
|
19
|
+
}
|
|
20
|
+
return currentTime;
|
|
21
|
+
};
|
|
22
|
+
const NewDate = function (...args) {
|
|
23
|
+
return Reflect.construct(globalObject_1.rootRealmGlobal.Date, args.length === 0 ? [now()] : args, new.target);
|
|
24
|
+
};
|
|
25
|
+
keys.forEach((key) => {
|
|
26
|
+
Reflect.defineProperty(NewDate, key, {
|
|
27
|
+
configurable: false,
|
|
28
|
+
writable: false,
|
|
29
|
+
value: key === 'now' ? now : globalObject_1.rootRealmGlobal.Date[key],
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
return { Date: harden(NewDate) };
|
|
33
|
+
}
|
|
34
|
+
const endowmentModule = {
|
|
35
|
+
names: ['Date'],
|
|
36
|
+
factory: createDate,
|
|
37
|
+
};
|
|
38
|
+
exports.default = endowmentModule;
|
|
39
|
+
//# sourceMappingURL=date.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"date.js","sourceRoot":"","sources":["../../../src/common/endowments/date.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,GAAG,GAAG,GAAG,EAAE;QACf,MAAM,MAAM,GAAG,8BAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QACnD,IAAI,OAAO,GAAG,WAAW,EAAE;YACzB,WAAW,GAAG,OAAO,CAAC;SACvB;QACD,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;IAEF,MAAM,OAAO,GAAG,UAAU,GAAG,IAAe;QAC1C,OAAO,OAAO,CAAC,SAAS,CACtB,8BAAe,CAAC,IAAI,EACpB,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAClC,GAAG,CAAC,MAAM,CACX,CAAC;IACJ,CAAoB,CAAC;IAErB,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QACnB,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE;YACnC,YAAY,EAAE,KAAK;YACnB,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC;SACvD,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;AACnC,CAAC;AAED,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,MAAM,CAAU;IACxB,OAAO,EAAE,UAAU;CACpB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\n/**\n * Creates a {@link Date} constructor, with most of the same properties as the global object.\n * The Date.now() function has added noise as to limit its precision and prevent potential timing attacks.\n * The Date constructor uses this now() function to seed itself if no arguments are given to the constructor.\n *\n * @returns A modified {@link Date} constructor with limited precision.\n */\nfunction createDate() {\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.Date,\n ) as (keyof typeof Date)[];\n\n let currentTime = 0;\n const now = () => {\n const actual = rootRealmGlobal.Date.now();\n const newTime = Math.round(actual + Math.random());\n if (newTime > currentTime) {\n currentTime = newTime;\n }\n return currentTime;\n };\n\n const NewDate = function (...args: unknown[]) {\n return Reflect.construct(\n rootRealmGlobal.Date,\n args.length === 0 ? [now()] : args,\n new.target,\n );\n } as DateConstructor;\n\n keys.forEach((key) => {\n Reflect.defineProperty(NewDate, key, {\n configurable: false,\n writable: false,\n value: key === 'now' ? now : rootRealmGlobal.Date[key],\n });\n });\n\n return { Date: harden(NewDate) };\n}\n\nconst endowmentModule = {\n names: ['Date'] as const,\n factory: createDate,\n};\n\nexport default endowmentModule;\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamProvider } from '@metamask/providers';
|
|
2
|
-
import { SnapsGlobalObject } from '@metamask/
|
|
2
|
+
import { SnapsGlobalObject } from '@metamask/rpc-methods';
|
|
3
3
|
/**
|
|
4
4
|
* Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
|
|
5
5
|
* and `clearTimeout`, must be attenuated so that they can only affect behavior
|
|
@@ -17,17 +17,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
17
17
|
exports.isConstructor = exports.createEndowments = void 0;
|
|
18
18
|
const utils_1 = require("@metamask/utils");
|
|
19
19
|
const globalObject_1 = require("../globalObject");
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const
|
|
20
|
+
const commonEndowmentFactory_1 = __importDefault(require("./commonEndowmentFactory"));
|
|
21
|
+
/**
|
|
22
|
+
* Retrieve consolidated endowment factories for common endowments.
|
|
23
|
+
*/
|
|
24
|
+
const registeredEndowments = (0, commonEndowmentFactory_1.default)();
|
|
25
25
|
/**
|
|
26
26
|
* A map of endowment names to their factory functions. Some endowments share
|
|
27
27
|
* the same factory function, but we only call each factory once for each snap.
|
|
28
28
|
* See {@link createEndowments} for details.
|
|
29
29
|
*/
|
|
30
|
-
const endowmentFactories =
|
|
30
|
+
const endowmentFactories = registeredEndowments.reduce((factories, builder) => {
|
|
31
31
|
builder.names.forEach((name) => {
|
|
32
32
|
factories.set(name, builder.factory);
|
|
33
33
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,2CAA8C;AAE9C,kDAAkD;AAClD,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,2CAA8C;AAE9C,kDAAkD;AAClD,sFAA6D;AAe7D;;GAEG;AACH,MAAM,oBAAoB,GAAG,IAAA,gCAAqB,GAAE,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IAC5E,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CA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';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\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, () => 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 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: SnapsGlobalObject,\n ethereum: StreamProvider,\n endowments: string[] = [],\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 const { teardownFunction, ...endowment } =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n endowmentFactories.get(endowmentName)!();\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\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 // 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] =\n typeof globalValue === 'function' && !isConstructor(globalValue)\n ? globalValue.bind(rootRealmGlobal)\n : 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 new Error(`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\n/**\n * Checks whether the specified function is a constructor.\n *\n * @param value - Any function value.\n * @returns Whether the specified function is a constructor.\n */\n// `Function` is exactly what we want here.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isConstructor<T extends Function>(value: T): boolean {\n // In our current usage, the string `prototype.constructor.name` should never\n // be empty, because you can't create a class with no name, and the\n // `prototype.constructor.name` property is configurable but not writable.\n // Nevertheless, that property was the empty string for `Date` in the iframe\n // execution environment during local testing. We have no idea why, but we\n // have to handle that case.\n // TODO: Does the `prototype` object always have a `constructor` property?\n return Boolean(typeof value.prototype?.constructor?.name === 'string');\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const MINIMUM_INTERVAL = 10;
|
|
3
4
|
/**
|
|
4
5
|
* Creates a pair of `setInterval` and `clearInterval` functions attenuated such
|
|
5
6
|
* that:
|
|
@@ -16,12 +17,14 @@ const createInterval = () => {
|
|
|
16
17
|
if (typeof handler !== 'function') {
|
|
17
18
|
throw new Error(`The interval handler must be a function. Received: ${typeof handler}`);
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
-
const
|
|
20
|
+
harden(handler);
|
|
21
|
+
const handle = Object.freeze(Object.create(null));
|
|
22
|
+
const platformHandle = setInterval(handler, Math.max(MINIMUM_INTERVAL, timeout !== null && timeout !== void 0 ? timeout : 0));
|
|
21
23
|
registeredHandles.set(handle, platformHandle);
|
|
22
24
|
return handle;
|
|
23
25
|
};
|
|
24
26
|
const _clearInterval = (handle) => {
|
|
27
|
+
harden(handle);
|
|
25
28
|
const platformHandle = registeredHandles.get(handle);
|
|
26
29
|
if (platformHandle !== undefined) {
|
|
27
30
|
clearInterval(platformHandle);
|
|
@@ -34,8 +37,8 @@ const createInterval = () => {
|
|
|
34
37
|
}
|
|
35
38
|
};
|
|
36
39
|
return {
|
|
37
|
-
setInterval: _setInterval,
|
|
38
|
-
clearInterval: _clearInterval,
|
|
40
|
+
setInterval: harden(_setInterval),
|
|
41
|
+
clearInterval: harden(_clearInterval),
|
|
39
42
|
teardownFunction,
|
|
40
43
|
};
|
|
41
44
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interval.js","sourceRoot":"","sources":["../../../src/common/endowments/interval.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAG,GAAG,EAAE;IAC1B,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,YAAY,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAA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CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,cAAc,CAAC,MAAM,CAAC,CAAC;SACxB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC;QACjC,aAAa,EAAE,MAAM,CAAC,cAAc,CAAC;QACrC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,EAAE,eAAe,CAAU;IAChD,OAAO,EAAE,cAAc;CACxB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"]}
|
|
@@ -18,7 +18,7 @@ function createMath() {
|
|
|
18
18
|
}
|
|
19
19
|
return Object.assign(Object.assign({}, target), { [key]: globalObject_1.rootRealmGlobal.Math[key] });
|
|
20
20
|
}, {});
|
|
21
|
-
return {
|
|
21
|
+
return harden({
|
|
22
22
|
Math: Object.assign(Object.assign({}, math), { random: () => {
|
|
23
23
|
// NOTE: This is not intended to be a secure replacement for the weak
|
|
24
24
|
// random number generator used by `Math.random`. It is only intended to
|
|
@@ -38,7 +38,7 @@ function createMath() {
|
|
|
38
38
|
// - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
|
|
39
39
|
return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
|
|
40
40
|
} }),
|
|
41
|
-
};
|
|
41
|
+
});
|
|
42
42
|
}
|
|
43
43
|
const endowmentModule = {
|
|
44
44
|
names: ['Math'],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,yEAAyE;IACzE,wDAAwD;IACxD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;QACtD,IAAI,GAAG,KAAK,QAAQ,EAAE;YACpB,OAAO,MAAM,CAAC;SACf;QAED,uCAAY,MAAM,KAAE,CAAC,GAAG,CAAC,EAAE,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC,IAAG;IACzD,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;
|
|
1
|
+
{"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,yEAAyE;IACzE,wDAAwD;IACxD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;QACtD,IAAI,GAAG,KAAK,QAAQ,EAAE;YACpB,OAAO,MAAM,CAAC;SACf;QAED,uCAAY,MAAM,KAAE,CAAC,GAAG,CAAC,EAAE,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC,IAAG;IACzD,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,MAAM,CAAC;QACZ,IAAI,kCACC,IAAI,KACP,MAAM,EAAE,GAAG,EAAE;gBACX,qEAAqE;gBACrE,wEAAwE;gBACxE,wEAAwE;gBACxE,gEAAgE;gBAChE,WAAW;gBACX,EAAE;gBACF,mEAAmE;gBACnE,qEAAqE;gBACrE,0BAA0B;gBAC1B,EAAE;gBACF,sEAAsE;gBACtE,sEAAsE;gBACtE,OAAO;gBACP,EAAE;gBACF,8EAA8E;gBAC9E,4EAA4E;gBAC5E,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;YACjE,CAAC,GACF;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,MAAM,CAAU;IACxB,OAAO,EAAE,UAAU;CACpB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\n/**\n * Create a {@link Math} object, with the same properties as the global\n * {@link Math} object, but with the {@link Math.random} method replaced.\n *\n * @returns The {@link Math} object with the {@link Math.random} method\n * replaced.\n */\nfunction createMath() {\n // `Math` does not work with `Object.keys`, `Object.entries`, etc., so we\n // need to create a new object with the same properties.\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.Math,\n ) as (keyof typeof Math)[];\n\n const math = keys.reduce<Partial<Math>>((target, key) => {\n if (key === 'random') {\n return target;\n }\n\n return { ...target, [key]: rootRealmGlobal.Math[key] };\n }, {});\n\n return harden({\n Math: {\n ...math,\n random: () => {\n // NOTE: This is not intended to be a secure replacement for the weak\n // random number generator used by `Math.random`. It is only intended to\n // prevent side channel attacks of `Math.random` by replacing it with an\n // alternative implementation that is not vulnerable to the same\n // attacks.\n //\n // This does not mean that this implementation is secure. It is not\n // intended to be used in a security context, and this implementation\n // may change at any time.\n //\n // To securely generate random numbers, use a cryptographically secure\n // random number generator, such as the one provided by the Web Crypto\n // API:\n //\n // - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey\n // - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\n return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;\n },\n },\n });\n}\n\nconst endowmentModule = {\n names: ['Math'] as const,\n factory: createMath,\n};\n\nexport default endowmentModule;\n"]}
|
|
@@ -146,7 +146,7 @@ const createNetwork = () => {
|
|
|
146
146
|
/* istanbul ignore next: can't test garbage collection without modifying node parameters */
|
|
147
147
|
() => openConnections.delete(openBodyConnection));
|
|
148
148
|
}
|
|
149
|
-
return res;
|
|
149
|
+
return harden(res);
|
|
150
150
|
};
|
|
151
151
|
const teardownFunction = async () => {
|
|
152
152
|
teardownRef.lastTeardown += 1;
|
|
@@ -156,7 +156,7 @@ const createNetwork = () => {
|
|
|
156
156
|
await Promise.all(promises);
|
|
157
157
|
};
|
|
158
158
|
return {
|
|
159
|
-
fetch: _fetch,
|
|
159
|
+
fetch: harden(_fetch),
|
|
160
160
|
teardownFunction,
|
|
161
161
|
};
|
|
162
162
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names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,IAAI,CAAC,KAAK,EAAE,0CAAE,MAAM,EAAE,CAAA,CAAC;qBAC9B;oBAAC,WAAM;wBACN,gBAAgB;qBACjB;gBACH,CAAC;aACJ,CAAC;YACF,eAAe,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YACxC,OAAO,CAAC,QAAQ,CACd,GAAG,CAAC,IAAI;YACR,2FAA2F;YAC3F,GAAG,EAAE,CAAC,eAAe,CAAC,MAAM,CAAC,kBAAkB,CAAC,CACjD,CAAC;SACH;QACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;QAClC,WAAW,CAAC,YAAY,IAAI,CAAC,CAAC;QAC9B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,eAAe,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,CAAU;IACzB,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","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"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
declare const endowmentModule: {
|
|
2
|
+
names: readonly ["TextDecoder"];
|
|
3
|
+
factory: () => {
|
|
4
|
+
readonly TextDecoder: {
|
|
5
|
+
new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder;
|
|
6
|
+
prototype: TextDecoder;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
export default endowmentModule;
|