@metamask/snaps-utils 5.2.0 → 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.
- package/CHANGELOG.md +18 -3
- package/dist/cjs/caveats.js +6 -0
- package/dist/cjs/caveats.js.map +1 -1
- package/dist/cjs/eval-worker.js +3 -1
- package/dist/cjs/eval-worker.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 +74 -3
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/manifest/validation.js +50 -14
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/structs.js +86 -17
- package/dist/cjs/structs.js.map +1 -1
- package/dist/esm/caveats.js +6 -0
- package/dist/esm/caveats.js.map +1 -1
- package/dist/esm/eval-worker.js +3 -1
- package/dist/esm/eval-worker.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 +45 -4
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/manifest/validation.js +38 -16
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/structs.js +133 -21
- package/dist/esm/structs.js.map +1 -1
- package/dist/types/caveats.d.ts +9 -1
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +349 -10
- package/dist/types/localization.d.ts +33 -13
- package/dist/types/manifest/validation.d.ts +230 -75
- package/dist/types/structs.d.ts +61 -7
- package/package.json +4 -4
package/dist/cjs/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 } 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;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzRS;uBACQ;sBACT;6BAEoC;yBAGrC;AAgDhB,SAASV;IACd,OAAOW,IAAAA,mBAAM,EAACC,IAAAA,mBAAM,KAAIA,IAAAA,mBAAM,KAAI,CAACC;QACjC,OAAOC,IAAAA,aAAO,EAACC,QAAQC,GAAG,IAAIH;IAChC;AACF;AAWO,SAASZ,MACdgB,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIC,mBAAM,CAAC;QAChB,GAAGD,MAAM;QACTE,MAAMH;IACR;AACF;AAEO,MAAMf,yBAAuCmB,wBAAW;IAC7DC,YACEJ,MAA4B,EAC5BK,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,CAClC;QACA,KAAK,CAACD,SAASC;QAEf,IAAI,CAACT,IAAI,GAAG;QACZ,IAAI,CAACU,OAAO,GAAG,CAAC,EAAEJ,OAAO,KAAK,EAAEb,sBAAsBQ,QAAQ;eACzDQ;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AASnC,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;;IA6EAC,qBAAqB;eAArBA;;IA0CAC,aAAa;eAAbA;;IAoFAC,WAAW;eAAXA;;;0BApeM;uBAEW;uBACA;sBACT;6BAWjB;yBAGgB;AA6BvB;;;;;;;;;;CAUC,GACD,SAASC,MACPC,KAAa,EACbC,aAAwC,EACxCC,OAAgB;IAEhB,IAAIA,SAAS;QACX,OAAOD,cAAcD;IACvB;IAEA,OAAOA;AACT;AAqBO,SAASd;IACd,OAAOiB,IAAAA,mBAAiB,EAACC,IAAAA,mBAAM,KAAIA,IAAAA,mBAAM,KAAI,CAACJ;QAC5C,OAAOK,IAAAA,aAAO,EAACC,QAAQC,GAAG,IAAIP;IAChC;AACF;AAWO,SAASb,MACdqB,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIC,mBAAM,CAAC;QAChB,GAAGD,MAAM;QACTE,MAAMH;IACR;AACF;AAEO,MAAMpB,yBAAuCwB,wBAAW;IAC7DC,YACEJ,MAA4B,EAC5BK,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,EAClCC,WAAW,IAAI,CACf;QACA,KAAK,CAACF,SAASC;QAEf,IAAI,CAAC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AAE;AAEnE;AAkBO,SAASnB,YACdE,KAAc,EACdS,MAA4B,EAC5BsC,SAAqB;IAErB,OAAOlD,cAAcG,OAAOS,QAAQsC,WAAW;AACjD"}
|
package/dist/esm/caveats.js
CHANGED
|
@@ -27,6 +27,12 @@ export var SnapCaveatType;
|
|
|
27
27
|
SnapCaveatType[/**
|
|
28
28
|
* Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
|
|
29
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';
|
|
30
36
|
})(SnapCaveatType || (SnapCaveatType = {}));
|
|
31
37
|
|
|
32
38
|
//# sourceMappingURL=caveats.js.map
|
package/dist/esm/caveats.js.map
CHANGED
|
@@ -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 * 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"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","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,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;
|
|
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"}
|
package/dist/esm/eval-worker.js
CHANGED
|
@@ -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
|
-
|
|
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\
|
|
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"}
|
|
@@ -9,6 +9,7 @@ export var HandlerType;
|
|
|
9
9
|
HandlerType["OnNameLookup"] = 'onNameLookup';
|
|
10
10
|
HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
|
|
11
11
|
HandlerType["OnHomePage"] = 'onHomePage';
|
|
12
|
+
HandlerType["OnUserInput"] = 'onUserInput';
|
|
12
13
|
})(HandlerType || (HandlerType = {}));
|
|
13
14
|
export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
|
|
14
15
|
|
|
@@ -1 +1 @@
|
|
|
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}\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","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;
|
|
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"}
|
package/dist/esm/handlers.js
CHANGED
|
@@ -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]: {
|
|
@@ -64,15 +64,56 @@ export const SNAP_EXPORTS = {
|
|
|
64
64
|
validator: (snapExport)=>{
|
|
65
65
|
return typeof snapExport === 'function';
|
|
66
66
|
}
|
|
67
|
+
},
|
|
68
|
+
[HandlerType.OnUserInput]: {
|
|
69
|
+
type: HandlerType.OnUserInput,
|
|
70
|
+
required: true,
|
|
71
|
+
validator: (snapExport)=>{
|
|
72
|
+
return typeof snapExport === 'function';
|
|
73
|
+
}
|
|
67
74
|
}
|
|
68
75
|
};
|
|
69
|
-
export const
|
|
70
|
-
content: ComponentStruct,
|
|
76
|
+
export const OnTransactionSeverityResponseStruct = object({
|
|
71
77
|
severity: optional(literal(SeverityLevel.Critical))
|
|
78
|
+
});
|
|
79
|
+
export const OnTransactionResponseWithIdStruct = assign(OnTransactionSeverityResponseStruct, object({
|
|
80
|
+
id: string()
|
|
72
81
|
}));
|
|
82
|
+
export const OnTransactionResponseWithContentStruct = assign(OnTransactionSeverityResponseStruct, object({
|
|
83
|
+
content: ComponentStruct
|
|
84
|
+
}));
|
|
85
|
+
export const OnTransactionResponseStruct = nullable(union([
|
|
86
|
+
OnTransactionResponseWithContentStruct,
|
|
87
|
+
OnTransactionResponseWithIdStruct
|
|
88
|
+
]));
|
|
73
89
|
export const OnSignatureResponseStruct = OnTransactionResponseStruct;
|
|
74
|
-
export const
|
|
90
|
+
export const OnHomePageResponseWithContentStruct = object({
|
|
75
91
|
content: ComponentStruct
|
|
76
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)
|
|
113
|
+
});
|
|
114
|
+
export const OnNameLookupResponseStruct = nullable(union([
|
|
115
|
+
AddressResolutionResponseStruct,
|
|
116
|
+
DomainResolutionResponseStruct
|
|
117
|
+
]));
|
|
77
118
|
|
|
78
119
|
//# sourceMappingURL=handlers.js.map
|
package/dist/esm/handlers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnSignatureHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n} from '@metamask/snaps-sdk';\nimport { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnSignatureHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n OnUserInputHandler,\n} from '@metamask/snaps-sdk';\nimport { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';\nimport {\n assign,\n literal,\n nullable,\n object,\n optional,\n string,\n array,\n size,\n union,\n} from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnSignature]: {\n type: HandlerType.OnSignature,\n required: true,\n validator: (snapExport: unknown): snapExport is OnSignatureHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUserInput]: {\n type: HandlerType.OnUserInput,\n required: true,\n validator: (snapExport: unknown): snapExport is OnUserInputHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\nexport const OnTransactionSeverityResponseStruct = object({\n severity: optional(literal(SeverityLevel.Critical)),\n});\n\nexport const OnTransactionResponseWithIdStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n id: string(),\n }),\n);\n\nexport const OnTransactionResponseWithContentStruct = assign(\n OnTransactionSeverityResponseStruct,\n object({\n content: ComponentStruct,\n }),\n);\n\nexport const OnTransactionResponseStruct = nullable(\n union([\n OnTransactionResponseWithContentStruct,\n OnTransactionResponseWithIdStruct,\n ]),\n);\n\nexport const OnSignatureResponseStruct = OnTransactionResponseStruct;\n\nexport const OnHomePageResponseWithContentStruct = object({\n content: ComponentStruct,\n});\n\nexport const OnHomePageResponseWithIdStruct = object({\n id: string(),\n});\n\nexport const OnHomePageResponseStruct = union([\n OnHomePageResponseWithContentStruct,\n OnHomePageResponseWithIdStruct,\n]);\n\nexport const AddressResolutionStruct = object({\n protocol: string(),\n resolvedDomain: string(),\n});\n\nexport const DomainResolutionStruct = object({\n protocol: string(),\n resolvedAddress: string(),\n});\n\nexport const AddressResolutionResponseStruct = object({\n resolvedDomains: size(array(AddressResolutionStruct), 1, Infinity),\n});\n\nexport const DomainResolutionResponseStruct = object({\n resolvedAddresses: size(array(DomainResolutionStruct), 1, Infinity),\n});\n\nexport const OnNameLookupResponseStruct = nullable(\n union([AddressResolutionResponseStruct, DomainResolutionResponseStruct]),\n);\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n (typeof SNAP_EXPORTS)[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["SeverityLevel","ComponentStruct","assign","literal","nullable","object","optional","string","array","size","union","HandlerType","SNAP_EXPORTS","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","OnSignature","OnUserInput","OnTransactionSeverityResponseStruct","severity","Critical","OnTransactionResponseWithIdStruct","id","OnTransactionResponseWithContentStruct","content","OnTransactionResponseStruct","OnSignatureResponseStruct","OnHomePageResponseWithContentStruct","OnHomePageResponseWithIdStruct","OnHomePageResponseStruct","AddressResolutionStruct","protocol","resolvedDomain","DomainResolutionStruct","resolvedAddress","AddressResolutionResponseStruct","resolvedDomains","Infinity","DomainResolutionResponseStruct","resolvedAddresses","OnNameLookupResponseStruct"],"mappings":"AAYA,SAASA,aAAa,EAAEC,eAAe,QAAQ,sBAAsB;AACrE,SACEC,MAAM,EACNC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,KAAK,EACLC,IAAI,EACJC,KAAK,QACA,cAAc;AAGrB,SAASC,WAAW,QAAQ,kBAAkB;AAQ9C,OAAO,MAAMC,eAAe;IAC1B,CAACD,YAAYE,YAAY,CAAC,EAAE;QAC1BC,MAAMH,YAAYE,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA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,sCAAsCtB,OAAO;IACxDuB,UAAUtB,SAASH,QAAQH,cAAc6B,QAAQ;AACnD,GAAG;AAEH,OAAO,MAAMC,oCAAoC5B,OAC/CyB,qCACAtB,OAAO;IACL0B,IAAIxB;AACN,IACA;AAEF,OAAO,MAAMyB,yCAAyC9B,OACpDyB,qCACAtB,OAAO;IACL4B,SAAShC;AACX,IACA;AAEF,OAAO,MAAMiC,8BAA8B9B,SACzCM,MAAM;IACJsB;IACAF;CACD,GACD;AAEF,OAAO,MAAMK,4BAA4BD,4BAA4B;AAErE,OAAO,MAAME,sCAAsC/B,OAAO;IACxD4B,SAAShC;AACX,GAAG;AAEH,OAAO,MAAMoC,iCAAiChC,OAAO;IACnD0B,IAAIxB;AACN,GAAG;AAEH,OAAO,MAAM+B,2BAA2B5B,MAAM;IAC5C0B;IACAC;CACD,EAAE;AAEH,OAAO,MAAME,0BAA0BlC,OAAO;IAC5CmC,UAAUjC;IACVkC,gBAAgBlC;AAClB,GAAG;AAEH,OAAO,MAAMmC,yBAAyBrC,OAAO;IAC3CmC,UAAUjC;IACVoC,iBAAiBpC;AACnB,GAAG;AAEH,OAAO,MAAMqC,kCAAkCvC,OAAO;IACpDwC,iBAAiBpC,KAAKD,MAAM+B,0BAA0B,GAAGO;AAC3D,GAAG;AAEH,OAAO,MAAMC,iCAAiC1C,OAAO;IACnD2C,mBAAmBvC,KAAKD,MAAMkC,yBAAyB,GAAGI;AAC5D,GAAG;AAEH,OAAO,MAAMG,6BAA6B7C,SACxCM,MAAM;IAACkC;IAAiCG;CAA+B,GACvE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isValidBIP32PathSegment } from '@metamask/key-tree';
|
|
2
|
-
import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange } from '@metamask/utils';
|
|
3
|
-
import { array, boolean, create, enums, integer, is, literal, object, optional, refine, record, size, string, type, union, intersection } from 'superstruct';
|
|
2
|
+
import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange, inMilliseconds, Duration } from '@metamask/utils';
|
|
3
|
+
import { array, boolean, create, enums, integer, is, literal, object, optional, refine, record, size, string, type, union, intersection, assign } from 'superstruct';
|
|
4
4
|
import { isEqual } from '../array';
|
|
5
5
|
import { CronjobSpecificationArrayStruct } from '../cronjob';
|
|
6
6
|
import { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';
|
|
@@ -72,26 +72,48 @@ export const SnapIdsStruct = refine(record(SnapIdStruct, object({
|
|
|
72
72
|
}
|
|
73
73
|
return true;
|
|
74
74
|
});
|
|
75
|
-
export const ChainIdsStruct = array(ChainIdStruct);
|
|
75
|
+
export const ChainIdsStruct = size(array(ChainIdStruct), 1, Infinity);
|
|
76
|
+
export const LookupMatchersStruct = union([
|
|
77
|
+
object({
|
|
78
|
+
tlds: size(array(string()), 1, Infinity)
|
|
79
|
+
}),
|
|
80
|
+
object({
|
|
81
|
+
schemes: size(array(string()), 1, Infinity)
|
|
82
|
+
}),
|
|
83
|
+
object({
|
|
84
|
+
tlds: size(array(string()), 1, Infinity),
|
|
85
|
+
schemes: size(array(string()), 1, Infinity)
|
|
86
|
+
})
|
|
87
|
+
]);
|
|
88
|
+
export const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);
|
|
89
|
+
export const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);
|
|
90
|
+
export const MaxRequestTimeStruct = size(integer(), MINIMUM_REQUEST_TIMEOUT, MAXIMUM_REQUEST_TIMEOUT);
|
|
91
|
+
// Utility type to union with for all handler structs
|
|
92
|
+
export const HandlerCaveatsStruct = object({
|
|
93
|
+
maxRequestTime: optional(MaxRequestTimeStruct)
|
|
94
|
+
});
|
|
76
95
|
/* eslint-disable @typescript-eslint/naming-convention */ export const PermissionsStruct = type({
|
|
96
|
+
'endowment:cronjob': optional(assign(HandlerCaveatsStruct, object({
|
|
97
|
+
jobs: CronjobSpecificationArrayStruct
|
|
98
|
+
}))),
|
|
77
99
|
'endowment:ethereum-provider': optional(object({})),
|
|
100
|
+
'endowment:keyring': optional(assign(HandlerCaveatsStruct, KeyringOriginsStruct)),
|
|
101
|
+
'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),
|
|
102
|
+
'endowment:name-lookup': optional(assign(HandlerCaveatsStruct, object({
|
|
103
|
+
chains: optional(ChainIdsStruct),
|
|
104
|
+
matchers: optional(LookupMatchersStruct)
|
|
105
|
+
}))),
|
|
78
106
|
'endowment:network-access': optional(object({})),
|
|
79
|
-
'endowment:
|
|
80
|
-
'endowment:
|
|
107
|
+
'endowment:page-home': optional(HandlerCaveatsStruct),
|
|
108
|
+
'endowment:rpc': optional(RpcOriginsStruct),
|
|
109
|
+
'endowment:signature-insight': optional(assign(HandlerCaveatsStruct, object({
|
|
81
110
|
allowSignatureOrigin: optional(boolean())
|
|
82
|
-
})),
|
|
83
|
-
'endowment:transaction-insight': optional(object({
|
|
111
|
+
}))),
|
|
112
|
+
'endowment:transaction-insight': optional(assign(HandlerCaveatsStruct, object({
|
|
84
113
|
allowTransactionOrigin: optional(boolean())
|
|
85
|
-
})),
|
|
86
|
-
'endowment:
|
|
87
|
-
jobs: CronjobSpecificationArrayStruct
|
|
88
|
-
})),
|
|
89
|
-
'endowment:rpc': optional(RpcOriginsStruct),
|
|
90
|
-
'endowment:name-lookup': optional(ChainIdsStruct),
|
|
91
|
-
'endowment:keyring': optional(KeyringOriginsStruct),
|
|
114
|
+
}))),
|
|
115
|
+
'endowment:webassembly': optional(object({})),
|
|
92
116
|
snap_dialog: optional(object({})),
|
|
93
|
-
// TODO: Remove
|
|
94
|
-
snap_confirm: optional(object({})),
|
|
95
117
|
snap_manageState: optional(object({})),
|
|
96
118
|
snap_manageAccounts: optional(object({})),
|
|
97
119
|
snap_notify: optional(object({})),
|
|
@@ -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 intersection,\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 = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:signature-insight': optional(\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\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 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":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","refine","record","size","string","type","union","intersection","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","uri","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","PermissionsStruct","allowSignatureOrigin","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","snap_getLocale","wallet_snap","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],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C;gBAC5BkC,UAAU1E,SAASG,KAAKC,UAAU,GAAGoC;gBACrCmC,aAAa3D;gBACb4D,UAAUtE,MAAM;oBACdR,QAAQ;oBACRA,QAAQ;iBACT;YACH;QACF;QACA+E,OAAO7E,SAAS8D;QAChBgB,SAAS9E,SAAS8D;IACpB;IACAiB,oBAAoB/E,SAAS+D;IAC7BiB,oBAAoBjC;IACpBkC,iBAAiBnF,QAAQ;IACzBoF,SAASlF,SAASI;AACpB,GAAG;AAIH;;;;;CAKC,GACD,OAAO,SAAS+E,eAAehD,KAAc;IAC3C,OAAOtC,GAAGsC,OAAO6B;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASoB,qBACdjD,KAAc;IAEd/C,aACE+C,OACA6B,oBACA,CAAC,CAAC,EAAE/C,iBAAiBoE,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmBnD,KAAc;IAC/C,qEAAqE;IACrE,OAAOzC,OAAOyC,OAAO6B;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":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","inMilliseconds","Duration","array","boolean","create","enums","integer","is","literal","object","optional","refine","record","size","string","type","union","intersection","assign","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","uri","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","LookupMatchersStruct","tlds","schemes","MINIMUM_REQUEST_TIMEOUT","Second","MAXIMUM_REQUEST_TIMEOUT","Minute","MaxRequestTimeStruct","HandlerCaveatsStruct","maxRequestTime","PermissionsStruct","jobs","chains","matchers","allowSignatureOrigin","allowTransactionOrigin","snap_dialog","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","snap_getLocale","wallet_snap","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAE7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,cAAc,EACdC,QAAQ,QACH,kBAAkB;AAEzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,EAAE,EACFC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,YAAY,EACZC,MAAM,QACD,cAAc;AAErB,SAASC,OAAO,QAAQ,WAAW;AACnC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,iBAAiB,EAAEC,4BAA4B,QAAQ,aAAa;AAC7E,SAASC,oBAAoB,EAAEC,gBAAgB,QAAQ,cAAc;AACrE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SAASC,YAAY,QAAQ,WAAW;AAExC,SAASC,UAAU,EAAEC,gBAAgB,EAAEC,GAAG,QAAQ,WAAW;AAE7D,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCT;IACAC;CACD;AAED,OAAO,MAAMS,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC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