@metamask/snaps-controllers 0.38.0-flask.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +568 -11
- package/dist/{types/cronjob → cronjob}/CronjobController.d.ts +6 -7
- package/dist/cronjob/CronjobController.js +248 -0
- package/dist/cronjob/CronjobController.js.map +1 -0
- package/dist/cronjob/index.js +18 -0
- package/dist/cronjob/index.js.map +1 -0
- package/dist/{types/fsm.d.ts → fsm.d.ts} +1 -1
- package/dist/fsm.js +75 -0
- package/dist/fsm.js.map +1 -0
- package/dist/{types/index.d.ts → index.d.ts} +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/logging.js +13 -0
- package/dist/logging.js.map +1 -0
- package/dist/multichain/MultiChainController.d.ts +137 -0
- package/dist/multichain/MultiChainController.js +339 -0
- package/dist/multichain/MultiChainController.js.map +1 -0
- package/dist/multichain/index.d.ts +3 -0
- package/dist/multichain/index.js +20 -0
- package/dist/multichain/index.js.map +1 -0
- package/dist/multichain/matching.d.ts +9 -0
- package/dist/multichain/matching.js +57 -0
- package/dist/multichain/matching.js.map +1 -0
- package/dist/multichain/middleware.d.ts +14 -0
- package/dist/multichain/middleware.js +42 -0
- package/dist/multichain/middleware.js.map +1 -0
- package/dist/{types/services → services}/AbstractExecutionService.d.ts +4 -4
- package/dist/services/AbstractExecutionService.js +318 -0
- package/dist/services/AbstractExecutionService.js.map +1 -0
- package/dist/{types/services → services}/ExecutionService.d.ts +3 -3
- package/dist/services/ExecutionService.js +4 -0
- package/dist/services/ExecutionService.js.map +1 -0
- package/dist/{types/services → services}/browser.d.ts +0 -2
- package/dist/services/browser.js +22 -0
- package/dist/services/browser.js.map +1 -0
- package/dist/{types/services → services}/iframe/IframeExecutionService.d.ts +2 -3
- package/dist/services/iframe/IframeExecutionService.js +30 -0
- package/dist/services/iframe/IframeExecutionService.js.map +1 -0
- package/dist/services/iframe/index.js +18 -0
- package/dist/services/iframe/index.js.map +1 -0
- package/dist/{types/services → services}/index.d.ts +0 -2
- package/dist/services/index.js +22 -0
- package/dist/services/index.js.map +1 -0
- package/dist/{types/services → services}/node/NodeProcessExecutionService.d.ts +3 -4
- package/dist/services/node/NodeProcessExecutionService.js +18 -0
- package/dist/services/node/NodeProcessExecutionService.js.map +1 -0
- package/dist/{types/services → services}/node/NodeThreadExecutionService.d.ts +2 -3
- package/dist/services/node/NodeThreadExecutionService.js +19 -0
- package/dist/services/node/NodeThreadExecutionService.js.map +1 -0
- package/dist/services/node/index.js +19 -0
- package/dist/services/node/index.js.map +1 -0
- package/dist/{types/services → services}/offscreen/OffscreenExecutionService.d.ts +3 -4
- package/dist/services/offscreen/OffscreenExecutionService.js +100 -0
- package/dist/services/offscreen/OffscreenExecutionService.js.map +1 -0
- package/dist/{types/services/ProxyPostMessageStream.d.ts → services/offscreen/OffscreenPostMessageStream.d.ts} +10 -10
- package/dist/services/offscreen/OffscreenPostMessageStream.js +66 -0
- package/dist/services/offscreen/OffscreenPostMessageStream.js.map +1 -0
- package/dist/services/offscreen/index.d.ts +2 -0
- package/dist/services/offscreen/index.js +19 -0
- package/dist/services/offscreen/index.js.map +1 -0
- package/dist/snaps/RequestQueue.js +44 -0
- package/dist/snaps/RequestQueue.js.map +1 -0
- package/dist/{types/snaps → snaps}/SnapController.d.ts +38 -62
- package/dist/snaps/SnapController.js +1478 -0
- package/dist/snaps/SnapController.js.map +1 -0
- package/dist/snaps/Timer.js +86 -0
- package/dist/snaps/Timer.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/cronjob.d.ts +3 -5
- package/dist/snaps/endowments/cronjob.js +105 -0
- package/dist/snaps/endowments/cronjob.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/enum.d.ts +2 -2
- package/dist/snaps/endowments/enum.js +15 -0
- package/dist/snaps/endowments/enum.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/ethereum-provider.d.ts +1 -2
- package/dist/snaps/endowments/ethereum-provider.js +32 -0
- package/dist/snaps/endowments/ethereum-provider.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/index.d.ts +14 -11
- package/dist/snaps/endowments/index.js +60 -0
- package/dist/snaps/endowments/index.js.map +1 -0
- package/dist/snaps/endowments/keyring.d.ts +40 -0
- package/dist/snaps/endowments/keyring.js +103 -0
- package/dist/snaps/endowments/keyring.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/long-running.d.ts +1 -2
- package/dist/snaps/endowments/long-running.js +29 -0
- package/dist/snaps/endowments/long-running.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/network-access.d.ts +1 -2
- package/dist/snaps/endowments/network-access.js +30 -0
- package/dist/snaps/endowments/network-access.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/rpc.d.ts +3 -5
- package/dist/snaps/endowments/rpc.js +92 -0
- package/dist/snaps/endowments/rpc.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/transaction-insight.d.ts +2 -3
- package/dist/snaps/endowments/transaction-insight.js +106 -0
- package/dist/snaps/endowments/transaction-insight.js.map +1 -0
- package/dist/{types/snaps → snaps}/endowments/web-assembly.d.ts +1 -2
- package/dist/snaps/endowments/web-assembly.js +31 -0
- package/dist/snaps/endowments/web-assembly.js.map +1 -0
- package/dist/{types/snaps → snaps}/index.d.ts +0 -2
- package/dist/snaps/index.js +21 -0
- package/dist/snaps/index.js.map +1 -0
- package/dist/{types/snaps → snaps}/location/http.d.ts +2 -3
- package/dist/{esm/snaps → snaps}/location/http.js +31 -52
- package/dist/snaps/location/http.js.map +1 -0
- package/dist/snaps/location/index.js +21 -0
- package/dist/snaps/location/index.js.map +1 -0
- package/dist/{types/snaps → snaps}/location/local.d.ts +3 -3
- package/dist/snaps/location/local.js +51 -0
- package/dist/snaps/location/local.js.map +1 -0
- package/dist/{types/snaps → snaps}/location/location.d.ts +2 -2
- package/dist/snaps/location/location.js +34 -0
- package/dist/snaps/location/location.js.map +1 -0
- package/dist/snaps/location/npm.d.ts +28 -0
- package/dist/{esm/snaps → snaps}/location/npm.js +117 -141
- package/dist/snaps/location/npm.js.map +1 -0
- package/dist/snaps/registry/index.js +19 -0
- package/dist/snaps/registry/index.js.map +1 -0
- package/dist/{types/snaps → snaps}/registry/json.d.ts +4 -5
- package/dist/snaps/registry/json.js +171 -0
- package/dist/snaps/registry/json.js.map +1 -0
- package/dist/{types/snaps → snaps}/registry/registry.d.ts +5 -5
- package/dist/snaps/registry/registry.js +11 -0
- package/dist/snaps/registry/registry.js.map +1 -0
- package/dist/snaps/selectors.d.ts +2 -0
- package/dist/snaps/selectors.js +6 -0
- package/dist/snaps/selectors.js.map +1 -0
- package/dist/{types/utils.d.ts → utils.d.ts} +14 -14
- package/dist/{esm/utils.js → utils.js} +30 -21
- package/dist/utils.js.map +1 -0
- package/package.json +32 -46
- package/dist/cjs/cronjob/CronjobController.js +0 -290
- package/dist/cjs/cronjob/CronjobController.js.map +0 -1
- package/dist/cjs/cronjob/index.js +0 -20
- package/dist/cjs/cronjob/index.js.map +0 -1
- package/dist/cjs/fsm.js +0 -69
- package/dist/cjs/fsm.js.map +0 -1
- package/dist/cjs/index.js +0 -23
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/logging.js +0 -15
- package/dist/cjs/logging.js.map +0 -1
- package/dist/cjs/services/AbstractExecutionService.js +0 -386
- package/dist/cjs/services/AbstractExecutionService.js.map +0 -1
- package/dist/cjs/services/ExecutionService.js +0 -7
- package/dist/cjs/services/ExecutionService.js.map +0 -1
- package/dist/cjs/services/ProxyPostMessageStream.js +0 -116
- package/dist/cjs/services/ProxyPostMessageStream.js.map +0 -1
- package/dist/cjs/services/browser.js +0 -32
- package/dist/cjs/services/browser.js.map +0 -1
- package/dist/cjs/services/iframe/IframeExecutionService.js +0 -54
- package/dist/cjs/services/iframe/IframeExecutionService.js.map +0 -1
- package/dist/cjs/services/iframe/index.js +0 -20
- package/dist/cjs/services/iframe/index.js.map +0 -1
- package/dist/cjs/services/index.js +0 -32
- package/dist/cjs/services/index.js.map +0 -1
- package/dist/cjs/services/node/NodeProcessExecutionService.js +0 -30
- package/dist/cjs/services/node/NodeProcessExecutionService.js.map +0 -1
- package/dist/cjs/services/node/NodeThreadExecutionService.js +0 -30
- package/dist/cjs/services/node/NodeThreadExecutionService.js.map +0 -1
- package/dist/cjs/services/node/index.js +0 -21
- package/dist/cjs/services/node/index.js.map +0 -1
- package/dist/cjs/services/offscreen/OffscreenExecutionService.js +0 -159
- package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +0 -1
- package/dist/cjs/services/offscreen/index.js +0 -20
- package/dist/cjs/services/offscreen/index.js.map +0 -1
- package/dist/cjs/services/webworker/WebWorkerExecutionService.js +0 -148
- package/dist/cjs/services/webworker/WebWorkerExecutionService.js.map +0 -1
- package/dist/cjs/services/webworker/index.js +0 -20
- package/dist/cjs/services/webworker/index.js.map +0 -1
- package/dist/cjs/snaps/RequestQueue.js +0 -63
- package/dist/cjs/snaps/RequestQueue.js.map +0 -1
- package/dist/cjs/snaps/SnapController.js +0 -1735
- package/dist/cjs/snaps/SnapController.js.map +0 -1
- package/dist/cjs/snaps/Timer.js +0 -117
- package/dist/cjs/snaps/Timer.js.map +0 -1
- package/dist/cjs/snaps/endowments/cronjob.js +0 -100
- package/dist/cjs/snaps/endowments/cronjob.js.map +0 -1
- package/dist/cjs/snaps/endowments/enum.js +0 -23
- package/dist/cjs/snaps/endowments/enum.js.map +0 -1
- package/dist/cjs/snaps/endowments/ethereum-provider.js +0 -43
- package/dist/cjs/snaps/endowments/ethereum-provider.js.map +0 -1
- package/dist/cjs/snaps/endowments/index.js +0 -82
- package/dist/cjs/snaps/endowments/index.js.map +0 -1
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js +0 -37
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +0 -1
- package/dist/cjs/snaps/endowments/long-running.js +0 -38
- package/dist/cjs/snaps/endowments/long-running.js.map +0 -1
- package/dist/cjs/snaps/endowments/network-access.js +0 -44
- package/dist/cjs/snaps/endowments/network-access.js.map +0 -1
- package/dist/cjs/snaps/endowments/rpc.js +0 -99
- package/dist/cjs/snaps/endowments/rpc.js.map +0 -1
- package/dist/cjs/snaps/endowments/transaction-insight.js +0 -106
- package/dist/cjs/snaps/endowments/transaction-insight.js.map +0 -1
- package/dist/cjs/snaps/endowments/web-assembly.js +0 -42
- package/dist/cjs/snaps/endowments/web-assembly.js.map +0 -1
- package/dist/cjs/snaps/index.js +0 -25
- package/dist/cjs/snaps/index.js.map +0 -1
- package/dist/cjs/snaps/location/http.js +0 -106
- package/dist/cjs/snaps/location/http.js.map +0 -1
- package/dist/cjs/snaps/location/index.js +0 -23
- package/dist/cjs/snaps/location/index.js.map +0 -1
- package/dist/cjs/snaps/location/local.js +0 -93
- package/dist/cjs/snaps/location/local.js.map +0 -1
- package/dist/cjs/snaps/location/location.js +0 -34
- package/dist/cjs/snaps/location/location.js.map +0 -1
- package/dist/cjs/snaps/location/npm.js +0 -291
- package/dist/cjs/snaps/location/npm.js.map +0 -1
- package/dist/cjs/snaps/permissions.js +0 -61
- package/dist/cjs/snaps/permissions.js.map +0 -1
- package/dist/cjs/snaps/registry/index.js +0 -21
- package/dist/cjs/snaps/registry/index.js.map +0 -1
- package/dist/cjs/snaps/registry/json.js +0 -250
- package/dist/cjs/snaps/registry/json.js.map +0 -1
- package/dist/cjs/snaps/registry/registry.js +0 -18
- package/dist/cjs/snaps/registry/registry.js.map +0 -1
- package/dist/cjs/snaps/selectors.js +0 -13
- package/dist/cjs/snaps/selectors.js.map +0 -1
- package/dist/cjs/utils.js +0 -70
- package/dist/cjs/utils.js.map +0 -1
- package/dist/esm/cronjob/CronjobController.js +0 -275
- package/dist/esm/cronjob/CronjobController.js.map +0 -1
- package/dist/esm/cronjob/index.js +0 -3
- package/dist/esm/cronjob/index.js.map +0 -1
- package/dist/esm/fsm.js +0 -70
- package/dist/esm/fsm.js.map +0 -1
- package/dist/esm/index.js +0 -6
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/logging.js +0 -10
- package/dist/esm/logging.js.map +0 -1
- package/dist/esm/services/AbstractExecutionService.js +0 -369
- package/dist/esm/services/AbstractExecutionService.js.map +0 -1
- package/dist/esm/services/ExecutionService.js +0 -4
- package/dist/esm/services/ExecutionService.js.map +0 -1
- package/dist/esm/services/ProxyPostMessageStream.js +0 -109
- package/dist/esm/services/ProxyPostMessageStream.js.map +0 -1
- package/dist/esm/services/browser.js +0 -9
- package/dist/esm/services/browser.js.map +0 -1
- package/dist/esm/services/iframe/IframeExecutionService.js +0 -44
- package/dist/esm/services/iframe/IframeExecutionService.js.map +0 -1
- package/dist/esm/services/iframe/index.js +0 -3
- package/dist/esm/services/iframe/index.js.map +0 -1
- package/dist/esm/services/index.js +0 -9
- package/dist/esm/services/index.js.map +0 -1
- package/dist/esm/services/node/NodeProcessExecutionService.js +0 -20
- package/dist/esm/services/node/NodeProcessExecutionService.js.map +0 -1
- package/dist/esm/services/node/NodeThreadExecutionService.js +0 -21
- package/dist/esm/services/node/NodeThreadExecutionService.js.map +0 -1
- package/dist/esm/services/node/index.js +0 -4
- package/dist/esm/services/node/index.js.map +0 -1
- package/dist/esm/services/offscreen/OffscreenExecutionService.js +0 -149
- package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +0 -1
- package/dist/esm/services/offscreen/index.js +0 -3
- package/dist/esm/services/offscreen/index.js.map +0 -1
- package/dist/esm/services/webworker/WebWorkerExecutionService.js +0 -130
- package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +0 -1
- package/dist/esm/services/webworker/index.js +0 -3
- package/dist/esm/services/webworker/index.js.map +0 -1
- package/dist/esm/snaps/RequestQueue.js +0 -53
- package/dist/esm/snaps/RequestQueue.js.map +0 -1
- package/dist/esm/snaps/SnapController.js +0 -1714
- package/dist/esm/snaps/SnapController.js.map +0 -1
- package/dist/esm/snaps/Timer.js +0 -107
- package/dist/esm/snaps/Timer.js.map +0 -1
- package/dist/esm/snaps/endowments/cronjob.js +0 -99
- package/dist/esm/snaps/endowments/cronjob.js.map +0 -1
- package/dist/esm/snaps/endowments/enum.js +0 -13
- package/dist/esm/snaps/endowments/enum.js.map +0 -1
- package/dist/esm/snaps/endowments/ethereum-provider.js +0 -33
- package/dist/esm/snaps/endowments/ethereum-provider.js.map +0 -1
- package/dist/esm/snaps/endowments/index.js +0 -41
- package/dist/esm/snaps/endowments/index.js.map +0 -1
- package/dist/esm/snaps/endowments/lifecycle-hooks.js +0 -27
- package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +0 -1
- package/dist/esm/snaps/endowments/long-running.js +0 -28
- package/dist/esm/snaps/endowments/long-running.js.map +0 -1
- package/dist/esm/snaps/endowments/network-access.js +0 -34
- package/dist/esm/snaps/endowments/network-access.js.map +0 -1
- package/dist/esm/snaps/endowments/rpc.js +0 -88
- package/dist/esm/snaps/endowments/rpc.js.map +0 -1
- package/dist/esm/snaps/endowments/transaction-insight.js +0 -99
- package/dist/esm/snaps/endowments/transaction-insight.js.map +0 -1
- package/dist/esm/snaps/endowments/web-assembly.js +0 -32
- package/dist/esm/snaps/endowments/web-assembly.js.map +0 -1
- package/dist/esm/snaps/index.js +0 -8
- package/dist/esm/snaps/index.js.map +0 -1
- package/dist/esm/snaps/location/http.js.map +0 -1
- package/dist/esm/snaps/location/index.js +0 -6
- package/dist/esm/snaps/location/index.js.map +0 -1
- package/dist/esm/snaps/location/local.js +0 -83
- package/dist/esm/snaps/location/local.js.map +0 -1
- package/dist/esm/snaps/location/location.js +0 -30
- package/dist/esm/snaps/location/location.js.map +0 -1
- package/dist/esm/snaps/location/npm.js.map +0 -1
- package/dist/esm/snaps/permissions.js +0 -50
- package/dist/esm/snaps/permissions.js.map +0 -1
- package/dist/esm/snaps/registry/index.js +0 -4
- package/dist/esm/snaps/registry/index.js.map +0 -1
- package/dist/esm/snaps/registry/json.js +0 -240
- package/dist/esm/snaps/registry/json.js.map +0 -1
- package/dist/esm/snaps/registry/registry.js +0 -8
- package/dist/esm/snaps/registry/registry.js.map +0 -1
- package/dist/esm/snaps/selectors.js +0 -3
- package/dist/esm/snaps/selectors.js.map +0 -1
- package/dist/esm/utils.js.map +0 -1
- package/dist/types/services/offscreen/index.d.ts +0 -1
- package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +0 -45
- package/dist/types/services/webworker/index.d.ts +0 -1
- package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +0 -15
- package/dist/types/snaps/location/npm.d.ts +0 -49
- package/dist/types/snaps/permissions.d.ts +0 -16
- package/dist/types/snaps/selectors.d.ts +0 -2
- /package/dist/{types/cronjob → cronjob}/index.d.ts +0 -0
- /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
- /package/dist/{types/services → services}/iframe/index.d.ts +0 -0
- /package/dist/{types/services → services}/node/index.d.ts +0 -0
- /package/dist/{types/snaps → snaps}/RequestQueue.d.ts +0 -0
- /package/dist/{types/snaps → snaps}/Timer.d.ts +0 -0
- /package/dist/{types/snaps → snaps}/location/index.d.ts +0 -0
- /package/dist/{types/snaps → snaps}/registry/index.d.ts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport type { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n}\nexport interface NpmOptions {\n /**\n * @default DEFAULT_REQUESTED_SNAP_VERSION\n */\n versionRange?: SemVerRange;\n /**\n * Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.\n *\n * @default false\n */\n allowCustomRegistries?: boolean;\n}\n\nexport class NpmLocation implements SnapLocation {\n private readonly meta: NpmMeta;\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private files?: Map<string, VirtualFile>;\n\n constructor(url: URL, opts: DetectSnapLocationOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);\n const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;\n\n assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');\n\n let registry: string | URL;\n if (\n url.host === '' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n ) {\n registry = new URL(DEFAULT_NPM_REGISTRY);\n } else {\n registry = 'https://';\n if (url.username) {\n registry += url.username;\n if (url.password) {\n registry += `:${url.password}`;\n }\n registry += '@';\n }\n registry += url.host;\n registry = new URL(registry);\n assert(\n allowCustomRegistries,\n new TypeError(\n `Custom NPM registries are disabled, tried to use \"${registry.toString()}\".`,\n ),\n );\n }\n\n assert(\n registry.pathname === '/' &&\n registry.search === '' &&\n registry.hash === '',\n );\n\n assert(\n url.pathname !== '' && url.pathname !== '/',\n new TypeError('The package name in NPM location is empty.'),\n );\n let packageName = url.pathname;\n if (packageName.startsWith('/')) {\n packageName = packageName.slice(1);\n }\n\n this.meta = {\n requestedRange,\n registry,\n packageName,\n fetch: fetchFunction,\n };\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n const vfile = await this.fetch('snap.manifest.json');\n const result = parseJson(vfile.toString());\n vfile.result = createSnapManifest(result);\n this.validatedManifest = vfile as VirtualFile<SnapManifest>;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = normalizeRelative(path);\n if (!this.files) {\n await this.#lazyInit();\n assert(this.files !== undefined);\n }\n const vfile = this.files.get(relativePath);\n assert(\n vfile !== undefined,\n new TypeError(`File \"${path}\" not found in package.`),\n );\n return vfile.clone();\n }\n\n get packageName(): string {\n return this.meta.packageName;\n }\n\n get version(): string {\n assert(\n this.meta.version !== undefined,\n 'Tried to access version without first fetching NPM package.',\n );\n return this.meta.version;\n }\n\n get registry(): URL {\n return this.meta.registry;\n }\n\n get versionRange(): SemVerRange {\n return this.meta.requestedRange;\n }\n\n async #lazyInit() {\n assert(this.files === undefined);\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n this.meta.requestedRange,\n this.meta.registry,\n this.meta.fetch,\n );\n this.meta.version = actualVersion;\n\n let canonicalBase = 'npm://';\n if (this.meta.registry.username !== '') {\n canonicalBase += this.meta.registry.username;\n if (this.meta.registry.password !== '') {\n canonicalBase += `:${this.meta.registry.password}`;\n }\n canonicalBase += '@';\n }\n canonicalBase += this.meta.registry.host;\n\n // TODO(ritave): Lazily extract files instead of up-front extracting all of them\n // We would need to replace tar-stream package because it requires immediate consumption of streams.\n await new Promise<void>((resolve, reject) => {\n this.files = new Map();\n pump(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.\n createGunzipStream(1),\n createTarballStream(\n `${canonicalBase}/${this.meta.packageName}/`,\n this.files,\n ),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n }\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nconst TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n * @throws If fetching the tarball fails.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\".`,\n );\n }\n\n const tarballUrlString =\n packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n if (\n !isValidUrl(tarballUrlString) ||\n !tarballUrlString.toString().endsWith('.tgz')\n ) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return [tarballResponse.body, targetVersion];\n}\n\n/**\n * The paths of files within npm tarballs appear to always be prefixed with\n * \"package/\".\n */\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nfunction getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.\n * @param files - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nfunction createTarballStream(\n canonicalBase: string,\n files: Map<string, VirtualFile>,\n): Writable {\n assert(\n canonicalBase.endsWith('/'),\n \"Base needs to end with '/' for relative paths to be added as children instead of siblings.\",\n );\n\n assert(\n canonicalBase.startsWith('npm:'),\n 'Protocol mismatch, expected \"npm:\".',\n );\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n let totalSize = 0;\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n return entryStream.pipe(\n concat((data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\n assert(\n !files.has(path),\n 'Malformed tarball, multiple files with the same path.',\n );\n files.set(path, vfile);\n return next();\n } catch (error) {\n return extractStream.destroy(error);\n }\n }),\n );\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","concat","createGunzipStream","pump","ReadableWebToNodeStream","extract","tarExtract","DEFAULT_NPM_REGISTRY","NpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","host","port","username","password","URL","pathname","search","hash","startsWith","slice","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","versions","Object","keys","map","targetVersion","tarballUrlString","dist","tarball","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,QACJ,wBAAwB;AAE/B,SACEC,MAAM,EACNC,qBAAqB,EACrBC,YAAY,EACZC,QAAQ,QACH,kBAAkB;AACzB,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,wBAAwB,eAAe;AAC9C,OAAOC,UAAU,OAAO;AACxB,SAASC,uBAAuB,QAAQ,8BAA8B;AAEtE,SAASC,WAAWC,UAAU,QAAQ,aAAa;AAInD,OAAO,MAAMC,uBAAuB,6BAA6B;IAqIzD;AA/GR,OAAO,MAAMC;IAgEX,MAAMC,WAA+C;QACnD,IAAI,IAAI,CAACC,iBAAiB,EAAE;YAC1B,OAAO,IAAI,CAACA,iBAAiB,CAACC,KAAK;QACrC;QAEA,MAAMC,QAAQ,MAAM,IAAI,CAACC,KAAK,CAAC;QAC/B,MAAMC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D;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CmC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYe,MAAM;IAC3B;IACA,OAAOnB;AACT"}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { caveatMappers, restrictedMethodPermissionBuilders, selectHooks } from '@metamask/rpc-methods';
|
|
2
|
-
import { hasProperty } from '@metamask/utils';
|
|
3
|
-
import { endowmentCaveatMappers, endowmentPermissionBuilders } from './endowments';
|
|
4
|
-
/**
|
|
5
|
-
* Map initial permissions as defined in a Snap manifest to something that can
|
|
6
|
-
* be processed by the PermissionsController. Each caveat mapping function
|
|
7
|
-
* should return a valid permission caveat value.
|
|
8
|
-
*
|
|
9
|
-
* This function does not validate the caveat values, since that is done by
|
|
10
|
-
* the PermissionsController itself, upon requesting the permissions.
|
|
11
|
-
*
|
|
12
|
-
* @param initialPermissions - The initial permissions to process.
|
|
13
|
-
* @returns The processed permissions.
|
|
14
|
-
*/ export function processSnapPermissions(initialPermissions) {
|
|
15
|
-
return Object.fromEntries(Object.entries(initialPermissions).map(([initialPermission, value])=>{
|
|
16
|
-
if (hasProperty(caveatMappers, initialPermission)) {
|
|
17
|
-
return [
|
|
18
|
-
initialPermission,
|
|
19
|
-
caveatMappers[initialPermission](value)
|
|
20
|
-
];
|
|
21
|
-
} else if (hasProperty(endowmentCaveatMappers, initialPermission)) {
|
|
22
|
-
return [
|
|
23
|
-
initialPermission,
|
|
24
|
-
endowmentCaveatMappers[initialPermission](value)
|
|
25
|
-
];
|
|
26
|
-
}
|
|
27
|
-
// If we have no mapping, this may be a non-snap permission, return as-is
|
|
28
|
-
return [
|
|
29
|
-
initialPermission,
|
|
30
|
-
value
|
|
31
|
-
];
|
|
32
|
-
}));
|
|
33
|
-
}
|
|
34
|
-
export const buildSnapEndowmentSpecifications = (excludedEndowments)=>Object.values(endowmentPermissionBuilders).reduce((allSpecifications, { targetName, specificationBuilder })=>{
|
|
35
|
-
if (!excludedEndowments.includes(targetName)) {
|
|
36
|
-
allSpecifications[targetName] = specificationBuilder({});
|
|
37
|
-
}
|
|
38
|
-
return allSpecifications;
|
|
39
|
-
}, {});
|
|
40
|
-
export const buildSnapRestrictedMethodSpecifications = (excludedPermissions, hooks)=>Object.values(restrictedMethodPermissionBuilders).reduce((specifications, { targetName, specificationBuilder, methodHooks })=>{
|
|
41
|
-
if (!excludedPermissions.includes(targetName)) {
|
|
42
|
-
specifications[targetName] = specificationBuilder({
|
|
43
|
-
// @ts-expect-error The selectHooks type is wonky
|
|
44
|
-
methodHooks: selectHooks(hooks, methodHooks)
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
return specifications;
|
|
48
|
-
}, {});
|
|
49
|
-
|
|
50
|
-
//# sourceMappingURL=permissions.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/snaps/permissions.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n PermissionSpecificationConstraint,\n} from '@metamask/permission-controller';\nimport {\n caveatMappers,\n restrictedMethodPermissionBuilders,\n selectHooks,\n} from '@metamask/rpc-methods';\nimport type { SnapPermissions } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n endowmentCaveatMappers,\n endowmentPermissionBuilders,\n} from './endowments';\n\n/**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n */\nexport function processSnapPermissions(\n initialPermissions: SnapPermissions,\n): Record<string, Pick<PermissionConstraint, 'caveats'>> {\n return Object.fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n // If we have no mapping, this may be a non-snap permission, return as-is\n return [\n initialPermission,\n value as Pick<PermissionConstraint, 'caveats'>,\n ];\n }),\n );\n}\n\nexport const buildSnapEndowmentSpecifications = (\n excludedEndowments: string[],\n) =>\n Object.values(endowmentPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((allSpecifications, { targetName, specificationBuilder }) => {\n if (!excludedEndowments.includes(targetName)) {\n allSpecifications[targetName] = specificationBuilder({});\n }\n return allSpecifications;\n }, {});\n\nexport const buildSnapRestrictedMethodSpecifications = (\n excludedPermissions: string[],\n hooks: Record<string, unknown>,\n) =>\n Object.values(restrictedMethodPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((specifications, { targetName, specificationBuilder, methodHooks }) => {\n if (!excludedPermissions.includes(targetName)) {\n specifications[targetName] = specificationBuilder({\n // @ts-expect-error The selectHooks type is wonky\n methodHooks: selectHooks<typeof hooks, keyof typeof methodHooks>(\n hooks,\n methodHooks,\n ) as Pick<typeof hooks, keyof typeof methodHooks>,\n });\n }\n return specifications;\n }, {});\n"],"names":["caveatMappers","restrictedMethodPermissionBuilders","selectHooks","hasProperty","endowmentCaveatMappers","endowmentPermissionBuilders","processSnapPermissions","initialPermissions","Object","fromEntries","entries","map","initialPermission","value","buildSnapEndowmentSpecifications","excludedEndowments","values","reduce","allSpecifications","targetName","specificationBuilder","includes","buildSnapRestrictedMethodSpecifications","excludedPermissions","hooks","specifications","methodHooks"],"mappings":"AAIA,SACEA,aAAa,EACbC,kCAAkC,EAClCC,WAAW,QACN,wBAAwB;AAE/B,SAASC,WAAW,QAAQ,kBAAkB;AAE9C,SACEC,sBAAsB,EACtBC,2BAA2B,QACtB,eAAe;AAEtB;;;;;;;;;;CAUC,GACD,OAAO,SAASC,uBACdC,kBAAmC;IAEnC,OAAOC,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACH,oBAAoBI,GAAG,CAAC,CAAC,CAACC,mBAAmBC,MAAM;QAChE,IAAIV,YAAYH,eAAeY,oBAAoB;YACjD,OAAO;gBAACA;gBAAmBZ,aAAa,CAACY,kBAAkB,CAACC;aAAO;QACrE,OAAO,IAAIV,YAAYC,wBAAwBQ,oBAAoB;YACjE,OAAO;gBACLA;gBACAR,sBAAsB,CAACQ,kBAAkB,CAACC;aAC3C;QACH;QAEA,yEAAyE;QACzE,OAAO;YACLD;YACAC;SACD;IACH;AAEJ;AAEA,OAAO,MAAMC,mCAAmC,CAC9CC,qBAEAP,OAAOQ,MAAM,CAACX,6BAA6BY,MAAM,CAE/C,CAACC,mBAAmB,EAAEC,UAAU,EAAEC,oBAAoB,EAAE;QACxD,IAAI,CAACL,mBAAmBM,QAAQ,CAACF,aAAa;YAC5CD,iBAAiB,CAACC,WAAW,GAAGC,qBAAqB,CAAC;QACxD;QACA,OAAOF;IACT,GAAG,CAAC,GAAG;AAET,OAAO,MAAMI,0CAA0C,CACrDC,qBACAC,QAEAhB,OAAOQ,MAAM,CAACf,oCAAoCgB,MAAM,CAEtD,CAACQ,gBAAgB,EAAEN,UAAU,EAAEC,oBAAoB,EAAEM,WAAW,EAAE;QAClE,IAAI,CAACH,oBAAoBF,QAAQ,CAACF,aAAa;YAC7CM,cAAc,CAACN,WAAW,GAAGC,qBAAqB;gBAChD,iDAAiD;gBACjDM,aAAaxB,YACXsB,OACAE;YAEJ;QACF;QACA,OAAOD;IACT,GAAG,CAAC,GAAG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/index.ts"],"sourcesContent":["export * from './registry';\nexport * from './json';\n"],"names":[],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,SAAS"}
|
|
@@ -1,240 +0,0 @@
|
|
|
1
|
-
function _check_private_redeclaration(obj, privateCollection) {
|
|
2
|
-
if (privateCollection.has(obj)) {
|
|
3
|
-
throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
4
|
-
}
|
|
5
|
-
}
|
|
6
|
-
function _class_apply_descriptor_get(receiver, descriptor) {
|
|
7
|
-
if (descriptor.get) {
|
|
8
|
-
return descriptor.get.call(receiver);
|
|
9
|
-
}
|
|
10
|
-
return descriptor.value;
|
|
11
|
-
}
|
|
12
|
-
function _class_apply_descriptor_set(receiver, descriptor, value) {
|
|
13
|
-
if (descriptor.set) {
|
|
14
|
-
descriptor.set.call(receiver, value);
|
|
15
|
-
} else {
|
|
16
|
-
if (!descriptor.writable) {
|
|
17
|
-
throw new TypeError("attempted to set read only private field");
|
|
18
|
-
}
|
|
19
|
-
descriptor.value = value;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
function _class_extract_field_descriptor(receiver, privateMap, action) {
|
|
23
|
-
if (!privateMap.has(receiver)) {
|
|
24
|
-
throw new TypeError("attempted to " + action + " private field on non-instance");
|
|
25
|
-
}
|
|
26
|
-
return privateMap.get(receiver);
|
|
27
|
-
}
|
|
28
|
-
function _class_private_field_get(receiver, privateMap) {
|
|
29
|
-
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
|
|
30
|
-
return _class_apply_descriptor_get(receiver, descriptor);
|
|
31
|
-
}
|
|
32
|
-
function _class_private_field_init(obj, privateMap, value) {
|
|
33
|
-
_check_private_redeclaration(obj, privateMap);
|
|
34
|
-
privateMap.set(obj, value);
|
|
35
|
-
}
|
|
36
|
-
function _class_private_field_set(receiver, privateMap, value) {
|
|
37
|
-
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
|
|
38
|
-
_class_apply_descriptor_set(receiver, descriptor, value);
|
|
39
|
-
return value;
|
|
40
|
-
}
|
|
41
|
-
function _class_private_method_get(receiver, privateSet, fn) {
|
|
42
|
-
if (!privateSet.has(receiver)) {
|
|
43
|
-
throw new TypeError("attempted to get private field on non-instance");
|
|
44
|
-
}
|
|
45
|
-
return fn;
|
|
46
|
-
}
|
|
47
|
-
function _class_private_method_init(obj, privateSet) {
|
|
48
|
-
_check_private_redeclaration(obj, privateSet);
|
|
49
|
-
privateSet.add(obj);
|
|
50
|
-
}
|
|
51
|
-
import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
|
|
52
|
-
import { verify } from '@metamask/snaps-registry';
|
|
53
|
-
import { assert, Duration, inMilliseconds, satisfiesVersionRange } from '@metamask/utils';
|
|
54
|
-
import { SnapsRegistryStatus } from './registry';
|
|
55
|
-
// TODO: Replace with a Codefi URL
|
|
56
|
-
const SNAP_REGISTRY_URL = 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';
|
|
57
|
-
const SNAP_REGISTRY_SIGNATURE_URL = 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';
|
|
58
|
-
const controllerName = 'SnapsRegistry';
|
|
59
|
-
const defaultState = {
|
|
60
|
-
database: null,
|
|
61
|
-
lastUpdated: null
|
|
62
|
-
};
|
|
63
|
-
var _url = /*#__PURE__*/ new WeakMap(), _publicKey = /*#__PURE__*/ new WeakMap(), _fetchFunction = /*#__PURE__*/ new WeakMap(), _recentFetchThreshold = /*#__PURE__*/ new WeakMap(), _refetchOnAllowlistMiss = /*#__PURE__*/ new WeakMap(), _failOnUnavailableRegistry = /*#__PURE__*/ new WeakMap(), _wasRecentlyFetched = /*#__PURE__*/ new WeakSet(), _update = /*#__PURE__*/ new WeakSet(), _getDatabase = /*#__PURE__*/ new WeakSet(), _getSingle = /*#__PURE__*/ new WeakSet(), _get = /*#__PURE__*/ new WeakSet(), _getMetadata = /*#__PURE__*/ new WeakSet(), _verifySignature = /*#__PURE__*/ new WeakSet(), _safeFetch = /*#__PURE__*/ new WeakSet();
|
|
64
|
-
export class JsonSnapsRegistry extends BaseController {
|
|
65
|
-
constructor({ messenger, state, url = {
|
|
66
|
-
registry: SNAP_REGISTRY_URL,
|
|
67
|
-
signature: SNAP_REGISTRY_SIGNATURE_URL
|
|
68
|
-
}, publicKey, fetchFunction = globalThis.fetch.bind(globalThis), recentFetchThreshold = inMilliseconds(5, Duration.Minute), failOnUnavailableRegistry = true, refetchOnAllowlistMiss = true }){
|
|
69
|
-
super({
|
|
70
|
-
messenger,
|
|
71
|
-
metadata: {
|
|
72
|
-
database: {
|
|
73
|
-
persist: true,
|
|
74
|
-
anonymous: false
|
|
75
|
-
},
|
|
76
|
-
lastUpdated: {
|
|
77
|
-
persist: true,
|
|
78
|
-
anonymous: false
|
|
79
|
-
}
|
|
80
|
-
},
|
|
81
|
-
name: controllerName,
|
|
82
|
-
state: {
|
|
83
|
-
...defaultState,
|
|
84
|
-
...state
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
_class_private_method_init(this, _wasRecentlyFetched);
|
|
88
|
-
_class_private_method_init(this, _update);
|
|
89
|
-
_class_private_method_init(this, _getDatabase);
|
|
90
|
-
_class_private_method_init(this, _getSingle);
|
|
91
|
-
_class_private_method_init(this, _get);
|
|
92
|
-
/**
|
|
93
|
-
* Get metadata for the given snap ID.
|
|
94
|
-
*
|
|
95
|
-
* @param snapId - The ID of the snap to get metadata for.
|
|
96
|
-
* @returns The metadata for the given snap ID, or `null` if the snap is not
|
|
97
|
-
* verified.
|
|
98
|
-
*/ _class_private_method_init(this, _getMetadata);
|
|
99
|
-
/**
|
|
100
|
-
* Verify the signature of the registry.
|
|
101
|
-
*
|
|
102
|
-
* @param database - The registry database.
|
|
103
|
-
* @param signature - The signature of the registry.
|
|
104
|
-
* @throws If the signature is invalid.
|
|
105
|
-
* @private
|
|
106
|
-
*/ _class_private_method_init(this, _verifySignature);
|
|
107
|
-
/**
|
|
108
|
-
* Fetch the given URL, throwing if the response is not OK.
|
|
109
|
-
*
|
|
110
|
-
* @param url - The URL to fetch.
|
|
111
|
-
* @returns The response body.
|
|
112
|
-
* @private
|
|
113
|
-
*/ _class_private_method_init(this, _safeFetch);
|
|
114
|
-
_class_private_field_init(this, _url, {
|
|
115
|
-
writable: true,
|
|
116
|
-
value: void 0
|
|
117
|
-
});
|
|
118
|
-
_class_private_field_init(this, _publicKey, {
|
|
119
|
-
writable: true,
|
|
120
|
-
value: void 0
|
|
121
|
-
});
|
|
122
|
-
_class_private_field_init(this, _fetchFunction, {
|
|
123
|
-
writable: true,
|
|
124
|
-
value: void 0
|
|
125
|
-
});
|
|
126
|
-
_class_private_field_init(this, _recentFetchThreshold, {
|
|
127
|
-
writable: true,
|
|
128
|
-
value: void 0
|
|
129
|
-
});
|
|
130
|
-
_class_private_field_init(this, _refetchOnAllowlistMiss, {
|
|
131
|
-
writable: true,
|
|
132
|
-
value: void 0
|
|
133
|
-
});
|
|
134
|
-
_class_private_field_init(this, _failOnUnavailableRegistry, {
|
|
135
|
-
writable: true,
|
|
136
|
-
value: void 0
|
|
137
|
-
});
|
|
138
|
-
_class_private_field_set(this, _url, url);
|
|
139
|
-
_class_private_field_set(this, _publicKey, publicKey);
|
|
140
|
-
_class_private_field_set(this, _fetchFunction, fetchFunction);
|
|
141
|
-
_class_private_field_set(this, _recentFetchThreshold, recentFetchThreshold);
|
|
142
|
-
_class_private_field_set(this, _refetchOnAllowlistMiss, refetchOnAllowlistMiss);
|
|
143
|
-
_class_private_field_set(this, _failOnUnavailableRegistry, failOnUnavailableRegistry);
|
|
144
|
-
this.messagingSystem.registerActionHandler('SnapsRegistry:get', async (...args)=>_class_private_method_get(this, _get, get).call(this, ...args));
|
|
145
|
-
this.messagingSystem.registerActionHandler('SnapsRegistry:getMetadata', async (...args)=>_class_private_method_get(this, _getMetadata, getMetadata).call(this, ...args));
|
|
146
|
-
this.messagingSystem.registerActionHandler('SnapsRegistry:update', async ()=>_class_private_method_get(this, _update, update).call(this));
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
function wasRecentlyFetched() {
|
|
150
|
-
return this.state.lastUpdated && Date.now() - this.state.lastUpdated < _class_private_field_get(this, _recentFetchThreshold);
|
|
151
|
-
}
|
|
152
|
-
async function update() {
|
|
153
|
-
// No-op if we recently fetched the registry.
|
|
154
|
-
if (_class_private_method_get(this, _wasRecentlyFetched, wasRecentlyFetched).call(this)) {
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
try {
|
|
158
|
-
const database = await _class_private_method_get(this, _safeFetch, safeFetch).call(this, _class_private_field_get(this, _url).registry);
|
|
159
|
-
if (_class_private_field_get(this, _publicKey)) {
|
|
160
|
-
const signature = await _class_private_method_get(this, _safeFetch, safeFetch).call(this, _class_private_field_get(this, _url).signature);
|
|
161
|
-
await _class_private_method_get(this, _verifySignature, verifySignature).call(this, database, signature);
|
|
162
|
-
}
|
|
163
|
-
this.update((state)=>{
|
|
164
|
-
state.database = JSON.parse(database);
|
|
165
|
-
state.lastUpdated = Date.now();
|
|
166
|
-
});
|
|
167
|
-
} catch {
|
|
168
|
-
// Ignore
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
async function getDatabase() {
|
|
172
|
-
if (this.state.database === null) {
|
|
173
|
-
await _class_private_method_get(this, _update, update).call(this);
|
|
174
|
-
}
|
|
175
|
-
// If the database is still null and we require it, throw.
|
|
176
|
-
if (_class_private_field_get(this, _failOnUnavailableRegistry) && this.state.database === null) {
|
|
177
|
-
throw new Error('Snaps registry is unavailable, installation blocked.');
|
|
178
|
-
}
|
|
179
|
-
return this.state.database;
|
|
180
|
-
}
|
|
181
|
-
async function getSingle(snapId, snapInfo, refetch = false) {
|
|
182
|
-
const database = await _class_private_method_get(this, _getDatabase, getDatabase).call(this);
|
|
183
|
-
const blockedEntry = database?.blockedSnaps.find((blocked)=>{
|
|
184
|
-
if ('id' in blocked) {
|
|
185
|
-
return blocked.id === snapId && satisfiesVersionRange(snapInfo.version, blocked.versionRange);
|
|
186
|
-
}
|
|
187
|
-
return blocked.checksum === snapInfo.checksum;
|
|
188
|
-
});
|
|
189
|
-
if (blockedEntry) {
|
|
190
|
-
return {
|
|
191
|
-
status: SnapsRegistryStatus.Blocked,
|
|
192
|
-
reason: blockedEntry.reason
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
const verified = database?.verifiedSnaps[snapId];
|
|
196
|
-
const version = verified?.versions?.[snapInfo.version];
|
|
197
|
-
if (version && version.checksum === snapInfo.checksum) {
|
|
198
|
-
return {
|
|
199
|
-
status: SnapsRegistryStatus.Verified
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
// For now, if we have an allowlist miss, we can refetch once and try again.
|
|
203
|
-
if (_class_private_field_get(this, _refetchOnAllowlistMiss) && !refetch) {
|
|
204
|
-
await _class_private_method_get(this, _update, update).call(this);
|
|
205
|
-
return _class_private_method_get(this, _getSingle, getSingle).call(this, snapId, snapInfo, true);
|
|
206
|
-
}
|
|
207
|
-
return {
|
|
208
|
-
status: SnapsRegistryStatus.Unverified
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
async function get(snaps) {
|
|
212
|
-
return Object.entries(snaps).reduce(async (previousPromise, [snapId, snapInfo])=>{
|
|
213
|
-
const result = await _class_private_method_get(this, _getSingle, getSingle).call(this, snapId, snapInfo);
|
|
214
|
-
const acc = await previousPromise;
|
|
215
|
-
acc[snapId] = result;
|
|
216
|
-
return acc;
|
|
217
|
-
}, Promise.resolve({}));
|
|
218
|
-
}
|
|
219
|
-
async function getMetadata(snapId) {
|
|
220
|
-
const database = await _class_private_method_get(this, _getDatabase, getDatabase).call(this);
|
|
221
|
-
return database?.verifiedSnaps[snapId]?.metadata ?? null;
|
|
222
|
-
}
|
|
223
|
-
async function verifySignature(database, signature) {
|
|
224
|
-
assert(_class_private_field_get(this, _publicKey), 'No public key provided.');
|
|
225
|
-
const valid = await verify({
|
|
226
|
-
registry: database,
|
|
227
|
-
signature: JSON.parse(signature),
|
|
228
|
-
publicKey: _class_private_field_get(this, _publicKey)
|
|
229
|
-
});
|
|
230
|
-
assert(valid, 'Invalid registry signature.');
|
|
231
|
-
}
|
|
232
|
-
async function safeFetch(url) {
|
|
233
|
-
const response = await _class_private_field_get(this, _fetchFunction).call(this, url);
|
|
234
|
-
if (!response.ok) {
|
|
235
|
-
throw new Error(`Failed to fetch ${url}.`);
|
|
236
|
-
}
|
|
237
|
-
return await response.text();
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
//# sourceMappingURL=json.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/json.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { verify } from '@metamask/snaps-registry';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\n assert,\n Duration,\n inMilliseconds,\n satisfiesVersionRange,\n} from '@metamask/utils';\n\nimport type {\n SnapsRegistry,\n SnapsRegistryInfo,\n SnapsRegistryMetadata,\n SnapsRegistryRequest,\n SnapsRegistryResult,\n} from './registry';\nimport { SnapsRegistryStatus } from './registry';\n\n// TODO: Replace with a Codefi URL\nconst SNAP_REGISTRY_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';\n\nconst SNAP_REGISTRY_SIGNATURE_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';\n\ntype JsonSnapsRegistryUrl = {\n registry: string;\n signature: string;\n};\n\nexport type JsonSnapsRegistryArgs = {\n messenger: SnapsRegistryMessenger;\n state?: SnapsRegistryState;\n fetchFunction?: typeof fetch;\n url?: JsonSnapsRegistryUrl;\n recentFetchThreshold?: number;\n refetchOnAllowlistMiss?: boolean;\n failOnUnavailableRegistry?: boolean;\n publicKey?: Hex;\n};\n\nexport type GetResult = {\n type: `${typeof controllerName}:get`;\n handler: SnapsRegistry['get'];\n};\n\nexport type GetMetadata = {\n type: `${typeof controllerName}:getMetadata`;\n handler: SnapsRegistry['getMetadata'];\n};\n\nexport type Update = {\n type: `${typeof controllerName}:update`;\n handler: SnapsRegistry['update'];\n};\n\nexport type SnapsRegistryActions = GetResult | GetMetadata | Update;\n\nexport type SnapsRegistryEvents = never;\n\nexport type SnapsRegistryMessenger = RestrictedControllerMessenger<\n 'SnapsRegistry',\n SnapsRegistryActions,\n SnapsRegistryEvents,\n SnapsRegistryActions['type'],\n SnapsRegistryEvents['type']\n>;\n\nexport type SnapsRegistryState = {\n database: SnapsRegistryDatabase | null;\n lastUpdated: number | null;\n};\n\nconst controllerName = 'SnapsRegistry';\n\nconst defaultState = {\n database: null,\n lastUpdated: null,\n};\n\nexport class JsonSnapsRegistry extends BaseController<\n typeof controllerName,\n SnapsRegistryState,\n SnapsRegistryMessenger\n> {\n #url: JsonSnapsRegistryUrl;\n\n #publicKey?: Hex;\n\n #fetchFunction: typeof fetch;\n\n #recentFetchThreshold: number;\n\n #refetchOnAllowlistMiss: boolean;\n\n #failOnUnavailableRegistry: boolean;\n\n constructor({\n messenger,\n state,\n url = {\n registry: SNAP_REGISTRY_URL,\n signature: SNAP_REGISTRY_SIGNATURE_URL,\n },\n publicKey,\n fetchFunction = globalThis.fetch.bind(globalThis),\n recentFetchThreshold = inMilliseconds(5, Duration.Minute),\n failOnUnavailableRegistry = true,\n refetchOnAllowlistMiss = true,\n }: JsonSnapsRegistryArgs) {\n super({\n messenger,\n metadata: {\n database: { persist: true, anonymous: false },\n lastUpdated: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n ...defaultState,\n ...state,\n },\n });\n this.#url = url;\n this.#publicKey = publicKey;\n this.#fetchFunction = fetchFunction;\n this.#recentFetchThreshold = recentFetchThreshold;\n this.#refetchOnAllowlistMiss = refetchOnAllowlistMiss;\n this.#failOnUnavailableRegistry = failOnUnavailableRegistry;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#update(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n async #update() {\n // No-op if we recently fetched the registry.\n if (this.#wasRecentlyFetched()) {\n return;\n }\n\n try {\n const database = await this.#safeFetch(this.#url.registry);\n\n if (this.#publicKey) {\n const signature = await this.#safeFetch(this.#url.signature);\n await this.#verifySignature(database, signature);\n }\n\n this.update((state) => {\n state.database = JSON.parse(database);\n state.lastUpdated = Date.now();\n });\n } catch {\n // Ignore\n }\n }\n\n async #getDatabase(): Promise<SnapsRegistryDatabase | null> {\n if (this.state.database === null) {\n await this.#update();\n }\n\n // If the database is still null and we require it, throw.\n if (this.#failOnUnavailableRegistry && this.state.database === null) {\n throw new Error('Snaps registry is unavailable, installation blocked.');\n }\n return this.state.database;\n }\n\n async #getSingle(\n snapId: SnapId,\n snapInfo: SnapsRegistryInfo,\n refetch = false,\n ): Promise<SnapsRegistryResult> {\n const database = await this.#getDatabase();\n\n const blockedEntry = database?.blockedSnaps.find((blocked) => {\n if ('id' in blocked) {\n return (\n blocked.id === snapId &&\n satisfiesVersionRange(snapInfo.version, blocked.versionRange)\n );\n }\n\n return blocked.checksum === snapInfo.checksum;\n });\n\n if (blockedEntry) {\n return {\n status: SnapsRegistryStatus.Blocked,\n reason: blockedEntry.reason,\n };\n }\n\n const verified = database?.verifiedSnaps[snapId];\n const version = verified?.versions?.[snapInfo.version];\n if (version && version.checksum === snapInfo.checksum) {\n return { status: SnapsRegistryStatus.Verified };\n }\n // For now, if we have an allowlist miss, we can refetch once and try again.\n if (this.#refetchOnAllowlistMiss && !refetch) {\n await this.#update();\n return this.#getSingle(snapId, snapInfo, true);\n }\n return { status: SnapsRegistryStatus.Unverified };\n }\n\n async #get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<SnapId, SnapsRegistryResult>>\n >(async (previousPromise, [snapId, snapInfo]) => {\n const result = await this.#getSingle(snapId, snapInfo);\n const acc = await previousPromise;\n acc[snapId] = result;\n return acc;\n }, Promise.resolve({}));\n }\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n async #getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null> {\n const database = await this.#getDatabase();\n return database?.verifiedSnaps[snapId]?.metadata ?? null;\n }\n\n /**\n * Verify the signature of the registry.\n *\n * @param database - The registry database.\n * @param signature - The signature of the registry.\n * @throws If the signature is invalid.\n * @private\n */\n async #verifySignature(database: string, signature: string) {\n assert(this.#publicKey, 'No public key provided.');\n\n const valid = await verify({\n registry: database,\n signature: JSON.parse(signature),\n publicKey: this.#publicKey,\n });\n\n assert(valid, 'Invalid registry signature.');\n }\n\n /**\n * Fetch the given URL, throwing if the response is not OK.\n *\n * @param url - The URL to fetch.\n * @returns The response body.\n * @private\n */\n async #safeFetch(url: string) {\n const response = await this.#fetchFunction(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}.`);\n }\n\n return await response.text();\n }\n}\n"],"names":["BaseControllerV2","BaseController","verify","assert","Duration","inMilliseconds","satisfiesVersionRange","SnapsRegistryStatus","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","JsonSnapsRegistry","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","messagingSystem","registerActionHandler","args","get","getMetadata","update","Date","now","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","version","versionRange","checksum","status","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","valid","response","ok","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4
|
-
SnapsRegistryStatus[SnapsRegistryStatus["Blocked"] = 1] = "Blocked";
|
|
5
|
-
SnapsRegistryStatus[SnapsRegistryStatus["Verified"] = 2] = "Verified";
|
|
6
|
-
})(SnapsRegistryStatus || (SnapsRegistryStatus = {}));
|
|
7
|
-
|
|
8
|
-
//# sourceMappingURL=registry.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';\nimport type { SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified = 0,\n Blocked = 1,\n Verified = 2,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;\n\n update(): Promise<void>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"],"names":["SnapsRegistryStatus","Unverified","Blocked","Verified"],"mappings":"WAaO;UAAKA,mBAAmB;IAAnBA,oBAAAA,oBACVC,gBAAa,KAAbA;IADUD,oBAAAA,oBAEVE,aAAU,KAAVA;IAFUF,oBAAAA,oBAGVG,cAAW,KAAXA;GAHUH,wBAAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/snaps/selectors.ts"],"sourcesContent":["import type { TruncatedSnap } from '@metamask/snaps-utils';\n\nexport const getRunnableSnaps = <Snap extends TruncatedSnap>(snaps: Snap[]) =>\n snaps.filter((snap) => snap.enabled && !snap.blocked);\n"],"names":["getRunnableSnaps","snaps","filter","snap","enabled","blocked"],"mappings":"AAEA,OAAO,MAAMA,mBAAmB,CAA6BC,QAC3DA,MAAMC,MAAM,CAAC,CAACC,OAASA,KAAKC,OAAO,IAAI,CAACD,KAAKE,OAAO,EAAE"}
|
package/dist/esm/utils.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n"],"names":["Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race"],"mappings":"AAAA,SAASA,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAAe;IAEf,OAAOC,eAAe,IAAIb,MAAMW,KAAKC;AACvC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,eACdC,KAAY,EACZF,MAAe;IAEf,IAAIG;IACJ,MAAMC,UAAe,IAAIC,QAAgB,CAACC,SAAcC;QACtDL,MAAMM,KAAK,CAAC;YACVR,WAAWS,YAAYH,YAAYA,QAAQN;QAC7C;QACAG,aAAaI;IACf;IAEAH,QAAQM,MAAM,GAAG;QACf,IAAIR,MAAMS,MAAM,KAAK,YAAY;YAC/BT,MAAMQ,MAAM;YACZP,WAAW,IAAIS,MAAM;QACvB;IACF;IACA,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,MAAMS,cAAcC,OACzB,wEACA;AAEF;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,YACpBX,OAA8B,EAC9BY,SAAyB;IAEzB,MAAMd,QACJ,OAAOc,cAAc,WAAW,IAAI5B,MAAM4B,aAAaA;IACzD,MAAMC,eAAehB,eAAeC,OAAOW;IAC3C,IAAI;QACF,OAAO,MAAMR,QAAQa,IAAI,CAAC;YAACd;YAASa;SAAa;IACnD,SAAU;QACRA,aAAaP,MAAM;IACrB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './OffscreenExecutionService';
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
|
|
2
|
-
import { AbstractExecutionService } from '../AbstractExecutionService';
|
|
3
|
-
import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
|
|
4
|
-
declare type WebWorkerExecutionEnvironmentServiceArgs = {
|
|
5
|
-
documentUrl: URL;
|
|
6
|
-
} & ExecutionServiceArgs;
|
|
7
|
-
export declare const WORKER_POOL_ID = "snaps-worker-pool";
|
|
8
|
-
export declare class WebWorkerExecutionService extends AbstractExecutionService<string> {
|
|
9
|
-
#private;
|
|
10
|
-
/**
|
|
11
|
-
* Create a new webworker execution service.
|
|
12
|
-
*
|
|
13
|
-
* @param args - The constructor arguments.
|
|
14
|
-
* @param args.documentUrl - The URL of the worker pool document to use as the
|
|
15
|
-
* execution environment.
|
|
16
|
-
* @param args.messenger - The messenger to use for communication with the
|
|
17
|
-
* `SnapController`.
|
|
18
|
-
* @param args.setupSnapProvider - The function to use to set up the snap
|
|
19
|
-
* provider.
|
|
20
|
-
*/
|
|
21
|
-
constructor({ documentUrl, messenger, setupSnapProvider, }: WebWorkerExecutionEnvironmentServiceArgs);
|
|
22
|
-
/**
|
|
23
|
-
* Send a termination command to the worker pool document.
|
|
24
|
-
*
|
|
25
|
-
* @param job - The job to terminate.
|
|
26
|
-
*/
|
|
27
|
-
protected terminateJob(job: Job<string>): Promise<void>;
|
|
28
|
-
/**
|
|
29
|
-
* Create a new stream for the specified job. This wraps the runtime stream
|
|
30
|
-
* in a stream specific to the job.
|
|
31
|
-
*
|
|
32
|
-
* @param jobId - The job ID.
|
|
33
|
-
*/
|
|
34
|
-
protected initEnvStream(jobId: string): Promise<{
|
|
35
|
-
worker: string;
|
|
36
|
-
stream: ProxyPostMessageStream;
|
|
37
|
-
}>;
|
|
38
|
-
/**
|
|
39
|
-
* Creates the worker pool document to be used as the execution environment.
|
|
40
|
-
*
|
|
41
|
-
* If the document already exists, this does nothing.
|
|
42
|
-
*/
|
|
43
|
-
private createDocument;
|
|
44
|
-
}
|
|
45
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './WebWorkerExecutionService';
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { PermissionSpecificationBuilder, EndowmentGetterParams } from '@metamask/permission-controller';
|
|
2
|
-
import { PermissionType } from '@metamask/permission-controller';
|
|
3
|
-
import type { NonEmptyArray } from '@metamask/utils';
|
|
4
|
-
import { SnapEndowments } from './enum';
|
|
5
|
-
declare const permissionName = SnapEndowments.LifecycleHooks;
|
|
6
|
-
export declare const lifecycleHooksEndowmentBuilder: Readonly<{
|
|
7
|
-
readonly targetName: SnapEndowments.LifecycleHooks;
|
|
8
|
-
readonly specificationBuilder: PermissionSpecificationBuilder<PermissionType.Endowment, any, {
|
|
9
|
-
permissionType: PermissionType.Endowment;
|
|
10
|
-
targetName: typeof permissionName;
|
|
11
|
-
endowmentGetter: (_options?: EndowmentGetterParams) => undefined;
|
|
12
|
-
allowedCaveats: Readonly<NonEmptyArray<string>> | null;
|
|
13
|
-
}>;
|
|
14
|
-
}>;
|
|
15
|
-
export {};
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import type { SnapManifest } from '@metamask/snaps-utils';
|
|
2
|
-
import { VirtualFile } from '@metamask/snaps-utils';
|
|
3
|
-
import type { SemVerRange } from '@metamask/utils';
|
|
4
|
-
import type { DetectSnapLocationOptions, SnapLocation } from './location';
|
|
5
|
-
export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
6
|
-
export interface NpmOptions {
|
|
7
|
-
/**
|
|
8
|
-
* @default DEFAULT_REQUESTED_SNAP_VERSION
|
|
9
|
-
*/
|
|
10
|
-
versionRange?: SemVerRange;
|
|
11
|
-
/**
|
|
12
|
-
* Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.
|
|
13
|
-
*
|
|
14
|
-
* @default false
|
|
15
|
-
*/
|
|
16
|
-
allowCustomRegistries?: boolean;
|
|
17
|
-
}
|
|
18
|
-
export declare class NpmLocation implements SnapLocation {
|
|
19
|
-
#private;
|
|
20
|
-
private readonly meta;
|
|
21
|
-
private validatedManifest?;
|
|
22
|
-
private files?;
|
|
23
|
-
constructor(url: URL, opts?: DetectSnapLocationOptions);
|
|
24
|
-
manifest(): Promise<VirtualFile<SnapManifest>>;
|
|
25
|
-
fetch(path: string): Promise<VirtualFile>;
|
|
26
|
-
get packageName(): string;
|
|
27
|
-
get version(): string;
|
|
28
|
-
get registry(): URL;
|
|
29
|
-
get versionRange(): SemVerRange;
|
|
30
|
-
}
|
|
31
|
-
export declare type PartialNpmMetadata = {
|
|
32
|
-
versions: Record<string, {
|
|
33
|
-
dist: {
|
|
34
|
-
tarball: string;
|
|
35
|
-
};
|
|
36
|
-
}>;
|
|
37
|
-
};
|
|
38
|
-
/**
|
|
39
|
-
* Fetches the NPM metadata of the specified package from
|
|
40
|
-
* the public npm registry.
|
|
41
|
-
*
|
|
42
|
-
* @param packageName - The name of the package whose metadata to fetch.
|
|
43
|
-
* @param registryUrl - The URL of the npm registry to fetch the metadata from.
|
|
44
|
-
* @param fetchFunction - The fetch function to use. Defaults to the global
|
|
45
|
-
* {@link fetch}. Useful for Node.js compatibility.
|
|
46
|
-
* @returns The NPM metadata object.
|
|
47
|
-
* @throws If fetching the metadata fails.
|
|
48
|
-
*/
|
|
49
|
-
export declare function fetchNpmMetadata(packageName: string, registryUrl: URL | string, fetchFunction: typeof fetch): Promise<PartialNpmMetadata>;
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { PermissionConstraint, PermissionSpecificationConstraint } from '@metamask/permission-controller';
|
|
2
|
-
import type { SnapPermissions } from '@metamask/snaps-utils';
|
|
3
|
-
/**
|
|
4
|
-
* Map initial permissions as defined in a Snap manifest to something that can
|
|
5
|
-
* be processed by the PermissionsController. Each caveat mapping function
|
|
6
|
-
* should return a valid permission caveat value.
|
|
7
|
-
*
|
|
8
|
-
* This function does not validate the caveat values, since that is done by
|
|
9
|
-
* the PermissionsController itself, upon requesting the permissions.
|
|
10
|
-
*
|
|
11
|
-
* @param initialPermissions - The initial permissions to process.
|
|
12
|
-
* @returns The processed permissions.
|
|
13
|
-
*/
|
|
14
|
-
export declare function processSnapPermissions(initialPermissions: SnapPermissions): Record<string, Pick<PermissionConstraint, 'caveats'>>;
|
|
15
|
-
export declare const buildSnapEndowmentSpecifications: (excludedEndowments: string[]) => Record<string, PermissionSpecificationConstraint>;
|
|
16
|
-
export declare const buildSnapRestrictedMethodSpecifications: (excludedPermissions: string[], hooks: Record<string, unknown>) => Record<string, PermissionSpecificationConstraint>;
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|