@metamask/snaps-utils 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -1
- package/dist/cjs/auxiliary-files.js +40 -0
- package/dist/cjs/auxiliary-files.js.map +1 -0
- package/dist/cjs/errors.js +353 -3
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/index.browser.js +1 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.executionenv.js +1 -0
- package/dist/cjs/index.executionenv.js.map +1 -1
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +25 -5
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +6 -1
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/npm.js +5 -3
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js +3 -2
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/validation.js.map +1 -1
- package/dist/cjs/virtual-file/VirtualFile.js +6 -0
- package/dist/cjs/virtual-file/VirtualFile.js.map +1 -1
- package/dist/esm/auxiliary-files.js +28 -0
- package/dist/esm/auxiliary-files.js.map +1 -0
- package/dist/esm/errors.js +350 -1
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/index.browser.js +1 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.executionenv.js +1 -0
- package/dist/esm/index.executionenv.js.map +1 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/manifest/manifest.js +30 -5
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +3 -1
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/npm.js +5 -3
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js +3 -2
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/validation.js.map +1 -1
- package/dist/esm/virtual-file/VirtualFile.js +7 -1
- package/dist/esm/virtual-file/VirtualFile.js.map +1 -1
- package/dist/types/auxiliary-files.d.ts +13 -0
- package/dist/types/errors.d.ts +182 -0
- package/dist/types/index.browser.d.ts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.executionenv.d.ts +1 -0
- package/dist/types/manifest/manifest.d.ts +11 -1
- package/dist/types/manifest/validation.d.ts +4 -0
- package/dist/types/snaps.d.ts +13 -6
- package/dist/types/types.d.ts +6 -0
- package/dist/types/validation.d.ts +2 -2
- package/package.json +17 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAC7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,QACb,kBAAkB;AAEzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,EAAE,EACFC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,QACA,cAAc;AAErB,SAASC,OAAO,QAAQ,WAAW;AACnC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,iBAAiB,EAAEC,4BAA4B,QAAQ,aAAa;AAC7E,SAASC,oBAAoB,EAAEC,gBAAgB,QAAQ,cAAc;AACrE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,UAAU,EAAEC,gBAAgB,QAAQ,WAAW;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCR;IACAC;CACD;AAED,OAAO,MAAMQ,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAED,OAAO,MAAMC,kBAAkBrB,OAC7BV,MAAMa,WACN,eACA,CAACmB;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,IAAIA,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B,aAAatD;gBACbuD,UAAUhE,MAAM;oBACdT,QAAQ;oBACRA,QAAQ;iBACT;YACH;QACF;IACF;IACA0E,oBAAoB1B;IACpB2B,iBAAiB3E,QAAQ;IACzB4E,SAAS1E,SAASK;AACpB,GAAG;AAIH;;;;;CAKC,GACD,OAAO,SAASsE,eAAezC,KAAc;IAC3C,OAAOrC,GAAGqC,OAAOyB;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASiB,qBACd1C,KAAc;IAEd9C,aACE8C,OACAyB,oBACA,CAAC,CAAC,EAAE1C,iBAAiB4D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB5C,KAAc;IAC/C,qEAAqE;IACrE,OAAOxC,OAAOwC,OAAOyB;AACvB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","KeyringOriginsStruct","RpcOriginsStruct","ChainIdStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","ChainIdsStruct","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapAuxilaryFilesStruct","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","files","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAC7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,QACb,kBAAkB;AAEzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,EAAE,EACFC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,QACA,cAAc;AAErB,SAASC,OAAO,QAAQ,WAAW;AACnC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,iBAAiB,EAAEC,4BAA4B,QAAQ,aAAa;AAC7E,SAASC,oBAAoB,EAAEC,gBAAgB,QAAQ,cAAc;AACrE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,UAAU,EAAEC,gBAAgB,QAAQ,WAAW;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCR;IACAC;CACD;AAED,OAAO,MAAMQ,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAED,OAAO,MAAMC,kBAAkBrB,OAC7BV,MAAMa,WACN,eACA,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B;IAEF0B,QAAQlE,OAAO;QACbmE,QAAQ7E;QACR8E,UAAUpE,OAAO;YACfqE,KAAKrE,OAAO;gBACVsE,UAAUjE,KAAKC,UAAU,GAAGkC;gBAC5B+B,UAAUtE,SAASI,KAAKC,UAAU,GAAGkC;gBACrCgC,aAAavD;gBACbwD,UAAUjE,MAAM;oBACdT,QAAQ;oBACRA,QAAQ;iBACT;YACH;QACF;QACA2E,OAAOzE,SAAS2D;IAClB;IACAe,oBAAoB5B;IACpB6B,iBAAiB7E,QAAQ;IACzB8E,SAAS5E,SAASK;AACpB,GAAG;AAIH;;;;;CAKC,GACD,OAAO,SAASwE,eAAe3C,KAAc;IAC3C,OAAOrC,GAAGqC,OAAO0B;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASkB,qBACd5C,KAAc;IAEd9C,aACE8C,OACA0B,oBACA,CAAC,CAAC,EAAE3C,iBAAiB8D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB9C,KAAc;IAC/C,qEAAqE;IACrE,OAAOxC,OAAOwC,OAAO0B;AACvB"}
|
package/dist/esm/npm.js
CHANGED
|
@@ -29,7 +29,7 @@ export const SnapFileNameFromKey = {
|
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
31
|
// Typecast: We are assured that the required files exist if we get here.
|
|
32
|
-
const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
|
|
32
|
+
const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles } = snapFiles;
|
|
33
33
|
try {
|
|
34
34
|
assertIsSnapManifest(manifest.result);
|
|
35
35
|
} catch (error) {
|
|
@@ -50,7 +50,8 @@ export const SnapFileNameFromKey = {
|
|
|
50
50
|
manifest: validatedManifest,
|
|
51
51
|
packageJson: validatedPackageJson,
|
|
52
52
|
sourceCode,
|
|
53
|
-
svgIcon
|
|
53
|
+
svgIcon,
|
|
54
|
+
auxiliaryFiles
|
|
54
55
|
});
|
|
55
56
|
if (svgIcon) {
|
|
56
57
|
try {
|
|
@@ -63,7 +64,8 @@ export const SnapFileNameFromKey = {
|
|
|
63
64
|
manifest: validatedManifest,
|
|
64
65
|
packageJson: validatedPackageJson,
|
|
65
66
|
sourceCode,
|
|
66
|
-
svgIcon
|
|
67
|
+
svgIcon,
|
|
68
|
+
auxiliaryFiles
|
|
67
69
|
};
|
|
68
70
|
}
|
|
69
71
|
|
package/dist/esm/npm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon }
|
|
1
|
+
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles } =\n snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n };\n}\n"],"names":["assertIsSnapIcon","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","auxiliaryFiles","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAE7D,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,UAAU;AAEvE,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA+D;AAE/D;;;;;;;;;CASC,GACD,OAAO,SAASC,gBACdC,SAA+B,EAC/BC,WAA2B;IAE3BT,oBAAoBU,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAER,mBAAmB,CAACU,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEE,WAAW,EAAEE,UAAU,EAAEO,OAAO,EAAEC,cAAc,EAAE,GAClEN;IACF,IAAI;QACFX,qBAAqBK,SAASa,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBhB;IAE1B,MAAM,EAAEiB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACN,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEO,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFrB,2BAA2BM,YAAYW,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMM,uBAAuBnB;IAE7BR,wBAAwB;QACtBM,UAAUgB;QACVd,aAAamB;QACbjB;QACAO;QACAC;IACF;IAEA,IAAID,SAAS;QACX,IAAI;YACFlB,iBAAiBkB;QACnB,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLf,UAAUgB;QACVd,aAAamB;QACbjB;QACAO;QACAC;IACF;AACF"}
|
package/dist/esm/snaps.js
CHANGED
|
@@ -73,11 +73,12 @@ export var SnapStatusEvents;
|
|
|
73
73
|
* @param files - All required Snap files to be included in the checksum.
|
|
74
74
|
* @returns The Base64-encoded SHA-256 digest of the source code.
|
|
75
75
|
*/ export function getSnapChecksum(files) {
|
|
76
|
-
const { manifest, sourceCode, svgIcon } = files;
|
|
76
|
+
const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;
|
|
77
77
|
const all = [
|
|
78
78
|
getChecksummableManifest(manifest),
|
|
79
79
|
sourceCode,
|
|
80
|
-
svgIcon
|
|
80
|
+
svgIcon,
|
|
81
|
+
...auxiliaryFiles
|
|
81
82
|
].filter((file)=>file !== undefined);
|
|
82
83
|
return base64.encode(checksumFiles(all));
|
|
83
84
|
}
|
package/dist/esm/snaps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAOA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AAErC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,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;IAE9CrG,OACEC,SAASqG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBtG,OACEuG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBhG,OACEC,SAASgG,WACPA,OAAOC,IAAI,KAAKnF,eAAeoF,OAAO,IACtClG,SAASgG,OAAOrD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeoF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
|
1
|
+
{"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type {\n Json,\n JsonRpcError,\n Opaque,\n SemVerVersion,\n} from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult = TruncatedSnap | { error: JsonRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(files: FetchedSnapFiles): string {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ].filter((file) => file !== undefined);\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["assert","isObject","assertStruct","base64","stableStringify","empty","enums","intersection","literal","pattern","refine","string","union","validate","validateNPMPackage","SnapCaveatType","checksumFiles","SnapIdPrefixes","SnapValidationFailureReason","uri","PROPOSED_NAME_REGEX","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","ProgrammaticallyFixableSnapError","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","getSnapChecksum","files","sourceCode","svgIcon","auxiliaryFiles","all","filter","file","undefined","encode","validateSnapShasum","errorMessage","ShasumMismatch","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdSubUrlStruct","protocol","hostname","hash","search","LocalSnapIdStruct","startsWith","local","error","slice","length","NpmSnapIdStruct","npm","pathname","normalized","errors","validForNewPackages","warnings","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","snapId","prefix","Object","values","find","possiblePrefix","stripSnapPrefix","replace","assertIsValidSnapId","isCaipChainId","chainId","test","isSnapPermitted","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapIds","verifyRequestedSnapPermissions","requestedPermissions","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;AAYA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,kBAAkB;AACjE,SAASC,MAAM,QAAQ,cAAc;AACrC,OAAOC,qBAAqB,6BAA6B;AAEzD,SACEC,KAAK,EACLC,KAAK,EACLC,YAAY,EACZC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACH,cAAc;AACrB,OAAOC,wBAAwB,4BAA4B;AAE3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,aAAa,QAAQ,aAAa;AAG3C,SAASC,cAAc,EAAEC,2BAA2B,EAAEC,GAAG,QAAQ,UAAU;AAG3E,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,OAAO,MAAMC,sBACX,mHAAmH;WAW9G;UAAKC,UAAU;IAAVA,WACVC,gBAAa;IADHD,WAEVE,cAAW;IAFDF,WAGVG,aAAU;IAHAH,WAIVI,aAAU;IAJAJ,WAKVK,aAAU;GALAL,eAAAA;WAQL;UAAKM,gBAAgB;IAAhBA,iBACVC,WAAQ;IADED,iBAEVE,UAAO;IAFGF,iBAGVG,WAAQ;IAHEH,iBAIVI,YAAS;GAJCJ,qBAAAA;AA6GZ;;;CAGC,GACD,OAAO,MAAMK,yCAAyCC;IAGpDC,YAAYC,OAAe,EAAEC,MAAmC,CAAE;QAChE,KAAK,CAACD;QAHRC,uBAAAA,UAAAA,KAAAA;QAIE,IAAI,CAACA,MAAM,GAAGA;IAChB;AACF;AAEA;;;;;CAKC,GACD,SAASC,yBACPC,QAAmC;IAEnC,MAAMC,eAAeD,SAASE,KAAK;IACnC,OAAOD,aAAaE,MAAM,CAACC,MAAM,CAACC,MAAM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AY,YACnB,+EAAmEC,IAAI,CACrED;AAGN;AAEA;;;;;;CAMC,GACD,OAAO,SAASE,gBACdC,WAAqD,EACrDb,MAAc;IAEd,OAAOc,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAASZ,KAClC,CAACa,SAAWA,OAAOC,IAAI,KAAKpF,eAAeqF,OAAO,KAC/C,CAAC,CAAA,EACNxD,KAAK,EACN,CAACqC,OAAO;AAEf;AAEA;;;;;;CAMC,GACD,OAAO,SAASoB,+BACdC,oBAA6B;IAE7BtG,OACEC,SAASqG,uBACT;IAGF,MAAM,EAAEN,aAAaO,oBAAoB,EAAE,GAAGD;IAE9CtG,OACEC,SAASsG,uBACT;IAGF,MAAM,EAAEN,OAAO,EAAE,GAAGM;IAEpBvG,OACEwG,MAAMC,OAAO,CAACR,YAAYA,QAAQ3B,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC4B,OAAO,GAAGD;IAEjBjG,OACEC,SAASiG,WACPA,OAAOC,IAAI,KAAKpF,eAAeqF,OAAO,IACtCnG,SAASiG,OAAOtD,KAAK,GACvB,CAAC,8CAA8C,EAAE7B,eAAeqF,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
package/dist/esm/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports } from './handlers';\nimport { HandlerType } from './handlers';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","HandlerType","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","SNAP_EXPORT_NAMES","Object","values","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AACA,SAASA,YAAY,EAAEC,aAAa,QAAQ,kBAAkB;AAE9D,SACEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,UAAUC,iBAAiB,QACtB,cAAc;AAIrB,SAASC,WAAW,QAAQ,aAAa;WAIlC;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKZ,OAAO,MAAMG,aAAaV,KACxBF,QACEG,UACA,gEAEF,GACA,KACA;AAEF,2EAA2E;AAC3E,sBAAsB;AACtB,OAAO,MAAMU,2BAA2BT,KAAK;IAC3CU,SAASnB;IACToB,MAAMH;IACNI,MAAMjB,SAASG,KAAKC,UAAU,GAAGc;IACjCC,YAAYnB,SACVD,OAAO;QACLM,MAAMF,KAAKC,UAAU,GAAGc;QACxBE,KAAKjB,KAAKC,UAAU,GAAGc;IACzB;AAEJ,GAAG;AAKH;;;;;CAKC,GACD,OAAO,SAASG,qBACdC,KAAc;IAEd,OAAOxB,GAAGwB,OAAOR;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASS,2BACdD,KAAc;IAEd3B,aACE2B,OACAR,0BACA,CAAC,CAAC,EAAEJ,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;
|
|
1
|
+
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports } from './handlers';\nimport { HandlerType } from './handlers';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["assertStruct","VersionStruct","instance","is","object","optional","pattern","refine","size","string","type","union","assert","assertSuperstruct","HandlerType","NpmSnapFileNames","PackageJson","Manifest","NameStruct","NpmSnapPackageJsonStruct","version","name","main","Infinity","repository","url","isNpmSnapPackageJson","value","assertIsNpmSnapPackageJson","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","SNAP_EXPORT_NAMES","Object","values","uri","opts","URL","UrlStruct","toString","isValidUrl","WALLET_SNAP_PERMISSION_KEY"],"mappings":"AACA,SAASA,YAAY,EAAEC,aAAa,QAAQ,kBAAkB;AAE9D,SACEC,QAAQ,EACRC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC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AC/C,IAAI;YACF,MAAMF,MAAM,IAAIoB,IAAIlB;YAEpB,MAAMmB,YAAYpC,KAAKkC;YACvB/B,kBAAkBY,KAAKqB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEnB,MAAMoB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,SAASC,WACdvB,GAAY,EACZmB,OAAwB,CAAC,CAAC;IAE1B,OAAOzC,GAAGsB,KAAKkB,IAAIC;AACrB;AAEA,+CAA+C;AAC/C,OAAO,MAAMK,6BAA6B,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(files: FetchedSnapFiles): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["assertIsSnapIcon","assertIsSnapManifest","validateSnapShasum","validateFetchedSnap","files","manifest","result","svgIcon"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,kBAAkB,QAAQ,UAAU;AAG7C;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,KAAuB;IACzDH,qBAAqBG,MAAMC,QAAQ,CAACC,MAAM;IAC1CJ,mBAAmBE;IAEnB,IAAIA,MAAMG,OAAO,EAAE;QACjBP,iBAAiBI,MAAMG,OAAO;IAChC;AACF"}
|
|
@@ -19,13 +19,19 @@ function _define_property(obj, key, value) {
|
|
|
19
19
|
}
|
|
20
20
|
return obj;
|
|
21
21
|
}
|
|
22
|
-
import { assert } from '@metamask/utils';
|
|
22
|
+
import { assert, bytesToHex } from '@metamask/utils';
|
|
23
|
+
import { base64 } from '@scure/base';
|
|
23
24
|
import { deepClone } from '../deep-clone';
|
|
24
25
|
export class VirtualFile {
|
|
25
26
|
toString(encoding) {
|
|
26
27
|
if (typeof this.value === 'string') {
|
|
27
28
|
assert(encoding === undefined, 'Tried to encode string.');
|
|
28
29
|
return this.value;
|
|
30
|
+
} else if (this.value instanceof Uint8Array && encoding === 'hex') {
|
|
31
|
+
return bytesToHex(this.value);
|
|
32
|
+
} else if (this.value instanceof Uint8Array && encoding === 'base64') {
|
|
33
|
+
// TODO: Use @metamask/utils for this
|
|
34
|
+
return base64.encode(this.value);
|
|
29
35
|
}
|
|
30
36
|
const decoder = new TextDecoder(encoding);
|
|
31
37
|
return decoder.decode(this.value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert } from '@metamask/utils';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["assert","deepClone","VirtualFile","toString","encoding","value","undefined","decoder","TextDecoder","decode","clone","vfile","slice","result","data","path","constructor","options"
|
|
1
|
+
{"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert, bytesToHex } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n } else if (this.value instanceof Uint8Array && encoding === 'hex') {\n return bytesToHex(this.value);\n } else if (this.value instanceof Uint8Array && encoding === 'base64') {\n // TODO: Use @metamask/utils for this\n return base64.encode(this.value);\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["assert","bytesToHex","base64","deepClone","VirtualFile","toString","encoding","value","undefined","Uint8Array","encode","decoder","TextDecoder","decode","clone","vfile","slice","result","data","path","constructor","options"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;;;;;;;;;;AACtD,SAASA,MAAM,EAAEC,UAAU,QAAQ,kBAAkB;AACrD,SAASC,MAAM,QAAQ,cAAc;AAErC,SAASC,SAAS,QAAQ,gBAAgB;AA+B1C,OAAO,MAAMC;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK,KAAK,UAAU;YAClCP,OAAOM,aAAaE,WAAW;YAC/B,OAAO,IAAI,CAACD,KAAK;QACnB,OAAO,IAAI,IAAI,CAACA,KAAK,YAAYE,cAAcH,aAAa,OAAO;YACjE,OAAOL,WAAW,IAAI,CAACM,KAAK;QAC9B,OAAO,IAAI,IAAI,CAACA,KAAK,YAAYE,cAAcH,aAAa,UAAU;YACpE,qCAAqC;YACrC,OAAOJ,OAAOQ,MAAM,CAAC,IAAI,CAACH,KAAK;QACjC;QACA,MAAMI,UAAU,IAAIC,YAAYN;QAChC,OAAOK,QAAQE,MAAM,CAAC,IAAI,CAACN,KAAK;IAClC;IAEAO,QAAQ;QACN,MAAMC,QAAQ,IAAIX;QAClB,IAAI,OAAO,IAAI,CAACG,KAAK,KAAK,UAAU;YAClCQ,MAAMR,KAAK,GAAG,IAAI,CAACA,KAAK;QAC1B,OAAO;YACL,mFAAmF;YACnFQ,MAAMR,KAAK,GAAG,IAAI,CAACA,KAAK,CAACS,KAAK,CAAC;QACjC;QACAD,MAAME,MAAM,GAAGd,UAAU,IAAI,CAACc,MAAM;QACpCF,MAAMG,IAAI,GAAGf,UAAU,IAAI,CAACe,IAAI;QAChCH,MAAMI,IAAI,GAAG,IAAI,CAACA,IAAI;QACtB,OAAOJ;IACT;IAzDAK,YAAYb,KAA0B,CAAE;QAuBxCA,uBAAAA,SAAAA,KAAAA;QAEAU,uBAAAA,UAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QA5BE,IAAIE;QACJ,IAAI,OAAOd,UAAU,YAAYA,iBAAiBE,YAAY;YAC5DY,UAAU;gBAAEd;YAAM;QACpB,OAAO;YACLc,UAAUd;QACZ;QAEA,IAAI,CAACA,KAAK,GAAGc,SAASd,SAAS;QAC/B,wDAAwD;QACxD,gEAAgE;QAChE,4DAA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAACU,MAAM,GAAGI,SAASJ,UAAWT;QAClC,IAAI,CAACU,IAAI,GAAGG,SAASH,QAAQ,CAAC;QAC9B,IAAI,CAACC,IAAI,GAAGE,SAASF,QAAQ;IAC/B;AAqCF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare enum AuxiliaryFileEncoding {
|
|
2
|
+
Base64 = "base64",
|
|
3
|
+
Hex = "hex",
|
|
4
|
+
Utf8 = "utf8"
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Re-encodes an auxiliary file if needed depending on the requested file encoding.
|
|
8
|
+
*
|
|
9
|
+
* @param value - The base64 value stored for the auxiliary file.
|
|
10
|
+
* @param encoding - The chosen encoding.
|
|
11
|
+
* @returns The file encoded in the requested encoding.
|
|
12
|
+
*/
|
|
13
|
+
export declare function encodeAuxiliaryFile(value: string, encoding: AuxiliaryFileEncoding): string;
|
package/dist/types/errors.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { JsonRpcError as RpcError } from '@metamask/rpc-errors';
|
|
2
|
+
import type { DataWithOptionalCause } from '@metamask/rpc-errors';
|
|
3
|
+
import type { Json, JsonRpcError } from '@metamask/utils';
|
|
1
4
|
/**
|
|
2
5
|
* Get the error message from an unknown error type.
|
|
3
6
|
*
|
|
@@ -8,3 +11,182 @@
|
|
|
8
11
|
* @returns The error message.
|
|
9
12
|
*/
|
|
10
13
|
export declare function getErrorMessage(error: unknown): string;
|
|
14
|
+
/**
|
|
15
|
+
* Get the error stack from an unknown error type.
|
|
16
|
+
*
|
|
17
|
+
* @param error - The error to get the stack from.
|
|
18
|
+
* @returns The error stack, or undefined if the error does not have a valid
|
|
19
|
+
* stack.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getErrorStack(error: unknown): string | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Get the error code from an unknown error type.
|
|
24
|
+
*
|
|
25
|
+
* @param error - The error to get the code from.
|
|
26
|
+
* @returns The error code, or `-32603` if the error does not have a valid code.
|
|
27
|
+
*/
|
|
28
|
+
export declare function getErrorCode(error: unknown): number;
|
|
29
|
+
/**
|
|
30
|
+
* Get the error data from an unknown error type.
|
|
31
|
+
*
|
|
32
|
+
* @param error - The error to get the data from.
|
|
33
|
+
* @returns The error data, or an empty object if the error does not have valid
|
|
34
|
+
* data.
|
|
35
|
+
*/
|
|
36
|
+
export declare function getErrorData(error: unknown): {
|
|
37
|
+
[prop: string]: Json;
|
|
38
|
+
};
|
|
39
|
+
export declare const SNAP_ERROR_WRAPPER_CODE = -31001;
|
|
40
|
+
export declare const SNAP_ERROR_WRAPPER_MESSAGE = "Wrapped Snap Error";
|
|
41
|
+
export declare const SNAP_ERROR_CODE = -31002;
|
|
42
|
+
export declare const SNAP_ERROR_MESSAGE = "Snap Error";
|
|
43
|
+
export declare type SerializedSnapErrorWrapper = {
|
|
44
|
+
code: typeof SNAP_ERROR_WRAPPER_CODE;
|
|
45
|
+
message: typeof SNAP_ERROR_WRAPPER_MESSAGE;
|
|
46
|
+
data: {
|
|
47
|
+
cause: Json;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
export declare type SerializedSnapError = {
|
|
51
|
+
code: typeof SNAP_ERROR_CODE;
|
|
52
|
+
message: typeof SNAP_ERROR_MESSAGE;
|
|
53
|
+
data: {
|
|
54
|
+
cause: JsonRpcError & {
|
|
55
|
+
data: Record<string, Json>;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
export declare class WrappedSnapError extends Error {
|
|
60
|
+
#private;
|
|
61
|
+
/**
|
|
62
|
+
* Create a new `WrappedSnapError`.
|
|
63
|
+
*
|
|
64
|
+
* @param error - The error to create the `WrappedSnapError` from.
|
|
65
|
+
*/
|
|
66
|
+
constructor(error: unknown);
|
|
67
|
+
/**
|
|
68
|
+
* The error name.
|
|
69
|
+
*
|
|
70
|
+
* @returns The error name.
|
|
71
|
+
*/
|
|
72
|
+
get name(): string;
|
|
73
|
+
/**
|
|
74
|
+
* The error message.
|
|
75
|
+
*
|
|
76
|
+
* @returns The error message.
|
|
77
|
+
*/
|
|
78
|
+
get message(): string;
|
|
79
|
+
/**
|
|
80
|
+
* The error stack.
|
|
81
|
+
*
|
|
82
|
+
* @returns The error stack.
|
|
83
|
+
*/
|
|
84
|
+
get stack(): string | undefined;
|
|
85
|
+
/**
|
|
86
|
+
* Convert the error to a JSON object.
|
|
87
|
+
*
|
|
88
|
+
* @returns The JSON object.
|
|
89
|
+
*/
|
|
90
|
+
toJSON(): SerializedSnapErrorWrapper;
|
|
91
|
+
/**
|
|
92
|
+
* Serialize the error to a JSON object. This is called by
|
|
93
|
+
* `@metamask/rpc-errors` when serializing the error.
|
|
94
|
+
*
|
|
95
|
+
* @returns The JSON object.
|
|
96
|
+
*/
|
|
97
|
+
serialize(): SerializedSnapErrorWrapper;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A generic error which can be thrown by a Snap, without it causing the Snap to
|
|
101
|
+
* crash.
|
|
102
|
+
*/
|
|
103
|
+
export declare class SnapError extends Error {
|
|
104
|
+
#private;
|
|
105
|
+
/**
|
|
106
|
+
* Create a new `SnapError`.
|
|
107
|
+
*
|
|
108
|
+
* @param error - The error to create the `SnapError` from. If this is a
|
|
109
|
+
* `string`, it will be used as the error message. If this is an `Error`, its
|
|
110
|
+
* `message` property will be used as the error message. If this is a
|
|
111
|
+
* `JsonRpcError`, its `message` property will be used as the error message
|
|
112
|
+
* and its `code` property will be used as the error code. Otherwise, the
|
|
113
|
+
* error will be converted to a string and used as the error message.
|
|
114
|
+
* @param data - Additional data to include in the error. This will be merged
|
|
115
|
+
* with the error data, if any.
|
|
116
|
+
*/
|
|
117
|
+
constructor(error: string | Error | JsonRpcError, data?: Record<string, Json>);
|
|
118
|
+
/**
|
|
119
|
+
* The error name.
|
|
120
|
+
*
|
|
121
|
+
* @returns The error name.
|
|
122
|
+
*/
|
|
123
|
+
get name(): string;
|
|
124
|
+
/**
|
|
125
|
+
* The error code.
|
|
126
|
+
*
|
|
127
|
+
* @returns The error code.
|
|
128
|
+
*/
|
|
129
|
+
get code(): number;
|
|
130
|
+
/**
|
|
131
|
+
* The error message.
|
|
132
|
+
*
|
|
133
|
+
* @returns The error message.
|
|
134
|
+
*/
|
|
135
|
+
get message(): string;
|
|
136
|
+
/**
|
|
137
|
+
* Additional data for the error.
|
|
138
|
+
*
|
|
139
|
+
* @returns Additional data for the error.
|
|
140
|
+
*/
|
|
141
|
+
get data(): Record<string, Json>;
|
|
142
|
+
/**
|
|
143
|
+
* The error stack.
|
|
144
|
+
*
|
|
145
|
+
* @returns The error stack.
|
|
146
|
+
*/
|
|
147
|
+
get stack(): string | undefined;
|
|
148
|
+
/**
|
|
149
|
+
* Convert the error to a JSON object.
|
|
150
|
+
*
|
|
151
|
+
* @returns The JSON object.
|
|
152
|
+
*/
|
|
153
|
+
toJSON(): SerializedSnapError;
|
|
154
|
+
/**
|
|
155
|
+
* Serialize the error to a JSON object. This is called by
|
|
156
|
+
* `@metamask/rpc-errors` when serializing the error.
|
|
157
|
+
*
|
|
158
|
+
* @returns The JSON object.
|
|
159
|
+
*/
|
|
160
|
+
serialize(): SerializedSnapError;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Check if an object is a `SnapError`.
|
|
164
|
+
*
|
|
165
|
+
* @param error - The object to check.
|
|
166
|
+
* @returns Whether the object is a `SnapError`.
|
|
167
|
+
*/
|
|
168
|
+
export declare function isSnapError(error: unknown): error is SnapError;
|
|
169
|
+
/**
|
|
170
|
+
* Check if a JSON-RPC error is a `SnapError`.
|
|
171
|
+
*
|
|
172
|
+
* @param error - The object to check.
|
|
173
|
+
* @returns Whether the object is a `SnapError`.
|
|
174
|
+
*/
|
|
175
|
+
export declare function isSerializedSnapError(error: JsonRpcError): error is SerializedSnapError;
|
|
176
|
+
/**
|
|
177
|
+
* Check if a JSON-RPC error is a `WrappedSnapError`.
|
|
178
|
+
*
|
|
179
|
+
* @param error - The object to check.
|
|
180
|
+
* @returns Whether the object is a `WrappedSnapError`.
|
|
181
|
+
*/
|
|
182
|
+
export declare function isWrappedSnapError(error: unknown): error is SerializedSnapErrorWrapper;
|
|
183
|
+
/**
|
|
184
|
+
* Attempt to unwrap an unknown error to a `JsonRpcError`. This function will
|
|
185
|
+
* try to get the error code, message, and data from the error, and return a
|
|
186
|
+
* `JsonRpcError` with those properties.
|
|
187
|
+
*
|
|
188
|
+
* @param error - The error to unwrap.
|
|
189
|
+
* @returns A tuple containing the unwrapped error and a boolean indicating
|
|
190
|
+
* whether the error was handled.
|
|
191
|
+
*/
|
|
192
|
+
export declare function unwrapError(error: unknown): [error: RpcError<DataWithOptionalCause>, isHandled: boolean];
|
package/dist/types/index.d.ts
CHANGED
|
@@ -66,6 +66,15 @@ export declare function getSnapSourceCode(basePath: string, manifest: Json, sour
|
|
|
66
66
|
* @returns The contents of the icon, if any.
|
|
67
67
|
*/
|
|
68
68
|
export declare function getSnapIcon(basePath: string, manifest: Json): Promise<VirtualFile | undefined>;
|
|
69
|
+
/**
|
|
70
|
+
* Given an unvalidated Snap manifest, attempts to extract the auxiliary files
|
|
71
|
+
* and read them.
|
|
72
|
+
*
|
|
73
|
+
* @param basePath - The path to the folder with the manifest files.
|
|
74
|
+
* @param manifest - The unvalidated Snap manifest file contents.
|
|
75
|
+
* @returns A list of auxiliary files and their contents, if any.
|
|
76
|
+
*/
|
|
77
|
+
export declare function getSnapAuxiliaryFiles(basePath: string, manifest: Json): Promise<VirtualFile[] | undefined>;
|
|
69
78
|
/**
|
|
70
79
|
* Sorts the given manifest in our preferred sort order and removes the
|
|
71
80
|
* `repository` field if it is falsy (it may be `null`).
|
|
@@ -83,5 +92,6 @@ export declare function getWritableManifest(manifest: SnapManifest): SnapManifes
|
|
|
83
92
|
* @param snapFiles.packageJson - The npm Snap's `package.json`.
|
|
84
93
|
* @param snapFiles.sourceCode - The Snap's source code.
|
|
85
94
|
* @param snapFiles.svgIcon - The Snap's optional icon.
|
|
95
|
+
* @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.
|
|
86
96
|
*/
|
|
87
|
-
export declare function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, }: SnapFiles): void;
|
|
97
|
+
export declare function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, }: SnapFiles): void;
|
|
@@ -190,6 +190,7 @@ export declare const PermissionsStruct: Struct<{
|
|
|
190
190
|
}> | undefined, null>;
|
|
191
191
|
}>;
|
|
192
192
|
export declare type SnapPermissions = Infer<typeof PermissionsStruct>;
|
|
193
|
+
export declare const SnapAuxilaryFilesStruct: Struct<string[], Struct<string, null>>;
|
|
193
194
|
export declare const SnapManifestStruct: Struct<{
|
|
194
195
|
description: string;
|
|
195
196
|
version: import("@metamask/utils").SemVerVersion;
|
|
@@ -204,6 +205,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
204
205
|
};
|
|
205
206
|
};
|
|
206
207
|
shasum: string;
|
|
208
|
+
files?: string[] | undefined;
|
|
207
209
|
};
|
|
208
210
|
initialPermissions: {
|
|
209
211
|
'endowment:network-access'?: {} | undefined;
|
|
@@ -279,6 +281,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
279
281
|
};
|
|
280
282
|
};
|
|
281
283
|
shasum: string;
|
|
284
|
+
files?: string[] | undefined;
|
|
282
285
|
}, {
|
|
283
286
|
shasum: Struct<string, null>;
|
|
284
287
|
location: Struct<{
|
|
@@ -301,6 +304,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
301
304
|
registry: Struct<"https://registry.npmjs.org" | "https://registry.npmjs.org/", null>;
|
|
302
305
|
}>;
|
|
303
306
|
}>;
|
|
307
|
+
files: Struct<string[] | undefined, Struct<string, null>>;
|
|
304
308
|
}>;
|
|
305
309
|
initialPermissions: Struct<{
|
|
306
310
|
'endowment:network-access'?: {} | undefined;
|