@metamask/snaps-utils 11.3.0 → 11.4.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 +18 -1
- package/dist/manifest/manifest.cjs +9 -6
- package/dist/manifest/manifest.cjs.map +1 -1
- package/dist/manifest/manifest.d.cts +10 -2
- package/dist/manifest/manifest.d.cts.map +1 -1
- package/dist/manifest/manifest.d.mts +10 -2
- package/dist/manifest/manifest.d.mts.map +1 -1
- package/dist/manifest/manifest.mjs +10 -7
- package/dist/manifest/manifest.mjs.map +1 -1
- package/dist/manifest/validation.cjs +8 -4
- package/dist/manifest/validation.cjs.map +1 -1
- package/dist/manifest/validation.d.cts +4 -0
- package/dist/manifest/validation.d.cts.map +1 -1
- package/dist/manifest/validation.d.mts +4 -0
- package/dist/manifest/validation.d.mts.map +1 -1
- package/dist/manifest/validation.mjs +7 -3
- package/dist/manifest/validation.mjs.map +1 -1
- package/dist/manifest/validator.cjs +15 -3
- package/dist/manifest/validator.cjs.map +1 -1
- package/dist/manifest/validator.d.cts +10 -1
- package/dist/manifest/validator.d.cts.map +1 -1
- package/dist/manifest/validator.d.mts +10 -1
- package/dist/manifest/validator.d.mts.map +1 -1
- package/dist/manifest/validator.mjs +13 -2
- package/dist/manifest/validator.mjs.map +1 -1
- package/dist/snaps.cjs.map +1 -1
- package/dist/snaps.d.cts +6 -2
- package/dist/snaps.d.cts.map +1 -1
- package/dist/snaps.d.mts +6 -2
- package/dist/snaps.d.mts.map +1 -1
- package/dist/snaps.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -56,6 +56,10 @@ export type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;
|
|
|
56
56
|
export declare const EmptyObjectStruct: Struct<EmptyObject, null>;
|
|
57
57
|
export declare const PermissionsStruct: Describe<InitialPermissions>;
|
|
58
58
|
export type SnapPermissions = InferMatching<typeof PermissionsStruct, InitialPermissions>;
|
|
59
|
+
export declare const SnapAuxiliaryFilesStruct: Struct<string[], Struct<string, null>>;
|
|
60
|
+
/**
|
|
61
|
+
* @deprecated Use SnapAuxiliaryFilesStruct instead. This was a typo that has been fixed.
|
|
62
|
+
*/
|
|
59
63
|
export declare const SnapAuxilaryFilesStruct: Struct<string[], Struct<string, null>>;
|
|
60
64
|
export declare const InitialConnectionsStruct: Struct<Record<string, {}>, null>;
|
|
61
65
|
export type InitialConnections = Infer<typeof InitialConnectionsStruct>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/manifest/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,2BAA2B;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,4BAA4B;AAC3E,OAAO,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAkCrE,OAAO,EAAgB,KAAK,aAAa,EAAE,uBAAmB;AAU9D,eAAO,MAAM,oBAAoB,EAAE,MAAM,EAAS,CAAC;AAOnD,eAAO,MAAM,eAAe,wCAoC3B,CAAC;AAEF,eAAO,MAAM,YAAY;UACF,MAAM,EAAE;WAAS,MAAM;gEAc1C,CAAC;AAEL,eAAO,MAAM,WAAW,EAAE,QAAQ,CAAC,cAAc,CAI/C,CAAC;AAGH,eAAO,MAAM,kBAAkB;;;;;;EAK9B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAE5D,eAAO,MAAM,oCAAoC;;;;;;;;;GAIhD,CAAC;AAEF,eAAO,MAAM,iBAAiB,sBAK5B,CAAC;AAEH,eAAO,MAAM,aAAa;;SAUzB,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAElD,eAAO,MAAM,cAAc,sEAA8C,CAAC;AAE1E,eAAO,MAAM,oBAAoB;;;;;;;QAW/B,CAAC;AAEH,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AO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,KAAK,IAAI,YAAY,CAM/B;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CAG/D"}
|
|
@@ -126,7 +126,11 @@ export const PermissionsStruct = type({
|
|
|
126
126
|
snap_getLocale: optional(EmptyObjectStruct),
|
|
127
127
|
wallet_snap: optional(SnapIdsStruct),
|
|
128
128
|
});
|
|
129
|
-
export const
|
|
129
|
+
export const SnapAuxiliaryFilesStruct = array(string());
|
|
130
|
+
/**
|
|
131
|
+
* @deprecated Use SnapAuxiliaryFilesStruct instead. This was a typo that has been fixed.
|
|
132
|
+
*/
|
|
133
|
+
export const SnapAuxilaryFilesStruct = SnapAuxiliaryFilesStruct;
|
|
130
134
|
export const InitialConnectionsStruct = record(intersection([string(), uri()]), object({}));
|
|
131
135
|
export const SnapManifestStruct = object({
|
|
132
136
|
version: VersionStruct,
|
|
@@ -149,8 +153,8 @@ export const SnapManifestStruct = object({
|
|
|
149
153
|
]),
|
|
150
154
|
}),
|
|
151
155
|
}),
|
|
152
|
-
files: optional(
|
|
153
|
-
locales: optional(
|
|
156
|
+
files: optional(SnapAuxiliaryFilesStruct),
|
|
157
|
+
locales: optional(SnapAuxiliaryFilesStruct),
|
|
154
158
|
}),
|
|
155
159
|
initialConnections: optional(InitialConnectionsStruct),
|
|
156
160
|
initialPermissions: PermissionsStruct,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/manifest/validation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,2BAA2B;AAG7D,OAAO,EACL,KAAK,EACL,OAAO,EACP,MAAM,EACN,KAAK,EACL,OAAO,EACP,EAAE,EACF,OAAO,EACP,MAAM,EACN,QAAQ,EACR,MAAM,EACN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EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;gBAC/C,WAAW,EAAE,UAAU;gBACvB,QAAQ,EAAE,KAAK,CAAC;oBACd,OAAO,CAAC,4BAA4B,CAAC;oBACrC,OAAO,CAAC,6BAA6B,CAAC;iBACvC,CAAC;aACH,CAAC;SACH,CAAC;QACF,KAAK,EAAE,QAAQ,CAAC,uBAAuB,CAAC;QACxC,OAAO,EAAE,QAAQ,CAAC,uBAAuB,CAAC;KAC3C,CAAC;IACF,kBAAkB,EAAE,QAAQ,CAAC,wBAAwB,CAAC;IACtD,kBAAkB,EAAE,iBAAiB;IACrC,eAAe,EAAE,OAAO,CAAC,KAAK,CAAC;IAC/B,eAAe,EAAE,QAAQ,CAAC,aAAa,CAAC;IACxC,OAAO,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,oDAAoD;CAClF,CAAC,CAAC;AAIH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,EAAE,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AACvC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAc;IAEd,YAAY,CACV,KAAK,EACL,kBAAkB,EAClB,IAAI,gBAAgB,CAAC,QAAQ,cAAc,CAC5C,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,qEAAqE;IACrE,OAAO,MAAM,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { EmptyObject, InitialPermissions } from '@metamask/snaps-sdk';\nimport type { Describe, Infer, Struct } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n} from '@metamask/superstruct';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n CaipChainIdStruct,\n} from '@metamask/utils';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { mergeStructs, type InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\nexport const CurveStruct: Describe<SupportedCurve> = enums([\n 'ed25519',\n 'secp256k1',\n 'ed25519Bip32',\n]);\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: CurveStruct,\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = size(array(CaipChainIdStruct), 1, Infinity);\n\nexport const LookupMatchersStruct = union([\n object({\n tlds: size(array(string()), 1, Infinity),\n }),\n object({\n schemes: size(array(string()), 1, Infinity),\n }),\n object({\n tlds: size(array(string()), 1, Infinity),\n schemes: size(array(string()), 1, Infinity),\n }),\n]);\n\nexport const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);\nexport const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);\n\nexport const MaxRequestTimeStruct = size(\n integer(),\n MINIMUM_REQUEST_TIMEOUT,\n MAXIMUM_REQUEST_TIMEOUT,\n);\n\nexport const ProtocolScopesStruct = record(\n CaipChainIdStruct,\n object({ methods: array(string()) }),\n);\n\n// Utility type to union with for all handler structs\nexport const HandlerCaveatsStruct = object({\n maxRequestTime: optional(MaxRequestTimeStruct),\n});\n\nexport type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;\n\nexport const EmptyObjectStruct = object<EmptyObject>({}) as unknown as Struct<\n EmptyObject,\n null\n>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct: Describe<InitialPermissions> = type({\n 'endowment:assets': optional(\n mergeStructs(HandlerCaveatsStruct, object({ scopes: ChainIdsStruct })),\n ),\n 'endowment:cronjob': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({ jobs: optional(CronjobSpecificationArrayStruct) }),\n ),\n ),\n 'endowment:ethereum-provider': optional(EmptyObjectStruct),\n 'endowment:keyring': optional(\n mergeStructs(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:protocol': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({ scopes: ProtocolScopesStruct }),\n ),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(EmptyObjectStruct),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(\n mergeStructs(HandlerCaveatsStruct, RpcOriginsStruct),\n ),\n 'endowment:signature-insight': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(EmptyObjectStruct),\n snap_dialog: optional(EmptyObjectStruct),\n snap_manageState: optional(EmptyObjectStruct),\n snap_manageAccounts: optional(EmptyObjectStruct),\n snap_notify: optional(EmptyObjectStruct),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(EmptyObjectStruct),\n snap_getLocale: optional(EmptyObjectStruct),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n type({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n platformVersion: optional(VersionStruct),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/manifest/validation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,2BAA2B;AAG7D,OAAO,EACL,KAAK,EACL,OAAO,EACP,MAAM,EACN,KAAK,EACL,OAAO,EACP,EAAE,EACF,OAAO,EACP,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,IAAI,EACJ,MAAM,EACN,IAAI,EACJ,KAAK,EACL,YAAY,EACb,8BAA8B;AAC/B,OAAO,EACL,YAAY,EACZ,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,QAAQ,EACR,iBAAiB,EAClB,wBAAwB;AAEzB,OAAO,EAAE,OAAO,EAAE,qBAAiB;AACnC,OAAO,EAAE,+BAA+B,EAAE,uBAAmB;AAC7D,OAAO,EAAE,iBAAiB,EAAE,4BAA4B,EAAE,uBAAmB;AAC7E,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,wBAAoB;AACrE,OAAO,EAAE,YAAY,EAAE,qBAAiB;AACxC,OAAO,EAAE,YAAY,EAAsB,uBAAmB;AAC9D,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,GAAG,EAAE,qBAAiB;AAE7D,+EAA+E;AAC/E,gCAAgC;AAChC,MAAM,kBAAkB,GAAa;IACnC,iBAAiB;IACjB,4BAA4B;CAC7B,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAa,CAAC,EAAE,CAAC,CAAC;AACnD,M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E,kBAAkB,CAAC,CAAC;AACvC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAc;IAEd,YAAY,CACV,KAAK,EACL,kBAAkB,EAClB,IAAI,gBAAgB,CAAC,QAAQ,cAAc,CAC5C,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,qEAAqE;IACrE,OAAO,MAAM,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { EmptyObject, InitialPermissions } from '@metamask/snaps-sdk';\nimport type { Describe, Infer, Struct } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n} from '@metamask/superstruct';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n CaipChainIdStruct,\n} from '@metamask/utils';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { mergeStructs, type InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\nexport const CurveStruct: Describe<SupportedCurve> = enums([\n 'ed25519',\n 'secp256k1',\n 'ed25519Bip32',\n]);\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: CurveStruct,\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = size(array(CaipChainIdStruct), 1, Infinity);\n\nexport const LookupMatchersStruct = union([\n object({\n tlds: size(array(string()), 1, Infinity),\n }),\n object({\n schemes: size(array(string()), 1, Infinity),\n }),\n object({\n tlds: size(array(string()), 1, Infinity),\n schemes: size(array(string()), 1, Infinity),\n }),\n]);\n\nexport const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);\nexport const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);\n\nexport const MaxRequestTimeStruct = size(\n integer(),\n MINIMUM_REQUEST_TIMEOUT,\n MAXIMUM_REQUEST_TIMEOUT,\n);\n\nexport const ProtocolScopesStruct = record(\n CaipChainIdStruct,\n object({ methods: array(string()) }),\n);\n\n// Utility type to union with for all handler structs\nexport const HandlerCaveatsStruct = object({\n maxRequestTime: optional(MaxRequestTimeStruct),\n});\n\nexport type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;\n\nexport const EmptyObjectStruct = object<EmptyObject>({}) as unknown as Struct<\n EmptyObject,\n null\n>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct: Describe<InitialPermissions> = type({\n 'endowment:assets': optional(\n mergeStructs(HandlerCaveatsStruct, object({ scopes: ChainIdsStruct })),\n ),\n 'endowment:cronjob': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({ jobs: optional(CronjobSpecificationArrayStruct) }),\n ),\n ),\n 'endowment:ethereum-provider': optional(EmptyObjectStruct),\n 'endowment:keyring': optional(\n mergeStructs(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:protocol': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({ scopes: ProtocolScopesStruct }),\n ),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(EmptyObjectStruct),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(\n mergeStructs(HandlerCaveatsStruct, RpcOriginsStruct),\n ),\n 'endowment:signature-insight': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n mergeStructs(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(EmptyObjectStruct),\n snap_dialog: optional(EmptyObjectStruct),\n snap_manageState: optional(EmptyObjectStruct),\n snap_manageAccounts: optional(EmptyObjectStruct),\n snap_notify: optional(EmptyObjectStruct),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(EmptyObjectStruct),\n snap_getLocale: optional(EmptyObjectStruct),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxiliaryFilesStruct = array(string());\n\n/**\n * @deprecated Use SnapAuxiliaryFilesStruct instead. This was a typo that has been fixed.\n */\nexport const SnapAuxilaryFilesStruct = SnapAuxiliaryFilesStruct;\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n type({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxiliaryFilesStruct),\n locales: optional(SnapAuxiliaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n platformVersion: optional(VersionStruct),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"]}
|
|
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.hasFixes = exports.runValidators = void 0;
|
|
26
|
+
exports.hasFixes = exports.isReportFixable = exports.runValidators = void 0;
|
|
27
27
|
const utils_1 = require("@metamask/utils");
|
|
28
28
|
const defaultValidators = __importStar(require("./validators/index.cjs"));
|
|
29
29
|
class Context {
|
|
@@ -96,14 +96,26 @@ async function runValidators(files, rules = Object.values(defaultValidators), op
|
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
98
|
exports.runValidators = runValidators;
|
|
99
|
+
/**
|
|
100
|
+
* Check whether a report is fixable.
|
|
101
|
+
*
|
|
102
|
+
* @param report - The report to check.
|
|
103
|
+
* @param errorsOnly - Whether to only consider errors for fixability.
|
|
104
|
+
* @returns Whether the report is fixable.
|
|
105
|
+
*/
|
|
106
|
+
function isReportFixable(report, errorsOnly) {
|
|
107
|
+
return Boolean(report.fix && (!errorsOnly || report.severity === 'error'));
|
|
108
|
+
}
|
|
109
|
+
exports.isReportFixable = isReportFixable;
|
|
99
110
|
/**
|
|
100
111
|
* Get whether any reports has pending fixes.
|
|
101
112
|
*
|
|
102
113
|
* @param results - Results of the validation run.
|
|
114
|
+
* @param errorsOnly - Whether to only consider errors for pending fixes.
|
|
103
115
|
* @returns Whether there are fixes pending.
|
|
104
116
|
*/
|
|
105
|
-
function hasFixes(results) {
|
|
106
|
-
return results.reports.some((report) => report
|
|
117
|
+
function hasFixes(results, errorsOnly) {
|
|
118
|
+
return results.reports.some((report) => isReportFixable(report, errorsOnly));
|
|
107
119
|
}
|
|
108
120
|
exports.hasFixes = hasFixes;
|
|
109
121
|
//# sourceMappingURL=validator.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.cjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyC;AAUzC,0EAAkD;AAQlD,MAAM,OAAO;IACX,OAAO,GAAsB,EAAE,CAAC;IAEvB,QAAQ,GAA4B,EAAE,CAAC;IAEhD,aAAa,GAAuB,SAAS,CAAC;IAE9C;;;;;OAKG;IACH,YAAY,OAAgC;QAC1C,IAAI,CAAC,QAAQ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/E,CAAC;AALD,4BAKC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport type {\n ValidatorContext,\n ValidatorContextOptions,\n ValidatorFix,\n ValidatorMeta,\n ValidatorReport,\n ValidatorSeverity,\n} from './validator-types';\nimport * as defaultValidators from './validators';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\n\nexport type ValidatorResults = {\n files?: SnapFiles;\n reports: ValidatorReport[];\n};\n\nclass Context implements ValidatorContext {\n reports: ValidatorReport[] = [];\n\n readonly #options: ValidatorContextOptions = {};\n\n #nextSeverity?: ValidatorSeverity = undefined;\n\n /**\n * Construct a new validator context.\n *\n * @param options - The options for the validator context.\n * @param options.exports - Exports detected by evaluating the bundle.\n */\n constructor(options: ValidatorContextOptions) {\n this.#options = options;\n }\n\n report(message: string, fix?: ValidatorFix): void {\n assert(this.#nextSeverity !== undefined);\n this.reports.push({\n severity: this.#nextSeverity,\n message,\n fix,\n });\n }\n\n prepareForValidator(settings: { severity: ValidatorSeverity }) {\n this.#nextSeverity = settings.severity;\n }\n\n get hasErrors() {\n return this.reports.some((report) => report.severity === 'error');\n }\n\n get options() {\n return this.#options;\n }\n}\n\n/**\n * Verify that snap files are completely valid.\n * First it runs validators on unparsed files to check structure.\n * Secondly it runs validators on parsed files to check semantics.\n *\n * @param files - All files required to run a snap.\n * @param rules - Validators to run.\n * @param options - Options for the validation.\n * @param options.exports - Exports detected by evaluating the bundle.\n * @returns The validation results.\n */\n// TODO(ritave): snap.manifest.json and package.json should check\n// json parsing as well instead of assuming it's\n// already parsed\nexport async function runValidators(\n files: UnvalidatedSnapFiles,\n rules: ValidatorMeta[] = Object.values(defaultValidators),\n options: ValidatorContextOptions = {},\n): Promise<ValidatorResults> {\n const context = new Context(options);\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.structureCheck?.(files, context);\n }\n\n if (context.hasErrors) {\n return {\n reports: context.reports,\n };\n }\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.semanticCheck?.(files as SnapFiles, context);\n }\n\n return {\n files: files as SnapFiles,\n reports: context.reports,\n };\n}\n\n/**\n * Check whether a report is fixable.\n *\n * @param report - The report to check.\n * @param errorsOnly - Whether to only consider errors for fixability.\n * @returns Whether the report is fixable.\n */\nexport function isReportFixable(report: ValidatorReport, errorsOnly?: boolean) {\n return Boolean(report.fix && (!errorsOnly || report.severity === 'error'));\n}\n\n/**\n * Get whether any reports has pending fixes.\n *\n * @param results - Results of the validation run.\n * @param errorsOnly - Whether to only consider errors for pending fixes.\n * @returns Whether there are fixes pending.\n */\nexport function hasFixes(\n results: ValidatorResults,\n errorsOnly?: boolean,\n): boolean {\n return results.reports.some((report) => isReportFixable(report, errorsOnly));\n}\n"]}
|
|
@@ -16,11 +16,20 @@ export type ValidatorResults = {
|
|
|
16
16
|
* @returns The validation results.
|
|
17
17
|
*/
|
|
18
18
|
export declare function runValidators(files: UnvalidatedSnapFiles, rules?: ValidatorMeta[], options?: ValidatorContextOptions): Promise<ValidatorResults>;
|
|
19
|
+
/**
|
|
20
|
+
* Check whether a report is fixable.
|
|
21
|
+
*
|
|
22
|
+
* @param report - The report to check.
|
|
23
|
+
* @param errorsOnly - Whether to only consider errors for fixability.
|
|
24
|
+
* @returns Whether the report is fixable.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isReportFixable(report: ValidatorReport, errorsOnly?: boolean): boolean;
|
|
19
27
|
/**
|
|
20
28
|
* Get whether any reports has pending fixes.
|
|
21
29
|
*
|
|
22
30
|
* @param results - Results of the validation run.
|
|
31
|
+
* @param errorsOnly - Whether to only consider errors for pending fixes.
|
|
23
32
|
* @returns Whether there are fixes pending.
|
|
24
33
|
*/
|
|
25
|
-
export declare function hasFixes(results: ValidatorResults): boolean;
|
|
34
|
+
export declare function hasFixes(results: ValidatorResults, errorsOnly?: boolean): boolean;
|
|
26
35
|
//# sourceMappingURL=validator.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.cts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,uBAAuB,EAEvB,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyCF;;;;;;;;;;GAUG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,EACzD,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA2B3B;AAED
|
|
1
|
+
{"version":3,"file":"validator.d.cts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,uBAAuB,EAEvB,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyCF;;;;;;;;;;GAUG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,EACzD,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA2B3B;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,EAAE,UAAU,CAAC,EAAE,OAAO,WAE5E;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,OAAO,EAAE,gBAAgB,EACzB,UAAU,CAAC,EAAE,OAAO,GACnB,OAAO,CAET"}
|
|
@@ -16,11 +16,20 @@ export type ValidatorResults = {
|
|
|
16
16
|
* @returns The validation results.
|
|
17
17
|
*/
|
|
18
18
|
export declare function runValidators(files: UnvalidatedSnapFiles, rules?: ValidatorMeta[], options?: ValidatorContextOptions): Promise<ValidatorResults>;
|
|
19
|
+
/**
|
|
20
|
+
* Check whether a report is fixable.
|
|
21
|
+
*
|
|
22
|
+
* @param report - The report to check.
|
|
23
|
+
* @param errorsOnly - Whether to only consider errors for fixability.
|
|
24
|
+
* @returns Whether the report is fixable.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isReportFixable(report: ValidatorReport, errorsOnly?: boolean): boolean;
|
|
19
27
|
/**
|
|
20
28
|
* Get whether any reports has pending fixes.
|
|
21
29
|
*
|
|
22
30
|
* @param results - Results of the validation run.
|
|
31
|
+
* @param errorsOnly - Whether to only consider errors for pending fixes.
|
|
23
32
|
* @returns Whether there are fixes pending.
|
|
24
33
|
*/
|
|
25
|
-
export declare function hasFixes(results: ValidatorResults): boolean;
|
|
34
|
+
export declare function hasFixes(results: ValidatorResults, errorsOnly?: boolean): boolean;
|
|
26
35
|
//# sourceMappingURL=validator.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.mts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,uBAAuB,EAEvB,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyCF;;;;;;;;;;GAUG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,EACzD,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA2B3B;AAED
|
|
1
|
+
{"version":3,"file":"validator.d.mts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,uBAAuB,EAEvB,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyCF;;;;;;;;;;GAUG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,EACzD,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA2B3B;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,EAAE,UAAU,CAAC,EAAE,OAAO,WAE5E;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,OAAO,EAAE,gBAAgB,EACzB,UAAU,CAAC,EAAE,OAAO,GACnB,OAAO,CAET"}
|
|
@@ -69,13 +69,24 @@ export async function runValidators(files, rules = Object.values(defaultValidato
|
|
|
69
69
|
reports: context.reports,
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Check whether a report is fixable.
|
|
74
|
+
*
|
|
75
|
+
* @param report - The report to check.
|
|
76
|
+
* @param errorsOnly - Whether to only consider errors for fixability.
|
|
77
|
+
* @returns Whether the report is fixable.
|
|
78
|
+
*/
|
|
79
|
+
export function isReportFixable(report, errorsOnly) {
|
|
80
|
+
return Boolean(report.fix && (!errorsOnly || report.severity === 'error'));
|
|
81
|
+
}
|
|
72
82
|
/**
|
|
73
83
|
* Get whether any reports has pending fixes.
|
|
74
84
|
*
|
|
75
85
|
* @param results - Results of the validation run.
|
|
86
|
+
* @param errorsOnly - Whether to only consider errors for pending fixes.
|
|
76
87
|
* @returns Whether there are fixes pending.
|
|
77
88
|
*/
|
|
78
|
-
export function hasFixes(results) {
|
|
79
|
-
return results.reports.some((report) => report
|
|
89
|
+
export function hasFixes(results, errorsOnly) {
|
|
90
|
+
return results.reports.some((report) => isReportFixable(report, errorsOnly));
|
|
80
91
|
}
|
|
81
92
|
//# sourceMappingURL=validator.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.mjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB;AAUzC,OAAO,KAAK,iBAAiB,+BAAqB;AAQlD,MAAM,OAAO;IACX,OAAO,GAAsB,EAAE,CAAC;IAEvB,QAAQ,GAA4B,EAAE,CAAC;IAEhD,aAAa,GAAuB,SAAS,CAAC;IAE9C;;;;;OAKG;IACH,YAAY,OAAgC;QAC1C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED,MAAM,CAAC,OAAe,EAAE,GAAkB;QACxC,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC;QACzC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAChB,QAAQ,EAAE,IAAI,CAAC,aAAa;YAC5B,OAAO;YACP,GAAG;SACJ,CAAC,CAAC;IACL,CAAC;IAED,mBAAmB,CAAC,QAAyC;QAC3D,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC,QAAQ,CAAC;IACzC,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IACpE,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;CACF;AAED;;;;;;;;;;GAUG;AACH,iEAAiE;AACjE,8DAA8D;AAC9D,+BAA+B;AAC/B,MAAM,CAAC,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CAAC,aAAa,EAAE,CAAC,KAAkB,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED,OAAO;QACL,KAAK,EAAE,KAAkB;QACzB,OAAO,EAAE,OAAO,CAAC,OAAO;KACzB,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,MAAuB,EAAE,UAAoB;IAC3E,OAAO,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,UAAU,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CACtB,OAAyB,EACzB,UAAoB;IAEpB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport type {\n ValidatorContext,\n ValidatorContextOptions,\n ValidatorFix,\n ValidatorMeta,\n ValidatorReport,\n ValidatorSeverity,\n} from './validator-types';\nimport * as defaultValidators from './validators';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\n\nexport type ValidatorResults = {\n files?: SnapFiles;\n reports: ValidatorReport[];\n};\n\nclass Context implements ValidatorContext {\n reports: ValidatorReport[] = [];\n\n readonly #options: ValidatorContextOptions = {};\n\n #nextSeverity?: ValidatorSeverity = undefined;\n\n /**\n * Construct a new validator context.\n *\n * @param options - The options for the validator context.\n * @param options.exports - Exports detected by evaluating the bundle.\n */\n constructor(options: ValidatorContextOptions) {\n this.#options = options;\n }\n\n report(message: string, fix?: ValidatorFix): void {\n assert(this.#nextSeverity !== undefined);\n this.reports.push({\n severity: this.#nextSeverity,\n message,\n fix,\n });\n }\n\n prepareForValidator(settings: { severity: ValidatorSeverity }) {\n this.#nextSeverity = settings.severity;\n }\n\n get hasErrors() {\n return this.reports.some((report) => report.severity === 'error');\n }\n\n get options() {\n return this.#options;\n }\n}\n\n/**\n * Verify that snap files are completely valid.\n * First it runs validators on unparsed files to check structure.\n * Secondly it runs validators on parsed files to check semantics.\n *\n * @param files - All files required to run a snap.\n * @param rules - Validators to run.\n * @param options - Options for the validation.\n * @param options.exports - Exports detected by evaluating the bundle.\n * @returns The validation results.\n */\n// TODO(ritave): snap.manifest.json and package.json should check\n// json parsing as well instead of assuming it's\n// already parsed\nexport async function runValidators(\n files: UnvalidatedSnapFiles,\n rules: ValidatorMeta[] = Object.values(defaultValidators),\n options: ValidatorContextOptions = {},\n): Promise<ValidatorResults> {\n const context = new Context(options);\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.structureCheck?.(files, context);\n }\n\n if (context.hasErrors) {\n return {\n reports: context.reports,\n };\n }\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.semanticCheck?.(files as SnapFiles, context);\n }\n\n return {\n files: files as SnapFiles,\n reports: context.reports,\n };\n}\n\n/**\n * Check whether a report is fixable.\n *\n * @param report - The report to check.\n * @param errorsOnly - Whether to only consider errors for fixability.\n * @returns Whether the report is fixable.\n */\nexport function isReportFixable(report: ValidatorReport, errorsOnly?: boolean) {\n return Boolean(report.fix && (!errorsOnly || report.severity === 'error'));\n}\n\n/**\n * Get whether any reports has pending fixes.\n *\n * @param results - Results of the validation run.\n * @param errorsOnly - Whether to only consider errors for pending fixes.\n * @returns Whether there are fixes pending.\n */\nexport function hasFixes(\n results: ValidatorResults,\n errorsOnly?: boolean,\n): boolean {\n return results.reports.some((report) => isReportFixable(report, errorsOnly));\n}\n"]}
|
package/dist/snaps.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,mDAI6B;AAE7B,uDAS+B;AAE/B,2CAAgF;AAChF,sCAAqC;AACrC,4FAAyD;AACzD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AC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } 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, 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 /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 Error(errorMessage);\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 = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\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 SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\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 * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\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 * 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
|
+
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,mDAI6B;AAE7B,uDAS+B;AAE/B,2CAAgF;AAChF,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,I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AAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } 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, 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 SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\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?: SnapAuxiliaryFile[];\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 /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 Error(errorMessage);\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 = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\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 SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\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 * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\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 * 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"]}
|
package/dist/snaps.d.cts
CHANGED
|
@@ -36,10 +36,14 @@ export type VersionHistory = {
|
|
|
36
36
|
version: string;
|
|
37
37
|
date: number;
|
|
38
38
|
};
|
|
39
|
-
export type
|
|
39
|
+
export type SnapAuxiliaryFile = {
|
|
40
40
|
path: string;
|
|
41
41
|
value: string;
|
|
42
42
|
};
|
|
43
|
+
/**
|
|
44
|
+
* @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.
|
|
45
|
+
*/
|
|
46
|
+
export type SnapAuxilaryFile = SnapAuxiliaryFile;
|
|
43
47
|
export type PersistedSnap = Snap;
|
|
44
48
|
/**
|
|
45
49
|
* A Snap as it exists in {@link SnapController} state.
|
|
@@ -78,7 +82,7 @@ export type Snap = TruncatedSnap & {
|
|
|
78
82
|
/**
|
|
79
83
|
* Static auxiliary files that can be loaded at runtime.
|
|
80
84
|
*/
|
|
81
|
-
auxiliaryFiles?:
|
|
85
|
+
auxiliaryFiles?: SnapAuxiliaryFile[];
|
|
82
86
|
/**
|
|
83
87
|
* Localization files which are used to translate the manifest.
|
|
84
88
|
*/
|
package/dist/snaps.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,IAAI,IAAI,aAAa,EAC3B,4BAA4B;AAC7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAmBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAChB,kCAA8B;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAAgB;AACxE,OAAO,EAAE,cAAc,EAAO,oBAAgB;AAY9C,eAAO,MAAM,mBAAmB,QACoF,CAAC;AAErH,oBAAY,UAAU;IACpB,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,gBAAgB;IAC1B,KAAK,UAAU;IACf,IAAI,SAAS;IACb,KAAK,UAAU;IACf,MAAM,WAAW;CAClB;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAC/C,MAAM,MAAM,YAAY,GAAG;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,CAAC;AACtD,MAAM,MAAM,YAAY,GAAG;IACzB,KAAK,EAAE,UAAU,CAAC;IAClB,OAAO,EAAE,aAAa,CAAC;CACxB,CAAC;AACF,MAAM,MAAM,MAAM,GAAG,YAAY,CAA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export type SnapAuxiliaryFile = {
|
|
40
40
|
path: string;
|
|
41
41
|
value: string;
|
|
42
42
|
};
|
|
43
|
+
/**
|
|
44
|
+
* @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.
|
|
45
|
+
*/
|
|
46
|
+
export type SnapAuxilaryFile = SnapAuxiliaryFile;
|
|
43
47
|
export type PersistedSnap = Snap;
|
|
44
48
|
/**
|
|
45
49
|
* A Snap as it exists in {@link SnapController} state.
|
|
@@ -78,7 +82,7 @@ export type Snap = TruncatedSnap & {
|
|
|
78
82
|
/**
|
|
79
83
|
* Static auxiliary files that can be loaded at runtime.
|
|
80
84
|
*/
|
|
81
|
-
auxiliaryFiles?:
|
|
85
|
+
auxiliaryFiles?: SnapAuxiliaryFile[];
|
|
82
86
|
/**
|
|
83
87
|
* Localization files which are used to translate the manifest.
|
|
84
88
|
*/
|
package/dist/snaps.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.d.mts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,IAAI,IAAI,aAAa,EAC3B,4BAA4B;AAC7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAmBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAChB,kCAA8B;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAAgB;AACxE,OAAO,EAAE,cAAc,EAAO,oBAAgB;AAY9C,eAAO,MAAM,mBAAmB,QACoF,CAAC;AAErH,oBAAY,UAAU;IACpB,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAA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AAK,EAAE,YAAY,EAAE,iBAAiB,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,WAAqD,EACrD,MAAc;IAEd,OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAC5C,oBAA6B;IAE7B,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,MAAM,CACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,MAAM,CACJ,QAAQ,CAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO;QACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,cAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } 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, 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 /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 Error(errorMessage);\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 = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\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 SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\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 * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\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 * 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
|
+
{"version":3,"file":"snaps.mjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EACL,cAAc,EAGf,4BAA4B;AAE7B,OAAO,EACL,EAAE,EACF,KAAK,EACL,KAAK,EACL,YAAY,EACZ,OAAO,EACP,MAAM,EACN,MAAM,EACN,QAAQ,EACT,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,aAAa,EAAE,wBAAwB;AAChF,OAAO,EAAE,MAAM,EAAE,oBAAoB;AACrC,OAAO,gBAAe,mCAAmC;;AACzD,OAAO,mBAAkB,kCAAkC;;AAE3D,OAAO,EAAE,cAAc,EAAE,sBAAkB;AAC3C,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAQ3C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,oBAAgB;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,MAAM,CAAC,MAAM,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,MAAM,CAAN,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,KAAV,UAAU,QAMrB;AAED,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,KAAhB,gBAA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AAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAC5C,oBAA6B;IAE7B,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,MAAM,CACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,MAAM,CACJ,QAAQ,CAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO;QACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,cAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } 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, 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 SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\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?: SnapAuxiliaryFile[];\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 /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\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 Error(errorMessage);\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 = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\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 SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\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 * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\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 * 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"]}
|