@metamask/snaps-utils 7.7.0 → 7.8.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 +19 -1
- package/dist/auxiliary-files.js +8 -5
- package/dist/auxiliary-files.mjs +9 -6
- package/dist/base64.js +4 -4
- package/dist/base64.mjs +3 -3
- package/dist/bytes.js +3 -3
- package/dist/bytes.mjs +2 -2
- package/dist/checksum.js +4 -4
- package/dist/checksum.mjs +3 -3
- package/dist/{chunk-7LOVOG6X.js → chunk-25ESL4NL.js} +27 -27
- package/dist/{chunk-6YRUDGNL.mjs → chunk-3S4INAGA.mjs} +2 -2
- package/dist/{chunk-I4TRH6VO.mjs → chunk-4AA3TKRJ.mjs} +2 -2
- package/dist/chunk-4AA3TKRJ.mjs.map +1 -0
- package/dist/{chunk-2LBN5T56.js → chunk-4ZJOU3LR.js} +9 -2
- package/dist/chunk-4ZJOU3LR.js.map +1 -0
- package/dist/{chunk-ZJKG5Q2C.js → chunk-5I5WPAVD.js} +20 -20
- package/dist/chunk-5I5WPAVD.js.map +1 -0
- package/dist/chunk-5WKQI22S.js +7 -0
- package/dist/chunk-5WKQI22S.js.map +1 -0
- package/dist/{chunk-J5B5YRG5.js → chunk-6ATNGN44.js} +35 -2
- package/dist/chunk-6ATNGN44.js.map +1 -0
- package/dist/{chunk-G6BVXNNZ.js → chunk-6HXIPMBN.js} +3 -3
- package/dist/{chunk-5ZIWKLVB.mjs → chunk-7HLSXEHK.mjs} +35 -2
- package/dist/chunk-7HLSXEHK.mjs.map +1 -0
- package/dist/{chunk-T6FWIDA6.mjs → chunk-AJNKQYKP.mjs} +3 -3
- package/dist/chunk-AJNKQYKP.mjs.map +1 -0
- package/dist/{chunk-MLOQHUOY.js → chunk-AMW2VJ3N.js} +3 -3
- package/dist/{chunk-K2OTEZZZ.mjs → chunk-ANYNWSCA.mjs} +11 -4
- package/dist/chunk-ANYNWSCA.mjs.map +1 -0
- package/dist/{chunk-R5DO7T2D.js → chunk-B5GNTDE2.js} +2 -2
- package/dist/chunk-B5GNTDE2.js.map +1 -0
- package/dist/{chunk-WZ457PEQ.mjs → chunk-CJK7DDV2.mjs} +2 -2
- package/dist/chunk-CJK7DDV2.mjs.map +1 -0
- package/dist/{chunk-ZJRWU4AJ.mjs → chunk-DE22V5AO.mjs} +4 -1
- package/dist/{chunk-ZJRWU4AJ.mjs.map → chunk-DE22V5AO.mjs.map} +1 -1
- package/dist/{chunk-HJYRGKCX.js → chunk-DEQUNIME.js} +4 -1
- package/dist/chunk-DEQUNIME.js.map +1 -0
- package/dist/chunk-F6G67XQ4.js +1 -0
- package/dist/{chunk-NHGIT2SZ.mjs → chunk-FLSK6ISS.mjs} +6 -6
- package/dist/chunk-FLSK6ISS.mjs.map +1 -0
- package/dist/{chunk-YCIPY3UP.mjs → chunk-H35ZUVQT.mjs} +7 -7
- package/dist/chunk-H35ZUVQT.mjs.map +1 -0
- package/dist/{chunk-IPOE62V4.js → chunk-I2SWLZ34.js} +2 -2
- package/dist/chunk-I2SWLZ34.js.map +1 -0
- package/dist/{chunk-FOWIC2SO.mjs → chunk-JJTIVHFX.mjs} +2 -2
- package/dist/{chunk-NN2HXPZN.mjs → chunk-KCECQM3L.mjs} +11 -11
- package/dist/{chunk-EXUEHPZ4.mjs → chunk-LHQP7CUJ.mjs} +2 -2
- package/dist/chunk-LHQP7CUJ.mjs.map +1 -0
- package/dist/{chunk-6LOYTBS3.js → chunk-LOJA2ZS4.js} +2 -2
- package/dist/chunk-LOJA2ZS4.js.map +1 -0
- package/dist/{chunk-QSCKTRRU.js → chunk-MKFQAXRF.js} +3 -3
- package/dist/{chunk-UMZNVWEM.mjs → chunk-N5HVDE3P.mjs} +2 -2
- package/dist/chunk-N5HVDE3P.mjs.map +1 -0
- package/dist/{chunk-IHQPAJ2B.js → chunk-OBN2WDFU.js} +3 -3
- package/dist/chunk-OYZPBNHS.mjs +1 -0
- package/dist/chunk-PLNIERDY.js +34 -0
- package/dist/chunk-PLNIERDY.js.map +1 -0
- package/dist/{chunk-CMOSYNZR.js → chunk-PZNIU23I.js} +3 -3
- package/dist/chunk-PZNIU23I.js.map +1 -0
- package/dist/{chunk-K4B37F3L.js → chunk-RD6BN2TQ.js} +12 -12
- package/dist/chunk-RD6BN2TQ.js.map +1 -0
- package/dist/{chunk-F72OSQD6.js → chunk-SB43G2RI.js} +8 -8
- package/dist/chunk-SPCIIRSB.mjs +7 -0
- package/dist/chunk-SPCIIRSB.mjs.map +1 -0
- package/dist/{chunk-37VHIRUJ.js → chunk-T2VA4YJE.js} +11 -4
- package/dist/chunk-T2VA4YJE.js.map +1 -0
- package/dist/{chunk-473MIETW.js → chunk-UAINMOUU.js} +3 -3
- package/dist/chunk-VIAHMNTA.mjs +34 -0
- package/dist/chunk-VIAHMNTA.mjs.map +1 -0
- package/dist/{chunk-HEXZ4DFV.js → chunk-VOPTAKVG.js} +4 -4
- package/dist/chunk-VOPTAKVG.js.map +1 -0
- package/dist/{chunk-OJM2SKJZ.js → chunk-X2GGUOMY.js} +2 -2
- package/dist/chunk-X2GGUOMY.js.map +1 -0
- package/dist/{chunk-LBCPJOAV.mjs → chunk-X3UZCGO5.mjs} +2 -2
- package/dist/{chunk-HJRCBSNA.mjs → chunk-XF2AZMWG.mjs} +2 -2
- package/dist/{chunk-VDJTPG6F.js → chunk-XWYJQWHG.js} +3 -3
- package/dist/{chunk-PWLXPALG.mjs → chunk-XZ7362GQ.mjs} +2 -2
- package/dist/{chunk-IGMAXVPP.mjs → chunk-XZNJFDBF.mjs} +2 -2
- package/dist/{chunk-EA2FOAEG.mjs → chunk-YJHQZFR4.mjs} +9 -2
- package/dist/chunk-YJHQZFR4.mjs.map +1 -0
- package/dist/{chunk-BT2AEFEP.mjs → chunk-YNOZU43P.mjs} +6 -6
- package/dist/{chunk-EXEEDJ6N.mjs → chunk-ZXHR322P.mjs} +19 -19
- package/dist/chunk-ZXHR322P.mjs.map +1 -0
- package/dist/constants.js +8 -0
- package/dist/constants.js.map +1 -0
- package/dist/constants.mjs +8 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/cronjob.js +2 -2
- package/dist/cronjob.mjs +1 -1
- package/dist/eval-worker.js +1 -1
- package/dist/eval-worker.mjs +1 -1
- package/dist/eval.js +5 -5
- package/dist/eval.mjs +4 -4
- package/dist/fs.js +4 -4
- package/dist/fs.mjs +3 -3
- package/dist/handlers.js +2 -2
- package/dist/handlers.mjs +1 -1
- package/dist/index.executionenv.js +4 -4
- package/dist/index.executionenv.mjs +15 -15
- package/dist/index.js +37 -29
- package/dist/index.mjs +74 -66
- package/dist/json-rpc.js +2 -2
- package/dist/json-rpc.mjs +1 -1
- package/dist/localization.js +2 -2
- package/dist/localization.mjs +1 -1
- package/dist/manifest/index.js +11 -11
- package/dist/manifest/index.mjs +10 -10
- package/dist/manifest/manifest.js +15 -15
- package/dist/manifest/manifest.mjs +14 -14
- package/dist/manifest/node.js +15 -15
- package/dist/manifest/node.mjs +14 -14
- package/dist/manifest/validation.js +11 -11
- package/dist/manifest/validation.mjs +10 -10
- package/dist/namespace.js +2 -2
- package/dist/namespace.mjs +1 -1
- package/dist/node.js +41 -33
- package/dist/node.mjs +78 -70
- package/dist/npm.js +15 -15
- package/dist/npm.mjs +14 -14
- package/dist/snaps.js +6 -6
- package/dist/snaps.mjs +5 -5
- package/dist/structs.js +2 -2
- package/dist/structs.mjs +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/auxiliary-files.d.ts +7 -0
- package/dist/types/constants.d.ts +1 -0
- package/dist/types/cronjob.d.ts +22 -22
- package/dist/types/handlers.d.ts +39 -39
- package/dist/types/index.d.ts +1 -0
- package/dist/types/json-rpc.d.ts +7 -7
- package/dist/types/localization.d.ts +4 -4
- package/dist/types/manifest/validation.d.ts +1 -1
- package/dist/types/namespace.d.ts +18 -18
- package/dist/types/snaps.d.ts +1 -1
- package/dist/types/structs.d.ts +2 -3
- package/dist/types/types.d.ts +1 -1
- package/dist/types/ui.d.ts +10 -1
- package/dist/types/virtual-file/VirtualFile.d.ts +1 -0
- package/dist/types.js +2 -2
- package/dist/types.mjs +1 -1
- package/dist/ui.js +4 -2
- package/dist/ui.mjs +3 -1
- package/dist/validation.js +13 -13
- package/dist/validation.mjs +12 -12
- package/dist/versions.js +2 -2
- package/dist/versions.mjs +1 -1
- package/dist/virtual-file/VirtualFile.js +2 -2
- package/dist/virtual-file/VirtualFile.mjs +1 -1
- package/dist/virtual-file/index.js +2 -2
- package/dist/virtual-file/index.mjs +1 -1
- package/dist/virtual-file/node.js +3 -3
- package/dist/virtual-file/node.mjs +2 -2
- package/dist/virtual-file/toVirtualFile.js +3 -3
- package/dist/virtual-file/toVirtualFile.mjs +2 -2
- package/package.json +9 -9
- package/dist/chunk-2LBN5T56.js.map +0 -1
- package/dist/chunk-37VHIRUJ.js.map +0 -1
- package/dist/chunk-5ZIWKLVB.mjs.map +0 -1
- package/dist/chunk-6LOYTBS3.js.map +0 -1
- package/dist/chunk-7LOABHVW.js +0 -1
- package/dist/chunk-7MTAHOWC.mjs +0 -1
- package/dist/chunk-CMOSYNZR.js.map +0 -1
- package/dist/chunk-EA2FOAEG.mjs.map +0 -1
- package/dist/chunk-EXEEDJ6N.mjs.map +0 -1
- package/dist/chunk-EXUEHPZ4.mjs.map +0 -1
- package/dist/chunk-HEXZ4DFV.js.map +0 -1
- package/dist/chunk-HJYRGKCX.js.map +0 -1
- package/dist/chunk-I4TRH6VO.mjs.map +0 -1
- package/dist/chunk-IPOE62V4.js.map +0 -1
- package/dist/chunk-IXBJNVHK.js +0 -22
- package/dist/chunk-IXBJNVHK.js.map +0 -1
- package/dist/chunk-J5B5YRG5.js.map +0 -1
- package/dist/chunk-K2OTEZZZ.mjs.map +0 -1
- package/dist/chunk-K4B37F3L.js.map +0 -1
- package/dist/chunk-KMLVVVK3.mjs +0 -22
- package/dist/chunk-KMLVVVK3.mjs.map +0 -1
- package/dist/chunk-NHGIT2SZ.mjs.map +0 -1
- package/dist/chunk-OJM2SKJZ.js.map +0 -1
- package/dist/chunk-R5DO7T2D.js.map +0 -1
- package/dist/chunk-T6FWIDA6.mjs.map +0 -1
- package/dist/chunk-UMZNVWEM.mjs.map +0 -1
- package/dist/chunk-WZ457PEQ.mjs.map +0 -1
- package/dist/chunk-YCIPY3UP.mjs.map +0 -1
- package/dist/chunk-ZJKG5Q2C.js.map +0 -1
- /package/dist/{chunk-7LOVOG6X.js.map → chunk-25ESL4NL.js.map} +0 -0
- /package/dist/{chunk-6YRUDGNL.mjs.map → chunk-3S4INAGA.mjs.map} +0 -0
- /package/dist/{chunk-G6BVXNNZ.js.map → chunk-6HXIPMBN.js.map} +0 -0
- /package/dist/{chunk-MLOQHUOY.js.map → chunk-AMW2VJ3N.js.map} +0 -0
- /package/dist/{chunk-7LOABHVW.js.map → chunk-F6G67XQ4.js.map} +0 -0
- /package/dist/{chunk-FOWIC2SO.mjs.map → chunk-JJTIVHFX.mjs.map} +0 -0
- /package/dist/{chunk-NN2HXPZN.mjs.map → chunk-KCECQM3L.mjs.map} +0 -0
- /package/dist/{chunk-QSCKTRRU.js.map → chunk-MKFQAXRF.js.map} +0 -0
- /package/dist/{chunk-IHQPAJ2B.js.map → chunk-OBN2WDFU.js.map} +0 -0
- /package/dist/{chunk-7MTAHOWC.mjs.map → chunk-OYZPBNHS.mjs.map} +0 -0
- /package/dist/{chunk-F72OSQD6.js.map → chunk-SB43G2RI.js.map} +0 -0
- /package/dist/{chunk-473MIETW.js.map → chunk-UAINMOUU.js.map} +0 -0
- /package/dist/{chunk-LBCPJOAV.mjs.map → chunk-X3UZCGO5.mjs.map} +0 -0
- /package/dist/{chunk-HJRCBSNA.mjs.map → chunk-XF2AZMWG.mjs.map} +0 -0
- /package/dist/{chunk-PWLXPALG.mjs.map → chunk-XWYJQWHG.js.map} +0 -0
- /package/dist/{chunk-VDJTPG6F.js.map → chunk-XZ7362GQ.mjs.map} +0 -0
- /package/dist/{chunk-IGMAXVPP.mjs.map → chunk-XZNJFDBF.mjs.map} +0 -0
- /package/dist/{chunk-BT2AEFEP.mjs.map → chunk-YNOZU43P.mjs.map} +0 -0
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
SnapIdPrefixes,
|
|
3
3
|
uri
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-AJNKQYKP.mjs";
|
|
5
5
|
import {
|
|
6
6
|
checksumFiles
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-XF2AZMWG.mjs";
|
|
8
8
|
|
|
9
9
|
// src/snaps.ts
|
|
10
|
-
import { assert, isObject, assertStruct } from "@metamask/utils";
|
|
11
|
-
import { base64 } from "@scure/base";
|
|
12
|
-
import stableStringify from "fast-json-stable-stringify";
|
|
13
10
|
import {
|
|
14
11
|
empty,
|
|
15
12
|
enums,
|
|
@@ -20,7 +17,10 @@ import {
|
|
|
20
17
|
string,
|
|
21
18
|
union,
|
|
22
19
|
validate
|
|
23
|
-
} from "superstruct";
|
|
20
|
+
} from "@metamask/superstruct";
|
|
21
|
+
import { assert, isObject, assertStruct } from "@metamask/utils";
|
|
22
|
+
import { base64 } from "@scure/base";
|
|
23
|
+
import stableStringify from "fast-json-stable-stringify";
|
|
24
24
|
import validateNPMPackage from "validate-npm-package-name";
|
|
25
25
|
var PROPOSED_NAME_REGEX = /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;
|
|
26
26
|
var SnapStatus = /* @__PURE__ */ ((SnapStatus2) => {
|
|
@@ -190,4 +190,4 @@ export {
|
|
|
190
190
|
isSnapPermitted,
|
|
191
191
|
verifyRequestedSnapPermissions
|
|
192
192
|
};
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
193
|
+
//# sourceMappingURL=chunk-H35ZUVQT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"mappings":"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","names":["SnapStatus","SnapStatusEvents"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/versions.ts
|
|
2
|
+
var _superstruct = require('@metamask/superstruct');
|
|
2
3
|
var _utils = require('@metamask/utils');
|
|
3
4
|
var _semver = require('semver');
|
|
4
|
-
var _superstruct = require('superstruct');
|
|
5
5
|
var DEFAULT_REQUESTED_SNAP_VERSION = "*";
|
|
6
6
|
function getTargetVersion(versions, versionRange) {
|
|
7
7
|
const maxSatisfyingNonPreRelease = _semver.maxSatisfying.call(void 0,
|
|
@@ -27,4 +27,4 @@ function resolveVersionRange(version) {
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
exports.DEFAULT_REQUESTED_SNAP_VERSION = DEFAULT_REQUESTED_SNAP_VERSION; exports.getTargetVersion = getTargetVersion; exports.resolveVersionRange = resolveVersionRange;
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
30
|
+
//# sourceMappingURL=chunk-I2SWLZ34.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/versions.ts"],"names":[],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,2BAA2B;AAE9C,IAAM,iCAAiC;AAYvC,SAAS,iBACd,UACA,cACsB;AACtB,QAAM,6BAA6B;AAAA,IACjC;AAAA,IACA;AAAA,EACF;AAGA,MAAI,4BAA4B;AAC9B,WAAO;AAAA,EACT;AAGA,SAAO,oBAAoB,UAAU,cAAc;AAAA,IACjD,mBAAmB;AAAA,EACrB,CAAC;AACH;AASO,SAAS,oBACd,SAC2E;AAC3E,MAAI,YAAY,UAAa,YAAY,UAAU;AACjD,WAAO,CAAC,QAAW,8BAA8B;AAAA,EACnD;AACA,SAAO,SAAS,SAAS,kBAAkB;AAC7C","sourcesContent":["import { validate } from '@metamask/superstruct';\nimport type { Json, SemVerVersion, SemVerRange } from '@metamask/utils';\nimport { VersionRangeStruct } from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getBytes
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-3S4INAGA.mjs";
|
|
4
4
|
|
|
5
5
|
// src/base64.ts
|
|
6
6
|
import { bytesToBase64 } from "@metamask/utils";
|
|
@@ -35,4 +35,4 @@ export {
|
|
|
35
35
|
encodeBase64,
|
|
36
36
|
decodeBase64
|
|
37
37
|
};
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-JJTIVHFX.mjs.map
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertIsSnapManifest
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ZXHR322P.mjs";
|
|
4
4
|
import {
|
|
5
5
|
ProgrammaticallyFixableSnapError,
|
|
6
6
|
getSnapChecksum,
|
|
7
7
|
validateSnapShasum
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-H35ZUVQT.mjs";
|
|
9
|
+
import {
|
|
10
|
+
getValidatedLocalizationFiles,
|
|
11
|
+
validateSnapManifestLocalizations
|
|
12
|
+
} from "./chunk-CJK7DDV2.mjs";
|
|
9
13
|
import {
|
|
10
14
|
assertIsSnapIcon,
|
|
11
15
|
getSvgDimensions
|
|
@@ -13,20 +17,16 @@ import {
|
|
|
13
17
|
import {
|
|
14
18
|
SnapValidationFailureReason,
|
|
15
19
|
assertIsNpmSnapPackageJson
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
import {
|
|
18
|
-
getValidatedLocalizationFiles,
|
|
19
|
-
validateSnapManifestLocalizations
|
|
20
|
-
} from "./chunk-WZ457PEQ.mjs";
|
|
20
|
+
} from "./chunk-AJNKQYKP.mjs";
|
|
21
21
|
import {
|
|
22
22
|
readJsonFile
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-X3UZCGO5.mjs";
|
|
24
24
|
import {
|
|
25
25
|
readVirtualFile
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-XZNJFDBF.mjs";
|
|
27
27
|
import {
|
|
28
28
|
VirtualFile
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-DE22V5AO.mjs";
|
|
30
30
|
import {
|
|
31
31
|
deepClone
|
|
32
32
|
} from "./chunk-Z2JQNSVL.mjs";
|
|
@@ -406,4 +406,4 @@ export {
|
|
|
406
406
|
getWritableManifest,
|
|
407
407
|
validateNpmSnapManifest
|
|
408
408
|
};
|
|
409
|
-
//# sourceMappingURL=chunk-
|
|
409
|
+
//# sourceMappingURL=chunk-KCECQM3L.mjs.map
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
pattern,
|
|
9
9
|
size,
|
|
10
10
|
string
|
|
11
|
-
} from "superstruct";
|
|
11
|
+
} from "@metamask/superstruct";
|
|
12
12
|
var CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
|
|
13
13
|
var ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
14
14
|
var ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
@@ -104,4 +104,4 @@ export {
|
|
|
104
104
|
isAccountIdArray,
|
|
105
105
|
isNamespace
|
|
106
106
|
};
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-LHQP7CUJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/namespace.ts"],"sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from '@metamask/superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"mappings":";AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIA,IAAM,iBACX;AAEK,IAAM,mBACX;AAEK,IAAM,wBAAwB;AAS9B,SAAS,aAAa,SAG3B;AACA,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,mBAAmB;AAAA,EACrC;AAEA,SAAO;AAAA,IACL,WAAW,MAAM,OAAO;AAAA,IACxB,WAAW,MAAM,OAAO;AAAA,EAC1B;AACF;AASO,SAAS,eAAe,WAI7B;AACA,QAAM,QAAQ,iBAAiB,KAAK,SAAS;AAC7C,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,SAAO;AAAA,IACL,SAAS,MAAM,OAAO;AAAA,IACtB,SAAS,MAAM,OAAO;AAAA,IACtB,OAAO;AAAA,MACL,WAAW,MAAM,OAAO;AAAA,MACxB,WAAW,MAAM,OAAO;AAAA,IAC1B;AAAA,EACF;AACF;AAMO,IAAM,gBAAgB,KAAK,OAAO,GAAG,GAAG,EAAE;AAE1C,IAAM,sBAAsB;AAAA,EACjC;AAAA,EACA,OAAO,EAAE;AACX;AAKO,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AACF;AAIO,IAAM,kBAAkB,QAAQ,OAAO,GAAG,gBAAgB;AAE1D,IAAM,uBAAuB,MAAM,eAAe;AAClD,IAAM,uBAAuB,QAAQ,OAAO,GAAG,qBAAqB;AAMpE,IAAM,cAAc,OAAO;AAAA,EAChC,IAAI;AAAA,EACJ,MAAM;AACR,CAAC;AAGM,IAAM,kBAAkB,OAAO;AAAA;AAAA;AAAA;AAAA,EAIpC,QAAQ,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA,EAKzB,SAAS,SAAS,MAAM,aAAa,CAAC;AAAA;AAAA;AAAA;AAAA,EAKtC,QAAQ,SAAS,MAAM,aAAa,CAAC;AACvC,CAAC;AAMM,IAAM,oBAAoB,QAAQ,OAAO,GAAG,mBAAmB;AAS/D,SAAS,cAAc,OAAsC;AAClE,SAAO,GAAG,OAAO,iBAAiB;AACpC;AAQO,SAAS,UAAU,OAAkC;AAC1D,SAAO,GAAG,OAAO,aAAa;AAChC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC;AAQO,SAAS,iBAAiB,OAAsC;AACrE,SAAO,GAAG,OAAO,oBAAoB;AACvC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC;","names":[]}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
var _superstruct = require('superstruct');
|
|
11
|
+
var _superstruct = require('@metamask/superstruct');
|
|
12
12
|
var CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
|
|
13
13
|
var ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
14
14
|
var ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
@@ -104,4 +104,4 @@ function isNamespace(value) {
|
|
|
104
104
|
|
|
105
105
|
|
|
106
106
|
exports.CHAIN_ID_REGEX = CHAIN_ID_REGEX; exports.ACCOUNT_ID_REGEX = ACCOUNT_ID_REGEX; exports.ACCOUNT_ADDRESS_REGEX = ACCOUNT_ADDRESS_REGEX; exports.parseChainId = parseChainId; exports.parseAccountId = parseAccountId; exports.LimitedString = LimitedString; exports.ChainIdStringStruct = ChainIdStringStruct; exports.ChainIdStruct = ChainIdStruct; exports.AccountIdStruct = AccountIdStruct; exports.AccountIdArrayStruct = AccountIdArrayStruct; exports.AccountAddressStruct = AccountAddressStruct; exports.ChainStruct = ChainStruct; exports.NamespaceStruct = NamespaceStruct; exports.NamespaceIdStruct = NamespaceIdStruct; exports.isNamespaceId = isNamespaceId; exports.isChainId = isChainId; exports.isAccountId = isAccountId; exports.isAccountIdArray = isAccountIdArray; exports.isNamespace = isNamespace;
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-LOJA2ZS4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/namespace.ts"],"names":[],"mappings":";AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIA,IAAM,iBACX;AAEK,IAAM,mBACX;AAEK,IAAM,wBAAwB;AAS9B,SAAS,aAAa,SAG3B;AACA,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,mBAAmB;AAAA,EACrC;AAEA,SAAO;AAAA,IACL,WAAW,MAAM,OAAO;AAAA,IACxB,WAAW,MAAM,OAAO;AAAA,EAC1B;AACF;AASO,SAAS,eAAe,WAI7B;AACA,QAAM,QAAQ,iBAAiB,KAAK,SAAS;AAC7C,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,SAAO;AAAA,IACL,SAAS,MAAM,OAAO;AAAA,IACtB,SAAS,MAAM,OAAO;AAAA,IACtB,OAAO;AAAA,MACL,WAAW,MAAM,OAAO;AAAA,MACxB,WAAW,MAAM,OAAO;AAAA,IAC1B;AAAA,EACF;AACF;AAMO,IAAM,gBAAgB,KAAK,OAAO,GAAG,GAAG,EAAE;AAE1C,IAAM,sBAAsB;AAAA,EACjC;AAAA,EACA,OAAO,EAAE;AACX;AAKO,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AACF;AAIO,IAAM,kBAAkB,QAAQ,OAAO,GAAG,gBAAgB;AAE1D,IAAM,uBAAuB,MAAM,eAAe;AAClD,IAAM,uBAAuB,QAAQ,OAAO,GAAG,qBAAqB;AAMpE,IAAM,cAAc,OAAO;AAAA,EAChC,IAAI;AAAA,EACJ,MAAM;AACR,CAAC;AAGM,IAAM,kBAAkB,OAAO;AAAA;AAAA;AAAA;AAAA,EAIpC,QAAQ,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA,EAKzB,SAAS,SAAS,MAAM,aAAa,CAAC;AAAA;AAAA;AAAA;AAAA,EAKtC,QAAQ,SAAS,MAAM,aAAa,CAAC;AACvC,CAAC;AAMM,IAAM,oBAAoB,QAAQ,OAAO,GAAG,mBAAmB;AAS/D,SAAS,cAAc,OAAsC;AAClE,SAAO,GAAG,OAAO,iBAAiB;AACpC;AAQO,SAAS,UAAU,OAAkC;AAC1D,SAAO,GAAG,OAAO,aAAa;AAChC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC;AAQO,SAAS,iBAAiB,OAAsC;AACrE,SAAO,GAAG,OAAO,oBAAoB;AACvC;AAQO,SAAS,YAAY,OAAoC;AAC9D,SAAO,GAAG,OAAO,eAAe;AAClC","sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from '@metamask/superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkDEQUNIMEjs = require('./chunk-DEQUNIME.js');
|
|
4
4
|
|
|
5
5
|
// src/virtual-file/toVirtualFile.ts
|
|
6
6
|
var _fs = require('fs');
|
|
7
7
|
async function readVirtualFile(path, encoding = null) {
|
|
8
|
-
return new (0,
|
|
8
|
+
return new (0, _chunkDEQUNIMEjs.VirtualFile)({
|
|
9
9
|
path,
|
|
10
10
|
value: await _fs.promises.readFile(path, { encoding })
|
|
11
11
|
});
|
|
@@ -18,4 +18,4 @@ async function writeVirtualFile(vfile, options) {
|
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
exports.readVirtualFile = readVirtualFile; exports.writeVirtualFile = writeVirtualFile;
|
|
21
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
//# sourceMappingURL=chunk-MKFQAXRF.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/versions.ts
|
|
2
|
+
import { validate } from "@metamask/superstruct";
|
|
2
3
|
import { VersionRangeStruct } from "@metamask/utils";
|
|
3
4
|
import { maxSatisfying as maxSatisfyingSemver } from "semver";
|
|
4
|
-
import { validate } from "superstruct";
|
|
5
5
|
var DEFAULT_REQUESTED_SNAP_VERSION = "*";
|
|
6
6
|
function getTargetVersion(versions, versionRange) {
|
|
7
7
|
const maxSatisfyingNonPreRelease = maxSatisfyingSemver(
|
|
@@ -27,4 +27,4 @@ export {
|
|
|
27
27
|
getTargetVersion,
|
|
28
28
|
resolveVersionRange
|
|
29
29
|
};
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
30
|
+
//# sourceMappingURL=chunk-N5HVDE3P.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/versions.ts"],"sourcesContent":["import { validate } from '@metamask/superstruct';\nimport type { Json, SemVerVersion, SemVerRange } from '@metamask/utils';\nimport { VersionRangeStruct } from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,2BAA2B;AAE9C,IAAM,iCAAiC;AAYvC,SAAS,iBACd,UACA,cACsB;AACtB,QAAM,6BAA6B;AAAA,IACjC;AAAA,IACA;AAAA,EACF;AAGA,MAAI,4BAA4B;AAC9B,WAAO;AAAA,EACT;AAGA,SAAO,oBAAoB,UAAU,cAAc;AAAA,IACjD,mBAAmB;AAAA,EACrB,CAAC;AACH;AASO,SAAS,oBACd,SAC2E;AAC3E,MAAI,YAAY,UAAa,YAAY,UAAU;AACjD,WAAO,CAAC,QAAW,8BAA8B;AAAA,EACnD;AACA,SAAO,SAAS,SAAS,kBAAkB;AAC7C;","names":[]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkUAINMOUUjs = require('./chunk-UAINMOUU.js');
|
|
4
4
|
|
|
5
5
|
// src/base64.ts
|
|
6
6
|
var _utils = require('@metamask/utils');
|
|
7
7
|
async function encodeBase64(input) {
|
|
8
|
-
const bytes =
|
|
8
|
+
const bytes = _chunkUAINMOUUjs.getBytes.call(void 0, input);
|
|
9
9
|
if ("FileReader" in globalThis) {
|
|
10
10
|
return await new Promise((resolve, reject) => {
|
|
11
11
|
const reader = Object.assign(new FileReader(), {
|
|
@@ -35,4 +35,4 @@ async function decodeBase64(base64) {
|
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
exports.encodeBase64 = encodeBase64; exports.decodeBase64 = decodeBase64;
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-OBN2WDFU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-OYZPBNHS.mjs.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunkOBN2WDFUjs = require('./chunk-OBN2WDFU.js');
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
var _chunk5WKQI22Sjs = require('./chunk-5WKQI22S.js');
|
|
7
|
+
|
|
8
|
+
// src/auxiliary-files.ts
|
|
9
|
+
var _snapssdk = require('@metamask/snaps-sdk');
|
|
10
|
+
var _utils = require('@metamask/utils');
|
|
11
|
+
async function encodeAuxiliaryFile(value, encoding) {
|
|
12
|
+
if (encoding === _snapssdk.AuxiliaryFileEncoding.Base64) {
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
const decoded = await _chunkOBN2WDFUjs.decodeBase64.call(void 0, value);
|
|
16
|
+
if (encoding === _snapssdk.AuxiliaryFileEncoding.Utf8) {
|
|
17
|
+
return _utils.bytesToString.call(void 0, decoded);
|
|
18
|
+
}
|
|
19
|
+
return _utils.bytesToHex.call(void 0, decoded);
|
|
20
|
+
}
|
|
21
|
+
function validateAuxiliaryFiles(files) {
|
|
22
|
+
for (const file of files) {
|
|
23
|
+
_utils.assert.call(void 0,
|
|
24
|
+
file.size < _chunk5WKQI22Sjs.MAX_FILE_SIZE,
|
|
25
|
+
"Static files required by the Snap must be smaller than 64 MB."
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
exports.encodeAuxiliaryFile = encodeAuxiliaryFile; exports.validateAuxiliaryFiles = validateAuxiliaryFiles;
|
|
34
|
+
//# sourceMappingURL=chunk-PLNIERDY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auxiliary-files.ts"],"names":[],"mappings":";;;;;;;;AAAA,SAAS,6BAA6B;AACtC,SAAS,QAAQ,YAAY,qBAAqB;AAalD,eAAsB,oBACpB,OACA,UACA;AAEA,MAAI,aAAa,sBAAsB,QAAQ;AAC7C,WAAO;AAAA,EACT;AAGA,QAAM,UAAU,MAAM,aAAa,KAAK;AACxC,MAAI,aAAa,sBAAsB,MAAM;AAC3C,WAAO,cAAc,OAAO;AAAA,EAC9B;AAEA,SAAO,WAAW,OAAO;AAC3B;AAOO,SAAS,uBAAuB,OAAsB;AAC3D,aAAW,QAAQ,OAAO;AACxB;AAAA,MACE,KAAK,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { assert, bytesToHex, bytesToString } from '@metamask/utils';\n\nimport { decodeBase64 } from './base64';\nimport { MAX_FILE_SIZE } from './constants';\nimport type { VirtualFile } from './virtual-file';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport async function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = await decodeBase64(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n\n/**\n * Validate that auxiliary files used by the Snap are within size limits.\n *\n * @param files - A list of auxiliary files.\n */\nexport function validateAuxiliaryFiles(files: VirtualFile[]) {\n for (const file of files) {\n assert(\n file.size < MAX_FILE_SIZE,\n 'Static files required by the Snap must be smaller than 64 MB.',\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/types.ts
|
|
2
|
-
var _utils = require('@metamask/utils');
|
|
3
2
|
|
|
4
3
|
|
|
5
4
|
|
|
@@ -12,7 +11,8 @@ var _utils = require('@metamask/utils');
|
|
|
12
11
|
|
|
13
12
|
|
|
14
13
|
|
|
15
|
-
var _superstruct = require('superstruct');
|
|
14
|
+
var _superstruct = require('@metamask/superstruct');
|
|
15
|
+
var _utils = require('@metamask/utils');
|
|
16
16
|
var NpmSnapFileNames = /* @__PURE__ */ ((NpmSnapFileNames2) => {
|
|
17
17
|
NpmSnapFileNames2["PackageJson"] = "package.json";
|
|
18
18
|
NpmSnapFileNames2["Manifest"] = "snap.manifest.json";
|
|
@@ -92,4 +92,4 @@ var WALLET_SNAP_PERMISSION_KEY = "wallet_snap";
|
|
|
92
92
|
|
|
93
93
|
|
|
94
94
|
exports.NpmSnapFileNames = NpmSnapFileNames; exports.NameStruct = NameStruct; exports.NpmSnapPackageJsonStruct = NpmSnapPackageJsonStruct; exports.isNpmSnapPackageJson = isNpmSnapPackageJson; exports.assertIsNpmSnapPackageJson = assertIsNpmSnapPackageJson; exports.SnapIdPrefixes = SnapIdPrefixes; exports.SnapValidationFailureReason = SnapValidationFailureReason; exports.SNAP_STREAM_NAMES = SNAP_STREAM_NAMES; exports.uri = uri; exports.isValidUrl = isValidUrl; exports.WALLET_SNAP_PERMISSION_KEY = WALLET_SNAP_PERMISSION_KEY;
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
95
|
+
//# sourceMappingURL=chunk-PZNIU23I.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":["NpmSnapFileNames","SnapIdPrefixes","SnapValidationFailureReason","SNAP_STREAM_NAMES"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,OACL;AAEP,SAAS,cAAc,qBAAqB;AAQrC,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,iBAAc;AACd,EAAAA,kBAAA,cAAW;AAFD,SAAAA;AAAA,GAAA;AAKL,IAAM,aAAa;AAAA,EACxB;AAAA,IACE,OAAO;AAAA,IACP;AAAA,EACF;AAAA,EACA;AAAA,EACA;AACF;AAIO,IAAM,2BAA2B,KAAK;AAAA,EAC3C,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM,SAAS,KAAK,OAAO,GAAG,GAAG,QAAQ,CAAC;AAAA,EAC1C,YAAY;AAAA,IACV,OAAO;AAAA,MACL,MAAM,KAAK,OAAO,GAAG,GAAG,QAAQ;AAAA,MAChC,KAAK,KAAK,OAAO,GAAG,GAAG,QAAQ;AAAA,IACjC,CAAC;AAAA,EACH;AACF,CAAC;AAWM,SAAS,qBACd,OAC6B;AAC7B,SAAO,GAAG,OAAO,wBAAwB;AAC3C;AAQO,SAAS,2BACd,OACqC;AACrC;AAAA,IACE;AAAA,IACA;AAAA,IACA,IAAI,gCAA4B;AAAA,EAClC;AACF;AAuCO,IAAK,iBAAL,kBAAKC,oBAAL;AACL,EAAAA,gBAAA,SAAM;AACN,EAAAA,gBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAUL,IAAK,8BAAL,kBAAKC,iCAAL;AACL,EAAAA,6BAAA,kBAAe;AACf,EAAAA,6BAAA,qBAAkB;AAClB,EAAAA,6BAAA,wBAAqB;AACrB,EAAAA,6BAAA,oBAAiB;AAJP,SAAAA;AAAA,GAAA;AAQL,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAwBL,IAAM,MAAM,CAAC,OAAwB,CAAC,MAC3C,OAAO,MAAM,CAAC,OAAO,GAAG,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU;AACzD,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AAEzB,UAAM,YAAY,KAAK,IAAI;AAC3B,sBAAkB,KAAK,SAAS;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,sBAAsB,MAAM,SAAS,CAAC;AAAA,EAC/C;AACF,CAAC;AASI,SAAS,WACd,KACA,OAAwB,CAAC,GACJ;AACrB,SAAO,GAAG,KAAK,IAAI,IAAI,CAAC;AAC1B;AAGO,IAAM,6BAA6B","sourcesContent":["import type { Infer, Struct } from '@metamask/superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"]}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkPZNIU23Ijs = require('./chunk-PZNIU23I.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
var
|
|
7
|
+
var _chunkAMW2VJ3Njs = require('./chunk-AMW2VJ3N.js');
|
|
8
8
|
|
|
9
9
|
// src/snaps.ts
|
|
10
|
-
var _utils = require('@metamask/utils');
|
|
11
|
-
var _base = require('@scure/base');
|
|
12
|
-
var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastjsonstablestringify2 = _interopRequireDefault(_fastjsonstablestringify);
|
|
13
10
|
|
|
14
11
|
|
|
15
12
|
|
|
@@ -20,7 +17,10 @@ var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastj
|
|
|
20
17
|
|
|
21
18
|
|
|
22
19
|
|
|
23
|
-
var _superstruct = require('superstruct');
|
|
20
|
+
var _superstruct = require('@metamask/superstruct');
|
|
21
|
+
var _utils = require('@metamask/utils');
|
|
22
|
+
var _base = require('@scure/base');
|
|
23
|
+
var _fastjsonstablestringify = require('fast-json-stable-stringify'); var _fastjsonstablestringify2 = _interopRequireDefault(_fastjsonstablestringify);
|
|
24
24
|
var _validatenpmpackagename = require('validate-npm-package-name'); var _validatenpmpackagename2 = _interopRequireDefault(_validatenpmpackagename);
|
|
25
25
|
var PROPOSED_NAME_REGEX = /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;
|
|
26
26
|
var SnapStatus = /* @__PURE__ */ ((SnapStatus2) => {
|
|
@@ -59,7 +59,7 @@ async function getSnapChecksum(files) {
|
|
|
59
59
|
...auxiliaryFiles,
|
|
60
60
|
...localizationFiles
|
|
61
61
|
].filter((file) => file !== void 0);
|
|
62
|
-
return _base.base64.encode(await
|
|
62
|
+
return _base.base64.encode(await _chunkAMW2VJ3Njs.checksumFiles.call(void 0, all));
|
|
63
63
|
}
|
|
64
64
|
async function validateSnapShasum(files, errorMessage = "Invalid Snap manifest: manifest shasum does not match computed shasum.") {
|
|
65
65
|
if (files.manifest.result.source.shasum !== await getSnapChecksum(files)) {
|
|
@@ -71,7 +71,7 @@ async function validateSnapShasum(files, errorMessage = "Invalid Snap manifest:
|
|
|
71
71
|
}
|
|
72
72
|
var LOCALHOST_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
|
|
73
73
|
var BaseSnapIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^[\x21-\x7E]*$/u);
|
|
74
|
-
var LocalSnapIdSubUrlStruct =
|
|
74
|
+
var LocalSnapIdSubUrlStruct = _chunkPZNIU23Ijs.uri.call(void 0, {
|
|
75
75
|
protocol: _superstruct.enums.call(void 0, ["http:", "https:"]),
|
|
76
76
|
hostname: _superstruct.enums.call(void 0, LOCALHOST_HOSTNAMES),
|
|
77
77
|
hash: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, )),
|
|
@@ -93,7 +93,7 @@ var LocalSnapIdStruct = _superstruct.refine.call(void 0,
|
|
|
93
93
|
);
|
|
94
94
|
var NpmSnapIdStruct = _superstruct.intersection.call(void 0, [
|
|
95
95
|
BaseSnapIdStruct,
|
|
96
|
-
|
|
96
|
+
_chunkPZNIU23Ijs.uri.call(void 0, {
|
|
97
97
|
protocol: _superstruct.literal.call(void 0, "npm:" /* npm */),
|
|
98
98
|
pathname: _superstruct.refine.call(void 0, _superstruct.string.call(void 0, ), "package name", function* (value) {
|
|
99
99
|
const normalized = value.startsWith("/") ? value.slice(1) : value;
|
|
@@ -114,7 +114,7 @@ var NpmSnapIdStruct = _superstruct.intersection.call(void 0, [
|
|
|
114
114
|
]);
|
|
115
115
|
var HttpSnapIdStruct = _superstruct.intersection.call(void 0, [
|
|
116
116
|
BaseSnapIdStruct,
|
|
117
|
-
|
|
117
|
+
_chunkPZNIU23Ijs.uri.call(void 0, {
|
|
118
118
|
protocol: _superstruct.enums.call(void 0, ["http:", "https:"]),
|
|
119
119
|
search: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, )),
|
|
120
120
|
hash: _superstruct.empty.call(void 0, _superstruct.string.call(void 0, ))
|
|
@@ -122,7 +122,7 @@ var HttpSnapIdStruct = _superstruct.intersection.call(void 0, [
|
|
|
122
122
|
]);
|
|
123
123
|
var SnapIdStruct = _superstruct.union.call(void 0, [NpmSnapIdStruct, LocalSnapIdStruct]);
|
|
124
124
|
function getSnapPrefix(snapId) {
|
|
125
|
-
const prefix = Object.values(
|
|
125
|
+
const prefix = Object.values(_chunkPZNIU23Ijs.SnapIdPrefixes).find(
|
|
126
126
|
(possiblePrefix) => snapId.startsWith(possiblePrefix)
|
|
127
127
|
);
|
|
128
128
|
if (prefix !== void 0) {
|
|
@@ -190,4 +190,4 @@ function verifyRequestedSnapPermissions(requestedPermissions) {
|
|
|
190
190
|
|
|
191
191
|
|
|
192
192
|
exports.PROPOSED_NAME_REGEX = PROPOSED_NAME_REGEX; exports.SnapStatus = SnapStatus; exports.SnapStatusEvents = SnapStatusEvents; exports.ProgrammaticallyFixableSnapError = ProgrammaticallyFixableSnapError; exports.getSnapChecksum = getSnapChecksum; exports.validateSnapShasum = validateSnapShasum; exports.LOCALHOST_HOSTNAMES = LOCALHOST_HOSTNAMES; exports.BaseSnapIdStruct = BaseSnapIdStruct; exports.LocalSnapIdStruct = LocalSnapIdStruct; exports.NpmSnapIdStruct = NpmSnapIdStruct; exports.HttpSnapIdStruct = HttpSnapIdStruct; exports.SnapIdStruct = SnapIdStruct; exports.getSnapPrefix = getSnapPrefix; exports.stripSnapPrefix = stripSnapPrefix; exports.assertIsValidSnapId = assertIsValidSnapId; exports.isCaipChainId = isCaipChainId; exports.isSnapPermitted = isSnapPermitted; exports.verifyRequestedSnapPermissions = verifyRequestedSnapPermissions;
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
193
|
+
//# sourceMappingURL=chunk-RD6BN2TQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/snaps.ts"],"names":["SnapStatus","SnapStatusEvents"],"mappings":"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","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunk5I5WPAVDjs = require('./chunk-5I5WPAVD.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkRD6BN2TQjs = require('./chunk-RD6BN2TQ.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunkB5GNTDE2js = require('./chunk-B5GNTDE2.js');
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
var
|
|
12
|
+
var _chunkW7KRIAIXjs = require('./chunk-W7KRIAIX.js');
|
|
13
13
|
|
|
14
14
|
// src/validation.ts
|
|
15
15
|
async function validateFetchedSnap(files) {
|
|
16
|
-
|
|
17
|
-
await
|
|
18
|
-
|
|
16
|
+
_chunk5I5WPAVDjs.assertIsSnapManifest.call(void 0, files.manifest.result);
|
|
17
|
+
await _chunkRD6BN2TQjs.validateSnapShasum.call(void 0, files);
|
|
18
|
+
_chunkB5GNTDE2js.validateSnapManifestLocalizations.call(void 0,
|
|
19
19
|
files.manifest.result,
|
|
20
20
|
files.localizationFiles.map((file) => file.result)
|
|
21
21
|
);
|
|
@@ -27,4 +27,4 @@ async function validateFetchedSnap(files) {
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
exports.validateFetchedSnap = validateFetchedSnap;
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
30
|
+
//# sourceMappingURL=chunk-SB43G2RI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts"],"sourcesContent":["// The max file size for Snap source code and auxiliary files.\n// 64 MB - we chose this number because it is the size limit for postMessage\n// between the extension and the offscreen document enforced by Chrome.\nexport const MAX_FILE_SIZE = 64_000_000;\n"],"mappings":";AAGO,IAAM,gBAAgB;","names":[]}
|
|
@@ -4,8 +4,15 @@ var _permissioncontroller = require('@metamask/permission-controller');
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
var _superstruct = require('@metamask/superstruct');
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
7
15
|
var _utils = require('@metamask/utils');
|
|
8
|
-
var _superstruct = require('superstruct');
|
|
9
16
|
var AllowedOriginsStruct = _superstruct.array.call(void 0,
|
|
10
17
|
_superstruct.refine.call(void 0, _superstruct.string.call(void 0, ), "Allowed origin", (value) => {
|
|
11
18
|
const wildcards = value.split("*").length - 1;
|
|
@@ -53,8 +60,8 @@ function assertIsKeyringOrigins(value, ErrorWrapper) {
|
|
|
53
60
|
}
|
|
54
61
|
function createOriginRegExp(matcher) {
|
|
55
62
|
const escaped = matcher.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
56
|
-
const regex = escaped.replace(
|
|
57
|
-
return RegExp(regex
|
|
63
|
+
const regex = escaped.replace(/\\\*/gu, ".*");
|
|
64
|
+
return RegExp(`${regex}$`, "u");
|
|
58
65
|
}
|
|
59
66
|
function checkAllowedOrigin(matcher, origin) {
|
|
60
67
|
if (matcher === "*" || matcher === origin) {
|
|
@@ -94,4 +101,4 @@ function assertIsJsonRpcSuccess(value) {
|
|
|
94
101
|
|
|
95
102
|
|
|
96
103
|
exports.RpcOriginsStruct = RpcOriginsStruct; exports.assertIsRpcOrigins = assertIsRpcOrigins; exports.KeyringOriginsStruct = KeyringOriginsStruct; exports.assertIsKeyringOrigins = assertIsKeyringOrigins; exports.isOriginAllowed = isOriginAllowed; exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
104
|
+
//# sourceMappingURL=chunk-T2VA4YJE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/json-rpc.ts"],"names":[],"mappings":";AAAA,SAAS,mBAAmB;AAE5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,IAAM,uBAAuB;AAAA,EAC3B,OAAO,OAAO,GAAG,kBAAkB,CAAC,UAAU;AAC5C,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,SAAS;AAC5C,QAAI,YAAY,GAAG;AACjB,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC;AACH;AAEO,IAAM,mBAAmB;AAAA,EAC9B,OAAO;AAAA,IACL,OAAO,SAAS,QAAQ,CAAC;AAAA,IACzB,OAAO,SAAS,QAAQ,CAAC;AAAA,IACzB,gBAAgB,SAAS,oBAAoB;AAAA,EAC/C,CAAC;AAAA,EACD;AAAA,EACA,CAAC,UAAU;AACT,UAAM,aAAa;AAAA,MACjB,MAAM,UAAU,QACd,MAAM,UAAU,QACf,MAAM,kBAAkB,MAAM,eAAe,SAAS;AAAA,IAC3D;AAEA,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AACF;AAYO,SAAS,mBACd,OAEA,cAC6B;AAC7B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB,OAAO;AAAA,EACzC,gBAAgB,SAAS,oBAAoB;AAC/C,CAAC;AAYM,SAAS,uBACd,OAEA,cACiC;AACjC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAUA,SAAS,mBAAmB,SAAiB;AAE3C,QAAM,UAAU,QAAQ,QAAQ,wBAAwB,MAAM;AAE9D,QAAM,QAAQ,QAAQ,QAAQ,UAAU,IAAI;AAC5C,SAAO,OAAO,GAAG,KAAK,KAAK,GAAG;AAChC;AAcA,SAAS,mBAAmB,SAAiB,QAAgB;AAE3D,MAAI,YAAY,OAAO,YAAY,QAAQ;AACzC,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,mBAAmB,OAAO;AACxC,SAAO,MAAM,KAAK,MAAM;AAC1B;AAUO,SAAS,gBACd,SACA,aACA,QACA;AAEA,MAAI,WAAW,YAAY;AACzB,WAAO;AAAA,EACT;AAGA,MACE,QAAQ,gBAAgB;AAAA,IAAK,CAAC,YAC5B,mBAAmB,SAAS,MAAM;AAAA,EACpC,GACA;AACA,WAAO;AAAA,EACT;AAGA,MAAI,gBAAgB,YAAY,WAAW,QAAQ,OAAO;AACxD,WAAO;AAAA,EACT;AAGA,SAAO,QAAQ,gBAAgB,YAAY,QAAQ,QAAQ,KAAK;AAClE;AAUO,SAAS,uBACd,OACuC;AACvC,MAAI,CAAC,iBAAiB,KAAK,GAAG;AAC5B,QAAI,iBAAiB,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,4BAA4B,MAAM,MAAM,OAAO,EAAE;AAAA,IACnE;AAEA,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACF","sourcesContent":["import { SubjectType } from '@metamask/permission-controller';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n object,\n optional,\n refine,\n string,\n} from '@metamask/superstruct';\nimport type {\n AssertionErrorConstructor,\n Json,\n JsonRpcSuccess,\n} from '@metamask/utils';\nimport {\n assertStruct,\n isJsonRpcFailure,\n isJsonRpcSuccess,\n} from '@metamask/utils';\n\nconst AllowedOriginsStruct = array(\n refine(string(), 'Allowed origin', (value) => {\n const wildcards = value.split('*').length - 1;\n if (wildcards > 2) {\n return 'No more than two wildcards (\"*\") are allowed in an origin specifier.';\n }\n\n return true;\n }),\n);\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n allowedOrigins: optional(AllowedOriginsStruct),\n }),\n 'RPC origins',\n (value) => {\n const hasOrigins = Boolean(\n value.snaps === true ||\n value.dapps === true ||\n (value.allowedOrigins && value.allowedOrigins.length > 0),\n );\n\n if (hasOrigins) {\n return true;\n }\n\n return 'Must specify at least one JSON-RPC origin.';\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\nexport const KeyringOriginsStruct = object({\n allowedOrigins: optional(AllowedOriginsStruct),\n});\n\nexport type KeyringOrigins = Infer<typeof KeyringOriginsStruct>;\n\n/**\n * Assert that the given value is a valid {@link KeyringOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link KeyringOrigins} object.\n */\nexport function assertIsKeyringOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is KeyringOrigins {\n assertStruct(\n value,\n KeyringOriginsStruct,\n 'Invalid keyring origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Create regular expression for matching against an origin while allowing wildcards.\n *\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n *\n * @param matcher - The string to create the regular expression with.\n * @returns The regular expression.\n */\nfunction createOriginRegExp(matcher: string) {\n // Escape potential Regex characters\n const escaped = matcher.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n // Support wildcards\n const regex = escaped.replace(/\\\\\\*/gu, '.*');\n return RegExp(`${regex}$`, 'u');\n}\n\n/**\n * Check whether an origin is allowed or not using a matcher string.\n *\n * The matcher string may be a specific origin to match or include wildcards.\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n * Note: this means that https://*metamask.io matches both https://metamask.io\n * and https://snaps.metamask.io.\n *\n * @param matcher - The matcher string.\n * @param origin - The origin.\n * @returns Whether the origin is allowed.\n */\nfunction checkAllowedOrigin(matcher: string, origin: string) {\n // If the matcher is a single wildcard or identical to the origin we can return true immediately.\n if (matcher === '*' || matcher === origin) {\n return true;\n }\n\n const regex = createOriginRegExp(matcher);\n return regex.test(origin);\n}\n\n/**\n * Check if the given origin is allowed by the given JSON-RPC origins object.\n *\n * @param origins - The JSON-RPC origins object.\n * @param subjectType - The type of the origin.\n * @param origin - The origin to check.\n * @returns Whether the origin is allowed.\n */\nexport function isOriginAllowed(\n origins: RpcOrigins,\n subjectType: SubjectType,\n origin: string,\n) {\n // The MetaMask client is always allowed.\n if (origin === 'metamask') {\n return true;\n }\n\n // If the origin is in the `allowedOrigins` list, it is allowed.\n if (\n origins.allowedOrigins?.some((matcher) =>\n checkAllowedOrigin(matcher, origin),\n )\n ) {\n return true;\n }\n\n // If the origin is a website and `dapps` is true, it is allowed.\n if (subjectType === SubjectType.Website && origins.dapps) {\n return true;\n }\n\n // If the origin is a snap and `snaps` is true, it is allowed.\n return Boolean(subjectType === SubjectType.Snap && origins.snaps);\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"]}
|