@metamask/snaps-utils 9.0.0 → 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/eval-worker.cjs +1 -1
  3. package/dist/eval-worker.cjs.map +1 -1
  4. package/dist/eval-worker.mjs +1 -1
  5. package/dist/eval-worker.mjs.map +1 -1
  6. package/dist/fs.cjs +1 -1
  7. package/dist/fs.cjs.map +1 -1
  8. package/dist/fs.mjs +1 -1
  9. package/dist/fs.mjs.map +1 -1
  10. package/dist/iframe.cjs +0 -1
  11. package/dist/iframe.cjs.map +1 -1
  12. package/dist/iframe.d.cts +0 -1
  13. package/dist/iframe.d.cts.map +1 -1
  14. package/dist/iframe.d.mts +0 -1
  15. package/dist/iframe.d.mts.map +1 -1
  16. package/dist/iframe.mjs +0 -1
  17. package/dist/iframe.mjs.map +1 -1
  18. package/dist/index.cjs +0 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.cts.map +1 -1
  22. package/dist/index.d.mts +1 -1
  23. package/dist/index.d.mts.map +1 -1
  24. package/dist/index.mjs +0 -1
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/json-rpc.cjs +2 -6
  27. package/dist/json-rpc.cjs.map +1 -1
  28. package/dist/json-rpc.d.cts.map +1 -1
  29. package/dist/json-rpc.d.mts.map +1 -1
  30. package/dist/json-rpc.mjs +2 -6
  31. package/dist/json-rpc.mjs.map +1 -1
  32. package/dist/manifest/manifest.cjs +1 -1
  33. package/dist/manifest/manifest.cjs.map +1 -1
  34. package/dist/manifest/manifest.d.cts +2 -2
  35. package/dist/manifest/manifest.d.cts.map +1 -1
  36. package/dist/manifest/manifest.d.mts +2 -2
  37. package/dist/manifest/manifest.d.mts.map +1 -1
  38. package/dist/manifest/manifest.mjs +1 -1
  39. package/dist/manifest/manifest.mjs.map +1 -1
  40. package/dist/manifest/validator-types.cjs.map +1 -1
  41. package/dist/manifest/validator-types.d.cts +1 -1
  42. package/dist/manifest/validator-types.d.cts.map +1 -1
  43. package/dist/manifest/validator-types.d.mts +1 -1
  44. package/dist/manifest/validator-types.d.mts.map +1 -1
  45. package/dist/manifest/validator-types.mjs.map +1 -1
  46. package/dist/manifest/validator.cjs.map +1 -1
  47. package/dist/manifest/validator.d.cts +1 -1
  48. package/dist/manifest/validator.d.cts.map +1 -1
  49. package/dist/manifest/validator.d.mts +1 -1
  50. package/dist/manifest/validator.d.mts.map +1 -1
  51. package/dist/manifest/validator.mjs.map +1 -1
  52. package/dist/manifest/validators/platform-version.cjs +1 -1
  53. package/dist/manifest/validators/platform-version.cjs.map +1 -1
  54. package/dist/manifest/validators/platform-version.mjs +1 -1
  55. package/dist/manifest/validators/platform-version.mjs.map +1 -1
  56. package/dist/mock.cjs +0 -3
  57. package/dist/mock.cjs.map +1 -1
  58. package/dist/mock.d.cts.map +1 -1
  59. package/dist/mock.d.mts.map +1 -1
  60. package/dist/mock.mjs +0 -3
  61. package/dist/mock.mjs.map +1 -1
  62. package/dist/node.cjs +1 -1
  63. package/dist/node.cjs.map +1 -1
  64. package/dist/node.mjs +1 -1
  65. package/dist/node.mjs.map +1 -1
  66. package/dist/post-process.cjs.map +1 -1
  67. package/dist/post-process.d.cts.map +1 -1
  68. package/dist/post-process.d.mts.map +1 -1
  69. package/dist/post-process.mjs.map +1 -1
  70. package/dist/snaps.cjs +21 -3
  71. package/dist/snaps.cjs.map +1 -1
  72. package/dist/snaps.d.cts +2 -1
  73. package/dist/snaps.d.cts.map +1 -1
  74. package/dist/snaps.d.mts +2 -1
  75. package/dist/snaps.d.mts.map +1 -1
  76. package/dist/snaps.mjs +22 -4
  77. package/dist/snaps.mjs.map +1 -1
  78. package/dist/types.cjs +1 -1
  79. package/dist/types.cjs.map +1 -1
  80. package/dist/types.d.cts.map +1 -1
  81. package/dist/types.d.mts.map +1 -1
  82. package/dist/types.mjs +3 -3
  83. package/dist/types.mjs.map +1 -1
  84. package/dist/ui.cjs +7 -5
  85. package/dist/ui.cjs.map +1 -1
  86. package/dist/ui.d.cts.map +1 -1
  87. package/dist/ui.d.mts.map +1 -1
  88. package/dist/ui.mjs +7 -5
  89. package/dist/ui.mjs.map +1 -1
  90. package/dist/virtual-file/VirtualFile.cjs.map +1 -1
  91. package/dist/virtual-file/VirtualFile.mjs.map +1 -1
  92. package/package.json +8 -22
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAElC,4BAAkB;AAClB,2BAAuB;AACvB,yBAAqB;AACrB,oCAAgC;AAChC,2BAAuB;AACvB,mCAA+B;AAC/B,wCAAoC","sourcesContent":["/* eslint-disable import/export */\n\nexport * from '.';\nexport * from './eval';\nexport * from './fs';\nexport * from './manifest/node';\nexport * from './mock';\nexport * from './post-process';\nexport * from './virtual-file/node';\n"]}
1
+ {"version":3,"file":"node.mjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,oCAAoC;AAEpC,4BAAkB;AAClB,2BAAuB;AACvB,yBAAqB;AACrB,oCAAgC;AAChC,2BAAuB;AACvB,mCAA+B;AAC/B,wCAAoC","sourcesContent":["/* eslint-disable import-x/export */\n\nexport * from '.';\nexport * from './eval';\nexport * from './fs';\nexport * from './manifest/node';\nexport * from './mock';\nexport * from './post-process';\nexport * from './virtual-file/node';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"post-process.cjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAEA,sCAAsD;AAEtD,wCAOsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,kCAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;A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,CAAC;SAC/B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC;AAhSD,8CAgSC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(--)(!)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
1
+ {"version":3,"file":"post-process.cjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AACA,sCAAsD;AAEtD,wCAOsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,kCAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;AAEtE,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,WAA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,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC/B,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,IAAA,oBAAa,EAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC;AAhSD,8CAgSC","sourcesContent":["import type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(--)(!)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"post-process.d.cts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AAaA;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,SAAS,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC/B,cAAc,CAAC,EAAE,SAAS,CAAC;CAC5B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;IAC7B,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAChC,CAAC;AAEF,oBAAY,kBAAkB;IAC5B,gBAAgB,gLAAgL;CACjM;AA+HD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,EACE,aAAoB,EACpB,SAAS,EAAE,UAAU,EACrB,cAAc,GACf,GAAE,OAAO,CAAC,kBAAkB,CAAM,GAClC,mBAAmB,CAyRrB"}
1
+ {"version":3,"file":"post-process.d.cts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AAYA;;;G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AC,KAAK,CAAC,CAAC;gBAExE,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC/B,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(--)(!)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
1
+ {"version":3,"file":"post-process.mjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,oBAAoB;AAEtD,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,eAAe,EAChB,qBAAqB;AAgDtB,MAAM,CAAN,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,KAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;AAEtE,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,eAAe,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,QAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,QAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACxC,OAAO,CACL,MAAM;QACJ,oEAAoE;QACpE,sEAAsE;SACrE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,SAAS,CAAC,CAC1D,CAAC;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tE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC","sourcesContent":["import type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(--)(!)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"]}
package/dist/snaps.cjs CHANGED
@@ -3,7 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.verifyRequestedSnapPermissions = exports.isSnapPermitted = exports.assertIsValidSnapId = exports.isSnapId = exports.stripSnapPrefix = exports.getSnapPrefix = exports.SnapIdStruct = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.BaseSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapChecksum = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = void 0;
6
+ exports.verifyRequestedSnapPermissions = exports.isSnapPermitted = exports.assertIsValidSnapId = exports.isSnapId = exports.stripSnapPrefix = exports.getSnapPrefix = exports.SnapIdStruct = exports.SnapIdPrefixStruct = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.BaseSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapChecksum = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = void 0;
7
+ const snaps_sdk_1 = require("@metamask/snaps-sdk");
7
8
  const superstruct_1 = require("@metamask/superstruct");
8
9
  const utils_1 = require("@metamask/utils");
9
10
  const base_1 = require("@scure/base");
@@ -84,7 +85,7 @@ async function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest:
84
85
  exports.validateSnapShasum = validateSnapShasum;
85
86
  exports.LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
86
87
  // Require snap ids to only consist of printable ASCII characters
87
- exports.BaseSnapIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^[\x21-\x7E]*$/u);
88
+ exports.BaseSnapIdStruct = (0, utils_1.definePattern)('Base Snap Id', /^[\x21-\x7E]*$/u);
88
89
  const LocalSnapIdSubUrlStruct = (0, types_1.uri)({
89
90
  protocol: (0, superstruct_1.enums)(['http:', 'https:']),
90
91
  hostname: (0, superstruct_1.enums)(exports.LOCALHOST_HOSTNAMES),
@@ -128,7 +129,24 @@ exports.HttpSnapIdStruct = (0, superstruct_1.intersection)([
128
129
  hash: (0, superstruct_1.empty)((0, superstruct_1.string)()),
129
130
  }),
130
131
  ]);
131
- exports.SnapIdStruct = (0, superstruct_1.union)([exports.NpmSnapIdStruct, exports.LocalSnapIdStruct]);
132
+ exports.SnapIdPrefixStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Snap ID prefix', (value) => {
133
+ if (Object.values(types_1.SnapIdPrefixes).some((prefix) => value.startsWith(prefix))) {
134
+ return true;
135
+ }
136
+ const allowedPrefixes = Object.values(types_1.SnapIdPrefixes)
137
+ .map((prefix) => `"${prefix}"`)
138
+ .join(', ');
139
+ return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: "${value}"`;
140
+ });
141
+ exports.SnapIdStruct = (0, snaps_sdk_1.selectiveUnion)((value) => {
142
+ if (typeof value === 'string' && value.startsWith(types_1.SnapIdPrefixes.npm)) {
143
+ return exports.NpmSnapIdStruct;
144
+ }
145
+ if (typeof value === 'string' && value.startsWith(types_1.SnapIdPrefixes.local)) {
146
+ return exports.LocalSnapIdStruct;
147
+ }
148
+ return exports.SnapIdPrefixStruct;
149
+ });
132
150
  /**
133
151
  * Extracts the snap prefix from a snap ID.
134
152
  *
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAQA,uDAW+B;AAE/B,2CAAiE;AACjE,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC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AoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = 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 * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
1
+ {"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,mDAI6B;AAE7B,uDAS+B;AAE/B,2CAAgF;AAChF,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,0BAAV,UAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,gCAAhB,gBAAgB,QAK3B;AA2GD;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,QAAmC;IAEnC,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,EAAsB,CA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B,eAAe,CAC7B,WAAqD,EACrD,MAAc;IAEd,OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAbD,0CAaC;AAED;;;;;;GAMG;AACH,SAAgB,8BAA8B,CAC5C,oBAA6B;IAE7B,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
package/dist/snaps.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { SubjectPermissions, PermissionConstraint } from "@metamask/permission-controller";
2
2
  import type { BlockReason } from "@metamask/snaps-registry";
3
- import type { SnapId, Snap as TruncatedSnap } from "@metamask/snaps-sdk";
3
+ import { type SnapId, type Snap as TruncatedSnap } from "@metamask/snaps-sdk";
4
4
  import type { Struct } from "@metamask/superstruct";
5
5
  import type { LocalizationFile } from "./localization.cjs";
6
6
  import type { InitialConnections, SnapManifest, SnapPermissions } from "./manifest/validation.cjs";
@@ -125,6 +125,7 @@ export declare const BaseSnapIdStruct: Struct<string, null>;
125
125
  export declare const LocalSnapIdStruct: Struct<string, null>;
126
126
  export declare const NpmSnapIdStruct: Struct<string, null>;
127
127
  export declare const HttpSnapIdStruct: Struct<string, null>;
128
+ export declare const SnapIdPrefixStruct: Struct<string, null>;
128
129
  export declare const SnapIdStruct: Struct<string, null>;
129
130
  /**
130
131
  * Extracts the snap prefix from a snap ID.
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAqBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAChB,kCAA8B;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAA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  import type { SubjectPermissions, PermissionConstraint } from "@metamask/permission-controller";
2
2
  import type { BlockReason } from "@metamask/snaps-registry";
3
- import type { SnapId, Snap as TruncatedSnap } from "@metamask/snaps-sdk";
3
+ import { type SnapId, type Snap as TruncatedSnap } from "@metamask/snaps-sdk";
4
4
  import type { Struct } from "@metamask/superstruct";
5
5
  import type { LocalizationFile } from "./localization.mjs";
6
6
  import type { InitialConnections, SnapManifest, SnapPermissions } from "./manifest/validation.mjs";
@@ -125,6 +125,7 @@ export declare const BaseSnapIdStruct: Struct<string, null>;
125
125
  export declare const LocalSnapIdStruct: Struct<string, null>;
126
126
  export declare const NpmSnapIdStruct: Struct<string, null>;
127
127
  export declare const HttpSnapIdStruct: Struct<string, null>;
128
+ export declare const SnapIdPrefixStruct: Struct<string, null>;
128
129
  export declare const SnapIdStruct: Struct<string, null>;
129
130
  /**
130
131
  * Extracts the snap prefix from a snap ID.
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.d.mts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAqBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAChB,kCAA8B;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAAgB;AACxE,OAAO,EAAE,cAAc,EAAO,oBAAgB;AAY9C,eAAO,MAAM,mBAAmB,QACoF,CAAC;AAErH,oBAAY,UAAU;IACpB,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,OAAO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tC,KAAK,EAAE,gBAAgB,EACvB,YAAY,SAA2E,GACtF,OAAO,CAAC,IAAI,CAAC,CAIf;AAED,eAAO,MAAM,mBAAmB,8CAA+C,CAAC;AAGhF,eAAO,MAAM,gBAAgB,sBAG5B,CAAC;AASF,eAAO,MAAM,iBAAiB,sBAc7B,CAAC;AACF,eAAO,MAAM,eAAe,sBAqBS,CAAC;AAEtC,eAAO,MAAM,gBAAgB,sBAOQ,CAAC;AAEtC,eAAO,MAAM,kBAAkB,sBAgB9B,CAAC;AAEF,eAAO,MAAM,YAAY,sBAUvB,CAAC;AAEH;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,CAQ5D;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAExD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,MAAM,CAE3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,kBAAkB,CAAC,oBAAoB,CAAC,EACrD,MAAM,EAAE,MAAM,WAWf;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC5C,oBAAoB,EAAE,OAAO,GAC5B,OAAO,CAAC,oBAAoB,IAAI,sBAAsB,CA4BxD;AAED,YAAY,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B"}
package/dist/snaps.mjs CHANGED
@@ -4,8 +4,9 @@ function $importDefault(module) {
4
4
  }
5
5
  return module;
6
6
  }
7
- import { is, empty, enums, intersection, literal, pattern, refine, string, union, validate } from "@metamask/superstruct";
8
- import { assert, isObject, assertStruct } from "@metamask/utils";
7
+ import { selectiveUnion } from "@metamask/snaps-sdk";
8
+ import { is, empty, enums, intersection, literal, refine, string, validate } from "@metamask/superstruct";
9
+ import { assert, isObject, assertStruct, definePattern } from "@metamask/utils";
9
10
  import { base64 } from "@scure/base";
10
11
  import $stableStringify from "fast-json-stable-stringify";
11
12
  const stableStringify = $importDefault($stableStringify);
@@ -84,7 +85,7 @@ export async function validateSnapShasum(files, errorMessage = 'Invalid Snap man
84
85
  }
85
86
  export const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
86
87
  // Require snap ids to only consist of printable ASCII characters
87
- export const BaseSnapIdStruct = pattern(string(), /^[\x21-\x7E]*$/u);
88
+ export const BaseSnapIdStruct = definePattern('Base Snap Id', /^[\x21-\x7E]*$/u);
88
89
  const LocalSnapIdSubUrlStruct = uri({
89
90
  protocol: enums(['http:', 'https:']),
90
91
  hostname: enums(LOCALHOST_HOSTNAMES),
@@ -128,7 +129,24 @@ export const HttpSnapIdStruct = intersection([
128
129
  hash: empty(string()),
129
130
  }),
130
131
  ]);
131
- export const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);
132
+ export const SnapIdPrefixStruct = refine(string(), 'Snap ID prefix', (value) => {
133
+ if (Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))) {
134
+ return true;
135
+ }
136
+ const allowedPrefixes = Object.values(SnapIdPrefixes)
137
+ .map((prefix) => `"${prefix}"`)
138
+ .join(', ');
139
+ return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: "${value}"`;
140
+ });
141
+ export const SnapIdStruct = selectiveUnion((value) => {
142
+ if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {
143
+ return NpmSnapIdStruct;
144
+ }
145
+ if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {
146
+ return LocalSnapIdStruct;
147
+ }
148
+ return SnapIdPrefixStruct;
149
+ });
132
150
  /**
133
151
  * Extracts the snap prefix from a snap ID.
134
152
  *