@metamask/snaps-controllers 3.1.0 → 3.2.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 +14 -1
- package/dist/cjs/snaps/SnapController.js +25 -6
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/location/location.js.map +1 -1
- package/dist/cjs/snaps/location/npm.js +6 -2
- package/dist/cjs/snaps/location/npm.js.map +1 -1
- package/dist/cjs/snaps/registry/json.js +2 -2
- package/dist/cjs/snaps/registry/json.js.map +1 -1
- package/dist/esm/snaps/SnapController.js +27 -8
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/location/location.js.map +1 -1
- package/dist/esm/snaps/location/npm.js +6 -2
- package/dist/esm/snaps/location/npm.js.map +1 -1
- package/dist/esm/snaps/registry/json.js +2 -2
- package/dist/esm/snaps/registry/json.js.map +1 -1
- package/dist/types/snaps/SnapController.d.ts +2 -1
- package/dist/types/snaps/location/location.d.ts +2 -0
- package/package.json +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/location/location.ts"],"sourcesContent":["import type { SnapManifest, VirtualFile } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { HttpLocation } from './http';\nimport { LocalLocation } from './local';\nimport type { NpmOptions } from './npm';\nimport { NpmLocation } from './npm';\n\ndeclare module '@metamask/snaps-utils' {\n interface DataMap {\n /**\n * Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.\n */\n canonicalPath: string;\n }\n}\n\nexport interface SnapLocation {\n /**\n * All files are relative to the manifest, except the manifest itself.\n */\n manifest(): Promise<VirtualFile<SnapManifest>>;\n fetch(path: string): Promise<VirtualFile>;\n\n readonly shouldAlwaysReload?: boolean;\n}\n\nexport type DetectSnapLocationOptions = NpmOptions & {\n /**\n * The function used to fetch data.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * @default false\n */\n allowHttp?: boolean;\n /**\n * @default false\n */\n allowLocal?: boolean;\n};\n\n/**\n * Auto-magically detects which SnapLocation object to create based on the provided {@link location}.\n *\n * @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.\n * @param opts - NPM options and feature flags.\n * @returns SnapLocation based on url.\n */\nexport function detectSnapLocation(\n location: string | URL,\n opts?: DetectSnapLocationOptions,\n): SnapLocation {\n const allowHttp = opts?.allowHttp ?? false;\n const allowLocal = opts?.allowLocal ?? false;\n const root = new URL(location);\n switch (root.protocol) {\n case 'npm:':\n return new NpmLocation(root, opts);\n case 'local:':\n assert(allowLocal, new TypeError('Fetching local snaps is disabled.'));\n return new LocalLocation(root, opts);\n case 'http:':\n case 'https:':\n assert(\n allowHttp,\n new TypeError('Fetching snaps through http/https is disabled.'),\n );\n return new HttpLocation(root, opts);\n default:\n throw new TypeError(\n `Unrecognized \"${root.protocol}\" snap location protocol.`,\n );\n }\n}\n"],"names":["detectSnapLocation","location","opts","allowHttp","allowLocal","root","URL","protocol","NpmLocation","assert","TypeError","LocalLocation","HttpLocation"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/location/location.ts"],"sourcesContent":["import type { SnapManifest, VirtualFile } from '@metamask/snaps-utils';\nimport type { SemVerRange } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\nimport { HttpLocation } from './http';\nimport { LocalLocation } from './local';\nimport type { NpmOptions } from './npm';\nimport { NpmLocation } from './npm';\n\ndeclare module '@metamask/snaps-utils' {\n interface DataMap {\n /**\n * Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.\n */\n canonicalPath: string;\n }\n}\n\nexport interface SnapLocation {\n /**\n * All files are relative to the manifest, except the manifest itself.\n */\n manifest(): Promise<VirtualFile<SnapManifest>>;\n fetch(path: string): Promise<VirtualFile>;\n\n readonly shouldAlwaysReload?: boolean;\n}\n\nexport type DetectSnapLocationOptions = NpmOptions & {\n /**\n * The function used to fetch data.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * @default false\n */\n allowHttp?: boolean;\n /**\n * @default false\n */\n allowLocal?: boolean;\n\n resolveVersion?: (range: SemVerRange) => Promise<SemVerRange>;\n};\n\n/**\n * Auto-magically detects which SnapLocation object to create based on the provided {@link location}.\n *\n * @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.\n * @param opts - NPM options and feature flags.\n * @returns SnapLocation based on url.\n */\nexport function detectSnapLocation(\n location: string | URL,\n opts?: DetectSnapLocationOptions,\n): SnapLocation {\n const allowHttp = opts?.allowHttp ?? false;\n const allowLocal = opts?.allowLocal ?? false;\n const root = new URL(location);\n switch (root.protocol) {\n case 'npm:':\n return new NpmLocation(root, opts);\n case 'local:':\n assert(allowLocal, new TypeError('Fetching local snaps is disabled.'));\n return new LocalLocation(root, opts);\n case 'http:':\n case 'https:':\n assert(\n allowHttp,\n new TypeError('Fetching snaps through http/https is disabled.'),\n );\n return new HttpLocation(root, opts);\n default:\n throw new TypeError(\n `Unrecognized \"${root.protocol}\" snap location protocol.`,\n );\n }\n}\n"],"names":["detectSnapLocation","location","opts","allowHttp","allowLocal","root","URL","protocol","NpmLocation","assert","TypeError","LocalLocation","HttpLocation"],"mappings":";;;;+BAsDgBA;;;eAAAA;;;uBApDO;sBAEM;uBACC;qBAEF;AA+CrB,SAASA,mBACdC,QAAsB,EACtBC,IAAgC;IAEhC,MAAMC,YAAYD,MAAMC,aAAa;IACrC,MAAMC,aAAaF,MAAME,cAAc;IACvC,MAAMC,OAAO,IAAIC,IAAIL;IACrB,OAAQI,KAAKE,QAAQ;QACnB,KAAK;YACH,OAAO,IAAIC,gBAAW,CAACH,MAAMH;QAC/B,KAAK;YACHO,IAAAA,aAAM,EAACL,YAAY,IAAIM,UAAU;YACjC,OAAO,IAAIC,oBAAa,CAACN,MAAMH;QACjC,KAAK;QACL,KAAK;YACHO,IAAAA,aAAM,EACJN,WACA,IAAIO,UAAU;YAEhB,OAAO,IAAIE,kBAAY,CAACP,MAAMH;QAChC;YACE,MAAM,IAAIQ,UACR,CAAC,cAAc,EAAEL,KAAKE,QAAQ,CAAC,yBAAyB,CAAC;IAE/D;AACF"}
|
|
@@ -104,6 +104,8 @@ class NpmLocation {
|
|
|
104
104
|
const allowCustomRegistries = opts.allowCustomRegistries ?? false;
|
|
105
105
|
const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
106
106
|
const requestedRange = opts.versionRange ?? _snapsutils.DEFAULT_REQUESTED_SNAP_VERSION;
|
|
107
|
+
const defaultResolve = async (range)=>range;
|
|
108
|
+
const resolveVersion = opts.resolveVersion ?? defaultResolve;
|
|
107
109
|
(0, _utils.assertStruct)(url.toString(), _snapsutils.NpmSnapIdStruct, 'Invalid Snap Id: ');
|
|
108
110
|
let registry;
|
|
109
111
|
if (url.host === '' && url.port === '' && url.username === '' && url.password === '') {
|
|
@@ -131,13 +133,15 @@ class NpmLocation {
|
|
|
131
133
|
requestedRange,
|
|
132
134
|
registry,
|
|
133
135
|
packageName,
|
|
134
|
-
fetch: fetchFunction
|
|
136
|
+
fetch: fetchFunction,
|
|
137
|
+
resolveVersion
|
|
135
138
|
};
|
|
136
139
|
}
|
|
137
140
|
}
|
|
138
141
|
async function lazyInit() {
|
|
139
142
|
(0, _utils.assert)(this.files === undefined);
|
|
140
|
-
const
|
|
143
|
+
const resolvedVersion = await this.meta.resolveVersion(this.meta.requestedRange);
|
|
144
|
+
const [tarballResponse, actualVersion] = await fetchNpmTarball(this.meta.packageName, resolvedVersion, this.meta.registry, this.meta.fetch);
|
|
141
145
|
this.meta.version = actualVersion;
|
|
142
146
|
let canonicalBase = 'npm://';
|
|
143
147
|
if (this.meta.registry.username !== '') {
|
|
@@ -1 +1 @@
|
|
|
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 isValidSemVerVersion,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport getNpmTarballUrl from 'get-npm-tarball-url';\nimport createGunzipStream from 'gunzip-maybe';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { pipeline } from '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 = new URL('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 = 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 pipeline(\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 * Resolves a version range to a version using the NPM registry.\n *\n * Unless the version range is already a version, then the NPM registry is skipped.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param versionRange - The version range of the package.\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 An object containing the resolved version and a URL for its tarball.\n * @throws If fetching the metadata fails.\n */\nasync function resolveNpmVersion(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<{ tarballURL: string; targetVersion: SemVerVersion }> {\n // If the version range is already a static version we don't need to look for the metadata.\n if (\n registryUrl.toString() === DEFAULT_NPM_REGISTRY.toString() &&\n isValidSemVerVersion(versionRange)\n ) {\n return {\n tarballURL: getNpmTarballUrl(packageName, versionRange),\n targetVersion: versionRange,\n };\n }\n\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 tarballURL = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n return { tarballURL, targetVersion };\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,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const { tarballURL, targetVersion } = await resolveNpmVersion(\n packageName,\n versionRange,\n registryUrl,\n fetchFunction,\n );\n\n if (!isValidUrl(tarballURL) || !tarballURL.toString().endsWith('.tgz')) {\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(tarballURL);\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({ encoding: 'uint8array' }, (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":["DEFAULT_NPM_REGISTRY","NpmLocation","fetchNpmMetadata","URL","manifest","validatedManifest","clone","vfile","fetch","result","parseJson","toString","createSnapManifest","path","relativePath","normalizeRelative","files","lazyInit","assert","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","DEFAULT_REQUESTED_SNAP_VERSION","assertStruct","NpmSnapIdStruct","host","port","username","password","pathname","search","hash","startsWith","slice","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","pipeline","getNodeStream","createGunzipStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","isObject","resolveNpmVersion","isValidSemVerVersion","tarballURL","getNpmTarballUrl","targetVersion","versions","Object","keys","map","assertIsSemVerVersion","getTargetVersion","dist","tarball","isValidUrl","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","ReadableWebToNodeStream","extractStream","tarExtract","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","concat","encoding","data","byteLength","VirtualFile","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;IA6BaA,oBAAoB;eAApBA;;IAsBAC,WAAW;eAAXA;;IA4KSC,gBAAgB;eAAhBA;;;4BArNf;uBAQA;qEACY;yEACU;oEACE;yCACS;wBACf;2BAEa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAI/B,MAAMF,uBAAuB,IAAIG,IAAI;IAqIpC;AA/GD,MAAMF;IAgEX,MAAMG,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,SAASC,IAAAA,qBAAS,EAACH,MAAMI,QAAQ;QACvCJ,MAAME,MAAM,GAAGG,IAAAA,8BAAkB,EAACH;QAClC,IAAI,CAACJ,iBAAiB,GAAGE;QAEzB,OAAO,IAAI,CAACH,QAAQ;IACtB;IAEA,MAAMI,MAAMK,IAAY,EAAwB;QAC9C,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AAM,EAAC;gBAAEC,UAAU;YAAa,GAAG,CAACC;gBAClC,IAAI;oBACFb,aAAaa,KAAKC,UAAU;oBAC5B,8EAA8E;oBAC9E/F,IAAAA,aAAM,EACJiF,YAAYvC,2BACZ,CAAC,8BAA8B,EAAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAMrD,QAAQ,IAAI2G,uBAAW,CAAC;wBAC5BC,OAAOH;wBACPnG;wBACAmG,MAAM;4BACJI,eAAe,IAAIjH,IAAIU,MAAMqC,eAAevC,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFO,IAAAA,aAAM,EACJ,CAACF,MAAMqG,GAAG,CAACxG,OACX;oBAEFG,MAAMsG,GAAG,CAACzG,MAAMN;oBAChB,OAAOgG;gBACT,EAAE,OAAO5C,OAAO;oBACd,OAAOsC,cAAcsB,OAAO,CAAC5D;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7C2C,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYkB,MAAM;IAC3B;IACA,OAAOvB;AACT"}
|
|
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 isValidSemVerVersion,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport getNpmTarballUrl from 'get-npm-tarball-url';\nimport createGunzipStream from 'gunzip-maybe';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { pipeline } from '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 = new URL('https://registry.npmjs.org');\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n resolveVersion: (range: SemVerRange) => Promise<SemVerRange>;\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 const defaultResolve = async (range: SemVerRange) => range;\n const resolveVersion = opts.resolveVersion ?? defaultResolve;\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 = 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 resolveVersion,\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 resolvedVersion = await this.meta.resolveVersion(\n this.meta.requestedRange,\n );\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n resolvedVersion,\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 pipeline(\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 * Resolves a version range to a version using the NPM registry.\n *\n * Unless the version range is already a version, then the NPM registry is skipped.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param versionRange - The version range of the package.\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 An object containing the resolved version and a URL for its tarball.\n * @throws If fetching the metadata fails.\n */\nasync function resolveNpmVersion(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<{ tarballURL: string; targetVersion: SemVerVersion }> {\n // If the version range is already a static version we don't need to look for the metadata.\n if (\n registryUrl.toString() === DEFAULT_NPM_REGISTRY.toString() &&\n isValidSemVerVersion(versionRange)\n ) {\n return {\n tarballURL: getNpmTarballUrl(packageName, versionRange),\n targetVersion: versionRange,\n };\n }\n\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 tarballURL = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n return { tarballURL, targetVersion };\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,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const { tarballURL, targetVersion } = await resolveNpmVersion(\n packageName,\n versionRange,\n registryUrl,\n fetchFunction,\n );\n\n if (!isValidUrl(tarballURL) || !tarballURL.toString().endsWith('.tgz')) {\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(tarballURL);\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({ encoding: 'uint8array' }, (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":["DEFAULT_NPM_REGISTRY","NpmLocation","fetchNpmMetadata","URL","manifest","validatedManifest","clone","vfile","fetch","result","parseJson","toString","createSnapManifest","path","relativePath","normalizeRelative","files","lazyInit","assert","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","DEFAULT_REQUESTED_SNAP_VERSION","defaultResolve","range","resolveVersion","assertStruct","NpmSnapIdStruct","host","port","username","password","pathname","search","hash","startsWith","slice","resolvedVersion","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","pipeline","getNodeStream","createGunzipStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","isObject","resolveNpmVersion","isValidSemVerVersion","tarballURL","getNpmTarballUrl","targetVersion","versions","Object","keys","map","assertIsSemVerVersion","getTargetVersion","dist","tarball","isValidUrl","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","ReadableWebToNodeStream","extractStream","tarExtract","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","concat","encoding","data","byteLength","VirtualFile","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;IA6BaA,oBAAoB;eAApBA;;IAuBAC,WAAW;eAAXA;;IAkLSC,gBAAgB;eAAhBA;;;4BA5Nf;uBAQA;qEACY;yEACU;oEACE;yCACS;wBACf;2BAEa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAI/B,MAAMF,uBAAuB,IAAIG,IAAI;IAyIpC;AAlHD,MAAMF;IAmEX,MAAMG,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,SAASC,IAAAA,qBAAS,EAACH,MAAMI,QAAQ;QACvCJ,MAAME,MAAM,GAAGG,IAAAA,8BAAkB,EAACH;QAClC,IAAI,CAACJ,iBAAiB,GAAGE;QAEzB,OAAO,IAAI,CAACH,QAAQ;IACtB;IAEA,MAAMI,MAAMK,IAAY,EAAwB;QAC9C,MAAMC,eAAeC,IAAAA,6BAAiB,EAACF;QACvC,IAAI,CAAC,IAAI,CAACG,KAAK,EAAE;YACf,MAAM,0BAAA,IAAI,EAAEC,WAAAA,eAAN,IAAI;YACVC,IAAAA,aAAM,EAAC,IAAI,CAACF,KAAK,KAAKG;QACxB;QACA,MAAMZ,QAAQ,IAAI,CAACS,KAAK,CAACI,GAAG,CAACN;QAC7BI,IAAAA,aAAM,EACJX,UAAUY,WACV,IAAIE,UAAU,CAAC,MAAM,EAAER,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C,2BACZ,CAAC,8BAA8B,EAAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAMzD,QAAQ,IAAI+G,uBAAW,CAAC;wBAC5BC,OAAOH;wBACPvG;wBACAuG,MAAM;4BACJI,eAAe,IAAIrH,IAAIU,MAAMyC,eAAe3C,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFO,IAAAA,aAAM,EACJ,CAACF,MAAMyG,GAAG,CAAC5G,OACX;oBAEFG,MAAM0G,GAAG,CAAC7G,MAAMN;oBAChB,OAAOoG;gBACT,EAAE,OAAO5C,OAAO;oBACd,OAAOsC,cAAcsB,OAAO,CAAC5D;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7C2C,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYkB,MAAM;IAC3B;IACA,OAAOvB;AACT"}
|
|
@@ -271,13 +271,13 @@ async function resolveVersion(snapId, versionRange, refetch = false) {
|
|
|
271
271
|
await _class_private_method_get(this, _triggerUpdate, triggerUpdate).call(this);
|
|
272
272
|
return _class_private_method_get(this, _resolveVersion, resolveVersion).call(this, snapId, versionRange, true);
|
|
273
273
|
}
|
|
274
|
-
(0, _utils.assert)(versions,
|
|
274
|
+
(0, _utils.assert)(versions, 'The snap is not on the allowlist');
|
|
275
275
|
const targetVersion = (0, _snapsutils.getTargetVersion)(Object.keys(versions), versionRange);
|
|
276
276
|
if (!targetVersion && _class_private_field_get(this, _refetchOnAllowlistMiss) && !refetch) {
|
|
277
277
|
await _class_private_method_get(this, _triggerUpdate, triggerUpdate).call(this);
|
|
278
278
|
return _class_private_method_get(this, _resolveVersion, resolveVersion).call(this, snapId, versionRange, true);
|
|
279
279
|
}
|
|
280
|
-
(0, _utils.assert)(targetVersion,
|
|
280
|
+
(0, _utils.assert)(targetVersion, 'No matching versions of the snap are on the allowlist');
|
|
281
281
|
// A semver version is technically also a valid semver range.
|
|
282
282
|
(0, _utils.assertIsSemVerRange)(targetVersion);
|
|
283
283
|
return targetVersion;
|
|
@@ -1 +1 @@
|
|
|
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 { getTargetVersion, type SnapId } from '@metamask/snaps-utils';\nimport type { Hex, SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerRange,\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 ResolveVersion = {\n type: `${typeof controllerName}:resolveVersion`;\n handler: SnapsRegistry['resolveVersion'];\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 =\n | GetResult\n | GetMetadata\n | Update\n | ResolveVersion;\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 #currentUpdate: Promise<void> | null;\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 this.#currentUpdate = null;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:resolveVersion',\n async (...args) => this.#resolveVersion(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#triggerUpdate(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n /**\n * Triggers an update of the registry database.\n *\n * If an existing update is in progress this function will await that update.\n */\n async #triggerUpdate() {\n // If an update is ongoing, wait for that.\n if (this.#currentUpdate) {\n await this.#currentUpdate;\n return;\n }\n // If no update exists, create promise and store globally.\n if (this.#currentUpdate === null) {\n this.#currentUpdate = this.#update();\n }\n await this.#currentUpdate;\n this.#currentUpdate = null;\n }\n\n /**\n * Updates the registry database if the registry hasn't been updated recently.\n *\n * NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.\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.#triggerUpdate();\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.#triggerUpdate();\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 * Find an allowlisted version within a specified version range.\n *\n * @param snapId - The ID of the snap we are trying to resolve a version for.\n * @param versionRange - The version range.\n * @param refetch - An optional flag used to determine if we are refetching the registry.\n * @returns An allowlisted version within the specified version range.\n * @throws If an allowlisted version does not exist within the version range.\n */\n async #resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n refetch = false,\n ): Promise<SemVerRange> {\n const database = await this.#getDatabase();\n const versions = database?.verifiedSnaps[snapId]?.versions ?? null;\n\n if (!versions && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(\n versions,\n `Cannot install snap \"${snapId}\": The snap is not on the allowlist.`,\n );\n\n const targetVersion = getTargetVersion(\n Object.keys(versions) as SemVerVersion[],\n versionRange,\n );\n\n if (!targetVersion && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(\n targetVersion,\n `Cannot install version \"${versionRange}\" of snap \"${snapId}\": No matching versions of the snap are on the allowlist.`,\n );\n\n // A semver version is technically also a valid semver range.\n assertIsSemVerRange(targetVersion);\n return targetVersion;\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":["JsonSnapsRegistry","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","BaseController","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","inMilliseconds","Duration","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","currentUpdate","messagingSystem","registerActionHandler","args","get","getMetadata","resolveVersion","triggerUpdate","Date","now","update","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","satisfiesVersionRange","version","versionRange","checksum","status","SnapsRegistryStatus","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","assert","targetVersion","getTargetVersion","keys","assertIsSemVerRange","valid","verify","response","ok","text"],"mappings":";;;;+BA8FaA;;;eAAAA;;;gCA7FsC;+BAE5B;4BACuB;uBAQvC;0BAS6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpC,kCAAkC;AAClC,MAAMC,oBACJ;AAEF,MAAMC,8BACJ;AA2DF,MAAMC,iBAAiB;AAEvB,MAAMC,eAAe;IACnBC,UAAU;IACVC,aAAa;AACf;IAOE,oCAEA,0CAEA,8CAEA,qDAEA,uDAEA,0DAEA,8CAwDA,mDAYM,8CAmBA,uCAuBA,4CAYA,0CAsCA,oCAsBA,+CA6CA,4CAaA,gDAmBA;AApRD,MAAMN,0BAA0BO,gCAAc;IAmBnDC,YAAY,EACVC,SAAS,EACTC,KAAK,EACLC,MAAM;QACJC,UAAUX;QACVY,WAAWX;IACb,CAAC,EACDY,SAAS,EACTC,gBAAgBC,WAAWC,KAAK,CAACC,IAAI,CAACF,WAAW,EACjDG,uBAAuBC,IAAAA,qBAAc,EAAC,GAAGC,eAAQ,CAACC,MAAM,CAAC,EACzDC,4BAA4B,IAAI,EAChCC,yBAAyB,IAAI,EACP,CAAE;QACxB,KAAK,CAAC;YACJf;YACAgB,UAAU;gBACRpB,UAAU;oBAAEqB,SAAS;oBAAMC,WAAW;gBAAM;gBAC5CrB,aAAa;oBAAEoB,SAAS;oBAAMC,WAAW;gBAAM;YACjD;YACAC,MAAMzB;YACNO,OAAO;gBACL,GAAGN,YAAY;gBACf,GAAGM,KAAK;YACV;QACF;QA8BF,iCAAA;QAOA;;;;GAIC,GACD,iCAAM;QAcN;;;;GAIC,GACD,iCAAM;QAuBN,iCAAM;QAYN,iCAAM;QAsCN,iCAAM;QAaN;;;;;;;;GAQC,GACD,iCAAM;QAsCN;;;;;;GAMC,GACD,iCAAM;QAKN;;;;;;;GAOC,GACD,iCAAM;QAYN;;;;;;GAM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AM,IAAIzC,MAAM,CAAC,gBAAgB,EAAElC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAM0E,SAASE,IAAI;AAC5B"}
|
|
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 { getTargetVersion, type SnapId } from '@metamask/snaps-utils';\nimport type { Hex, SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerRange,\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 ResolveVersion = {\n type: `${typeof controllerName}:resolveVersion`;\n handler: SnapsRegistry['resolveVersion'];\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 =\n | GetResult\n | GetMetadata\n | Update\n | ResolveVersion;\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 #currentUpdate: Promise<void> | null;\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 this.#currentUpdate = null;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:resolveVersion',\n async (...args) => this.#resolveVersion(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#triggerUpdate(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n /**\n * Triggers an update of the registry database.\n *\n * If an existing update is in progress this function will await that update.\n */\n async #triggerUpdate() {\n // If an update is ongoing, wait for that.\n if (this.#currentUpdate) {\n await this.#currentUpdate;\n return;\n }\n // If no update exists, create promise and store globally.\n if (this.#currentUpdate === null) {\n this.#currentUpdate = this.#update();\n }\n await this.#currentUpdate;\n this.#currentUpdate = null;\n }\n\n /**\n * Updates the registry database if the registry hasn't been updated recently.\n *\n * NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.\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.#triggerUpdate();\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.#triggerUpdate();\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 * Find an allowlisted version within a specified version range.\n *\n * @param snapId - The ID of the snap we are trying to resolve a version for.\n * @param versionRange - The version range.\n * @param refetch - An optional flag used to determine if we are refetching the registry.\n * @returns An allowlisted version within the specified version range.\n * @throws If an allowlisted version does not exist within the version range.\n */\n async #resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n refetch = false,\n ): Promise<SemVerRange> {\n const database = await this.#getDatabase();\n const versions = database?.verifiedSnaps[snapId]?.versions ?? null;\n\n if (!versions && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(versions, 'The snap is not on the allowlist');\n\n const targetVersion = getTargetVersion(\n Object.keys(versions) as SemVerVersion[],\n versionRange,\n );\n\n if (!targetVersion && this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#resolveVersion(snapId, versionRange, true);\n }\n\n assert(\n targetVersion,\n 'No matching versions of the snap are on the allowlist',\n );\n\n // A semver version is technically also a valid semver range.\n assertIsSemVerRange(targetVersion);\n return targetVersion;\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":["JsonSnapsRegistry","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","BaseController","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","inMilliseconds","Duration","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","currentUpdate","messagingSystem","registerActionHandler","args","get","getMetadata","resolveVersion","triggerUpdate","Date","now","update","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","satisfiesVersionRange","version","versionRange","checksum","status","SnapsRegistryStatus","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","assert","targetVersion","getTargetVersion","keys","assertIsSemVerRange","valid","verify","response","ok","text"],"mappings":";;;;+BA8FaA;;;eAAAA;;;gCA7FsC;+BAE5B;4BACuB;uBAQvC;0BAS6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpC,kCAAkC;AAClC,MAAMC,oBACJ;AAEF,MAAMC,8BACJ;AA2DF,MAAMC,iBAAiB;AAEvB,MAAMC,eAAe;IACnBC,UAAU;IACVC,aAAa;AACf;IAOE,oCAEA,0CAEA,8CAEA,qDAEA,uDAEA,0DAEA,8CAwDA,mDAYM,8CAmBA,uCAuBA,4CAYA,0CAsCA,oCAsBA,+CA0CA,4CAaA,gDAmBA;AAjRD,MAAMN,0BAA0BO,gCAAc;IAmBnDC,YAAY,EACVC,SAAS,EACTC,KAAK,EACLC,MAAM;QACJC,UAAUX;QACVY,WAAWX;IACb,CAAC,EACDY,SAAS,EACTC,gBAAgBC,WAAWC,KAAK,CAACC,IAAI,CAACF,WAAW,EACjDG,uBAAuBC,IAAAA,qBAAc,EAAC,GAAGC,eAAQ,CAACC,MAAM,CAAC,EACzDC,4BAA4B,IAAI,EAChCC,yBAAyB,IAAI,EACP,CAAE;QACxB,KAAK,CAAC;YACJf;YACAgB,UAAU;gBACRpB,UAAU;oBAAEqB,SAAS;oBAAMC,WAAW;gBAAM;gBAC5CrB,aAAa;oBAAEoB,SAAS;oBAAMC,WAAW;gBAAM;YACjD;YACAC,MAAMzB;YACNO,OAAO;gBACL,GAAGN,YAAY;gBACf,GAAGM,KAAK;YACV;QACF;QA8BF,iCAAA;QAOA;;;;GAIC,GACD,iCAAM;QAcN;;;;GAIC,GACD,iCAAM;QAuBN,iCAAM;QAYN,iCAAM;QAsCN,iCAAM;QAaN;;;;;;;;GAQC,GACD,iCAAM;QAmCN;;;;;;GAMC,GACD,iCAAM;QAKN;;;;;;;GAOC,GACD,iCAAM;QAYN;;;;;;GAMC,GACD,iCAAM;Q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,9 @@ import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
|
|
|
65
65
|
import { SubjectType } from '@metamask/permission-controller';
|
|
66
66
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
67
67
|
import { WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-rpc-methods';
|
|
68
|
-
import {
|
|
69
|
-
import {
|
|
68
|
+
import { assertUILinksAreSafe } from '@metamask/snaps-ui';
|
|
69
|
+
import { assertIsSnapManifest, assertIsValidSnapId, AuxiliaryFileEncoding, DEFAULT_ENDOWMENTS, DEFAULT_REQUESTED_SNAP_VERSION, encodeAuxiliaryFile, getErrorMessage, HandlerType, isOriginAllowed, logError, normalizeRelative, OnTransactionResponseStruct, resolveVersionRange, SnapCaveatType, SnapStatus, SnapStatusEvents, validateFetchedSnap, unwrapError } from '@metamask/snaps-utils';
|
|
70
|
+
import { assert, assertIsJsonRpcRequest, assertStruct, Duration, gtRange, gtVersion, hasProperty, inMilliseconds, isNonEmptyArray, isValidSemVerRange, satisfiesVersionRange, timeSince } from '@metamask/utils';
|
|
70
71
|
import { createMachine, interpret } from '@xstate/fsm';
|
|
71
72
|
import { nanoid } from 'nanoid';
|
|
72
73
|
import { forceStrict, validateMachine } from '../fsm';
|
|
@@ -166,7 +167,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
|
|
|
166
167
|
*
|
|
167
168
|
* @param snapId - The id of the Snap whose message handler to get.
|
|
168
169
|
* @returns The RPC handler for the given snap.
|
|
169
|
-
*/ _getRpcRequestHandler = /*#__PURE__*/ new WeakSet(), _executeWithTimeout = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestStart = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestFinish = /*#__PURE__*/ new WeakSet(), /**
|
|
170
|
+
*/ _getRpcRequestHandler = /*#__PURE__*/ new WeakSet(), _assertSnapRpcRequestResult = /*#__PURE__*/ new WeakSet(), _executeWithTimeout = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestStart = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestFinish = /*#__PURE__*/ new WeakSet(), /**
|
|
170
171
|
* Retrieves the rollback snapshot of a snap.
|
|
171
172
|
*
|
|
172
173
|
* @param snapId - The snap id.
|
|
@@ -576,16 +577,15 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
|
|
|
576
577
|
try {
|
|
577
578
|
for (const [snapId, { version: rawVersion }] of Object.entries(requestedSnaps)){
|
|
578
579
|
assertIsValidSnapId(snapId);
|
|
579
|
-
const [error,
|
|
580
|
+
const [error, version] = resolveVersionRange(rawVersion);
|
|
580
581
|
if (error) {
|
|
581
582
|
throw rpcErrors.invalidParams(`The "version" field must be a valid SemVer version range if specified. Received: "${rawVersion}".`);
|
|
582
583
|
}
|
|
583
|
-
// If we are running in allowlist mode, try to match the version with an allowlist version.
|
|
584
|
-
const version = _class_private_field_get(this, _featureFlags).requireAllowlist ? await _class_private_method_get(this, _resolveAllowlistVersion, resolveAllowlistVersion).call(this, snapId, resolvedVersion) : resolvedVersion;
|
|
585
584
|
const location = _class_private_field_get(this, _detectSnapLocation).call(this, snapId, {
|
|
586
585
|
versionRange: version,
|
|
587
586
|
fetch: _class_private_field_get(this, _fetchFunction),
|
|
588
|
-
allowLocal: _class_private_field_get(this, _featureFlags).allowLocalSnaps
|
|
587
|
+
allowLocal: _class_private_field_get(this, _featureFlags).allowLocalSnaps,
|
|
588
|
+
resolveVersion: async (range)=>_class_private_field_get(this, _featureFlags).requireAllowlist ? await _class_private_method_get(this, _resolveAllowlistVersion, resolveAllowlistVersion).call(this, snapId, range) : range
|
|
589
589
|
});
|
|
590
590
|
// Existing snaps may need to be updated, unless they should be re-installed (e.g. local snaps)
|
|
591
591
|
// Everything else is treated as an install
|
|
@@ -1001,6 +1001,12 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
|
|
|
1001
1001
|
_class_private_method_init(this, _validateSnapPermissions);
|
|
1002
1002
|
_class_private_method_init(this, _getRpcRequestHandler);
|
|
1003
1003
|
/**
|
|
1004
|
+
* Asserts that the returned result of a Snap RPC call is the expected shape.
|
|
1005
|
+
*
|
|
1006
|
+
* @param handlerType - The handler type of the RPC Request.
|
|
1007
|
+
* @param result - The result of the RPC request.
|
|
1008
|
+
*/ _class_private_method_init(this, _assertSnapRpcRequestResult);
|
|
1009
|
+
/**
|
|
1004
1010
|
* Awaits the specified promise and rejects if the promise doesn't resolve
|
|
1005
1011
|
* before the timeout.
|
|
1006
1012
|
*
|
|
@@ -1541,7 +1547,7 @@ function getRpcRequestHandler(snapId) {
|
|
|
1541
1547
|
// This will either get the result or reject due to the timeout.
|
|
1542
1548
|
try {
|
|
1543
1549
|
const result = await _class_private_method_get(this, _executeWithTimeout, executeWithTimeout).call(this, handleRpcRequestPromise, timer);
|
|
1544
|
-
_class_private_method_get(this,
|
|
1550
|
+
await _class_private_method_get(this, _assertSnapRpcRequestResult, assertSnapRpcRequestResult).call(this, handlerType, result);
|
|
1545
1551
|
return result;
|
|
1546
1552
|
} catch (error) {
|
|
1547
1553
|
const [jsonRpcError, handled] = unwrapError(error);
|
|
@@ -1549,11 +1555,24 @@ function getRpcRequestHandler(snapId) {
|
|
|
1549
1555
|
await this.stopSnap(snapId, SnapStatusEvents.Crash);
|
|
1550
1556
|
}
|
|
1551
1557
|
throw jsonRpcError;
|
|
1558
|
+
} finally{
|
|
1559
|
+
_class_private_method_get(this, _recordSnapRpcRequestFinish, recordSnapRpcRequestFinish).call(this, snapId, request.id);
|
|
1552
1560
|
}
|
|
1553
1561
|
};
|
|
1554
1562
|
runtime.rpcHandler = rpcHandler;
|
|
1555
1563
|
return rpcHandler;
|
|
1556
1564
|
}
|
|
1565
|
+
async function assertSnapRpcRequestResult(handlerType, result) {
|
|
1566
|
+
switch(handlerType){
|
|
1567
|
+
case HandlerType.OnTransaction:
|
|
1568
|
+
assertStruct(result, OnTransactionResponseStruct);
|
|
1569
|
+
await this.messagingSystem.call('PhishingController:maybeUpdateState');
|
|
1570
|
+
await assertUILinksAreSafe(result.content, (url)=>this.messagingSystem.call('PhishingController:testOrigin', url).result);
|
|
1571
|
+
break;
|
|
1572
|
+
default:
|
|
1573
|
+
break;
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1557
1576
|
async function executeWithTimeout(promise, timer) {
|
|
1558
1577
|
const result = await withTimeout(promise, timer ?? this.maxRequestTime);
|
|
1559
1578
|
if (result === hasTimedOut) {
|