@metamask/snaps-controllers 3.3.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,8 +31,8 @@ import { assert, assertIsSemVerVersion, assertStruct, isObject, isValidSemVerVer
31
31
  import concat from 'concat-stream';
32
32
  import getNpmTarballUrl from 'get-npm-tarball-url';
33
33
  import createGunzipStream from 'gunzip-maybe';
34
+ import { pipeline } from 'readable-stream';
34
35
  import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
35
- import { pipeline } from 'stream';
36
36
  import { extract as tarExtract } from 'tar-stream';
37
37
  export const DEFAULT_NPM_REGISTRY = new URL('https://registry.npmjs.org');
38
38
  var _lazyInit = /*#__PURE__*/ new WeakSet();
@@ -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 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":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","isValidSemVerVersion","concat","getNpmTarballUrl","createGunzipStream","ReadableWebToNodeStream","pipeline","extract","tarExtract","DEFAULT_NPM_REGISTRY","URL","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","defaultResolve","range","resolveVersion","host","port","username","password","pathname","search","hash","startsWith","slice","resolvedVersion","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","resolveNpmVersion","tarballURL","targetVersion","versions","Object","keys","map","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","encoding","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,EACRC,oBAAoB,QACf,kBAAkB;AACzB,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,sBAAsB,sBAAsB;AACnD,OAAOC,wBAAwB,eAAe;AAC9C,SAASC,uBAAuB,QAAQ,8BAA8B;AACtE,SAASC,QAAQ,QAAQ,SAAS;AAElC,SAASC,WAAWC,UAAU,QAAQ,aAAa;AAInD,OAAO,MAAMC,uBAAuB,IAAIC,IAAI,8BAA8B;IAyIlE;AAlHR,OAAO,MAAMC;IAmEX,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,SAASrB,UAAUmB,MAAMG,QAAQ;QACvCH,MAAME,MAAM,GAAG5B,mBAAmB4B;QAClC,IAAI,CAACJ,iBAAiB,GAAGE;QAEzB,OAAO,IAAI,CAACH,QAAQ;IACtB;IAEA,MAAMI,MAAMG,IAAY,EAAwB;QAC9C,MAAMC,eAAezB,kBAAkBwB;QACvC,IAAI,CAAC,IAAI,CAACE,KAAK,EAAE;YACf,MAAM,0BAAA,IAAI,EAAEC,WAAAA,eAAN,IAAI;YACVzB,OAAO,IAAI,CAACwB,KAAK,KAAKE;QACxB;QACA,MAAMR,QAAQ,IAAI,CAACM,KAAK,CAACG,GAAG,CAACJ;QAC7BvB,OACEkB,UAAUQ,WACV,IAAIE,U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MAAM0F,GAAG,CAAC5F,OACX;oBAEFE,MAAM2F,GAAG,CAAC7F,MAAMJ;oBAChB,OAAOoF;gBACT,EAAE,OAAOrC,OAAO;oBACd,OAAOgC,cAAcmB,OAAO,CAACnD;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CoC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;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 { pipeline } from 'readable-stream';\nimport type { Readable, Writable } from 'readable-stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-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: unknown) => {\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":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","isValidSemVerVersion","concat","getNpmTarballUrl","createGunzipStream","pipeline","ReadableWebToNodeStream","extract","tarExtract","DEFAULT_NPM_REGISTRY","URL","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","defaultResolve","range","resolveVersion","host","port","username","password","pathname","search","hash","startsWith","slice","resolvedVersion","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","resolveNpmVersion","tarballURL","targetVersion","versions","Object","keys","map","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","encoding","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBA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AEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CoC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;AACT"}
@@ -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(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":["BaseControllerV2","BaseController","verify","getTargetVersion","assert","assertIsSemVerRange","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","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","version","versionRange","checksum","status","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","targetVersion","keys","valid","response","ok","text"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,oBAAoBC,cAAc,QAAQ,4BAA4B;AAE/E,SAASC,MAAM,QAAQ,2BAA2B;AAClD,SAASC,gBAAgB,QAAqB,wBAAwB;AAEtE,SACEC,MAAM,EACNC,mBAAmB,EACnBC,QAAQ,EACRC,cAAc,EACdC,qBAAqB,QAChB,kBAAkB;AASzB,SAASC,mBAAmB,QAAQ,aAAa;AAEjD,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;AAjRR,OAAO,MAAMC,0BAA0Bf;IAmBrCgB,YAAY,EACVC,SAAS,EACTC,KAAK,EACLC,MAAM;QACJC,UAAUX;QACVY,WAAWX;IACb,CAAC,EACDY,SAAS,EACTC,gBAAgBC,WAAWC,KAAK,CAACC,IAAI,CAACF,WAAW,EACjDG,uBAAuBrB,eAAe,GAAGD,SAASuB,MAAM,CAAC,EACzDC,4BAA4B,IAAI,EAChCC,yBAAyB,IAAI,EACP,CAAE;QACxB,KAAK,CAAC;YACJb;YACAc,UAAU;gBACRlB,UAAU;oBAAEmB,SAAS;oBAAMC,WAAW;gBAAM;gBAC5CnB,aAAa;oBAAEkB,SAAS;oBAAMC,WAAW;gBAAM;YACjD;YACAC,MAAMvB;YACNO,OAAO;gBACL,GAAGN,YAAY;gBACf,GAAGM,KAAK;YACV;QACF;QA8BF,iCAAA;QAOA;;;;GAIC,GACD,iC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,EAAEhC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAMkE,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 } 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: string,\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<string, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<string, 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: string,\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: string): 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","getTargetVersion","assert","assertIsSemVerRange","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","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","version","versionRange","checksum","status","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","targetVersion","keys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ources":["../../../../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 { SemVerRange, 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 * 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 resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n ): Promise<SemVerRange>;\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
+ {"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][SnapId]['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<SnapId, SnapsRegistryResult>>;\n\n update(): Promise<void>;\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 resolveVersion(\n snapId: SnapId,\n versionRange: SemVerRange,\n ): Promise<SemVerRange>;\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,7 +1,8 @@
1
1
  import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
2
  import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
3
3
  import type { GetPermissions } from '@metamask/permission-controller';
4
- import type { SnapId, ValidatedSnapId, CronjobSpecification } from '@metamask/snaps-utils';
4
+ import type { SnapId } from '@metamask/snaps-sdk';
5
+ import type { CronjobSpecification } from '@metamask/snaps-utils';
5
6
  import type { GetAllSnaps, HandleSnapRequest, SnapDisabled, SnapEnabled, SnapInstalled, SnapRemoved, SnapUpdated } from '..';
6
7
  import { Timer } from '../snaps/Timer';
7
8
  export declare type CronjobControllerActions = GetAllSnaps | HandleSnapRequest | GetPermissions;
@@ -18,7 +19,7 @@ export declare type CronjobControllerArgs = {
18
19
  export declare type Cronjob = {
19
20
  timer?: Timer;
20
21
  id: string;
21
- snapId: ValidatedSnapId;
22
+ snapId: SnapId;
22
23
  } & CronjobSpecification;
23
24
  export declare type StoredJobInformation = {
24
25
  lastRun: number;
@@ -53,7 +54,7 @@ export declare class CronjobController extends BaseController<typeof controllerN
53
54
  *
54
55
  * @param snapId - ID of a snap.
55
56
  */
56
- register(snapId: ValidatedSnapId): void;
57
+ register(snapId: SnapId): void;
57
58
  /**
58
59
  * Schedule a new job.
59
60
  * This will interpret the cron expression and tell the timer to execute the job
@@ -77,7 +78,7 @@ export declare class CronjobController extends BaseController<typeof controllerN
77
78
  *
78
79
  * @param snapId - ID of a snap.
79
80
  */
80
- unregister(snapId: SnapId): void;
81
+ unregister(snapId: string): void;
81
82
  /**
82
83
  * Update time of a last run for the Cronjob specified by ID.
83
84
  *
@@ -3,7 +3,7 @@ import { JsonRpcEngine } from '@metamask/json-rpc-engine';
3
3
  import ObjectMultiplex from '@metamask/object-multiplex';
4
4
  import type { BasePostMessageStream } from '@metamask/post-message-stream';
5
5
  import type { SnapRpcHookArgs } from '@metamask/snaps-utils';
6
- import type { Duplex } from 'stream';
6
+ import type { Duplex } from 'readable-stream';
7
7
  import type { ExecutionService, ExecutionServiceMessenger, SnapExecutionData } from './ExecutionService';
8
8
  export declare type SetupSnapProvider = (snapId: string, stream: Duplex) => void;
9
9
  export declare type ExecutionServiceArgs = {
@@ -1,5 +1,5 @@
1
1
  import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
- import type { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';
2
+ import type { SnapRpcHookArgs } from '@metamask/snaps-utils';
3
3
  import type { Json } from '@metamask/utils';
4
4
  declare type TerminateSnap = (snapId: string) => Promise<void>;
5
5
  declare type TerminateAll = () => Promise<void>;
@@ -24,15 +24,15 @@ export declare type SnapErrorJson = {
24
24
  declare const controllerName = "ExecutionService";
25
25
  export declare type ErrorMessageEvent = {
26
26
  type: 'ExecutionService:unhandledError';
27
- payload: [SnapId, SnapErrorJson];
27
+ payload: [string, SnapErrorJson];
28
28
  };
29
29
  export declare type OutboundRequest = {
30
30
  type: 'ExecutionService:outboundRequest';
31
- payload: [SnapId];
31
+ payload: [string];
32
32
  };
33
33
  export declare type OutboundResponse = {
34
34
  type: 'ExecutionService:outboundResponse';
35
- payload: [SnapId];
35
+ payload: [string];
36
36
  };
37
37
  export declare type ExecutionServiceEvents = ErrorMessageEvent | OutboundRequest | OutboundResponse;
38
38
  /**
@@ -4,8 +4,10 @@ import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
4
4
  import type { GetEndowments, GetPermissions, GetSubjectMetadata, GetSubjects, GrantPermissions, HasPermission, HasPermissions, RevokeAllPermissions, RevokePermissionForAllSubjects, RevokePermissions, UpdateCaveat } from '@metamask/permission-controller';
5
5
  import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
6
6
  import type { BlockReason } from '@metamask/snaps-registry';
7
- import type { InstallSnapsResult, PersistedSnap, RequestedSnapPermissions, Snap, SnapId, SnapRpcHook, SnapRpcHookArgs, StatusContext, StatusEvents, StatusStates, TruncatedSnap, ValidatedSnapId } from '@metamask/snaps-utils';
8
- import { AuxiliaryFileEncoding, SnapStatusEvents } from '@metamask/snaps-utils';
7
+ import type { RequestSnapsParams, RequestSnapsResult, SnapId } from '@metamask/snaps-sdk';
8
+ import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
9
+ import type { PersistedSnap, Snap, SnapRpcHook, SnapRpcHookArgs, StatusContext, StatusEvents, StatusStates, TruncatedSnap } from '@metamask/snaps-utils';
10
+ import { SnapStatusEvents } from '@metamask/snaps-utils';
9
11
  import type { Json, NonEmptyArray } from '@metamask/utils';
10
12
  import type { StateMachine } from '@xstate/fsm';
11
13
  import type { Patch } from 'immer';
@@ -67,15 +69,15 @@ export declare type SnapError = {
67
69
  data?: Json;
68
70
  };
69
71
  declare type CloseAllConnectionsFunction = (origin: string) => void;
70
- declare type StoredSnaps = Record<ValidatedSnapId, Snap>;
72
+ declare type StoredSnaps = Record<SnapId, Snap>;
71
73
  export declare type SnapControllerState = {
72
74
  snaps: StoredSnaps;
73
- snapStates: Record<ValidatedSnapId, string | null>;
74
- unencryptedSnapStates: Record<ValidatedSnapId, string | null>;
75
+ snapStates: Record<SnapId, string | null>;
76
+ unencryptedSnapStates: Record<SnapId, string | null>;
75
77
  };
76
78
  export declare type PersistedSnapControllerState = SnapControllerState & {
77
- snaps: Record<ValidatedSnapId, PersistedSnap>;
78
- snapStates: Record<ValidatedSnapId, string>;
79
+ snaps: Record<SnapId, PersistedSnap>;
80
+ snapStates: Record<SnapId, string>;
79
81
  };
80
82
  /**
81
83
  * Gets the specified Snap from state.
@@ -339,30 +341,30 @@ export declare class SnapController extends BaseController<string, SnapControlle
339
341
  * for more information.
340
342
  */
341
343
  updateBlockedSnaps(): Promise<void>;
342
- _onUnhandledSnapError(snapId: SnapId, _error: SnapErrorJson): void;
343
- _onOutboundRequest(snapId: SnapId): void;
344
- _onOutboundResponse(snapId: SnapId): void;
344
+ _onUnhandledSnapError(snapId: string, _error: SnapErrorJson): void;
345
+ _onOutboundRequest(snapId: string): void;
346
+ _onOutboundResponse(snapId: string): void;
345
347
  /**
346
348
  * Starts the given snap. Throws an error if no such snap exists
347
349
  * or if it is already running.
348
350
  *
349
351
  * @param snapId - The id of the Snap to start.
350
352
  */
351
- startSnap(snapId: ValidatedSnapId): Promise<void>;
353
+ startSnap(snapId: SnapId): Promise<void>;
352
354
  /**
353
355
  * Enables the given snap. A snap can only be started if it is enabled. A snap
354
356
  * can only be enabled if it isn't blocked.
355
357
  *
356
358
  * @param snapId - The id of the Snap to enable.
357
359
  */
358
- enableSnap(snapId: ValidatedSnapId): void;
360
+ enableSnap(snapId: SnapId): void;
359
361
  /**
360
362
  * Disables the given snap. A snap can only be started if it is enabled.
361
363
  *
362
364
  * @param snapId - The id of the Snap to disable.
363
365
  * @returns A promise that resolves once the snap has been disabled.
364
366
  */
365
- disableSnap(snapId: ValidatedSnapId): Promise<void>;
367
+ disableSnap(snapId: SnapId): Promise<void>;
366
368
  /**
367
369
  * Stops the given snap, removes all hooks, closes all connections, and
368
370
  * terminates its worker.
@@ -371,7 +373,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
371
373
  * @param statusEvent - The Snap status event that caused the snap to be
372
374
  * stopped.
373
375
  */
374
- stopSnap(snapId: ValidatedSnapId, statusEvent?: SnapStatusEvents.Stop | SnapStatusEvents.Crash): Promise<void>;
376
+ stopSnap(snapId: SnapId, statusEvent?: SnapStatusEvents.Stop | SnapStatusEvents.Crash): Promise<void>;
375
377
  /**
376
378
  * Returns whether the given snap is running.
377
379
  * Throws an error if the snap doesn't exist.
@@ -379,14 +381,14 @@ export declare class SnapController extends BaseController<string, SnapControlle
379
381
  * @param snapId - The id of the Snap to check.
380
382
  * @returns `true` if the snap is running, otherwise `false`.
381
383
  */
382
- isRunning(snapId: ValidatedSnapId): boolean;
384
+ isRunning(snapId: SnapId): boolean;
383
385
  /**
384
386
  * Returns whether the given snap has been added to state.
385
387
  *
386
388
  * @param snapId - The id of the Snap to check for.
387
389
  * @returns `true` if the snap exists in the controller state, otherwise `false`.
388
390
  */
389
- has(snapId: ValidatedSnapId): boolean;
391
+ has(snapId: SnapId): boolean;
390
392
  /**
391
393
  * Gets the snap with the given id if it exists, including all data.
392
394
  * This should not be used if the snap is to be serializable, as e.g.
@@ -395,7 +397,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
395
397
  * @param snapId - The id of the Snap to get.
396
398
  * @returns The entire snap object from the controller state.
397
399
  */
398
- get(snapId: SnapId): Snap | undefined;
400
+ get(snapId: string): Snap | undefined;
399
401
  /**
400
402
  * Gets the snap with the given id, throws if doesn't.
401
403
  * This should not be used if the snap is to be serializable, as e.g.
@@ -406,7 +408,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
406
408
  * @param snapId - The id of the snap to get.
407
409
  * @returns The entire snap object.
408
410
  */
409
- getExpect(snapId: ValidatedSnapId): Snap;
411
+ getExpect(snapId: SnapId): Snap;
410
412
  /**
411
413
  * Gets the snap with the given id if it exists, excluding any
412
414
  * non-serializable or expensive-to-serialize data.
@@ -414,7 +416,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
414
416
  * @param snapId - The id of the Snap to get.
415
417
  * @returns A truncated version of the snap state, that is less expensive to serialize.
416
418
  */
417
- getTruncated(snapId: ValidatedSnapId): TruncatedSnap | null;
419
+ getTruncated(snapId: SnapId): TruncatedSnap | null;
418
420
  /**
419
421
  * Gets the snap with the given id, throw if it doesn't exist.
420
422
  *
@@ -422,7 +424,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
422
424
  * @param snapId - The id of the snap to get.
423
425
  * @returns A truncated version of the snap state, that is less expensive to serialize.
424
426
  */
425
- getTruncatedExpect(snapId: ValidatedSnapId): TruncatedSnap;
427
+ getTruncatedExpect(snapId: SnapId): TruncatedSnap;
426
428
  /**
427
429
  * Updates the own state of the snap with the given id.
428
430
  * This is distinct from the state MetaMask uses to manage snaps.
@@ -431,7 +433,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
431
433
  * @param newSnapState - The new state of the snap.
432
434
  * @param encrypted - A flag to indicate whether to use encrypted storage or not.
433
435
  */
434
- updateSnapState(snapId: ValidatedSnapId, newSnapState: string, encrypted: boolean): void;
436
+ updateSnapState(snapId: SnapId, newSnapState: string, encrypted: boolean): void;
435
437
  /**
436
438
  * Clears the state of the snap with the given id.
437
439
  * This is distinct from the state MetaMask uses to manage snaps.
@@ -439,7 +441,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
439
441
  * @param snapId - The id of the Snap whose state should be cleared.
440
442
  * @param encrypted - A flag to indicate whether to use encrypted storage or not.
441
443
  */
442
- clearSnapState(snapId: ValidatedSnapId, encrypted: boolean): void;
444
+ clearSnapState(snapId: SnapId, encrypted: boolean): void;
443
445
  /**
444
446
  * Gets the own state of the snap with the given id.
445
447
  * This is distinct from the state MetaMask uses to manage snaps.
@@ -448,7 +450,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
448
450
  * @param encrypted - A flag to indicate whether to use encrypted storage or not.
449
451
  * @returns The requested snap state or null if no state exists.
450
452
  */
451
- getSnapState(snapId: ValidatedSnapId, encrypted: boolean): Json;
453
+ getSnapState(snapId: SnapId, encrypted: boolean): Json;
452
454
  /**
453
455
  * Gets a static auxiliary snap file in a chosen file encoding.
454
456
  *
@@ -457,7 +459,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
457
459
  * @param encoding - An optional requested file encoding.
458
460
  * @returns The file requested in the chosen file encoding or null if the file is not found.
459
461
  */
460
- getSnapFile(snapId: ValidatedSnapId, path: string, encoding?: AuxiliaryFileEncoding): string | null;
462
+ getSnapFile(snapId: SnapId, path: string, encoding?: AuxiliaryFileEncoding): string | null;
461
463
  /**
462
464
  * Completely clear the controller's state: delete all associated data,
463
465
  * handlers, event listeners, and permissions; tear down all snap providers.
@@ -470,21 +472,21 @@ export declare class SnapController extends BaseController<string, SnapControlle
470
472
  * @param snapId - The id of the Snap.
471
473
  * @returns A promise that resolves once the snap has been removed.
472
474
  */
473
- removeSnap(snapId: ValidatedSnapId): Promise<void>;
475
+ removeSnap(snapId: SnapId): Promise<void>;
474
476
  /**
475
477
  * Stops the given snaps, removes them from state, and clears all associated
476
478
  * permissions, handlers, and listeners.
477
479
  *
478
480
  * @param snapIds - The ids of the Snaps.
479
481
  */
480
- removeSnaps(snapIds: ValidatedSnapId[]): Promise<void>;
482
+ removeSnaps(snapIds: SnapId[]): Promise<void>;
481
483
  /**
482
484
  * Removes a snap's permission (caveat) from the specified subject.
483
485
  *
484
486
  * @param origin - The origin from which to remove the snap.
485
487
  * @param snapId - The id of the snap to remove.
486
488
  */
487
- removeSnapFromSubject(origin: string, snapId: ValidatedSnapId): void;
489
+ removeSnapFromSubject(origin: string, snapId: SnapId): void;
488
490
  /**
489
491
  * Checks if a list of permissions are dynamic and allowed to be revoked, if they are they will all be revoked.
490
492
  *
@@ -498,13 +500,13 @@ export declare class SnapController extends BaseController<string, SnapControlle
498
500
  *
499
501
  * @param snapId - The snap id of the snap that was referenced.
500
502
  */
501
- incrementActiveReferences(snapId: ValidatedSnapId): void;
503
+ incrementActiveReferences(snapId: SnapId): void;
502
504
  /**
503
505
  * Handles decrement the activeReferences counter.
504
506
  *
505
507
  * @param snapId - The snap id of the snap that was referenced..
506
508
  */
507
- decrementActiveReferences(snapId: ValidatedSnapId): void;
509
+ decrementActiveReferences(snapId: SnapId): void;
508
510
  /**
509
511
  * Gets all snaps in their truncated format.
510
512
  *
@@ -517,7 +519,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
517
519
  * @param origin - The origin whose permitted snaps to retrieve.
518
520
  * @returns The serialized permitted snaps for the origin.
519
521
  */
520
- getPermittedSnaps(origin: string): InstallSnapsResult;
522
+ getPermittedSnaps(origin: string): RequestSnapsResult;
521
523
  /**
522
524
  * Installs the snaps requested by the given origin, returning the snap
523
525
  * object if the origin is permitted to install it, and an authorization error
@@ -528,7 +530,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
528
530
  * @returns An object of snap ids and snap objects, or errors if a
529
531
  * snap couldn't be installed.
530
532
  */
531
- installSnaps(origin: string, requestedSnaps: RequestedSnapPermissions): Promise<InstallSnapsResult>;
533
+ installSnaps(origin: string, requestedSnaps: RequestSnapsParams): Promise<RequestSnapsResult>;
532
534
  /**
533
535
  * Adds, authorizes, and runs the given snap with a snap provider.
534
536
  * Results from this method should be efficiently serializable.
@@ -559,7 +561,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
559
561
  * @param emitEvent - An optional boolean flag to indicate whether this update should emit an event.
560
562
  * @returns The snap metadata if updated, `null` otherwise.
561
563
  */
562
- updateSnap(origin: string, snapId: ValidatedSnapId, location: SnapLocation, newVersionRange?: string, emitEvent?: boolean): Promise<TruncatedSnap>;
564
+ updateSnap(origin: string, snapId: SnapId, location: SnapLocation, newVersionRange?: string, emitEvent?: boolean): Promise<TruncatedSnap>;
563
565
  /**
564
566
  * Get metadata for the given snap ID.
565
567
  *
@@ -567,7 +569,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
567
569
  * @returns The metadata for the given snap ID, or `null` if the snap is not
568
570
  * verified.
569
571
  */
570
- getRegistryMetadata(snapId: ValidatedSnapId): Promise<SnapsRegistryMetadata | null>;
572
+ getRegistryMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;
571
573
  /**
572
574
  * Initiates a request for the given snap's initial permissions.
573
575
  * Must be called in order. See processRequestedSnap.
@@ -591,7 +593,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
591
593
  * @returns The result of the JSON-RPC request.
592
594
  */
593
595
  handleRequest({ snapId, origin, handler: handlerType, request: rawRequest, }: SnapRpcHookArgs & {
594
- snapId: ValidatedSnapId;
596
+ snapId: SnapId;
595
597
  }): Promise<unknown>;
596
598
  }
597
599
  export {};
@@ -1,12 +1,12 @@
1
1
  import type { BlockReason, SnapsRegistryDatabase } from '@metamask/snaps-registry';
2
- import type { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';
2
+ import type { SnapId } from '@metamask/snaps-sdk';
3
3
  import type { SemVerRange, SemVerVersion } from '@metamask/utils';
4
4
  export declare type SnapsRegistryInfo = {
5
5
  version: SemVerVersion;
6
6
  checksum: string;
7
7
  };
8
8
  export declare type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;
9
- export declare type SnapsRegistryMetadata = SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];
9
+ export declare type SnapsRegistryMetadata = SnapsRegistryDatabase['verifiedSnaps'][SnapId]['metadata'];
10
10
  export declare enum SnapsRegistryStatus {
11
11
  Unverified = 0,
12
12
  Blocked = 1,
@@ -17,7 +17,7 @@ export declare type SnapsRegistryResult = {
17
17
  reason?: BlockReason;
18
18
  };
19
19
  export declare type SnapsRegistry = {
20
- get(snaps: SnapsRegistryRequest): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;
20
+ get(snaps: SnapsRegistryRequest): Promise<Record<SnapId, SnapsRegistryResult>>;
21
21
  update(): Promise<void>;
22
22
  /**
23
23
  * Find an allowlisted version within a specified version range.