@metamask/snaps-utils 5.1.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +28 -3
  2. package/dist/cjs/caveats.js +9 -0
  3. package/dist/cjs/caveats.js.map +1 -1
  4. package/dist/cjs/eval-worker.js +3 -1
  5. package/dist/cjs/eval-worker.js.map +1 -1
  6. package/dist/cjs/handler-types.js +2 -0
  7. package/dist/cjs/handler-types.js.map +1 -1
  8. package/dist/cjs/handlers.js +85 -3
  9. package/dist/cjs/handlers.js.map +1 -1
  10. package/dist/cjs/manifest/manifest.js +3 -2
  11. package/dist/cjs/manifest/manifest.js.map +1 -1
  12. package/dist/cjs/manifest/validation.js +61 -12
  13. package/dist/cjs/manifest/validation.js.map +1 -1
  14. package/dist/cjs/snaps.js.map +1 -1
  15. package/dist/cjs/structs.js +86 -17
  16. package/dist/cjs/structs.js.map +1 -1
  17. package/dist/esm/caveats.js +9 -0
  18. package/dist/esm/caveats.js.map +1 -1
  19. package/dist/esm/eval-worker.js +3 -1
  20. package/dist/esm/eval-worker.js.map +1 -1
  21. package/dist/esm/handler-types.js +2 -0
  22. package/dist/esm/handler-types.js.map +1 -1
  23. package/dist/esm/handlers.js +53 -4
  24. package/dist/esm/handlers.js.map +1 -1
  25. package/dist/esm/manifest/manifest.js +3 -2
  26. package/dist/esm/manifest/manifest.js.map +1 -1
  27. package/dist/esm/manifest/validation.js +47 -15
  28. package/dist/esm/manifest/validation.js.map +1 -1
  29. package/dist/esm/snaps.js.map +1 -1
  30. package/dist/esm/structs.js +133 -21
  31. package/dist/esm/structs.js.map +1 -1
  32. package/dist/types/caveats.d.ts +13 -1
  33. package/dist/types/handler-types.d.ts +3 -1
  34. package/dist/types/handlers.d.ts +427 -4
  35. package/dist/types/localization.d.ts +35 -9
  36. package/dist/types/manifest/validation.d.ts +239 -51
  37. package/dist/types/snaps.d.ts +12 -0
  38. package/dist/types/structs.d.ts +61 -7
  39. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from '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} from 'superstruct';\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 { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames } 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\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\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 = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\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(object({})),\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 SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\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 initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\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"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","locales","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA2CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOA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,qBAAQ,EAClBF,IAAAA,mBAAM,EAAC;QACLP,MAAME,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;QACxB+B,KAAKhC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;IACzB;IAEFgC,QAAQ5B,IAAAA,mBAAM,EAAC;QACb6B,QAAQC,qBAAc;QACtBC,UAAU/B,IAAAA,mBAAM,EAAC;YACfgC,KAAKhC,IAAAA,mBAAM,EAAC;gBACViC,UAAUtC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5BsC,UAAUhC,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrCuC,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAOtC,IAAAA,qBAAQ,EAACrC;QAChB4E,SAASvC,IAAAA,qBAAQ,EAACrC;IACpB;IACA6E,oBAAoB9E;IACpB+E,iBAAiBJ,IAAAA,oBAAO,EAAC;IACzBK,SAAS1C,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAOuD,IAAAA,eAAE,EAACvD,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdwD,IAAAA,mBAAY,EACVxD,OACAxB,oBACA,CAAC,CAAC,EAAEiF,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS/E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAO2D,IAAAA,mBAAM,EAAC3D,OAAOxB;AACvB"}
1
+ {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n} from '@metamask/utils';\nimport type { Infer, Struct } from '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 assign,\n} from 'superstruct';\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 { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport 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\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\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(ChainIdStruct), 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\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\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:cronjob': optional(\n assign(\n HandlerCaveatsStruct,\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n ),\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:keyring': optional(\n assign(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(object({})),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:signature-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(object({})),\n snap_dialog: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\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(object({})),\n snap_getLocale: optional(object({})),\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 object({\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 $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"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","LookupMatchersStruct","MINIMUM_REQUEST_TIMEOUT","MAXIMUM_REQUEST_TIMEOUT","MaxRequestTimeStruct","HandlerCaveatsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","union","tlds","schemes","inMilliseconds","Duration","Second","Minute","integer","maxRequestTime","assign","jobs","CronjobSpecificationArrayStruct","KeyringOriginsStruct","chains","matchers","RpcOriginsStruct","allowSignatureOrigin","boolean","allowTransactionOrigin","snap_dialog","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","snap_getLocale","wallet_snap","intersection","uri","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","literal","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA+CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAEAC,oBAAoB;eAApBA;;IAaAC,uBAAuB;eAAvBA;;IACAC,uBAAuB;eAAvBA;;IAEAC,oBAAoB;eAApBA;;IAOAC,oBAAoB;eAApBA;;IAOAC,iBAAiB;eAAjBA;;IAiEAC,uBAAuB;eAAvBA;;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C,EAAE+F,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS7F,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOyE,IAAAA,mBAAM,EAACzE,OAAOxB;AACvB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial 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\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","auxiliaryFiles","localizationFiles","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IA0CaA,mBAAmB;eAAnBA;;IAmGAC,gCAAgC;eAAhCA;;IAiCSC,eAAe;eAAfA;;IAwBAC,kBAAkB;eAAlBA;;IAYTC,mBAAmB;eAAnBA;;IAGAC,gBAAgB;eAAhBA;;IASAC,iBAAiB;eAAjBA;;IAeAC,eAAe;eAAfA;;IAuBAC,gBAAgB;eAAhBA;;IASAC,YAAY;eAAZA;;IAQGC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAUAC,mBAAmB;eAAnBA;;IAUAC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAsBAC,8BAA8B;eAA9BA;;;uBAvV+B;sBACxB;gFACK;6BAYrB;+EACwB;yBAEA;0BACD;uBAImC;;;;;;;;;;;;;;;;;;;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GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO5D,KAAK,GACvB,CAAC,8CAA8C,EAAE8D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
1
+ {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial 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\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","auxiliaryFiles","localizationFiles","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IA0CaA,mBAAmB;eAAnBA;;IAiHAC,gCAAg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;AAQO,SAASI,cAAc+E,OAAgB;IAC5C,OACE,OAAOA,YAAY,YACnB,+EAAmEC,IAAI,CACrED;AAGN;AASO,SAAS9E,gBACdgF,WAAqD,EACrDV,MAAc;IAEd,OAAOW,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAAST,KAClC,CAACU,SAAWA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,KAC/C,CAAC,CAAA,EACN/D,KAAK,EACN,CAAC8C,OAAO;AAEf;AASO,SAASrE,+BACduF,oBAA6B;IAE7BpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACD,uBACT;IAGF,MAAM,EAAEN,aAAaQ,oBAAoB,EAAE,GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO5D,KAAK,GACvB,CAAC,8CAA8C,EAAE8D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
@@ -41,13 +41,36 @@ _export(exports, {
41
41
  },
42
42
  getStructErrorMessage: function() {
43
43
  return getStructErrorMessage;
44
+ },
45
+ validateUnion: function() {
46
+ return validateUnion;
47
+ },
48
+ createUnion: function() {
49
+ return createUnion;
44
50
  }
45
51
  });
52
+ const _snapssdk = require("@metamask/snaps-sdk");
46
53
  const _utils = require("@metamask/utils");
47
54
  const _chalk = require("chalk");
48
55
  const _path = require("path");
49
56
  const _superstruct = require("superstruct");
50
57
  const _strings = require("./strings");
58
+ /**
59
+ * Colorize a value with a color function. This is useful for colorizing values
60
+ * in error messages. If colorization is disabled, the original value is
61
+ * returned.
62
+ *
63
+ * @param value - The value to colorize.
64
+ * @param colorFunction - The color function to use.
65
+ * @param enabled - Whether to colorize the value.
66
+ * @returns The colorized value, or the original value if colorization is
67
+ * disabled.
68
+ */ function color(value, colorFunction, enabled) {
69
+ if (enabled) {
70
+ return colorFunction(value);
71
+ }
72
+ return value;
73
+ }
51
74
  function file() {
52
75
  return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
53
76
  return (0, _path.resolve)(process.cwd(), value);
@@ -60,12 +83,12 @@ function named(name, struct) {
60
83
  });
61
84
  }
62
85
  class SnapsStructError extends _superstruct.StructError {
63
- constructor(struct, prefix, suffix, failure, failures){
86
+ constructor(struct, prefix, suffix, failure, failures, colorize = true){
64
87
  super(failure, failures);
65
88
  this.name = 'SnapsStructError';
66
89
  this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
67
90
  ...failures()
68
- ])}${suffix ? `\n\n${suffix}` : ''}`;
91
+ ], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
69
92
  }
70
93
  }
71
94
  function* arrayToGenerator(array) {
@@ -73,8 +96,8 @@ function* arrayToGenerator(array) {
73
96
  yield item;
74
97
  }
75
98
  }
76
- function getError({ struct, prefix, suffix = '', error }) {
77
- return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
99
+ function getError({ struct, prefix, suffix = '', error, colorize }) {
100
+ return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
78
101
  }
79
102
  function createFromStruct(value, struct, prefix, suffix = '') {
80
103
  try {
@@ -99,24 +122,24 @@ function getStructFromPath(struct, path) {
99
122
  return result;
100
123
  }, struct);
101
124
  }
102
- function getUnionStructNames(struct) {
125
+ function getUnionStructNames(struct, colorize = true) {
103
126
  if (Array.isArray(struct.schema)) {
104
- return struct.schema.map(({ type })=>(0, _chalk.green)(type));
127
+ return struct.schema.map(({ type })=>color(type, _chalk.green, colorize));
105
128
  }
106
129
  return null;
107
130
  }
108
- function getStructErrorPrefix(failure) {
131
+ function getStructErrorPrefix(failure, colorize = true) {
109
132
  if (failure.type === 'never' || failure.path.length === 0) {
110
133
  return '';
111
134
  }
112
- return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
135
+ return `At path: ${color(failure.path.join('.'), _chalk.bold, colorize)} — `;
113
136
  }
114
- function getStructFailureMessage(struct, failure) {
115
- const received = (0, _chalk.red)(JSON.stringify(failure.value));
116
- const prefix = getStructErrorPrefix(failure);
137
+ function getStructFailureMessage(struct, failure, colorize = true) {
138
+ const received = color(JSON.stringify(failure.value), _chalk.red, colorize);
139
+ const prefix = getStructErrorPrefix(failure, colorize);
117
140
  if (failure.type === 'union') {
118
141
  const childStruct = getStructFromPath(struct, failure.path);
119
- const unionNames = getUnionStructNames(childStruct);
142
+ const unionNames = getUnionStructNames(childStruct, colorize);
120
143
  if (unionNames) {
121
144
  return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
122
145
  }
@@ -125,17 +148,63 @@ function getStructFailureMessage(struct, failure) {
125
148
  if (failure.type === 'literal') {
126
149
  // Superstruct's failure does not provide information about which literal
127
150
  // value was expected, so we need to parse the message to get the literal.
128
- const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
151
+ const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', _chalk.green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', _chalk.red, colorize)}`);
129
152
  return `${prefix}${message}.`;
130
153
  }
131
154
  if (failure.type === 'never') {
132
- return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
155
+ return `Unknown key: ${color(failure.path.join('.'), _chalk.bold, colorize)}, received: ${received}.`;
133
156
  }
134
- return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
157
+ if (failure.refinement === 'size') {
158
+ const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', _chalk.green, colorize)} and ${color('$2', _chalk.green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', _chalk.red, colorize)}`).replace(/a array/u, 'an array');
159
+ return `${prefix}${message}.`;
160
+ }
161
+ return `${prefix}Expected a value of type ${color(failure.type, _chalk.green, colorize)}, but received: ${received}.`;
135
162
  }
136
- function getStructErrorMessage(struct, failures) {
137
- const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
163
+ function getStructErrorMessage(struct, failures, colorize = true) {
164
+ const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure, colorize)}`));
138
165
  return formattedFailures.join('\n');
139
166
  }
167
+ function validateUnion(value, struct, structKey, coerce = false) {
168
+ (0, _utils.assert)(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
169
+ (0, _utils.assert)(struct.schema.length > 0, 'Expected a non-empty array of structs.');
170
+ const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
171
+ const key = (0, _superstruct.type)({
172
+ [structKey]: (0, _snapssdk.union)(keyUnion)
173
+ });
174
+ const [keyError] = (0, _superstruct.validate)(value, key, {
175
+ coerce
176
+ });
177
+ if (keyError) {
178
+ throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
179
+ }
180
+ // At this point it's guaranteed that the value is an object, so we can safely
181
+ // cast it to a Record.
182
+ const objectValue = value;
183
+ const objectStructs = struct.schema.filter((innerStruct)=>(0, _superstruct.is)(objectValue[structKey], innerStruct.schema[structKey]));
184
+ (0, _utils.assert)(objectStructs.length > 0, 'Expected a struct to match the value.');
185
+ // We need to validate the value against all the object structs that match the
186
+ // struct key, and return the first validated value.
187
+ const validationResults = objectStructs.map((objectStruct)=>(0, _superstruct.validate)(objectValue, objectStruct, {
188
+ coerce
189
+ }));
190
+ const validatedValue = validationResults.find(([error])=>!error);
191
+ if (validatedValue) {
192
+ return validatedValue[1];
193
+ }
194
+ (0, _utils.assert)(validationResults[0][0], 'Expected at least one error.');
195
+ // If there is no validated value, we need to find the error with the least
196
+ // number of failures (with the assumption that it's the most specific error).
197
+ const validationError = validationResults.reduce((error, [innerError])=>{
198
+ (0, _utils.assert)(innerError, 'Expected an error.');
199
+ if (innerError.failures().length < error.failures().length) {
200
+ return innerError;
201
+ }
202
+ return error;
203
+ }, validationResults[0][0]);
204
+ throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
205
+ }
206
+ function createUnion(value, struct, structKey) {
207
+ return validateUnion(value, struct, structKey, true);
208
+ }
140
209
 
141
210
  //# sourceMappingURL=structs.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","coerce","string","value","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","bold","join","received","red","JSON","stringify","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuDgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;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AC,EAAEtB,OAAO,EAAEE,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BwB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAEV,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEU,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEL,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEvB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEuB,IAAAA,WAAI,EACzBlB,QAAQO,IAAI,CAACY,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEtB,OAAO,yBAAyB,EAAEkB,IAAAA,YAAK,EAC/ChB,QAAQL,IAAI,EACZ,gBAAgB,EAAEyB,SAAS,CAAC,CAAC;AACjC;AAUO,SAASnC,sBACdQ,MAA4B,EAC5BQ,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASc,GAAG,CAAC,CAACf,UACtC4B,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAE5C,wBAAwBS,QAAQO,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBR,IAAI,CAAC;AAChC"}
1
+ {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n string,\n coerce as superstructCoerce,\n} from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return superstructCoerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\n )}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n colorize?: boolean;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","validateUnion","createUnion","color","value","colorFunction","enabled","superstructCoerce","string","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","colorize","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","join","bold","received","JSON","stringify","red","childStruct","unionNames","replace","refinement","formattedFailures","indent","structKey","coerce","assert","keyUnion","innerStruct","superstructType","union","keyError","validate","Error","objectValue","objectStructs","filter","is","validationResults","objectStruct","validatedValue","find","validationError","innerError"],"mappings":";;;;;;;;;;;IAyFgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAoCIC,gBAAgB;eAAhBA;;IAoBDC,QAAQ;eAARA;;IA6BAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAqBAC,mBAAmB;eAAnBA;;IAmBAC,oBAAoB;eAApBA;;IAkBAC,uBAAuB;eAAvBA;;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ACpD,MAAM2B,oBAAoBH,cAAc1B,GAAG,CAAC,CAAC8B,eAC3CP,IAAAA,qBAAQ,EAACE,aAAaK,cAAc;YAAEd;QAAO;IAG/C,MAAMe,iBAAiBF,kBAAkBG,IAAI,CAAC,CAAC,CAAC1C,MAAM,GAAK,CAACA;IAC5D,IAAIyC,gBAAgB;QAClB,OAAOA,cAAc,CAAC,EAAE;IAC1B;IAEAd,IAAAA,aAAM,EAACY,iBAAiB,CAAC,EAAE,CAAC,EAAE,EAAE;IAEhC,2EAA2E;IAC3E,8EAA8E;IAC9E,MAAMI,kBAAkBJ,kBAAkBpC,MAAM,CAAC,CAACH,OAAO,CAAC4C,WAAW;QACnEjB,IAAAA,aAAM,EAACiB,YAAY;QACnB,IAAIA,WAAWjD,QAAQ,GAAGiB,MAAM,GAAGZ,MAAML,QAAQ,GAAGiB,MAAM,EAAE;YAC1D,OAAOgC;QACT;QAEA,OAAO5C;IACT,GAAGuC,iBAAiB,CAAC,EAAE,CAAC,EAAE;IAE1B,MAAM,IAAIL,MACR7D,wBAAwBc,QAAQwD,gBAAgBhD,QAAQ,EAAE,CAAC,EAAE,EAAE;AAEnE;AAkBO,SAASnB,YACdE,KAAc,EACdS,MAA4B,EAC5BsC,SAAqB;IAErB,OAAOlD,cAAcG,OAAOS,QAAQsC,WAAW;AACjD"}
@@ -13,6 +13,9 @@ export var SnapCaveatType;
13
13
  * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.
14
14
  */ "TransactionOrigin"] = 'transactionOrigin';
15
15
  SnapCaveatType[/**
16
+ * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.
17
+ */ "SignatureOrigin"] = 'signatureOrigin';
18
+ SnapCaveatType[/**
16
19
  * The origins that a Snap can receive JSON-RPC messages from.
17
20
  */ "RpcOrigin"] = 'rpcOrigin';
18
21
  SnapCaveatType[/**
@@ -24,6 +27,12 @@ export var SnapCaveatType;
24
27
  SnapCaveatType[/**
25
28
  * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
26
29
  */ "ChainIds"] = 'chainIds';
30
+ SnapCaveatType[/**
31
+ * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
32
+ */ "LookupMatchers"] = 'lookupMatchers';
33
+ SnapCaveatType[/**
34
+ * Caveat specifying the max request time for a handler endowment.
35
+ */ "MaxRequestTime"] = 'maxRequestTime';
27
36
  })(SnapCaveatType || (SnapCaveatType = {}));
28
37
 
29
38
  //# sourceMappingURL=caveats.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,eAAY;IAxBFL,eA0BV;;GAEC,GACDM,mBAAgB;IA7BNN,eA+BV;;GAEC,GACDO,aAAU;IAlCAP,eAoCV;;GAEC,GACDQ,cAAW;GAvCDR,mBAAAA"}
1
+ {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.\n */\n SignatureOrigin = 'signatureOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n\n /**\n * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.\n */\n LookupMatchers = 'lookupMatchers',\n\n /**\n * Caveat specifying the max request time for a handler endowment.\n */\n MaxRequestTime = 'maxRequestTime',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds","LookupMatchers","MaxRequestTime"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;IA5CDT,eA8CV;;GAEC,GACDU,oBAAiB;IAjDPV,eAmDV;;GAEC,GACDW,oBAAiB;GAtDPX,mBAAAA"}
@@ -33,6 +33,8 @@ if (invalidExports.length > 0) {
33
33
  // eslint-disable-next-line no-console
34
34
  console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
35
35
  }
36
- setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
36
+ // To ensure the worker exits we explicitly call exit here
37
+ // If we didn't the eval would wait for timers set during Compartment eval
38
+ process.exit(0);
37
39
 
38
40
  //# sourceMappingURL=eval-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["readFileSync","SNAP_EXPORT_NAMES","generateMockEndowments","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","module","globalThis","self","global","window","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,iBAAiB,QAAQ,kBAAkB;AACpD,SAASC,sBAAsB,QAAQ,SAAS;AAIhDC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGd,wBAAwB;IAC3Be,QAAQJ;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYG,UAAU,CAACC,IAAI,GAAGJ,YAAYG,UAAU;AACpDH,YAAYG,UAAU,CAACE,MAAM,GAAGL,YAAYG,UAAU;AACtDH,YAAYG,UAAU,CAACG,MAAM,GAAGN,YAAYG,UAAU;AAEtDH,YAAYO,QAAQ,CAACtB,aAAaU,cAAc;AAEhD,MAAMa,iBAAiBC,OAAOC,IAAI,CAACZ,WAAWC,OAAO,EAAEY,MAAM,CAC3D,CAACC,aAAe,CAAC1B,kBAAkB2B,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMtB,QAAQuB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
1
+ {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\n// To ensure the worker exits we explicitly call exit here\n// If we didn't the eval would wait for timers set during Compartment eval\nprocess.exit(0);\n"],"names":["readFileSync","SNAP_EXPORT_NAMES","generateMockEndowments","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","module","globalThis","self","global","window","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,iBAAiB,QAAQ,kBAAkB;AACpD,SAASC,sBAAsB,QAAQ,SAAS;AAIhDC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGd,wBAAwB;IAC3Be,QAAQJ;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYG,UAAU,CAACC,IAAI,GAAGJ,YAAYG,UAAU;AACpDH,YAAYG,UAAU,CAACE,MAAM,GAAGL,YAAYG,UAAU;AACtDH,YAAYG,UAAU,CAACG,MAAM,GAAGN,YAAYG,UAAU;AAEtDH,YAAYO,QAAQ,CAACtB,aAAaU,cAAc;AAEhD,MAAMa,iBAAiBC,OAAOC,IAAI,CAACZ,WAAWC,OAAO,EAAEY,MAAM,CAC3D,CAACC,aAAe,CAAC1B,kBAAkB2B,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEA,0DAA0D;AAC1D,0EAA0E;AAC1ErB,QAAQsB,IAAI,CAAC"}
@@ -1,6 +1,7 @@
1
1
  export var HandlerType;
2
2
  (function(HandlerType) {
3
3
  HandlerType["OnRpcRequest"] = 'onRpcRequest';
4
+ HandlerType["OnSignature"] = 'onSignature';
4
5
  HandlerType["OnTransaction"] = 'onTransaction';
5
6
  HandlerType["OnCronjob"] = 'onCronjob';
6
7
  HandlerType["OnInstall"] = 'onInstall';
@@ -8,6 +9,7 @@ export var HandlerType;
8
9
  HandlerType["OnNameLookup"] = 'onNameLookup';
9
10
  HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
10
11
  HandlerType["OnHomePage"] = 'onHomePage';
12
+ HandlerType["OnUserInput"] = 'onUserInput';
11
13
  })(HandlerType || (HandlerType = {}));
12
14
  export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
13
15
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","SNAP_EXPORT_NAMES","Object","values"],"mappings":"WAAO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;IALDL,YAMVM,kBAAe;IANLN,YAOVO,sBAAmB;IAPTP,YAQVQ,gBAAa;GARHR,gBAAAA;AAmCZ,OAAO,MAAMS,oBAAoBC,OAAOC,MAAM,CAACX,aAAa"}
1
+ {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n OnUserInput = 'onUserInput',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["HandlerType","OnRpcRequest","OnSignature","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","OnUserInput","SNAP_EXPORT_NAMES","Object","values"],"mappings":"WAAO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,iBAAc;IAFJF,YAGVG,mBAAgB;IAHNH,YAIVI,eAAY;IAJFJ,YAKVK,eAAY;IALFL,YAMVM,cAAW;IANDN,YAOVO,kBAAe;IAPLP,YAQVQ,sBAAmB;IARTR,YASVS,gBAAa;IATHT,YAUVU,iBAAc;GAVJV,gBAAAA;AAqCZ,OAAO,MAAMW,oBAAoBC,OAAOC,MAAM,CAACb,aAAa"}
@@ -1,5 +1,5 @@
1
1
  import { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';
2
- import { literal, nullable, object, optional } from 'superstruct';
2
+ import { assign, literal, nullable, object, optional, string, array, size, union } from 'superstruct';
3
3
  import { HandlerType } from './handler-types';
4
4
  export const SNAP_EXPORTS = {
5
5
  [HandlerType.OnRpcRequest]: {
@@ -57,14 +57,63 @@ export const SNAP_EXPORTS = {
57
57
  validator: (snapExport)=>{
58
58
  return typeof snapExport === 'function';
59
59
  }
60
+ },
61
+ [HandlerType.OnSignature]: {
62
+ type: HandlerType.OnSignature,
63
+ required: true,
64
+ validator: (snapExport)=>{
65
+ return typeof snapExport === 'function';
66
+ }
67
+ },
68
+ [HandlerType.OnUserInput]: {
69
+ type: HandlerType.OnUserInput,
70
+ required: true,
71
+ validator: (snapExport)=>{
72
+ return typeof snapExport === 'function';
73
+ }
60
74
  }
61
75
  };
62
- export const OnTransactionResponseStruct = nullable(object({
63
- content: ComponentStruct,
76
+ export const OnTransactionSeverityResponseStruct = object({
64
77
  severity: optional(literal(SeverityLevel.Critical))
78
+ });
79
+ export const OnTransactionResponseWithIdStruct = assign(OnTransactionSeverityResponseStruct, object({
80
+ id: string()
65
81
  }));
66
- export const OnHomePageResponseStruct = object({
82
+ export const OnTransactionResponseWithContentStruct = assign(OnTransactionSeverityResponseStruct, object({
67
83
  content: ComponentStruct
84
+ }));
85
+ export const OnTransactionResponseStruct = nullable(union([
86
+ OnTransactionResponseWithContentStruct,
87
+ OnTransactionResponseWithIdStruct
88
+ ]));
89
+ export const OnSignatureResponseStruct = OnTransactionResponseStruct;
90
+ export const OnHomePageResponseWithContentStruct = object({
91
+ content: ComponentStruct
92
+ });
93
+ export const OnHomePageResponseWithIdStruct = object({
94
+ id: string()
95
+ });
96
+ export const OnHomePageResponseStruct = union([
97
+ OnHomePageResponseWithContentStruct,
98
+ OnHomePageResponseWithIdStruct
99
+ ]);
100
+ export const AddressResolutionStruct = object({
101
+ protocol: string(),
102
+ resolvedDomain: string()
103
+ });
104
+ export const DomainResolutionStruct = object({
105
+ protocol: string(),
106
+ resolvedAddress: string()
107
+ });
108
+ export const AddressResolutionResponseStruct = object({
109
+ resolvedDomains: size(array(AddressResolutionStruct), 1, Infinity)
110
+ });
111
+ export const DomainResolutionResponseStruct = object({
112
+ resolvedAddresses: size(array(DomainResolutionStruct), 1, Infinity)
68
113
  });
114
+ export const OnNameLookupResponseStruct = nullable(union([
115
+ AddressResolutionResponseStruct,
116
+ DomainResolutionResponseStruct
117
+ ]));
69
118
 
70
119
  //# sourceMappingURL=handlers.js.map