@metamask/snaps-utils 3.2.0 → 4.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.
- package/CHANGELOG.md +35 -1
- package/dist/cjs/auxiliary-files.js +6 -19
- package/dist/cjs/auxiliary-files.js.map +1 -1
- package/dist/cjs/checksum.js +22 -5
- package/dist/cjs/checksum.js.map +1 -1
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/enum.js.map +1 -1
- package/dist/cjs/errors.js +6 -154
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +17 -11
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +2 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +2 -7
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/localization.js +113 -0
- package/dist/cjs/localization.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +33 -19
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +3 -2
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/namespace.js +5 -1
- package/dist/cjs/namespace.js.map +1 -1
- package/dist/cjs/npm.js +18 -5
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js +7 -6
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/structs.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/ui.js +51 -0
- package/dist/cjs/ui.js.map +1 -0
- package/dist/cjs/validation.js +4 -2
- package/dist/cjs/validation.js.map +1 -1
- package/dist/esm/auxiliary-files.js +1 -6
- package/dist/esm/auxiliary-files.js.map +1 -1
- package/dist/esm/checksum.js +25 -6
- package/dist/esm/checksum.js.map +1 -1
- package/dist/esm/cronjob.js +1 -1
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/enum.js.map +1 -1
- package/dist/esm/errors.js +2 -157
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +13 -7
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +2 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/localization.js +115 -0
- package/dist/esm/localization.js.map +1 -0
- package/dist/esm/manifest/manifest.js +37 -19
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +4 -3
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/namespace.js +3 -2
- package/dist/esm/namespace.js.map +1 -1
- package/dist/esm/npm.js +18 -5
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js +7 -6
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/structs.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/ui.js +48 -0
- package/dist/esm/ui.js.map +1 -0
- package/dist/esm/validation.js +4 -2
- package/dist/esm/validation.js.map +1 -1
- package/dist/types/auxiliary-files.d.ts +1 -5
- package/dist/types/checksum.d.ts +9 -2
- package/dist/types/enum.d.ts +1 -21
- package/dist/types/errors.d.ts +1 -109
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +73 -152
- package/dist/types/index.browser.d.ts +2 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/localization.d.ts +143 -0
- package/dist/types/manifest/manifest.d.ts +16 -7
- package/dist/types/manifest/validation.d.ts +83 -78
- package/dist/types/namespace.d.ts +11 -10
- package/dist/types/npm.d.ts +1 -1
- package/dist/types/snaps.d.ts +13 -43
- package/dist/types/structs.d.ts +23 -0
- package/dist/types/types.d.ts +4 -2
- package/dist/types/ui.d.ts +20 -0
- package/dist/types/validation.d.ts +1 -1
- package/package.json +3 -3
package/dist/esm/snaps.js.map
CHANGED
|
@@ -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 {\n Json,\n JsonRpcError,\n Opaque,\n SemVerVersion,\n} 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 { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapId, 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\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\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: ValidatedSnapId };\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 = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\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 * Whether the Snap is blocked.\n */\n blocked: boolean;\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 of the Snap.\n */\n version: SemVerVersion;\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\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult = TruncatedSnap | { error: JsonRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\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 function getSnapChecksum(files: FetchedSnapFiles): string {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ].filter((file) => file !== undefined);\n return base64.encode(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 function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== 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});\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\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\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(\n value: unknown,\n): asserts value is ValidatedSnapId {\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"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","auxiliaryFiles","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAYA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AACrC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KA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A6B;IAE7BtG,OACEC,SAASqG,uBACT;IAGF,MAAM,EAAEN,aAAaO,oBAAoB,EAAE,GAAGD;IAE9CtG,OACEC,SAASsG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBvG,OACEwG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBjG,OACEC,SAASiG,WACPA,OAAOC,IAAI,KAAKpF,eAAeqF,OAAO,IACtCnG,SAASiG,OAAOtD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeqF,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\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":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","auxiliaryFiles","localizationFiles","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAQA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AACrC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,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;AAEA;;;;;;CAMC,GACD,OAAO,SAASoB,+BACdC,oBAA6B;IAE7BvG,OACEC,SAASsG,uBACT;IAGF,MAAM,EAAEN,aAAaO,oBAAoB,EAAE,GAAGD;IAE9CvG,OACEC,SAASuG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBxG,OACEyG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBlG,OACEC,SAASkG,WACPA,OAAOC,IAAI,KAAKrF,eAAesF,OAAO,IACtCpG,SAASkG,OAAOvD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAesF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
package/dist/esm/structs.js.map
CHANGED
|
@@ -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, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\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 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":["isObject","bold","green","red","resolve","Struct","StructError","define","literal","superstructLiteral","union","superstructUnion","create","string","coerce","indent","value","JSON","stringify","validator","head","tail","struct","schema","file","process","cwd","named","name","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,WAAWC,kBAAkB,EAC7BC,SAASC,gBAAgB,EACzBC,MAAM,EACNC,MAAM,EACNC,MAAM,QACD,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AAEnC;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASP,QAAgDQ,KAAW;IACzE,OAAOT,OACLU,KAAKC,SAAS,CAACF,QACfP,mBAAmBO,OAAOG,SAAS;AAEvC;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAAST,MAAwD,CACtEU,MACA,GAAGC,KACyB;IAI5B,MAAMC,SAASX,iBAAiB;QAACS;WAASC;KAAK;IAE/C,OAAO,IAAIhB,OAAO;QAChB,GAAGiB,MAAM;QACTC,QAAQ;YAACH;eAASC;SAAK;IACzB;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASG;IACd,OAAOV,OAAOD,UAAUA,UAAU,CAACG;QACjC,OAAOZ,QAAQqB,QAAQC,GAAG,IAAIV;IAChC;AACF;AAEA;;;;;;;;CAQC,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C,EACrE0D,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEzD,IAAI,MAAM,CAAC;QAElE,OAAO,CAAC,EAAE6B,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAE5B,KACrBiC,QAAQW,IAAI,CAACU,IAAI,CAAC,MAClB,YAAY,EAAEE,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEzB,OAAO,yBAAyB,EAAE9B,MAC1CgC,QAAQL,IAAI,EACZ,gBAAgB,EAAE4B,SAAS,CAAC,CAAC;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASpB,sBACdf,MAA4B,EAC5Ba,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASiB,GAAG,CAAC,CAAClB,UACtCnB,OAAO,CAAC,EAAE,EAAEyC,wBAAwBlC,QAAQY,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBN,IAAI,CAAC;AAChC"}
|
|
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, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } 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 `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\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 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":["isObject","bold","green","red","resolve","Struct","StructError","define","literal","superstructLiteral","union","superstructUnion","create","string","coerce","indent","value","JSON","stringify","validator","head","tail","struct","schema","file","process","cwd","named","name","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,WAAWC,kBAAkB,EAC7BC,SAASC,gBAAgB,EACzBC,MAAM,EACNC,MAAM,EACNC,MAAM,QACD,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AA6Bn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../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\
|
|
1
|
+
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AACA,SAASA,YAAY,EAAEC,aAAa,QAAQ,kBAAkB;AAE9D,SACEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,UAAUC,iBAAiB,QACtB,cAAc;WAQd;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKZ,OAAO,MAAMG,aAAaT,KACxBF,QACEG,UACA,gEAEF,GACA,KACA;AAEF,2EAA2E;AAC3E,sBAAsB;AACtB,OAAO,MAAMS,2BAA2BR,KAAK;IAC3CS,SAASlB;IACTmB,MAAMH;IACNI,MAAMhB,SAASG,KAAKC,UAAU,GAAGa;IACjCC,YAAYlB,SACVD,OAAO;QACLM,MAAMF,KAAKC,UAAU,GAAGa;QACxBE,KAAKhB,KAAKC,UAAU,GAAGa;IACzB;AAEJ,GAAG;AAKH;;;;;CAKC,GACD,OAAO,SAASG,qBACdC,KAAc;IAEd,OAAOvB,GAAGuB,OAAOR;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASS,2BACdD,KAAc;IAEd1B,aACE0B,OACAR,0BACA,CAAC,CAAC,EAAEJ,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;WAuCO;UAAKa,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;WAUL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;WAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;AAwBZ,OAAO,MAAMG,MAAM,CAACC,OAAwB,CAAC,CAAC,GAC5CjC,OAAOI,MAAM;QAACF;QAAUP,SAASuC;KAAK,GAAG,OAAO,CAACf;QAC/C,IAAI;YACF,MAAMF,MAAM,IAAIiB,IAAIf;YAEpB,MAAMgB,YAAYhC,KAAK8B;YACvB3B,kBAAkBW,KAAKkB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEhB,MAAMiB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,SAASC,WACdpB,GAAY,EACZgB,OAAwB,CAAC,CAAC;IAE1B,OAAOrC,GAAGqB,KAAKe,IAAIC;AACrB;AAEA,+CAA+C;AAC/C,OAAO,MAAMK,6BAA6B,cAAc"}
|
package/dist/esm/ui.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { NodeType } from '@metamask/snaps-sdk';
|
|
2
|
+
import { assert, AssertionError, hasProperty } from '@metamask/utils';
|
|
3
|
+
const LINK_REGEX = RegExp("(?<protocol>[a-z]+:\\/?\\/?)(?<host>\\S+?(?:\\.[a-z]+)+)", "giu");
|
|
4
|
+
const ALLOWED_PROTOCOLS = [
|
|
5
|
+
'https:',
|
|
6
|
+
'mailto:'
|
|
7
|
+
];
|
|
8
|
+
/**
|
|
9
|
+
* Search for links in a sting and check them against the phishing list.
|
|
10
|
+
*
|
|
11
|
+
* @param text - The text to verify.
|
|
12
|
+
* @param isOnPhishingList - The function that checks the link against the
|
|
13
|
+
* phishing list.
|
|
14
|
+
* @throws If the text contains a link that is not allowed.
|
|
15
|
+
*/ export function validateTextLinks(text, isOnPhishingList) {
|
|
16
|
+
const links = text.match(LINK_REGEX);
|
|
17
|
+
if (links) {
|
|
18
|
+
links.forEach((link)=>{
|
|
19
|
+
try {
|
|
20
|
+
const url = new URL(link);
|
|
21
|
+
assert(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
|
|
22
|
+
const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
|
|
23
|
+
assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
|
|
24
|
+
} catch (error) {
|
|
25
|
+
throw new Error(`Invalid URL: ${error instanceof AssertionError ? error.message : 'Unable to parse URL.'}`);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Search for links in UI components and check that the URL they are trying to
|
|
32
|
+
* pass in is not in the phishing list.
|
|
33
|
+
*
|
|
34
|
+
* @param component - The custom UI component.
|
|
35
|
+
* @param isOnPhishingList - The function that checks the link against the
|
|
36
|
+
* phishing list.
|
|
37
|
+
* @throws If the component contains a link that is not allowed.
|
|
38
|
+
*/ export function validateComponentLinks(component, isOnPhishingList) {
|
|
39
|
+
const { type } = component;
|
|
40
|
+
if (type === NodeType.Panel) {
|
|
41
|
+
component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
|
|
42
|
+
}
|
|
43
|
+
if (hasProperty(component, 'value') && typeof component.value === 'string') {
|
|
44
|
+
validateTextLinks(component.value, isOnPhishingList);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=ui.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError, hasProperty } from '@metamask/utils';\n\nconst LINK_REGEX = /(?<protocol>[a-z]+:\\/?\\/?)(?<host>\\S+?(?:\\.[a-z]+)+)/giu;\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Search for links in a sting and check them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = text.match(LINK_REGEX);\n if (links) {\n links.forEach((link) => {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:'\n ? url.pathname.split('@')[1]\n : url.hostname;\n\n assert(\n !isOnPhishingList(hostname),\n 'The specified URL is not allowed.',\n );\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n });\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (hasProperty(component, 'value') && typeof component.value === 'string') {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["NodeType","assert","AssertionError","hasProperty","LINK_REGEX","ALLOWED_PROTOCOLS","validateTextLinks","text","isOnPhishingList","links","match","forEach","link","url","URL","includes","protocol","join","hostname","pathname","split","error","Error","message","validateComponentLinks","component","type","Panel","children","node","value"],"mappings":"AACA,SAASA,QAAQ,QAAQ,sBAAsB;AAC/C,SAASC,MAAM,EAAEC,cAAc,EAAEC,WAAW,QAAQ,kBAAkB;AAEtE,MAAMC,aAAa;AACnB,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAE/C;;;;;;;CAOC,GACD,OAAO,SAASC,kBACdC,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,QAAQF,KAAKG,KAAK,CAACN;IACzB,IAAIK,OAAO;QACTA,MAAME,OAAO,CAAC,CAACC;YACb,IAAI;gBACF,MAAMC,MAAM,IAAIC,IAAIF;gBACpBX,OACEI,kBAAkBU,QAAQ,CAACF,IAAIG,QAAQ,GACvC,CAAC,yBAAyB,EAAEX,kBAAkBY,IAAI,CAAC,MAAM,CAAC,CAAC;gBAG7D,MAAMC,WACJL,IAAIG,QAAQ,KAAK,YACbH,IAAIM,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAC1BP,IAAIK,QAAQ;gBAElBjB,OACE,CAACO,iBAAiBU,WAClB;YAEJ,EAAE,OAAOG,OAAO;gBACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBnB,iBACbmB,MAAME,OAAO,GACb,uBACL,CAAC;YAEN;QACF;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,uBACdC,SAAoB,EACpBjB,gBAA0C;IAE1C,MAAM,EAAEkB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAAS1B,SAAS2B,KAAK,EAAE;QAC3BF,UAAUG,QAAQ,CAACjB,OAAO,CAAC,CAACkB,OAC1BL,uBAAuBK,MAAMrB;IAEjC;IAEA,IAAIL,YAAYsB,WAAW,YAAY,OAAOA,UAAUK,KAAK,KAAK,UAAU;QAC1ExB,kBAAkBmB,UAAUK,KAAK,EAAEtB;IACrC;AACF"}
|
package/dist/esm/validation.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertIsSnapIcon } from './icon';
|
|
2
|
+
import { validateSnapManifestLocalizations } from './localization';
|
|
2
3
|
import { assertIsSnapManifest } from './manifest/validation';
|
|
3
4
|
import { validateSnapShasum } from './snaps';
|
|
4
5
|
/**
|
|
@@ -6,9 +7,10 @@ import { validateSnapShasum } from './snaps';
|
|
|
6
7
|
*
|
|
7
8
|
* @param files - All potentially included files in a fetched snap.
|
|
8
9
|
* @throws If any of the files are considered invalid.
|
|
9
|
-
*/ export function validateFetchedSnap(files) {
|
|
10
|
+
*/ export async function validateFetchedSnap(files) {
|
|
10
11
|
assertIsSnapManifest(files.manifest.result);
|
|
11
|
-
validateSnapShasum(files);
|
|
12
|
+
await validateSnapShasum(files);
|
|
13
|
+
validateSnapManifestLocalizations(files.manifest.result, files.localizationFiles.map((file)=>file.result));
|
|
12
14
|
if (files.svgIcon) {
|
|
13
15
|
assertIsSnapIcon(files.svgIcon);
|
|
14
16
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(files: FetchedSnapFiles): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["assertIsSnapIcon","assertIsSnapManifest","validateSnapShasum","validateFetchedSnap","files","manifest","result","svgIcon"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,kBAAkB,QAAQ,UAAU;AAG7C;;;;;CAKC,GACD,OAAO,
|
|
1
|
+
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateSnapManifestLocalizations } from './localization';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport async function validateFetchedSnap(\n files: FetchedSnapFiles,\n): Promise<void> {\n assertIsSnapManifest(files.manifest.result);\n await validateSnapShasum(files);\n validateSnapManifestLocalizations(\n files.manifest.result,\n files.localizationFiles.map((file) => file.result),\n );\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["assertIsSnapIcon","validateSnapManifestLocalizations","assertIsSnapManifest","validateSnapShasum","validateFetchedSnap","files","manifest","result","localizationFiles","map","file","svgIcon"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,iCAAiC,QAAQ,iBAAiB;AACnE,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,kBAAkB,QAAQ,UAAU;AAG7C;;;;;CAKC,GACD,OAAO,eAAeC,oBACpBC,KAAuB;IAEvBH,qBAAqBG,MAAMC,QAAQ,CAACC,MAAM;IAC1C,MAAMJ,mBAAmBE;IACzBJ,kCACEI,MAAMC,QAAQ,CAACC,MAAM,EACrBF,MAAMG,iBAAiB,CAACC,GAAG,CAAC,CAACC,OAASA,KAAKH,MAAM;IAGnD,IAAIF,MAAMM,OAAO,EAAE;QACjBX,iBAAiBK,MAAMM,OAAO;IAChC;AACF"}
|
package/dist/types/checksum.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { VirtualFile } from './virtual-file/VirtualFile';
|
|
2
|
+
/**
|
|
3
|
+
* Convert an input value to a Uint8Array for use in a checksum.
|
|
4
|
+
*
|
|
5
|
+
* @param bytes - A value to use for a checksum calculation.
|
|
6
|
+
* @returns The input value converted to a Uint8Array if necessary.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getChecksumBytes(bytes: VirtualFile | Uint8Array | string): Uint8Array;
|
|
2
9
|
/**
|
|
3
10
|
* Calculates checksum for a single byte array.
|
|
4
11
|
*
|
|
5
12
|
* @param bytes - The byte array to calculate the checksum for.
|
|
6
13
|
* @returns A single sha-256 checksum.
|
|
7
14
|
*/
|
|
8
|
-
export declare function checksum(bytes: VirtualFile | Uint8Array | string): Uint8Array
|
|
15
|
+
export declare function checksum(bytes: VirtualFile | Uint8Array | string): Promise<Uint8Array>;
|
|
9
16
|
/**
|
|
10
17
|
* Calculates checksum over multiple files in a reproducible way.
|
|
11
18
|
*
|
|
@@ -18,4 +25,4 @@ export declare function checksum(bytes: VirtualFile | Uint8Array | string): Uint
|
|
|
18
25
|
* @param files - The files over which to calculate the checksum.
|
|
19
26
|
* @returns A single sha-256 checksum.
|
|
20
27
|
*/
|
|
21
|
-
export declare function checksumFiles(files: VirtualFile[]): Uint8Array
|
|
28
|
+
export declare function checksumFiles(files: VirtualFile[]): Promise<Uint8Array>;
|
package/dist/types/enum.d.ts
CHANGED
|
@@ -1,25 +1,5 @@
|
|
|
1
|
+
import type { EnumToUnion } from '@metamask/snaps-sdk';
|
|
1
2
|
import type { Struct } from 'superstruct';
|
|
2
|
-
/**
|
|
3
|
-
* Get the enum values as union type. This allows using both the enum string
|
|
4
|
-
* values and the enum itself as values.
|
|
5
|
-
*
|
|
6
|
-
* Note: This only works for string enums.
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* ```typescript
|
|
10
|
-
* enum Foo {
|
|
11
|
-
* Bar = 'bar',
|
|
12
|
-
* Baz = 'baz',
|
|
13
|
-
* }
|
|
14
|
-
*
|
|
15
|
-
* type FooValue = EnumToUnion<Foo>;
|
|
16
|
-
* // FooValue is 'bar' | 'baz'
|
|
17
|
-
*
|
|
18
|
-
* const foo: FooValue = Foo.Bar; // Works
|
|
19
|
-
* const foo: FooValue = 'bar'; // Also works
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
export declare type EnumToUnion<Type extends string> = `${Type}`;
|
|
23
3
|
/**
|
|
24
4
|
* Superstruct struct for validating an enum value. This allows using both the
|
|
25
5
|
* enum string values and the enum itself as values.
|
package/dist/types/errors.d.ts
CHANGED
|
@@ -1,45 +1,9 @@
|
|
|
1
1
|
import { JsonRpcError as RpcError } from '@metamask/rpc-errors';
|
|
2
2
|
import type { DataWithOptionalCause } from '@metamask/rpc-errors';
|
|
3
|
+
import type { SerializedSnapError, SnapError } from '@metamask/snaps-sdk';
|
|
3
4
|
import type { Json, JsonRpcError } from '@metamask/utils';
|
|
4
|
-
/**
|
|
5
|
-
* Get the error message from an unknown error type.
|
|
6
|
-
*
|
|
7
|
-
* - If the error is an object with a `message` property, return the message.
|
|
8
|
-
* - Otherwise, return the error converted to a string.
|
|
9
|
-
*
|
|
10
|
-
* @param error - The error to get the message from.
|
|
11
|
-
* @returns The error message.
|
|
12
|
-
*/
|
|
13
|
-
export declare function getErrorMessage(error: unknown): string;
|
|
14
|
-
/**
|
|
15
|
-
* Get the error stack from an unknown error type.
|
|
16
|
-
*
|
|
17
|
-
* @param error - The error to get the stack from.
|
|
18
|
-
* @returns The error stack, or undefined if the error does not have a valid
|
|
19
|
-
* stack.
|
|
20
|
-
*/
|
|
21
|
-
export declare function getErrorStack(error: unknown): string | undefined;
|
|
22
|
-
/**
|
|
23
|
-
* Get the error code from an unknown error type.
|
|
24
|
-
*
|
|
25
|
-
* @param error - The error to get the code from.
|
|
26
|
-
* @returns The error code, or `-32603` if the error does not have a valid code.
|
|
27
|
-
*/
|
|
28
|
-
export declare function getErrorCode(error: unknown): number;
|
|
29
|
-
/**
|
|
30
|
-
* Get the error data from an unknown error type.
|
|
31
|
-
*
|
|
32
|
-
* @param error - The error to get the data from.
|
|
33
|
-
* @returns The error data, or an empty object if the error does not have valid
|
|
34
|
-
* data.
|
|
35
|
-
*/
|
|
36
|
-
export declare function getErrorData(error: unknown): {
|
|
37
|
-
[prop: string]: Json;
|
|
38
|
-
};
|
|
39
5
|
export declare const SNAP_ERROR_WRAPPER_CODE = -31001;
|
|
40
6
|
export declare const SNAP_ERROR_WRAPPER_MESSAGE = "Wrapped Snap Error";
|
|
41
|
-
export declare const SNAP_ERROR_CODE = -31002;
|
|
42
|
-
export declare const SNAP_ERROR_MESSAGE = "Snap Error";
|
|
43
7
|
export declare type SerializedSnapErrorWrapper = {
|
|
44
8
|
code: typeof SNAP_ERROR_WRAPPER_CODE;
|
|
45
9
|
message: typeof SNAP_ERROR_WRAPPER_MESSAGE;
|
|
@@ -47,15 +11,6 @@ export declare type SerializedSnapErrorWrapper = {
|
|
|
47
11
|
cause: Json;
|
|
48
12
|
};
|
|
49
13
|
};
|
|
50
|
-
export declare type SerializedSnapError = {
|
|
51
|
-
code: typeof SNAP_ERROR_CODE;
|
|
52
|
-
message: typeof SNAP_ERROR_MESSAGE;
|
|
53
|
-
data: {
|
|
54
|
-
cause: JsonRpcError & {
|
|
55
|
-
data: Record<string, Json>;
|
|
56
|
-
};
|
|
57
|
-
};
|
|
58
|
-
};
|
|
59
14
|
export declare class WrappedSnapError extends Error {
|
|
60
15
|
#private;
|
|
61
16
|
/**
|
|
@@ -96,69 +51,6 @@ export declare class WrappedSnapError extends Error {
|
|
|
96
51
|
*/
|
|
97
52
|
serialize(): SerializedSnapErrorWrapper;
|
|
98
53
|
}
|
|
99
|
-
/**
|
|
100
|
-
* A generic error which can be thrown by a Snap, without it causing the Snap to
|
|
101
|
-
* crash.
|
|
102
|
-
*/
|
|
103
|
-
export declare class SnapError extends Error {
|
|
104
|
-
#private;
|
|
105
|
-
/**
|
|
106
|
-
* Create a new `SnapError`.
|
|
107
|
-
*
|
|
108
|
-
* @param error - The error to create the `SnapError` from. If this is a
|
|
109
|
-
* `string`, it will be used as the error message. If this is an `Error`, its
|
|
110
|
-
* `message` property will be used as the error message. If this is a
|
|
111
|
-
* `JsonRpcError`, its `message` property will be used as the error message
|
|
112
|
-
* and its `code` property will be used as the error code. Otherwise, the
|
|
113
|
-
* error will be converted to a string and used as the error message.
|
|
114
|
-
* @param data - Additional data to include in the error. This will be merged
|
|
115
|
-
* with the error data, if any.
|
|
116
|
-
*/
|
|
117
|
-
constructor(error: string | Error | JsonRpcError, data?: Record<string, Json>);
|
|
118
|
-
/**
|
|
119
|
-
* The error name.
|
|
120
|
-
*
|
|
121
|
-
* @returns The error name.
|
|
122
|
-
*/
|
|
123
|
-
get name(): string;
|
|
124
|
-
/**
|
|
125
|
-
* The error code.
|
|
126
|
-
*
|
|
127
|
-
* @returns The error code.
|
|
128
|
-
*/
|
|
129
|
-
get code(): number;
|
|
130
|
-
/**
|
|
131
|
-
* The error message.
|
|
132
|
-
*
|
|
133
|
-
* @returns The error message.
|
|
134
|
-
*/
|
|
135
|
-
get message(): string;
|
|
136
|
-
/**
|
|
137
|
-
* Additional data for the error.
|
|
138
|
-
*
|
|
139
|
-
* @returns Additional data for the error.
|
|
140
|
-
*/
|
|
141
|
-
get data(): Record<string, Json>;
|
|
142
|
-
/**
|
|
143
|
-
* The error stack.
|
|
144
|
-
*
|
|
145
|
-
* @returns The error stack.
|
|
146
|
-
*/
|
|
147
|
-
get stack(): string | undefined;
|
|
148
|
-
/**
|
|
149
|
-
* Convert the error to a JSON object.
|
|
150
|
-
*
|
|
151
|
-
* @returns The JSON object.
|
|
152
|
-
*/
|
|
153
|
-
toJSON(): SerializedSnapError;
|
|
154
|
-
/**
|
|
155
|
-
* Serialize the error to a JSON object. This is called by
|
|
156
|
-
* `@metamask/rpc-errors` when serializing the error.
|
|
157
|
-
*
|
|
158
|
-
* @returns The JSON object.
|
|
159
|
-
*/
|
|
160
|
-
serialize(): SerializedSnapError;
|
|
161
|
-
}
|
|
162
54
|
/**
|
|
163
55
|
* Check if an object is a `SnapError`.
|
|
164
56
|
*
|
|
@@ -5,7 +5,8 @@ export declare enum HandlerType {
|
|
|
5
5
|
OnInstall = "onInstall",
|
|
6
6
|
OnUpdate = "onUpdate",
|
|
7
7
|
OnNameLookup = "onNameLookup",
|
|
8
|
-
OnKeyringRequest = "onKeyringRequest"
|
|
8
|
+
OnKeyringRequest = "onKeyringRequest",
|
|
9
|
+
OnHomePage = "onHomePage"
|
|
9
10
|
}
|
|
10
11
|
export declare type SnapHandler = {
|
|
11
12
|
/**
|