@metamask/permission-controller 6.0.0 → 7.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 +17 -1
- package/dist/Caveat.d.ts.map +1 -1
- package/dist/Caveat.js.map +1 -1
- package/dist/Permission.d.ts.map +1 -1
- package/dist/Permission.js.map +1 -1
- package/dist/PermissionController.d.ts.map +1 -1
- package/dist/PermissionController.js +8 -1
- package/dist/PermissionController.js.map +1 -1
- package/dist/SubjectMetadataController.d.ts +5 -1
- package/dist/SubjectMetadataController.d.ts.map +1 -1
- package/dist/SubjectMetadataController.js +5 -0
- package/dist/SubjectMetadataController.js.map +1 -1
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [7.1.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add `SubjectMetadataController:addSubjectMetadata` action ([#3733](https://github.com/MetaMask/core/pull/3733))
|
|
12
|
+
|
|
13
|
+
## [7.0.0]
|
|
14
|
+
### Changed
|
|
15
|
+
- **BREAKING:** Bump `@metamask/approval-controller` peer dependency from `^5.0.0` to `^5.1.1` ([#3680](https://github.com/MetaMask/core/pull/3680), [#3695](https://github.com/MetaMask/core/pull/3695))
|
|
16
|
+
- Bump `@metamask/base-controller` to `^4.0.1` ([#3695](https://github.com/MetaMask/core/pull/3695))
|
|
17
|
+
- Bump `@metamask/controller-utils` to `^8.0.1` ([#3695](https://github.com/MetaMask/core/pull/3695), [#3678](https://github.com/MetaMask/core/pull/3678), [#3667](https://github.com/MetaMask/core/pull/3667), [#3580](https://github.com/MetaMask/core/pull/3580))
|
|
18
|
+
- Bump `@metamask/json-rpc-engine` to `^7.3.1` ([#3695](https://github.com/MetaMask/core/pull/3695))
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
- Remove `@metamask/approval-controller` dependency ([#3607](https://github.com/MetaMask/core/pull/3607))
|
|
22
|
+
|
|
9
23
|
## [6.0.0]
|
|
10
24
|
### Added
|
|
11
25
|
- Add new handler to `permissionRpcMethods.handlers` for `wallet_revokePermissions` RPC method ([#1889](https://github.com/MetaMask/core/pull/1889))
|
|
@@ -113,7 +127,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
113
127
|
|
|
114
128
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
115
129
|
|
|
116
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@
|
|
130
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@7.1.0...HEAD
|
|
131
|
+
[7.1.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@7.0.0...@metamask/permission-controller@7.1.0
|
|
132
|
+
[7.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@6.0.0...@metamask/permission-controller@7.0.0
|
|
117
133
|
[6.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@5.0.1...@metamask/permission-controller@6.0.0
|
|
118
134
|
[5.0.1]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@5.0.0...@metamask/permission-controller@5.0.1
|
|
119
135
|
[5.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@4.1.2...@metamask/permission-controller@5.0.0
|
package/dist/Caveat.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Caveat.d.ts","sourceRoot":"","sources":["../src/Caveat.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAO5C,OAAO,KAAK,EACV,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,cAAc,CAAC;AAKtB,oBAAY,gBAAgB,GAAG;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC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aAAa,GACjB,oBAAoB,CAAC,MAAM,CAAC,IAAoC,CAAC,CAAC;QACpE,IAAI,CAAC,aAAa,EAAE;YAClB,MAAM,IAAI,oCAA2B,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SACpD;QAED,IAAI,CAAC,qCAAqC,CAAC,aAAa,CAAC,EAAE;YACzD,MAAM,IAAI,yCAAgC,CACxC,aAAa,EACb,2BAAc,CAAC,gBAAgB,CAChC,CAAC;SACH;QACD,SAAS,GAAG,aAAa,CAAC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;KACxD;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAjCD,kDAiCC","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n CaveatSpecificationMismatchError,\n UnrecognizedCaveatTypeError,\n} from './errors';\nimport type {\n AsyncRestrictedMethod,\n RestrictedMethod,\n PermissionConstraint,\n RestrictedMethodParameters,\n} from './Permission';\nimport { PermissionType } from './Permission';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { PermissionController } from './PermissionController';\n\nexport type CaveatConstraint = {\n /**\n * The type of the caveat. The type is presumed to be meaningful in the\n * context of the capability it is associated with.\n *\n * In MetaMask, every permission can only have one caveat of each type.\n */\n readonly type: string;\n\n // TODO:TS4.4 Make optional\n /**\n * Any additional data necessary to enforce the caveat.\n */\n readonly value: Json;\n};\n\n/**\n * A `ZCAP-LD`-like caveat object. A caveat is associated with a particular\n * permission, and stored in its `caveats` array. Conceptually, a caveat is\n * an arbitrary attenuation of the authority granted by its associated\n * permission. It is the responsibility of the host to interpret and apply\n * the restriction represented by a caveat.\n *\n * @template Type - The type of the caveat.\n * @template Value - The value associated with the caveat.\n */\nexport type Caveat<Type extends string, Value extends Json> = {\n /**\n * The type of the caveat. The type is presumed to be meaningful in the\n * context of the capability it is associated with.\n *\n * In MetaMask, every permission can only have one caveat of each type.\n */\n readonly type: Type;\n\n // TODO:TS4.4 Make optional\n /**\n * Any additional data necessary to enforce the caveat.\n */\n readonly value: Value;\n};\n\n// Next, we define types used for specifying caveats at the consumer layer,\n// and a function for applying caveats to a restricted method request. This is\n// Accomplished by decorating the restricted method implementation with the\n// the corresponding caveat functions.\n\n/**\n * A function for applying caveats to a restricted method request.\n *\n * @template ParentCaveat - The caveat type associated with this decorator.\n * @param decorated - The restricted method implementation to be decorated.\n * The method may have already been decorated with other caveats.\n * @param caveat - The caveat object.\n * @returns The decorated restricted method implementation.\n */\nexport type CaveatDecorator<ParentCaveat extends CaveatConstraint> = (\n decorated: AsyncRestrictedMethod<RestrictedMethodParameters, Json>,\n caveat: ParentCaveat,\n) => AsyncRestrictedMethod<RestrictedMethodParameters, Json>;\n\n/**\n * Extracts a caveat value type from a caveat decorator.\n *\n * @template Decorator - The {@link CaveatDecorator} to extract a caveat value\n * type from.\n */\ntype ExtractCaveatValueFromDecorator<Decorator extends CaveatDecorator<any>> =\n Decorator extends (\n decorated: any,\n caveat: infer ParentCaveat,\n ) => AsyncRestrictedMethod<any, any>\n ? ParentCaveat extends CaveatConstraint\n ? ParentCaveat['value']\n : never\n : never;\n\n/**\n * A function for validating caveats of a particular type.\n *\n * @template ParentCaveat - The caveat type associated with this validator.\n * @param caveat - The caveat object to validate.\n * @param origin - The origin associated with the parent permission.\n * @param target - The target of the parent permission.\n */\nexport type CaveatValidator<ParentCaveat extends CaveatConstraint> = (\n caveat: { type: ParentCaveat['type']; value: unknown },\n origin?: string,\n target?: string,\n) => void;\n\nexport type CaveatSpecificationBase = {\n /**\n * The string type of the caveat.\n */\n type: string;\n\n /**\n * The validator function used to validate caveats of the associated type\n * whenever they are instantiated. Caveat are instantiated whenever they are\n * created or mutated.\n *\n * The validator should throw an appropriate JSON-RPC error if validation fails.\n *\n * If no validator is specified, no validation of caveat values will be\n * performed. Although caveats can also be validated by permission validators,\n * validating caveat values separately is strongly recommended.\n */\n validator?: CaveatValidator<any>;\n};\n\nexport type RestrictedMethodCaveatSpecificationConstraint =\n CaveatSpecificationBase & {\n /**\n * The decorator function used to apply the caveat to restricted method\n * requests.\n */\n decorator: CaveatDecorator<any>;\n };\n\nexport type EndowmentCaveatSpecificationConstraint = CaveatSpecificationBase;\n\n/**\n * The constraint for caveat specification objects. Every {@link Caveat}\n * supported by a {@link PermissionController} must have an associated\n * specification, which is the source of truth for all caveat-related types.\n * In addition, a caveat specification may include a decorator function used\n * to apply the caveat's attenuation to a restricted method. It may also include\n * a validator function specified by the consumer.\n *\n * See the README for more details.\n */\nexport type CaveatSpecificationConstraint =\n | RestrictedMethodCaveatSpecificationConstraint\n | EndowmentCaveatSpecificationConstraint;\n\n/**\n * Options for {@link CaveatSpecificationBuilder} functions.\n */\ntype CaveatSpecificationBuilderOptions<\n DecoratorHooks extends Record<string, unknown>,\n ValidatorHooks extends Record<string, unknown>,\n> = {\n type?: string;\n decoratorHooks?: DecoratorHooks;\n validatorHooks?: ValidatorHooks;\n};\n\n/**\n * A function that builds caveat specifications. Modules that specify caveats\n * for external consumption should make this their primary / default export so\n * that host applications can use them to generate concrete specifications\n * tailored to their requirements.\n */\nexport type CaveatSpecificationBuilder<\n Options extends CaveatSpecificationBuilderOptions<any, any>,\n Specification extends CaveatSpecificationConstraint,\n> = (options: Options) => Specification;\n\n/**\n * A caveat specification export object, containing the\n * {@link CaveatSpecificationBuilder} function and \"hook name\" objects.\n */\nexport type CaveatSpecificationBuilderExportConstraint = {\n specificationBuilder: CaveatSpecificationBuilder<\n CaveatSpecificationBuilderOptions<any, any>,\n CaveatSpecificationConstraint\n >;\n decoratorHookNames?: Record<string, true>;\n validatorHookNames?: Record<string, true>;\n};\n\n/**\n * The specifications for all caveats supported by a particular\n * {@link PermissionController}.\n *\n * @template Specifications - The union of all {@link CaveatSpecificationConstraint} types.\n */\nexport type CaveatSpecificationMap<\n CaveatSpecification extends CaveatSpecificationConstraint,\n> = Record<CaveatSpecification['type'], CaveatSpecification>;\n\n/**\n * Extracts the union of all caveat types specified by the given\n * {@link CaveatSpecificationConstraint} type.\n *\n * @template CaveatSpecification - The {@link CaveatSpecificationConstraint} to extract a\n * caveat type union from.\n */\nexport type ExtractCaveats<\n CaveatSpecification extends CaveatSpecificationConstraint,\n> = CaveatSpecification extends any\n ? CaveatSpecification extends RestrictedMethodCaveatSpecificationConstraint\n ? Caveat<\n CaveatSpecification['type'],\n ExtractCaveatValueFromDecorator<\n RestrictedMethodCaveatSpecificationConstraint['decorator']\n >\n >\n : Caveat<CaveatSpecification['type'], Json>\n : never;\n\n/**\n * Extracts the type of a specific {@link Caveat} from a union of caveat\n * specifications.\n *\n * @template CaveatSpecifications - The union of all caveat specifications.\n * @template CaveatType - The type of the caveat to extract.\n */\nexport type ExtractCaveat<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n CaveatType extends string,\n> = Extract<ExtractCaveats<CaveatSpecifications>, { type: CaveatType }>;\n\n/**\n * Extracts the value type of a specific {@link Caveat} from a union of caveat\n * specifications.\n *\n * @template CaveatSpecifications - The union of all caveat specifications.\n * @template CaveatType - The type of the caveat whose value to extract.\n */\nexport type ExtractCaveatValue<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n CaveatType extends string,\n> = ExtractCaveat<CaveatSpecifications, CaveatType>['value'];\n\n/**\n * Determines whether a caveat specification is a restricted method caveat specification.\n *\n * @param specification - The caveat specification.\n * @returns True if the caveat specification is a restricted method caveat specification, otherwise false.\n */\nexport function isRestrictedMethodCaveatSpecification(\n specification: CaveatSpecificationConstraint,\n): specification is RestrictedMethodCaveatSpecificationConstraint {\n return hasProperty(specification, 'decorator');\n}\n\n/**\n * Decorate a restricted method implementation with its caveats.\n *\n * Note that all caveat functions (i.e. the argument and return value of the\n * decorator) must be awaited.\n *\n * @param methodImplementation - The restricted method implementation\n * @param permission - The origin's potential permission\n * @param caveatSpecifications - All caveat implementations\n * @returns The decorated method implementation\n */\nexport function decorateWithCaveats<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n>(\n methodImplementation: RestrictedMethod<RestrictedMethodParameters, Json>,\n permission: Readonly<PermissionConstraint>, // bound to the requesting origin\n caveatSpecifications: CaveatSpecificationMap<CaveatSpecifications>, // all caveat implementations\n): RestrictedMethod<RestrictedMethodParameters, Json> {\n const { caveats } = permission;\n if (!caveats) {\n return methodImplementation;\n }\n\n let decorated = async (\n args: Parameters<RestrictedMethod<RestrictedMethodParameters, Json>>[0],\n ) => methodImplementation(args);\n\n for (const caveat of caveats) {\n const specification =\n caveatSpecifications[caveat.type as CaveatSpecifications['type']];\n if (!specification) {\n throw new UnrecognizedCaveatTypeError(caveat.type);\n }\n\n if (!isRestrictedMethodCaveatSpecification(specification)) {\n throw new CaveatSpecificationMismatchError(\n specification,\n PermissionType.RestrictedMethod,\n );\n }\n decorated = specification.decorator(decorated, caveat);\n }\n\n return decorated;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Caveat.js","sourceRoot":"","sources":["../src/Caveat.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2CAA8C;AAE9C,qCAGkB;AAOlB,6CAA8C;AAsP9C;;;;;GAKG;AACH,SAAgB,qCAAqC,CACnD,aAA4C;IAE5C,OAAO,IAAA,mBAAW,EAAC,aAAa,EAAE,WAAW,CAAC,CAAC;AACjD,CAAC;AAJD,sFAIC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,mBAAmB,CAGjC,oBAAwE,EACxE,UAA0C,EAAE,iCAAiC;AAC7E,oBAAkE;IAElE,MAAM,EAAE,OAAO,EAAE,GAAG,UAAU,CAAC;IAC/B,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,oBAAoB,CAAC;KAC7B;IAED,IAAI,SAAS,GAAG,CACd,IAAuE,EACvE,EAAE,gDAAC,OAAA,oBAAoB,CAAC,IAAI,CAAC,CAAA,GAAA,CAAC;IAEhC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,MAAM,aAAa,GACjB,oBAAoB,CAAC,MAAM,CAAC,IAAoC,CAAC,CAAC;QACpE,IAAI,CAAC,aAAa,EAAE;YAClB,MAAM,IAAI,oCAA2B,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SACpD;QAED,IAAI,CAAC,qCAAqC,CAAC,aAAa,CAAC,EAAE;YACzD,MAAM,IAAI,yCAAgC,CACxC,aAAa,EACb,2BAAc,CAAC,gBAAgB,CAChC,CAAC;SACH;QACD,SAAS,GAAG,aAAa,CAAC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;KACxD;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAjCD,kDAiCC","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n CaveatSpecificationMismatchError,\n UnrecognizedCaveatTypeError,\n} from './errors';\nimport type {\n AsyncRestrictedMethod,\n RestrictedMethod,\n PermissionConstraint,\n RestrictedMethodParameters,\n} from './Permission';\nimport { PermissionType } from './Permission';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { PermissionController } from './PermissionController';\n\nexport type CaveatConstraint = {\n /**\n * The type of the caveat. The type is presumed to be meaningful in the\n * context of the capability it is associated with.\n *\n * In MetaMask, every permission can only have one caveat of each type.\n */\n readonly type: string;\n\n // TODO:TS4.4 Make optional\n /**\n * Any additional data necessary to enforce the caveat.\n */\n readonly value: Json;\n};\n\n/**\n * A `ZCAP-LD`-like caveat object. A caveat is associated with a particular\n * permission, and stored in its `caveats` array. Conceptually, a caveat is\n * an arbitrary attenuation of the authority granted by its associated\n * permission. It is the responsibility of the host to interpret and apply\n * the restriction represented by a caveat.\n *\n * @template Type - The type of the caveat.\n * @template Value - The value associated with the caveat.\n */\nexport type Caveat<Type extends string, Value extends Json> = {\n /**\n * The type of the caveat. The type is presumed to be meaningful in the\n * context of the capability it is associated with.\n *\n * In MetaMask, every permission can only have one caveat of each type.\n */\n readonly type: Type;\n\n // TODO:TS4.4 Make optional\n /**\n * Any additional data necessary to enforce the caveat.\n */\n readonly value: Value;\n};\n\n// Next, we define types used for specifying caveats at the consumer layer,\n// and a function for applying caveats to a restricted method request. This is\n// Accomplished by decorating the restricted method implementation with the\n// the corresponding caveat functions.\n\n/**\n * A function for applying caveats to a restricted method request.\n *\n * @template ParentCaveat - The caveat type associated with this decorator.\n * @param decorated - The restricted method implementation to be decorated.\n * The method may have already been decorated with other caveats.\n * @param caveat - The caveat object.\n * @returns The decorated restricted method implementation.\n */\nexport type CaveatDecorator<ParentCaveat extends CaveatConstraint> = (\n decorated: AsyncRestrictedMethod<RestrictedMethodParameters, Json>,\n caveat: ParentCaveat,\n) => AsyncRestrictedMethod<RestrictedMethodParameters, Json>;\n\n/**\n * Extracts a caveat value type from a caveat decorator.\n *\n * @template Decorator - The {@link CaveatDecorator} to extract a caveat value\n * type from.\n */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ExtractCaveatValueFromDecorator<Decorator extends CaveatDecorator<any>> =\n Decorator extends (\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n decorated: any,\n caveat: infer ParentCaveat,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) => AsyncRestrictedMethod<any, any>\n ? ParentCaveat extends CaveatConstraint\n ? ParentCaveat['value']\n : never\n : never;\n\n/**\n * A function for validating caveats of a particular type.\n *\n * @template ParentCaveat - The caveat type associated with this validator.\n * @param caveat - The caveat object to validate.\n * @param origin - The origin associated with the parent permission.\n * @param target - The target of the parent permission.\n */\nexport type CaveatValidator<ParentCaveat extends CaveatConstraint> = (\n caveat: { type: ParentCaveat['type']; value: unknown },\n origin?: string,\n target?: string,\n) => void;\n\nexport type CaveatSpecificationBase = {\n /**\n * The string type of the caveat.\n */\n type: string;\n\n /**\n * The validator function used to validate caveats of the associated type\n * whenever they are instantiated. Caveat are instantiated whenever they are\n * created or mutated.\n *\n * The validator should throw an appropriate JSON-RPC error if validation fails.\n *\n * If no validator is specified, no validation of caveat values will be\n * performed. Although caveats can also be validated by permission validators,\n * validating caveat values separately is strongly recommended.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n validator?: CaveatValidator<any>;\n};\n\nexport type RestrictedMethodCaveatSpecificationConstraint =\n CaveatSpecificationBase & {\n /**\n * The decorator function used to apply the caveat to restricted method\n * requests.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n decorator: CaveatDecorator<any>;\n };\n\nexport type EndowmentCaveatSpecificationConstraint = CaveatSpecificationBase;\n\n/**\n * The constraint for caveat specification objects. Every {@link Caveat}\n * supported by a {@link PermissionController} must have an associated\n * specification, which is the source of truth for all caveat-related types.\n * In addition, a caveat specification may include a decorator function used\n * to apply the caveat's attenuation to a restricted method. It may also include\n * a validator function specified by the consumer.\n *\n * See the README for more details.\n */\nexport type CaveatSpecificationConstraint =\n | RestrictedMethodCaveatSpecificationConstraint\n | EndowmentCaveatSpecificationConstraint;\n\n/**\n * Options for {@link CaveatSpecificationBuilder} functions.\n */\ntype CaveatSpecificationBuilderOptions<\n DecoratorHooks extends Record<string, unknown>,\n ValidatorHooks extends Record<string, unknown>,\n> = {\n type?: string;\n decoratorHooks?: DecoratorHooks;\n validatorHooks?: ValidatorHooks;\n};\n\n/**\n * A function that builds caveat specifications. Modules that specify caveats\n * for external consumption should make this their primary / default export so\n * that host applications can use them to generate concrete specifications\n * tailored to their requirements.\n */\nexport type CaveatSpecificationBuilder<\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Options extends CaveatSpecificationBuilderOptions<any, any>,\n Specification extends CaveatSpecificationConstraint,\n> = (options: Options) => Specification;\n\n/**\n * A caveat specification export object, containing the\n * {@link CaveatSpecificationBuilder} function and \"hook name\" objects.\n */\nexport type CaveatSpecificationBuilderExportConstraint = {\n specificationBuilder: CaveatSpecificationBuilder<\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n CaveatSpecificationBuilderOptions<any, any>,\n CaveatSpecificationConstraint\n >;\n decoratorHookNames?: Record<string, true>;\n validatorHookNames?: Record<string, true>;\n};\n\n/**\n * The specifications for all caveats supported by a particular\n * {@link PermissionController}.\n *\n * @template Specifications - The union of all {@link CaveatSpecificationConstraint} types.\n */\nexport type CaveatSpecificationMap<\n CaveatSpecification extends CaveatSpecificationConstraint,\n> = Record<CaveatSpecification['type'], CaveatSpecification>;\n\n/**\n * Extracts the union of all caveat types specified by the given\n * {@link CaveatSpecificationConstraint} type.\n *\n * @template CaveatSpecification - The {@link CaveatSpecificationConstraint} to extract a\n * caveat type union from.\n */\nexport type ExtractCaveats<\n CaveatSpecification extends CaveatSpecificationConstraint,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n> = CaveatSpecification extends any\n ? CaveatSpecification extends RestrictedMethodCaveatSpecificationConstraint\n ? Caveat<\n CaveatSpecification['type'],\n ExtractCaveatValueFromDecorator<\n RestrictedMethodCaveatSpecificationConstraint['decorator']\n >\n >\n : Caveat<CaveatSpecification['type'], Json>\n : never;\n\n/**\n * Extracts the type of a specific {@link Caveat} from a union of caveat\n * specifications.\n *\n * @template CaveatSpecifications - The union of all caveat specifications.\n * @template CaveatType - The type of the caveat to extract.\n */\nexport type ExtractCaveat<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n CaveatType extends string,\n> = Extract<ExtractCaveats<CaveatSpecifications>, { type: CaveatType }>;\n\n/**\n * Extracts the value type of a specific {@link Caveat} from a union of caveat\n * specifications.\n *\n * @template CaveatSpecifications - The union of all caveat specifications.\n * @template CaveatType - The type of the caveat whose value to extract.\n */\nexport type ExtractCaveatValue<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n CaveatType extends string,\n> = ExtractCaveat<CaveatSpecifications, CaveatType>['value'];\n\n/**\n * Determines whether a caveat specification is a restricted method caveat specification.\n *\n * @param specification - The caveat specification.\n * @returns True if the caveat specification is a restricted method caveat specification, otherwise false.\n */\nexport function isRestrictedMethodCaveatSpecification(\n specification: CaveatSpecificationConstraint,\n): specification is RestrictedMethodCaveatSpecificationConstraint {\n return hasProperty(specification, 'decorator');\n}\n\n/**\n * Decorate a restricted method implementation with its caveats.\n *\n * Note that all caveat functions (i.e. the argument and return value of the\n * decorator) must be awaited.\n *\n * @param methodImplementation - The restricted method implementation\n * @param permission - The origin's potential permission\n * @param caveatSpecifications - All caveat implementations\n * @returns The decorated method implementation\n */\nexport function decorateWithCaveats<\n CaveatSpecifications extends CaveatSpecificationConstraint,\n>(\n methodImplementation: RestrictedMethod<RestrictedMethodParameters, Json>,\n permission: Readonly<PermissionConstraint>, // bound to the requesting origin\n caveatSpecifications: CaveatSpecificationMap<CaveatSpecifications>, // all caveat implementations\n): RestrictedMethod<RestrictedMethodParameters, Json> {\n const { caveats } = permission;\n if (!caveats) {\n return methodImplementation;\n }\n\n let decorated = async (\n args: Parameters<RestrictedMethod<RestrictedMethodParameters, Json>>[0],\n ) => methodImplementation(args);\n\n for (const caveat of caveats) {\n const specification =\n caveatSpecifications[caveat.type as CaveatSpecifications['type']];\n if (!specification) {\n throw new UnrecognizedCaveatTypeError(caveat.type);\n }\n\n if (!isRestrictedMethodCaveatSpecification(specification)) {\n throw new CaveatSpecificationMismatchError(\n specification,\n PermissionType.RestrictedMethod,\n );\n }\n decorated = specification.decorator(decorated, caveat);\n }\n\n return decorated;\n}\n"]}
|
package/dist/Permission.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Permission.d.ts","sourceRoot":"","sources":["../src/Permission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAI5C,OAAO,KAAK,EAAE,gBAAgB,EAAU,MAAM,UAAU,CAAC;AACzD,OAAO,KAAK,EAGV,kBAAkB,E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AAC;AAEV;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,SAAS,iCAAiC,EACvD,IAAI,SAAS,cAAc,EAE3B,aAAa,EAAE,aAAa,EAC5B,YAAY,EAAE,IAAI,GACjB,aAAa,IAAI,aAAa,GAAG;IAClC,cAAc,EAAE,IAAI,CAAC;CACtB,CAEA;AAED;;;;;GAKG;AACH,oBAAY,0BAA0B,CACpC,aAAa,SAAS,iCAAiC,IACrD;KACD,IAAI,IAAI,aAAa,CAAC,YAAY,CAAC,GAAG,aAAa,SAAS;QAC3D,UAAU,EAAE,IAAI,CAAC;KAClB,GACG,aAAa,GACb,KAAK;CACV,CAAC;AAEF;;;;;;GAMG;AACH,oBAAY,8BAA8B,CACxC,aAAa,SAAS,iCAAiC,EACvD,IAAI,SAAS,aAAa,CAAC,YAAY,CAAC,IACtC,aAAa,SAAS;IACxB,UAAU,EAAE,IAAI,CAAC;CAClB,GACG,aAAa,GACb,KAAK,CAAC"}
|
package/dist/Permission.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Permission.js","sourceRoot":"","sources":["../src/Permission.ts"],"names":[],"mappings":";;;AAMA,mCAAgC;AAoJhC;;;;;;;;GAQG;AACH,SAAgB,mBAAmB,CAEjC,OAA4C;IAC5C,MAAM,EAAE,OAAO,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAEpD,OAAO;QACL,EAAE,EAAE,IAAA,eAAM,GAAE;QACZ,gBAAgB,EAAE,MAAM;QACxB,OAAO;QACP,OAAO;QACP,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;KACP,CAAC;AACxB,CAAC;AAZD,kDAYC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CACxB,UAAgC,EAChC,UAAkB;;IAElB,OAAO,MAAA,UAAU,CAAC,OAAO,0CAAE,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC;AAC1E,CAAC;AALD,gCAKC;AA6JD;;GAEG;AACH,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAqC,CAAA;IAErC;;;OAGG;IACH,yCAAuB,CAAA;AACzB,CAAC,EAZW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAYzB;AA0LD;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAIlC,aAA4B,EAC5B,YAAkB;IAIlB,OAAO,aAAa,CAAC,cAAc,KAAK,YAAY,CAAC;AACvD,CAAC;AAVD,oDAUC","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport type { NonEmptyArray } from '@metamask/controller-utils';\nimport type { Json } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { CaveatConstraint, Caveat } from './Caveat';\nimport type {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n PermissionController,\n PermissionsRequest,\n SideEffectMessenger,\n} from './PermissionController';\nimport type { SubjectType } from './SubjectMetadataController';\n\n/**\n * The origin of a subject.\n * Effectively the GUID of an entity that can have permissions.\n */\nexport type OriginString = string;\n\n/**\n * The name of a permission target.\n */\ntype TargetName = string;\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n */\nexport type PermissionConstraint = {\n /**\n * The context(s) in which this capability is meaningful.\n *\n * It is required by the standard, but we make it optional since there is only\n * one context in our usage (i.e. the user's MetaMask instance).\n */\n readonly '@context'?: NonEmptyArray<string>;\n\n // TODO:TS4.4 Make optional\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: null | NonEmptyArray<CaveatConstraint>;\n\n /**\n * The creation date of the permission, in UNIX epoch time.\n */\n readonly date: number;\n\n /**\n * The GUID of the permission object.\n */\n readonly id: string;\n\n /**\n * The origin string of the subject that has the permission.\n */\n readonly invoker: OriginString;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: string;\n};\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n *\n * @template Name - The name of the permission that the target corresponds to.\n * @template AllowedCaveat - A union of the allowed {@link Caveat} types\n * for the permission.\n */\nexport type ValidPermission<\n Name extends TargetName,\n AllowedCaveat extends CaveatConstraint,\n> = PermissionConstraint & {\n // TODO:TS4.4 Make optional\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: AllowedCaveat extends never\n ? null\n : NonEmptyArray<AllowedCaveat> | null;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: Name;\n};\n\n/**\n * Internal utility for extracting the members types of an array. The type\n * evalutes to `never` if the specified type is the empty tuple or neither\n * an array nor a tuple.\n *\n * @template ArrayType - The array type whose members to extract.\n */\ntype ExtractArrayMembers<ArrayType> = ArrayType extends []\n ? never\n : ArrayType extends any[] | readonly any[]\n ? ArrayType[number]\n : never;\n\n/**\n * A utility type for extracting the allowed caveat types for a particular\n * permission from a permission specification type.\n *\n * @template PermissionSpecification - The permission specification type to\n * extract valid caveat types from.\n */\nexport type ExtractAllowedCaveatTypes<\n PermissionSpecification extends PermissionSpecificationConstraint,\n> = ExtractArrayMembers<PermissionSpecification['allowedCaveats']>;\n\n/**\n * The options object of {@link constructPermission}.\n *\n * @template TargetPermission - The {@link Permission} that will be constructed.\n */\nexport type PermissionOptions<TargetPermission extends PermissionConstraint> = {\n target: TargetPermission['parentCapability'];\n /**\n * The origin string of the subject that has the permission.\n */\n invoker: OriginString;\n\n /**\n * The caveats of the permission.\n * See {@link Caveat}.\n */\n caveats?: NonEmptyArray<CaveatConstraint>;\n};\n\n/**\n * The default permission factory function. Naively constructs a permission from\n * the inputs. Sets a default, random `id` if none is provided.\n *\n * @see {@link Permission} For more details.\n * @template TargetPermission- - The {@link Permission} that will be constructed.\n * @param options - The options for the permission.\n * @returns The new permission object.\n */\nexport function constructPermission<\n TargetPermission extends PermissionConstraint,\n>(options: PermissionOptions<TargetPermission>): TargetPermission {\n const { caveats = null, invoker, target } = options;\n\n return {\n id: nanoid(),\n parentCapability: target,\n invoker,\n caveats,\n date: new Date().getTime(),\n } as TargetPermission;\n}\n\n/**\n * Gets the caveat of the specified type belonging to the specified permission.\n *\n * @param permission - The permission whose caveat to retrieve.\n * @param caveatType - The type of the caveat to retrieve.\n * @returns The caveat, or undefined if no such caveat exists.\n */\nexport function findCaveat(\n permission: PermissionConstraint,\n caveatType: string,\n): CaveatConstraint | undefined {\n return permission.caveats?.find((caveat) => caveat.type === caveatType);\n}\n\n/**\n * A requested permission object. Just an object with any of the properties\n * of a {@link PermissionConstraint} object.\n */\ntype RequestedPermission = Partial<PermissionConstraint>;\n\n/**\n * A record of target names and their {@link RequestedPermission} objects.\n */\nexport type RequestedPermissions = Record<TargetName, RequestedPermission>;\n\n/**\n * The restricted method context object. Essentially a way to pass internal\n * arguments to restricted methods and caveat functions, most importantly the\n * requesting origin.\n */\ntype RestrictedMethodContext = Readonly<{\n origin: OriginString;\n [key: string]: any;\n}>;\n\nexport type RestrictedMethodParameters = Json[] | Record<string, Json>;\n\n/**\n * The arguments passed to a restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n */\nexport type RestrictedMethodOptions<\n Params extends RestrictedMethodParameters | null,\n> = {\n method: TargetName;\n params?: Params;\n context: RestrictedMethodContext;\n};\n\n/**\n * A synchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type SyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Result;\n\n/**\n * An asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type AsyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Promise<Result>;\n\n/**\n * A synchronous or asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type RestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> =\n | SyncRestrictedMethod<Params, Result>\n | AsyncRestrictedMethod<Params, Result>;\n\nexport type ValidRestrictedMethod<\n MethodImplementation extends RestrictedMethod<any, any>,\n> = MethodImplementation extends (args: infer Options) => Json | Promise<Json>\n ? Options extends RestrictedMethodOptions<RestrictedMethodParameters>\n ? MethodImplementation\n : never\n : never;\n\n/**\n * {@link EndowmentGetter} parameter object.\n */\nexport type EndowmentGetterParams = {\n /**\n * The origin of the requesting subject.\n */\n origin: string;\n\n /**\n * Any additional data associated with the request.\n */\n requestData?: unknown;\n\n [key: string]: unknown;\n};\n\n/**\n * A synchronous or asynchronous function that gets the endowments for a\n * particular endowment permission. The getter receives the origin of the\n * requesting subject and, optionally, additional request metadata.\n */\nexport type EndowmentGetter<Endowments extends Json> = (\n options: EndowmentGetterParams,\n) => Endowments | Promise<Endowments>;\n\nexport type PermissionFactory<\n TargetPermission extends PermissionConstraint,\n RequestData extends Record<string, unknown>,\n> = (\n options: PermissionOptions<TargetPermission>,\n requestData?: RequestData,\n) => TargetPermission;\n\nexport type PermissionValidatorConstraint = (\n permission: PermissionConstraint,\n origin?: OriginString,\n target?: string,\n) => void;\n\n/**\n * The parameters passed to the side-effect function.\n */\nexport type SideEffectParams<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n requestData: PermissionsRequest;\n messagingSystem: SideEffectMessenger<Actions, Events>;\n};\n\n/**\n * A function that will execute actions as a permission side-effect.\n */\nexport type SideEffectHandler<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = (params: SideEffectParams<Actions, Events>) => Promise<unknown>;\n\n/**\n * The permissions side effects.\n */\nexport type PermissionSideEffect<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n /**\n * A method triggered when the permission is accepted by the user\n */\n onPermitted: SideEffectHandler<Actions, Events>;\n /**\n * A method triggered if a `onPermitted` method rejected.\n */\n onFailure?: SideEffectHandler<Actions, Events>;\n};\n\n/**\n * The different possible types of permissions.\n */\nexport enum PermissionType {\n /**\n * A restricted JSON-RPC method. A subject must have the requisite permission\n * to call a restricted JSON-RPC method.\n */\n RestrictedMethod = 'RestrictedMethod',\n\n /**\n * An \"endowment\" granted to subjects that possess the requisite permission,\n * such as a global environment variable exposing a restricted API, etc.\n */\n Endowment = 'Endowment',\n}\n\n/**\n * The base constraint for permission specification objects. Every\n * {@link Permission} supported by a {@link PermissionController} must have an\n * associated specification, which is the source of truth for all permission-\n * related types. A permission specification includes the list of permitted\n * caveats, and any factory and validation functions specified by the consumer.\n * A concrete permission specification may specify further fields as necessary.\n *\n * See the README for more details.\n */\ntype PermissionSpecificationBase<Type extends PermissionType> = {\n /**\n * The type of the specified permission.\n */\n permissionType: Type;\n\n /**\n * The name of the target resource of the permission.\n */\n targetName: string;\n\n /**\n * An array of the caveat types that may be added to instances of this\n * permission.\n */\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n\n /**\n * The factory function used to get permission objects. Permissions returned\n * by this function are presumed to valid, and they will not be passed to the\n * validator function associated with this specification (if any). In other\n * words, the factory function should validate the permissions it creates.\n *\n * If no factory is specified, the {@link Permission} constructor will be\n * used, and the validator function (if specified) will be called on newly\n * constructed permissions.\n */\n factory?: PermissionFactory<any, Record<string, unknown>>;\n\n /**\n * The validator function used to validate permissions of the associated type\n * whenever they are mutated. The only way a permission can be legally mutated\n * is when its caveats are modified by the permission controller.\n *\n * The validator should throw an appropriate JSON-RPC error if validation fails.\n */\n validator?: PermissionValidatorConstraint;\n\n /**\n * The side-effect triggered by the {@link PermissionController} once the user approved it.\n * The side-effect can only be an action allowed to be called inside the {@link PermissionController}.\n *\n * If the side-effect action fails, the permission that triggered it is revoked.\n */\n sideEffect?: PermissionSideEffect<any, any>;\n\n /**\n * The Permission may be available to only a subset of the subject types. If so, specify the subject types as an array.\n * If a subject with a type not in this array tries to request the permission, the call will fail.\n *\n * Leaving this as undefined uses default behaviour where the permission is available to request for all subject types.\n */\n subjectTypes?: readonly SubjectType[];\n};\n\n/**\n * The constraint for restricted method permission specification objects.\n * Permissions that correspond to JSON-RPC methods are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type RestrictedMethodSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.RestrictedMethod> & {\n /**\n * The implementation of the restricted method that the permission\n * corresponds to.\n */\n methodImplementation: RestrictedMethod<any, any>;\n };\n\n/**\n * The constraint for endowment permission specification objects. Permissions\n * that endow callers with some restricted resource are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type EndowmentSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.Endowment> & {\n /**\n * The {@link EndowmentGetter} function for the permission. This function\n * will be called by the {@link PermissionController} whenever the\n * permission is invoked, after which the host can apply the endowments to\n * the requesting subject in the intended manner.\n */\n endowmentGetter: EndowmentGetter<any>;\n };\n\n/**\n * The constraint for permission specification objects. Every {@link Permission}\n * supported by a {@link PermissionController} must have an associated\n * specification, which is the source of truth for all permission-related types.\n * All specifications must adhere to the {@link PermissionSpecificationBase}\n * interface, but specifications may have different fields depending on the\n * {@link PermissionType}.\n *\n * See the README for more details.\n */\nexport type PermissionSpecificationConstraint =\n | EndowmentSpecificationConstraint\n | RestrictedMethodSpecificationConstraint;\n\n/**\n * Options for {@link PermissionSpecificationBuilder} functions.\n */\ntype PermissionSpecificationBuilderOptions<\n FactoryHooks extends Record<string, unknown>,\n MethodHooks extends Record<string, unknown>,\n ValidatorHooks extends Record<string, unknown>,\n> = {\n targetName?: string;\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n factoryHooks?: FactoryHooks;\n methodHooks?: MethodHooks;\n validatorHooks?: ValidatorHooks;\n};\n\n/**\n * A function that builds a permission specification. Modules that specify\n * permissions for external consumption should make this their primary /\n * default export so that host applications can use them to generate concrete\n * specifications tailored to their requirements.\n */\nexport type PermissionSpecificationBuilder<\n Type extends PermissionType,\n Options extends PermissionSpecificationBuilderOptions<any, any, any>,\n Specification extends PermissionSpecificationConstraint & {\n permissionType: Type;\n },\n> = (options: Options) => Specification;\n\n/**\n * A restricted method permission export object, containing the\n * {@link PermissionSpecificationBuilder} function and \"hook name\" objects.\n */\nexport type PermissionSpecificationBuilderExportConstraint = {\n targetName: string;\n specificationBuilder: PermissionSpecificationBuilder<\n PermissionType,\n PermissionSpecificationBuilderOptions<any, any, any>,\n PermissionSpecificationConstraint\n >;\n factoryHookNames?: Record<string, true>;\n methodHookNames?: Record<string, true>;\n validatorHookNames?: Record<string, true>;\n};\n\ntype ValidRestrictedMethodSpecification<\n Specification extends RestrictedMethodSpecificationConstraint,\n> = Specification['methodImplementation'] extends ValidRestrictedMethod<\n Specification['methodImplementation']\n>\n ? Specification\n : never;\n\n/**\n * Constraint for {@link PermissionSpecificationConstraint} objects that\n * evaluates to `never` if the specification contains any invalid fields.\n *\n * @template Specification - The permission specification to validate.\n */\nexport type ValidPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n> = Specification['targetName'] extends TargetName\n ? Specification['permissionType'] extends PermissionType.Endowment\n ? Specification\n : Specification['permissionType'] extends PermissionType.RestrictedMethod\n ? ValidRestrictedMethodSpecification<\n Extract<Specification, RestrictedMethodSpecificationConstraint>\n >\n : never\n : never;\n\n/**\n * Checks that the specification has the expected permission type.\n *\n * @param specification - The specification to check.\n * @param expectedType - The expected permission type.\n * @template Specification - The specification to check.\n * @template Type - The expected permission type.\n * @returns Whether or not the specification is of the expected type.\n */\nexport function hasSpecificationType<\n Specification extends PermissionSpecificationConstraint,\n Type extends PermissionType,\n>(\n specification: Specification,\n expectedType: Type,\n): specification is Specification & {\n permissionType: Type;\n} {\n return specification.permissionType === expectedType;\n}\n\n/**\n * The specifications for all permissions supported by a particular\n * {@link PermissionController}.\n *\n * @template Specifications - The union of all {@link PermissionSpecificationConstraint} types.\n */\nexport type PermissionSpecificationMap<\n Specification extends PermissionSpecificationConstraint,\n> = {\n [Name in Specification['targetName']]: Specification extends {\n targetName: Name;\n }\n ? Specification\n : never;\n};\n\n/**\n * Extracts a specific {@link PermissionSpecificationConstraint} from a union of\n * permission specifications.\n *\n * @template Specification - The specification union type to extract from.\n * @template Name - The `targetName` of the specification to extract.\n */\nexport type ExtractPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n Name extends Specification['targetName'],\n> = Specification extends {\n targetName: Name;\n}\n ? Specification\n : never;\n"]}
|
|
1
|
+
{"version":3,"file":"Permission.js","sourceRoot":"","sources":["../src/Permission.ts"],"names":[],"mappings":";;;AAMA,mCAAgC;AAsJhC;;;;;;;;GAQG;AACH,SAAgB,mBAAmB,CAEjC,OAA4C;IAC5C,MAAM,EAAE,OAAO,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAEpD,OAAO;QACL,EAAE,EAAE,IAAA,eAAM,GAAE;QACZ,gBAAgB,EAAE,MAAM;QACxB,OAAO;QACP,OAAO;QACP,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;KACP,CAAC;AACxB,CAAC;AAZD,kDAYC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CACxB,UAAgC,EAChC,UAAkB;;IAElB,OAAO,MAAA,UAAU,CAAC,OAAO,0CAAE,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC;AAC1E,CAAC;AALD,gCAKC;AAiKD;;GAEG;AACH,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAqC,CAAA;IAErC;;;OAGG;IACH,yCAAuB,CAAA;AACzB,CAAC,EAZW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAYzB;AAsMD;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAIlC,aAA4B,EAC5B,YAAkB;IAIlB,OAAO,aAAa,CAAC,cAAc,KAAK,YAAY,CAAC;AACvD,CAAC;AAVD,oDAUC","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport type { NonEmptyArray } from '@metamask/controller-utils';\nimport type { Json } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { CaveatConstraint, Caveat } from './Caveat';\nimport type {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n PermissionController,\n PermissionsRequest,\n SideEffectMessenger,\n} from './PermissionController';\nimport type { SubjectType } from './SubjectMetadataController';\n\n/**\n * The origin of a subject.\n * Effectively the GUID of an entity that can have permissions.\n */\nexport type OriginString = string;\n\n/**\n * The name of a permission target.\n */\ntype TargetName = string;\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n */\nexport type PermissionConstraint = {\n /**\n * The context(s) in which this capability is meaningful.\n *\n * It is required by the standard, but we make it optional since there is only\n * one context in our usage (i.e. the user's MetaMask instance).\n */\n readonly '@context'?: NonEmptyArray<string>;\n\n // TODO:TS4.4 Make optional\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: null | NonEmptyArray<CaveatConstraint>;\n\n /**\n * The creation date of the permission, in UNIX epoch time.\n */\n readonly date: number;\n\n /**\n * The GUID of the permission object.\n */\n readonly id: string;\n\n /**\n * The origin string of the subject that has the permission.\n */\n readonly invoker: OriginString;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: string;\n};\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n *\n * @template Name - The name of the permission that the target corresponds to.\n * @template AllowedCaveat - A union of the allowed {@link Caveat} types\n * for the permission.\n */\nexport type ValidPermission<\n Name extends TargetName,\n AllowedCaveat extends CaveatConstraint,\n> = PermissionConstraint & {\n // TODO:TS4.4 Make optional\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: AllowedCaveat extends never\n ? null\n : NonEmptyArray<AllowedCaveat> | null;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: Name;\n};\n\n/**\n * Internal utility for extracting the members types of an array. The type\n * evalutes to `never` if the specified type is the empty tuple or neither\n * an array nor a tuple.\n *\n * @template ArrayType - The array type whose members to extract.\n */\ntype ExtractArrayMembers<ArrayType> = ArrayType extends []\n ? never\n : // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ArrayType extends any[] | readonly any[]\n ? ArrayType[number]\n : never;\n\n/**\n * A utility type for extracting the allowed caveat types for a particular\n * permission from a permission specification type.\n *\n * @template PermissionSpecification - The permission specification type to\n * extract valid caveat types from.\n */\nexport type ExtractAllowedCaveatTypes<\n PermissionSpecification extends PermissionSpecificationConstraint,\n> = ExtractArrayMembers<PermissionSpecification['allowedCaveats']>;\n\n/**\n * The options object of {@link constructPermission}.\n *\n * @template TargetPermission - The {@link Permission} that will be constructed.\n */\nexport type PermissionOptions<TargetPermission extends PermissionConstraint> = {\n target: TargetPermission['parentCapability'];\n /**\n * The origin string of the subject that has the permission.\n */\n invoker: OriginString;\n\n /**\n * The caveats of the permission.\n * See {@link Caveat}.\n */\n caveats?: NonEmptyArray<CaveatConstraint>;\n};\n\n/**\n * The default permission factory function. Naively constructs a permission from\n * the inputs. Sets a default, random `id` if none is provided.\n *\n * @see {@link Permission} For more details.\n * @template TargetPermission- - The {@link Permission} that will be constructed.\n * @param options - The options for the permission.\n * @returns The new permission object.\n */\nexport function constructPermission<\n TargetPermission extends PermissionConstraint,\n>(options: PermissionOptions<TargetPermission>): TargetPermission {\n const { caveats = null, invoker, target } = options;\n\n return {\n id: nanoid(),\n parentCapability: target,\n invoker,\n caveats,\n date: new Date().getTime(),\n } as TargetPermission;\n}\n\n/**\n * Gets the caveat of the specified type belonging to the specified permission.\n *\n * @param permission - The permission whose caveat to retrieve.\n * @param caveatType - The type of the caveat to retrieve.\n * @returns The caveat, or undefined if no such caveat exists.\n */\nexport function findCaveat(\n permission: PermissionConstraint,\n caveatType: string,\n): CaveatConstraint | undefined {\n return permission.caveats?.find((caveat) => caveat.type === caveatType);\n}\n\n/**\n * A requested permission object. Just an object with any of the properties\n * of a {@link PermissionConstraint} object.\n */\ntype RequestedPermission = Partial<PermissionConstraint>;\n\n/**\n * A record of target names and their {@link RequestedPermission} objects.\n */\nexport type RequestedPermissions = Record<TargetName, RequestedPermission>;\n\n/**\n * The restricted method context object. Essentially a way to pass internal\n * arguments to restricted methods and caveat functions, most importantly the\n * requesting origin.\n */\ntype RestrictedMethodContext = Readonly<{\n origin: OriginString;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}>;\n\nexport type RestrictedMethodParameters = Json[] | Record<string, Json>;\n\n/**\n * The arguments passed to a restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n */\nexport type RestrictedMethodOptions<\n Params extends RestrictedMethodParameters | null,\n> = {\n method: TargetName;\n params?: Params;\n context: RestrictedMethodContext;\n};\n\n/**\n * A synchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type SyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Result;\n\n/**\n * An asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type AsyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Promise<Result>;\n\n/**\n * A synchronous or asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type RestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> =\n | SyncRestrictedMethod<Params, Result>\n | AsyncRestrictedMethod<Params, Result>;\n\nexport type ValidRestrictedMethod<\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n MethodImplementation extends RestrictedMethod<any, any>,\n> = MethodImplementation extends (args: infer Options) => Json | Promise<Json>\n ? Options extends RestrictedMethodOptions<RestrictedMethodParameters>\n ? MethodImplementation\n : never\n : never;\n\n/**\n * {@link EndowmentGetter} parameter object.\n */\nexport type EndowmentGetterParams = {\n /**\n * The origin of the requesting subject.\n */\n origin: string;\n\n /**\n * Any additional data associated with the request.\n */\n requestData?: unknown;\n\n [key: string]: unknown;\n};\n\n/**\n * A synchronous or asynchronous function that gets the endowments for a\n * particular endowment permission. The getter receives the origin of the\n * requesting subject and, optionally, additional request metadata.\n */\nexport type EndowmentGetter<Endowments extends Json> = (\n options: EndowmentGetterParams,\n) => Endowments | Promise<Endowments>;\n\nexport type PermissionFactory<\n TargetPermission extends PermissionConstraint,\n RequestData extends Record<string, unknown>,\n> = (\n options: PermissionOptions<TargetPermission>,\n requestData?: RequestData,\n) => TargetPermission;\n\nexport type PermissionValidatorConstraint = (\n permission: PermissionConstraint,\n origin?: OriginString,\n target?: string,\n) => void;\n\n/**\n * The parameters passed to the side-effect function.\n */\nexport type SideEffectParams<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n requestData: PermissionsRequest;\n messagingSystem: SideEffectMessenger<Actions, Events>;\n};\n\n/**\n * A function that will execute actions as a permission side-effect.\n */\nexport type SideEffectHandler<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = (params: SideEffectParams<Actions, Events>) => Promise<unknown>;\n\n/**\n * The permissions side effects.\n */\nexport type PermissionSideEffect<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n /**\n * A method triggered when the permission is accepted by the user\n */\n onPermitted: SideEffectHandler<Actions, Events>;\n /**\n * A method triggered if a `onPermitted` method rejected.\n */\n onFailure?: SideEffectHandler<Actions, Events>;\n};\n\n/**\n * The different possible types of permissions.\n */\nexport enum PermissionType {\n /**\n * A restricted JSON-RPC method. A subject must have the requisite permission\n * to call a restricted JSON-RPC method.\n */\n RestrictedMethod = 'RestrictedMethod',\n\n /**\n * An \"endowment\" granted to subjects that possess the requisite permission,\n * such as a global environment variable exposing a restricted API, etc.\n */\n Endowment = 'Endowment',\n}\n\n/**\n * The base constraint for permission specification objects. Every\n * {@link Permission} supported by a {@link PermissionController} must have an\n * associated specification, which is the source of truth for all permission-\n * related types. A permission specification includes the list of permitted\n * caveats, and any factory and validation functions specified by the consumer.\n * A concrete permission specification may specify further fields as necessary.\n *\n * See the README for more details.\n */\ntype PermissionSpecificationBase<Type extends PermissionType> = {\n /**\n * The type of the specified permission.\n */\n permissionType: Type;\n\n /**\n * The name of the target resource of the permission.\n */\n targetName: string;\n\n /**\n * An array of the caveat types that may be added to instances of this\n * permission.\n */\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n\n /**\n * The factory function used to get permission objects. Permissions returned\n * by this function are presumed to valid, and they will not be passed to the\n * validator function associated with this specification (if any). In other\n * words, the factory function should validate the permissions it creates.\n *\n * If no factory is specified, the {@link Permission} constructor will be\n * used, and the validator function (if specified) will be called on newly\n * constructed permissions.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n factory?: PermissionFactory<any, Record<string, unknown>>;\n\n /**\n * The validator function used to validate permissions of the associated type\n * whenever they are mutated. The only way a permission can be legally mutated\n * is when its caveats are modified by the permission controller.\n *\n * The validator should throw an appropriate JSON-RPC error if validation fails.\n */\n validator?: PermissionValidatorConstraint;\n\n /**\n * The side-effect triggered by the {@link PermissionController} once the user approved it.\n * The side-effect can only be an action allowed to be called inside the {@link PermissionController}.\n *\n * If the side-effect action fails, the permission that triggered it is revoked.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n sideEffect?: PermissionSideEffect<any, any>;\n\n /**\n * The Permission may be available to only a subset of the subject types. If so, specify the subject types as an array.\n * If a subject with a type not in this array tries to request the permission, the call will fail.\n *\n * Leaving this as undefined uses default behaviour where the permission is available to request for all subject types.\n */\n subjectTypes?: readonly SubjectType[];\n};\n\n/**\n * The constraint for restricted method permission specification objects.\n * Permissions that correspond to JSON-RPC methods are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type RestrictedMethodSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.RestrictedMethod> & {\n /**\n * The implementation of the restricted method that the permission\n * corresponds to.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n methodImplementation: RestrictedMethod<any, any>;\n };\n\n/**\n * The constraint for endowment permission specification objects. Permissions\n * that endow callers with some restricted resource are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type EndowmentSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.Endowment> & {\n /**\n * The {@link EndowmentGetter} function for the permission. This function\n * will be called by the {@link PermissionController} whenever the\n * permission is invoked, after which the host can apply the endowments to\n * the requesting subject in the intended manner.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n endowmentGetter: EndowmentGetter<any>;\n };\n\n/**\n * The constraint for permission specification objects. Every {@link Permission}\n * supported by a {@link PermissionController} must have an associated\n * specification, which is the source of truth for all permission-related types.\n * All specifications must adhere to the {@link PermissionSpecificationBase}\n * interface, but specifications may have different fields depending on the\n * {@link PermissionType}.\n *\n * See the README for more details.\n */\nexport type PermissionSpecificationConstraint =\n | EndowmentSpecificationConstraint\n | RestrictedMethodSpecificationConstraint;\n\n/**\n * Options for {@link PermissionSpecificationBuilder} functions.\n */\ntype PermissionSpecificationBuilderOptions<\n FactoryHooks extends Record<string, unknown>,\n MethodHooks extends Record<string, unknown>,\n ValidatorHooks extends Record<string, unknown>,\n> = {\n targetName?: string;\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n factoryHooks?: FactoryHooks;\n methodHooks?: MethodHooks;\n validatorHooks?: ValidatorHooks;\n};\n\n/**\n * A function that builds a permission specification. Modules that specify\n * permissions for external consumption should make this their primary /\n * default export so that host applications can use them to generate concrete\n * specifications tailored to their requirements.\n */\nexport type PermissionSpecificationBuilder<\n Type extends PermissionType,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Options extends PermissionSpecificationBuilderOptions<any, any, any>,\n Specification extends PermissionSpecificationConstraint & {\n permissionType: Type;\n },\n> = (options: Options) => Specification;\n\n/**\n * A restricted method permission export object, containing the\n * {@link PermissionSpecificationBuilder} function and \"hook name\" objects.\n */\nexport type PermissionSpecificationBuilderExportConstraint = {\n targetName: string;\n specificationBuilder: PermissionSpecificationBuilder<\n PermissionType,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PermissionSpecificationBuilderOptions<any, any, any>,\n PermissionSpecificationConstraint\n >;\n factoryHookNames?: Record<string, true>;\n methodHookNames?: Record<string, true>;\n validatorHookNames?: Record<string, true>;\n};\n\ntype ValidRestrictedMethodSpecification<\n Specification extends RestrictedMethodSpecificationConstraint,\n> = Specification['methodImplementation'] extends ValidRestrictedMethod<\n Specification['methodImplementation']\n>\n ? Specification\n : never;\n\n/**\n * Constraint for {@link PermissionSpecificationConstraint} objects that\n * evaluates to `never` if the specification contains any invalid fields.\n *\n * @template Specification - The permission specification to validate.\n */\nexport type ValidPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n> = Specification['targetName'] extends TargetName\n ? Specification['permissionType'] extends PermissionType.Endowment\n ? Specification\n : Specification['permissionType'] extends PermissionType.RestrictedMethod\n ? ValidRestrictedMethodSpecification<\n Extract<Specification, RestrictedMethodSpecificationConstraint>\n >\n : never\n : never;\n\n/**\n * Checks that the specification has the expected permission type.\n *\n * @param specification - The specification to check.\n * @param expectedType - The expected permission type.\n * @template Specification - The specification to check.\n * @template Type - The expected permission type.\n * @returns Whether or not the specification is of the expected type.\n */\nexport function hasSpecificationType<\n Specification extends PermissionSpecificationConstraint,\n Type extends PermissionType,\n>(\n specification: Specification,\n expectedType: Type,\n): specification is Specification & {\n permissionType: Type;\n} {\n return specification.permissionType === expectedType;\n}\n\n/**\n * The specifications for all permissions supported by a particular\n * {@link PermissionController}.\n *\n * @template Specifications - The union of all {@link PermissionSpecificationConstraint} types.\n */\nexport type PermissionSpecificationMap<\n Specification extends PermissionSpecificationConstraint,\n> = {\n [Name in Specification['targetName']]: Specification extends {\n targetName: Name;\n }\n ? Specification\n : never;\n};\n\n/**\n * Extracts a specific {@link PermissionSpecificationConstraint} from a union of\n * permission specifications.\n *\n * @template Specification - The specification union type to extract from.\n * @template Name - The `targetName` of the specification to extract.\n */\nexport type ExtractPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n Name extends Specification['targetName'],\n> = Specification extends {\n targetName: Name;\n}\n ? Specification\n : never;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PermissionController.d.ts","sourceRoot":"","sources":["../src/PermissionController.ts"],"names":[],"mappings":"AACA,OAAO,KA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AAC,EAAE,OAAO,GACpB,OAAO,CAAC,IAAI,CAAC;IAYhB;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,uBAAuB,CAC3B,MAAM,EAAE,YAAY,EACpB,UAAU,EAAE,iCAAiC,CAC3C,iCAAiC,EACjC,6BAA6B,CAC9B,CAAC,kBAAkB,CAAC,EACrB,MAAM,CAAC,EAAE,0BAA0B,GAClC,OAAO,CAAC,IAAI,CAAC;IAoBhB;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,wBAAwB;CAsBjC"}
|
|
1
|
+
{"version":3,"file":"PermissionController.d.ts","sourceRoot":"","sources":["../src/PermissionController.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,aAAa,IAAI,qBAAqB,EACtC,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,IAAI,qBAAqB,EACvC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAEV,6BAA6B,EAC7B,gBAAgB,EAChB,eAAe,EACf,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAQhE,OAAO,KAAK,EAAE,IAAI,EAAW,MAAM,iBAAiB,CAAC;AAKrD,OAAO,KAAK,EACV,gBAAgB,EAChB,6BAA6B,EAC7B,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,kBAAkB,EACnB,MAAM,UAAU,CAAC;AA8BlB,OAAO,KAAK,EACV,gCAAgC,EAChC,yBAAyB,EAEzB,YAAY,EACZ,oBAAoB,EACpB,iCAAiC,EACjC,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,0BAA0B,EAC1B,uCAAuC,EACvC,iBAAiB,EACjB,eAAe,EACf,4BAA4B,EAC7B,MAAM,cAAc,CAAC;AAOtB,OAAO,EAAE,8BAA8B,EAAE,MAAM,yBAAyB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CAAC,2BAA2B;IAkDnC;;;;;OAKG;IACG,wBAAwB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IA+B1E;;;;;OAKG;IACG,wBAAwB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQzD;;;;;;;;;OASG;IACH,OAAO,CAAC,kBAAkB;IAY1B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,yBAAyB;IAQjC;;;;;;;;;;;OAWG;IACG,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,0BAA0B,CACpC,iCAAiC,EACjC,6BAA6B,CAC9B,CAAC,kBAAkB,CAAC,EACrB,WAAW,CAAC,EAAE,OAAO,GACpB,OAAO,CAAC,IAAI,CAAC;IAYhB;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,uBAAuB,CAC3B,MAAM,EAAE,YAAY,EACpB,UAAU,EAAE,iCAAiC,CAC3C,iCAAiC,EACjC,6BAA6B,CAC9B,CAAC,kBAAkB,CAAC,EACrB,MAAM,CAAC,EAAE,0BAA0B,GAClC,OAAO,CAAC,IAAI,CAAC;IAoBhB;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,wBAAwB;CAsBjC"}
|
|
@@ -533,6 +533,8 @@ class PermissionController extends base_controller_1.BaseController {
|
|
|
533
533
|
// is allowed to have caveats, but it should be impossible to call
|
|
534
534
|
// this method for a permission that may not have any caveats.
|
|
535
535
|
// If all else fails, the permission validator is also called.
|
|
536
|
+
// TODO: Replace `any` with type
|
|
537
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
536
538
|
permission.caveats = [caveat];
|
|
537
539
|
}
|
|
538
540
|
this.validateModifiedPermission(permission, origin);
|
|
@@ -599,7 +601,10 @@ class PermissionController extends base_controller_1.BaseController {
|
|
|
599
601
|
// This type check ensures that the switch statement is
|
|
600
602
|
// exhaustive.
|
|
601
603
|
const _exhaustiveCheck = mutatorResult;
|
|
602
|
-
throw new Error(`Unrecognized mutation result: "${
|
|
604
|
+
throw new Error(`Unrecognized mutation result: "${
|
|
605
|
+
// TODO: Replace `any` with type
|
|
606
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
607
|
+
_exhaustiveCheck.operation}"`);
|
|
603
608
|
}
|
|
604
609
|
}
|
|
605
610
|
});
|
|
@@ -1185,6 +1190,8 @@ class PermissionController extends base_controller_1.BaseController {
|
|
|
1185
1190
|
// Typecast: For some reason, the type here expects all of the possible
|
|
1186
1191
|
// HasApprovalRequest options to be specified, when they're actually all
|
|
1187
1192
|
// optional. Passing just the id is definitely valid, so we just cast it.
|
|
1193
|
+
// TODO: Replace `any` with type
|
|
1194
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1188
1195
|
options);
|
|
1189
1196
|
}
|
|
1190
1197
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PermissionController.js","sourceRoot":"","sources":["../src/PermissionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,+DAA2D;AAE3D,iEAIoC;AACpC,qDAAoD;AACpD,2CAA8C;AAE9C,4EAA4C;AAC5C,iCAA8C;AAC9C,mCAAgC;AAUhC,qCAGkB;AAClB,qCAwBkB;AAiBlB,6CAKsB;AACtB,mEAAyE;AAEzE,mCAAsC;AAmCtC;;GAEG;AACH,MAAM,cAAc,GAAG,sBAAsB,CAAC;AA4C9C;;;;;GAKG;AACH,SAAS,gBAAgB;IACvB,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAEpD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe;IACtB,OAAO,EAAE,QAAQ,EAAE,EAAE,EAA2C,CAAC;AACnE,CAAC;AAuLD;;GAEG;AACH,IAAY,sBAKX;AALD,WAAY,sBAAsB;IAChC,mEAAI,CAAA;IACJ,iFAAW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UAAU,EAAE;YACf,MAAM,IAAA,qBAAY,EAAC,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;SAClD;QAED,OAAO,IAAA,4BAAmB,EACxB,oBAAoB,EACpB,UAAU,EACV,IAAI,CAAC,qBAAqB,CAC3B,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7C,CAAC;CACF;AA50DD,oDA40DC","sourcesContent":["/* eslint-enable @typescript-eslint/no-unused-vars */\nimport type {\n AcceptRequest as AcceptApprovalRequest,\n AddApprovalRequest,\n HasApprovalRequest,\n RejectRequest as RejectApprovalRequest,\n} from '@metamask/approval-controller';\nimport type {\n StateMetadata,\n RestrictedControllerMessenger,\n ActionConstraint,\n EventConstraint,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { NonEmptyArray } from '@metamask/controller-utils';\nimport {\n isNonEmptyArray,\n isPlainObject,\n isValidJson,\n} from '@metamask/controller-utils';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport { hasProperty } from '@metamask/utils';\nimport type { Json, Mutable } from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\nimport { castDraft, type Draft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport type {\n CaveatConstraint,\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n ExtractCaveat,\n ExtractCaveats,\n ExtractCaveatValue,\n} from './Caveat';\nimport {\n decorateWithCaveats,\n isRestrictedMethodCaveatSpecification,\n} from './Caveat';\nimport {\n CaveatAlreadyExistsError,\n CaveatDoesNotExistError,\n CaveatInvalidJsonError,\n CaveatMissingValueError,\n CaveatSpecificationMismatchError,\n DuplicateCaveatError,\n EndowmentPermissionDoesNotExistError,\n ForbiddenCaveatError,\n internalError,\n InvalidApprovedPermissionError,\n InvalidCaveatError,\n InvalidCaveatFieldsError,\n InvalidCaveatsPropertyError,\n InvalidCaveatTypeError,\n invalidParams,\n InvalidSubjectIdentifierError,\n methodNotFound,\n PermissionDoesNotExistError,\n PermissionsRequestNotFoundError,\n unauthorized,\n UnrecognizedCaveatTypeError,\n UnrecognizedSubjectError,\n userRejectedRequest,\n} from './errors';\nimport type {\n EndowmentSpecificationConstraint,\n ExtractAllowedCaveatTypes,\n ExtractPermissionSpecification,\n OriginString,\n PermissionConstraint,\n PermissionSpecificationConstraint,\n PermissionSpecificationMap,\n RequestedPermissions,\n RestrictedMethod,\n RestrictedMethodParameters,\n RestrictedMethodSpecificationConstraint,\n SideEffectHandler,\n ValidPermission,\n ValidPermissionSpecification,\n} from './Permission';\nimport {\n constructPermission,\n findCaveat,\n hasSpecificationType,\n PermissionType,\n} from './Permission';\nimport { getPermissionMiddlewareFactory } from './permission-middleware';\nimport type { GetSubjectMetadata } from './SubjectMetadataController';\nimport { MethodNames } from './utils';\n\n/**\n * Metadata associated with {@link PermissionController} subjects.\n */\nexport type PermissionSubjectMetadata = {\n origin: OriginString;\n};\n\n/**\n * Metadata associated with permission requests.\n */\nexport type PermissionsRequestMetadata = PermissionSubjectMetadata & {\n id: string;\n};\n\n/**\n * Used for prompting the user about a proposed new permission.\n * Includes information about the grantee subject, requested permissions, and\n * any additional information added by the consumer.\n *\n * All properties except `permissions` are passed to any factories found for\n * the requested permissions.\n */\nexport type PermissionsRequest = {\n metadata: PermissionsRequestMetadata;\n permissions: RequestedPermissions;\n [key: string]: Json;\n};\n\nexport type SideEffects = {\n permittedHandlers: Record<string, SideEffectHandler<any, any>>;\n failureHandlers: Record<string, SideEffectHandler<any, any>>;\n};\n\n/**\n * The name of the {@link PermissionController}.\n */\nconst controllerName = 'PermissionController';\n\n/**\n * Permissions associated with a {@link PermissionController} subject.\n */\nexport type SubjectPermissions<Permission extends PermissionConstraint> =\n Record<Permission['parentCapability'], Permission>;\n\n/**\n * Permissions and metadata associated with a {@link PermissionController}\n * subject.\n */\nexport type PermissionSubjectEntry<\n SubjectPermission extends PermissionConstraint,\n> = {\n origin: SubjectPermission['invoker'];\n permissions: SubjectPermissions<SubjectPermission>;\n};\n\n/**\n * All subjects of a {@link PermissionController}.\n *\n * @template SubjectPermission - The permissions of the subject.\n */\nexport type PermissionControllerSubjects<\n SubjectPermission extends PermissionConstraint,\n> = Record<\n SubjectPermission['invoker'],\n PermissionSubjectEntry<SubjectPermission>\n>;\n\n// TODO:TS4.4 Enable compiler flags to forbid unchecked member access\n/**\n * The state of a {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n */\nexport type PermissionControllerState<Permission> =\n Permission extends PermissionConstraint\n ? {\n subjects: PermissionControllerSubjects<Permission>;\n }\n : never;\n\n/**\n * Get the state metadata of the {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n * @returns The state metadata\n */\nfunction getStateMetadata<Permission extends PermissionConstraint>() {\n return { subjects: { anonymous: true, persist: true } } as StateMetadata<\n PermissionControllerState<Permission>\n >;\n}\n\n/**\n * Get the default state of the {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n * @returns The default state of the controller\n */\nfunction getDefaultState<Permission extends PermissionConstraint>() {\n return { subjects: {} } as PermissionControllerState<Permission>;\n}\n\n/**\n * Gets the state of the {@link PermissionController}.\n */\nexport type GetPermissionControllerState = ControllerGetStateAction<\n typeof controllerName,\n PermissionControllerState<PermissionConstraint>\n>;\n\n/**\n * Gets the names of all subjects from the {@link PermissionController}.\n */\nexport type GetSubjects = {\n type: `${typeof controllerName}:getSubjectNames`;\n handler: () => (keyof PermissionControllerSubjects<PermissionConstraint>)[];\n};\n\n/**\n * Gets the permissions for specified subject\n */\nexport type GetPermissions = {\n type: `${typeof controllerName}:getPermissions`;\n handler: GenericPermissionController['getPermissions'];\n};\n\n/**\n * Checks whether the specified subject has any permissions.\n */\nexport type HasPermissions = {\n type: `${typeof controllerName}:hasPermissions`;\n handler: GenericPermissionController['hasPermissions'];\n};\n\n/**\n * Checks whether the specified subject has a specific permission.\n */\nexport type HasPermission = {\n type: `${typeof controllerName}:hasPermission`;\n handler: GenericPermissionController['hasPermission'];\n};\n\n/**\n * Directly grants given permissions for a specificed origin without requesting user approval\n */\nexport type GrantPermissions = {\n type: `${typeof controllerName}:grantPermissions`;\n handler: GenericPermissionController['grantPermissions'];\n};\n\n/**\n * Requests given permissions for a specified origin\n */\nexport type RequestPermissions = {\n type: `${typeof controllerName}:requestPermissions`;\n handler: GenericPermissionController['requestPermissions'];\n};\n\n/**\n * Removes the specified permissions for each origin.\n */\nexport type RevokePermissions = {\n type: `${typeof controllerName}:revokePermissions`;\n handler: GenericPermissionController['revokePermissions'];\n};\n\n/**\n * Removes all permissions for a given origin\n */\nexport type RevokeAllPermissions = {\n type: `${typeof controllerName}:revokeAllPermissions`;\n handler: GenericPermissionController['revokeAllPermissions'];\n};\n\n/**\n * Revokes all permissions corresponding to the specified target for all subjects.\n * Does nothing if no subjects or no such permission exists.\n */\nexport type RevokePermissionForAllSubjects = {\n type: `${typeof controllerName}:revokePermissionForAllSubjects`;\n handler: GenericPermissionController['revokePermissionForAllSubjects'];\n};\n\n/**\n * Updates a caveat value for a specified caveat type belonging to a specific target and origin.\n */\nexport type UpdateCaveat = {\n type: `${typeof controllerName}:updateCaveat`;\n handler: GenericPermissionController['updateCaveat'];\n};\n\n/**\n * Clears all permissions from the {@link PermissionController}.\n */\nexport type ClearPermissions = {\n type: `${typeof controllerName}:clearPermissions`;\n handler: () => void;\n};\n\n/**\n * Gets the endowments for the given subject and permission.\n */\nexport type GetEndowments = {\n type: `${typeof controllerName}:getEndowments`;\n handler: GenericPermissionController['getEndowments'];\n};\n\n/**\n * The {@link ControllerMessenger} actions of the {@link PermissionController}.\n */\nexport type PermissionControllerActions =\n | ClearPermissions\n | GetEndowments\n | GetPermissionControllerState\n | GetSubjects\n | GetPermissions\n | HasPermission\n | HasPermissions\n | GrantPermissions\n | RequestPermissions\n | RevokeAllPermissions\n | RevokePermissionForAllSubjects\n | RevokePermissions\n | UpdateCaveat;\n\n/**\n * The generic state change event of the {@link PermissionController}.\n */\nexport type PermissionControllerStateChange = ControllerStateChangeEvent<\n typeof controllerName,\n PermissionControllerState<PermissionConstraint>\n>;\n\n/**\n * The {@link ControllerMessenger} events of the {@link PermissionController}.\n *\n * The permission controller only emits its generic state change events.\n * Consumers should use selector subscriptions to subscribe to relevant\n * substate.\n */\nexport type PermissionControllerEvents = PermissionControllerStateChange;\n\n/**\n * The external {@link ControllerMessenger} actions available to the\n * {@link PermissionController}.\n */\ntype AllowedActions =\n | AddApprovalRequest\n | HasApprovalRequest\n | AcceptApprovalRequest\n | RejectApprovalRequest\n | GetSubjectMetadata;\n\n/**\n * The messenger of the {@link PermissionController}.\n */\nexport type PermissionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n PermissionControllerActions | AllowedActions,\n PermissionControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nexport type SideEffectMessenger<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = RestrictedControllerMessenger<\n typeof controllerName,\n Actions,\n Events,\n string,\n never\n>;\n\n/**\n * A generic {@link PermissionController}.\n */\nexport type GenericPermissionController = PermissionController<\n PermissionSpecificationConstraint,\n CaveatSpecificationConstraint\n>;\n\n/**\n * Describes the possible results of a {@link CaveatMutator} function.\n */\nexport enum CaveatMutatorOperation {\n noop,\n updateValue,\n deleteCaveat,\n revokePermission,\n}\n\n/**\n * Given a caveat value, returns a {@link CaveatMutatorOperation} and, optionally,\n * a new caveat value.\n *\n * @see {@link PermissionController.updatePermissionsByCaveat} for more details.\n * @template Caveat - The caveat type for which this mutator is intended.\n * @param caveatValue - The existing value of the caveat being mutated.\n * @returns A tuple of the mutation result and, optionally, the new caveat\n * value.\n */\nexport type CaveatMutator<TargetCaveat extends CaveatConstraint> = (\n caveatValue: TargetCaveat['value'],\n) => CaveatMutatorResult;\n\ntype CaveatMutatorResult =\n | Readonly<{\n operation: CaveatMutatorOperation.updateValue;\n value: CaveatConstraint['value'];\n }>\n | Readonly<{\n operation: Exclude<\n CaveatMutatorOperation,\n CaveatMutatorOperation.updateValue\n >;\n }>;\n\n/**\n * Extracts the permission(s) specified by the given permission and caveat\n * specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ControllerPermissionSpecification extends ValidPermissionSpecification<ControllerPermissionSpecification>\n ? ValidPermission<\n ControllerPermissionSpecification['targetName'],\n ExtractCaveats<ControllerCaveatSpecification>\n >\n : never;\n\n/**\n * Extracts the restricted method permission(s) specified by the given\n * permission and caveat specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractRestrictedMethodPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ExtractPermission<\n Extract<\n ControllerPermissionSpecification,\n RestrictedMethodSpecificationConstraint\n >,\n ControllerCaveatSpecification\n>;\n\n/**\n * Extracts the endowment permission(s) specified by the given permission and\n * caveat specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractEndowmentPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ExtractPermission<\n Extract<ControllerPermissionSpecification, EndowmentSpecificationConstraint>,\n ControllerCaveatSpecification\n>;\n\n/**\n * Options for the {@link PermissionController} constructor.\n *\n * @template ControllerPermissionSpecification - A union of the types of all\n * permission specifications available to the controller. Any referenced caveats\n * must be included in the controller's caveat specifications.\n * @template ControllerCaveatSpecification - A union of the types of all\n * caveat specifications available to the controller.\n */\nexport type PermissionControllerOptions<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = {\n messenger: PermissionControllerMessenger;\n caveatSpecifications: CaveatSpecificationMap<ControllerCaveatSpecification>;\n permissionSpecifications: PermissionSpecificationMap<ControllerPermissionSpecification>;\n unrestrictedMethods: readonly string[];\n state?: Partial<\n PermissionControllerState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n >;\n};\n\n/**\n * The permission controller. See the [Architecture](../ARCHITECTURE.md)\n * document for details.\n *\n * Assumes the existence of an {@link ApprovalController} reachable via the\n * {@link ControllerMessenger}.\n *\n * @template ControllerPermissionSpecification - A union of the types of all\n * permission specifications available to the controller. Any referenced caveats\n * must be included in the controller's caveat specifications.\n * @template ControllerCaveatSpecification - A union of the types of all\n * caveat specifications available to the controller.\n */\nexport class PermissionController<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> extends BaseController<\n typeof controllerName,\n PermissionControllerState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n PermissionControllerMessenger\n> {\n private readonly _caveatSpecifications: Readonly<\n CaveatSpecificationMap<ControllerCaveatSpecification>\n >;\n\n private readonly _permissionSpecifications: Readonly<\n PermissionSpecificationMap<ControllerPermissionSpecification>\n >;\n\n private readonly _unrestrictedMethods: ReadonlySet<string>;\n\n /**\n * The names of all JSON-RPC methods that will be ignored by the controller.\n *\n * @returns The names of all unrestricted JSON-RPC methods\n */\n public get unrestrictedMethods(): ReadonlySet<string> {\n return this._unrestrictedMethods;\n }\n\n /**\n * Returns a `json-rpc-engine` middleware function factory, so that the rules\n * described by the state of this controller can be applied to incoming\n * JSON-RPC requests.\n *\n * The middleware **must** be added in the correct place in the middleware\n * stack in order for it to work. See the README for an example.\n */\n public createPermissionMiddleware: ReturnType<\n typeof getPermissionMiddlewareFactory\n >;\n\n /**\n * Constructs the PermissionController.\n *\n * @param options - Permission controller options.\n * @param options.caveatSpecifications - The specifications of all caveats\n * available to the controller. See {@link CaveatSpecificationMap} and the\n * documentation for more details.\n * @param options.permissionSpecifications - The specifications of all\n * permissions available to the controller. See\n * {@link PermissionSpecificationMap} and the README for more details.\n * @param options.unrestrictedMethods - The callable names of all JSON-RPC\n * methods ignored by the new controller.\n * @param options.messenger - The controller messenger. See\n * {@link BaseController} for more information.\n * @param options.state - Existing state to hydrate the controller with at\n * initialization.\n */\n constructor(\n options: PermissionControllerOptions<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >,\n ) {\n const {\n caveatSpecifications,\n permissionSpecifications,\n unrestrictedMethods,\n messenger,\n state = {},\n } = options;\n\n super({\n name: controllerName,\n metadata:\n getStateMetadata<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n messenger,\n state: {\n ...getDefaultState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n ...state,\n },\n });\n\n this._unrestrictedMethods = new Set(unrestrictedMethods);\n this._caveatSpecifications = deepFreeze({ ...caveatSpecifications });\n\n this.validatePermissionSpecifications(\n permissionSpecifications,\n this._caveatSpecifications,\n );\n\n this._permissionSpecifications = deepFreeze({\n ...permissionSpecifications,\n });\n\n this.registerMessageHandlers();\n this.createPermissionMiddleware = getPermissionMiddlewareFactory({\n executeRestrictedMethod: this._executeRestrictedMethod.bind(this),\n getRestrictedMethod: this.getRestrictedMethod.bind(this),\n isUnrestrictedMethod: this.unrestrictedMethods.has.bind(\n this.unrestrictedMethods,\n ),\n });\n }\n\n /**\n * Gets a permission specification.\n *\n * @param targetName - The name of the permission specification to get.\n * @returns The permission specification with the specified target name.\n */\n private getPermissionSpecification<\n TargetName extends ControllerPermissionSpecification['targetName'],\n >(\n targetName: TargetName,\n ): ExtractPermissionSpecification<\n ControllerPermissionSpecification,\n TargetName\n > {\n return this._permissionSpecifications[targetName];\n }\n\n /**\n * Gets a caveat specification.\n *\n * @param caveatType - The type of the caveat specification to get.\n * @returns The caveat specification with the specified type.\n */\n private getCaveatSpecification<\n CaveatType extends ControllerCaveatSpecification['type'],\n >(caveatType: CaveatType) {\n return this._caveatSpecifications[caveatType];\n }\n\n /**\n * Constructor helper for validating permission specifications.\n *\n * Throws an error if validation fails.\n *\n * @param permissionSpecifications - The permission specifications passed to\n * this controller's constructor.\n * @param caveatSpecifications - The caveat specifications passed to this\n * controller.\n */\n private validatePermissionSpecifications(\n permissionSpecifications: PermissionSpecificationMap<ControllerPermissionSpecification>,\n caveatSpecifications: CaveatSpecificationMap<ControllerCaveatSpecification>,\n ) {\n Object.entries<ControllerPermissionSpecification>(\n permissionSpecifications,\n ).forEach(\n ([\n targetName,\n { permissionType, targetName: innerTargetName, allowedCaveats },\n ]) => {\n if (!permissionType || !hasProperty(PermissionType, permissionType)) {\n throw new Error(`Invalid permission type: \"${permissionType}\"`);\n }\n\n if (!targetName) {\n throw new Error(`Invalid permission target name: \"${targetName}\"`);\n }\n\n if (targetName !== innerTargetName) {\n throw new Error(\n `Invalid permission specification: target name \"${targetName}\" must match specification.targetName value \"${innerTargetName}\".`,\n );\n }\n\n if (allowedCaveats) {\n allowedCaveats.forEach((caveatType) => {\n if (!hasProperty(caveatSpecifications, caveatType)) {\n throw new UnrecognizedCaveatTypeError(caveatType);\n }\n\n const specification =\n caveatSpecifications[\n caveatType as ControllerCaveatSpecification['type']\n ];\n const isRestrictedMethodCaveat =\n isRestrictedMethodCaveatSpecification(specification);\n\n if (\n (permissionType === PermissionType.RestrictedMethod &&\n !isRestrictedMethodCaveat) ||\n (permissionType === PermissionType.Endowment &&\n isRestrictedMethodCaveat)\n ) {\n throw new CaveatSpecificationMismatchError(\n specification,\n permissionType,\n );\n }\n });\n }\n },\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:clearPermissions` as const,\n () => this.clearState(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getEndowments` as const,\n (origin: string, targetName: string, requestData?: unknown) =>\n this.getEndowments(origin, targetName, requestData),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSubjectNames` as const,\n () => this.getSubjectNames(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getPermissions` as const,\n (origin: OriginString) => this.getPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:hasPermission` as const,\n (origin: OriginString, targetName: string) =>\n this.hasPermission(origin, targetName),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:hasPermissions` as const,\n (origin: OriginString) => this.hasPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:grantPermissions` as const,\n this.grantPermissions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:requestPermissions` as const,\n (subject: PermissionSubjectMetadata, permissions: RequestedPermissions) =>\n this.requestPermissions(subject, permissions),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokeAllPermissions` as const,\n (origin: OriginString) => this.revokeAllPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokePermissionForAllSubjects` as const,\n (\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ) => this.revokePermissionForAllSubjects(target),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokePermissions` as const,\n this.revokePermissions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateCaveat` as const,\n (origin, target, caveatType, caveatValue) => {\n this.updateCaveat(\n origin,\n target,\n caveatType as ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n caveatValue,\n );\n },\n );\n }\n\n /**\n * Clears the state of the controller.\n */\n clearState(): void {\n this.update((_draftState) => {\n return {\n ...getDefaultState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n };\n });\n }\n\n /**\n * Gets the permission specification corresponding to the given permission\n * type and target name. Throws an error if the target name does not\n * correspond to a permission, or if the specification is not of the\n * given permission type.\n *\n * @template Type - The type of the permission specification to get.\n * @param permissionType - The type of the permission specification to get.\n * @param targetName - The name of the permission whose specification to get.\n * @param requestingOrigin - The origin of the requesting subject, if any.\n * Will be added to any thrown errors.\n * @returns The specification object corresponding to the given type and\n * target name.\n */\n private getTypedPermissionSpecification<Type extends PermissionType>(\n permissionType: Type,\n targetName: string,\n requestingOrigin?: string,\n ): ControllerPermissionSpecification & { permissionType: Type } {\n const failureError =\n permissionType === PermissionType.RestrictedMethod\n ? methodNotFound(\n targetName,\n requestingOrigin ? { origin: requestingOrigin } : undefined,\n )\n : new EndowmentPermissionDoesNotExistError(\n targetName,\n requestingOrigin,\n );\n\n if (!this.targetExists(targetName)) {\n throw failureError;\n }\n\n const specification = this.getPermissionSpecification(targetName);\n if (!hasSpecificationType(specification, permissionType)) {\n throw failureError;\n }\n\n return specification;\n }\n\n /**\n * Gets the implementation of the specified restricted method.\n *\n * A JSON-RPC error is thrown if the method does not exist.\n *\n * @see {@link PermissionController.executeRestrictedMethod} and\n * {@link PermissionController.createPermissionMiddleware} for internal usage.\n * @param method - The name of the restricted method.\n * @param origin - The origin associated with the request for the restricted\n * method, if any.\n * @returns The restricted method implementation.\n */\n getRestrictedMethod(\n method: string,\n origin?: string,\n ): RestrictedMethod<RestrictedMethodParameters, Json> {\n return this.getTypedPermissionSpecification(\n PermissionType.RestrictedMethod,\n method,\n origin,\n ).methodImplementation;\n }\n\n /**\n * Gets a list of all origins of subjects.\n *\n * @returns The origins (i.e. IDs) of all subjects.\n */\n getSubjectNames(): OriginString[] {\n return Object.keys(this.state.subjects);\n }\n\n /**\n * Gets the permission for the specified target of the subject corresponding\n * to the specified origin.\n *\n * @param origin - The origin of the subject.\n * @param targetName - The method name as invoked by a third party (i.e., not\n * a method key).\n * @returns The permission if it exists, or undefined otherwise.\n */\n getPermission<\n SubjectPermission extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >,\n >(\n origin: OriginString,\n targetName: SubjectPermission['parentCapability'],\n ): SubjectPermission | undefined {\n return this.state.subjects[origin]?.permissions[targetName] as\n | SubjectPermission\n | undefined;\n }\n\n /**\n * Gets all permissions for the specified subject, if any.\n *\n * @param origin - The origin of the subject.\n * @returns The permissions of the subject, if any.\n */\n getPermissions(\n origin: OriginString,\n ):\n | SubjectPermissions<\n ValidPermission<string, ExtractCaveats<ControllerCaveatSpecification>>\n >\n | undefined {\n return this.state.subjects[origin]?.permissions;\n }\n\n /**\n * Checks whether the subject with the specified origin has the specified\n * permission.\n *\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @returns Whether the subject has the permission.\n */\n hasPermission(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): boolean {\n return Boolean(this.getPermission(origin, target));\n }\n\n /**\n * Checks whether the subject with the specified origin has any permissions.\n * Use this if you want to know if a subject \"exists\".\n *\n * @param origin - The origin of the subject to check.\n * @returns Whether the subject has any permissions.\n */\n hasPermissions(origin: OriginString): boolean {\n return Boolean(this.state.subjects[origin]);\n }\n\n /**\n * Revokes all permissions from the specified origin.\n *\n * Throws an error of the origin has no permissions.\n *\n * @param origin - The origin whose permissions to revoke.\n */\n revokeAllPermissions(origin: OriginString): void {\n this.update((draftState) => {\n if (!draftState.subjects[origin]) {\n throw new UnrecognizedSubjectError(origin);\n }\n delete draftState.subjects[origin];\n });\n }\n\n /**\n * Revokes the specified permission from the subject with the specified\n * origin.\n *\n * Throws an error if the subject or the permission does not exist.\n *\n * @param origin - The origin of the subject whose permission to revoke.\n * @param target - The target name of the permission to revoke.\n */\n revokePermission(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n this.revokePermissions({ [origin]: [target] });\n }\n\n /**\n * Revokes the specified permissions from the specified subjects.\n *\n * Throws an error if any of the subjects or permissions do not exist.\n *\n * @param subjectsAndPermissions - An object mapping subject origins\n * to arrays of permission target names to revoke.\n */\n revokePermissions(\n subjectsAndPermissions: Record<\n OriginString,\n NonEmptyArray<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability']\n >\n >,\n ): void {\n this.update((draftState) => {\n Object.keys(subjectsAndPermissions).forEach((origin) => {\n if (!hasProperty(draftState.subjects, origin)) {\n throw new UnrecognizedSubjectError(origin);\n }\n\n subjectsAndPermissions[origin].forEach((target) => {\n const { permissions } = draftState.subjects[origin];\n if (!hasProperty(permissions as Record<string, unknown>, target)) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n this.deletePermission(draftState.subjects, origin, target);\n });\n });\n });\n }\n\n /**\n * Revokes all permissions corresponding to the specified target for all subjects.\n * Does nothing if no subjects or no such permission exists.\n *\n * @param target - The name of the target to revoke all permissions for.\n */\n revokePermissionForAllSubjects(\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n if (this.getSubjectNames().length === 0) {\n return;\n }\n\n this.update((draftState) => {\n Object.entries(draftState.subjects).forEach(([origin, subject]) => {\n const { permissions } = subject;\n\n if (hasProperty(permissions as Record<string, unknown>, target)) {\n this.deletePermission(draftState.subjects, origin, target);\n }\n });\n });\n }\n\n /**\n * Deletes the permission identified by the given origin and target. If the\n * permission is the single remaining permission of its subject, the subject\n * is also deleted.\n *\n * @param subjects - The draft permission controller subjects.\n * @param origin - The origin of the subject associated with the permission\n * to delete.\n * @param target - The target name of the permission to delete.\n */\n private deletePermission(\n subjects: Draft<PermissionControllerSubjects<PermissionConstraint>>,\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n const { permissions } = subjects[origin];\n if (Object.keys(permissions).length > 1) {\n delete permissions[target];\n } else {\n delete subjects[origin];\n }\n }\n\n /**\n * Checks whether the permission of the subject corresponding to the given\n * origin has a caveat of the specified type.\n *\n * Throws an error if the subject does not have a permission with the\n * specified target name.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to check for.\n * @returns Whether the permission has the specified caveat.\n */\n hasCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(origin: OriginString, target: TargetName, caveatType: CaveatType): boolean {\n return Boolean(this.getCaveat(origin, target, caveatType));\n }\n\n /**\n * Gets the caveat of the specified type, if any, for the permission of\n * the subject corresponding to the given origin.\n *\n * Throws an error if the subject does not have a permission with the\n * specified target name.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to get.\n * @returns The caveat, or `undefined` if no such caveat exists.\n */\n getCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n ): ExtractCaveat<ControllerCaveatSpecification, CaveatType> | undefined {\n const permission = this.getPermission(origin, target);\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n return findCaveat(permission, caveatType) as\n | ExtractCaveat<ControllerCaveatSpecification, CaveatType>\n | undefined;\n }\n\n /**\n * Adds a caveat of the specified type, with the specified caveat value, to\n * the permission corresponding to the given subject origin and permission\n * target.\n *\n * For modifying existing caveats, use\n * {@link PermissionController.updateCaveat}.\n *\n * Throws an error if no such permission exists, or if the caveat already\n * exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to add.\n * @param caveatValue - The value of the caveat to add.\n */\n addCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>,\n ): void {\n if (this.hasCaveat(origin, target, caveatType)) {\n throw new CaveatAlreadyExistsError(origin, target, caveatType);\n }\n\n this.setCaveat(origin, target, caveatType, caveatValue);\n }\n\n /**\n * Updates the value of the caveat of the specified type belonging to the\n * permission corresponding to the given subject origin and permission\n * target.\n *\n * For adding new caveats, use\n * {@link PermissionController.addCaveat}.\n *\n * Throws an error if no such permission or caveat exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to update.\n * @param caveatValue - The new value of the caveat.\n */\n updateCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n CaveatValue extends ExtractCaveatValue<\n ControllerCaveatSpecification,\n CaveatType\n >,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: CaveatValue,\n ): void {\n if (!this.hasCaveat(origin, target, caveatType)) {\n throw new CaveatDoesNotExistError(origin, target, caveatType);\n }\n\n this.setCaveat(origin, target, caveatType, caveatValue);\n }\n\n /**\n * Sets the specified caveat on the specified permission. Overwrites existing\n * caveats of the same type in-place (preserving array order), and adds the\n * caveat to the end of the array otherwise.\n *\n * Throws an error if the permission does not exist or fails to validate after\n * its caveats have been modified.\n *\n * @see {@link PermissionController.addCaveat}\n * @see {@link PermissionController.updateCaveat}\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to set.\n * @param caveatValue - The value of the caveat to set.\n */\n private setCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>,\n ): void {\n this.update((draftState) => {\n const subject = draftState.subjects[origin];\n\n // Unreachable because `hasCaveat` is always called before this, and it\n // throws if permissions are missing. TypeScript needs this, however.\n /* istanbul ignore if */\n if (!subject) {\n throw new UnrecognizedSubjectError(origin);\n }\n\n const permission = subject.permissions[target];\n\n /* istanbul ignore if: practically impossible, but TypeScript wants it */\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n const caveat = {\n type: caveatType,\n value: caveatValue,\n };\n this.validateCaveat(caveat, origin, target);\n\n if (permission.caveats) {\n const caveatIndex = permission.caveats.findIndex(\n (existingCaveat) => existingCaveat.type === caveat.type,\n );\n\n if (caveatIndex === -1) {\n permission.caveats.push(caveat);\n } else {\n permission.caveats.splice(caveatIndex, 1, caveat);\n }\n } else {\n // Typecast: At this point, we don't know if the specific permission\n // is allowed to have caveats, but it should be impossible to call\n // this method for a permission that may not have any caveats.\n // If all else fails, the permission validator is also called.\n permission.caveats = [caveat] as any;\n }\n\n this.validateModifiedPermission(permission, origin);\n });\n }\n\n /**\n * Updates all caveats with the specified type for all subjects and\n * permissions by applying the specified mutator function to them.\n *\n * ATTN: Permissions can be revoked entirely by the action of this method,\n * read on for details.\n *\n * Caveat mutators are functions that receive a caveat value and return a\n * tuple consisting of a {@link CaveatMutatorOperation} and, optionally, a new\n * value to update the existing caveat with.\n *\n * For each caveat, depending on the mutator result, this method will:\n * - Do nothing ({@link CaveatMutatorOperation.noop})\n * - Update the value of the caveat ({@link CaveatMutatorOperation.updateValue}). The caveat specification validator, if any, will be called after updating the value.\n * - Delete the caveat ({@link CaveatMutatorOperation.deleteCaveat}). The permission specification validator, if any, will be called after deleting the caveat.\n * - Revoke the parent permission ({@link CaveatMutatorOperation.revokePermission})\n *\n * This method throws if the validation of any caveat or permission fails.\n *\n * @param targetCaveatType - The type of the caveats to update.\n * @param mutator - The mutator function which will be applied to all caveat\n * values.\n */\n updatePermissionsByCaveat<\n CaveatType extends ExtractCaveats<ControllerCaveatSpecification>['type'],\n TargetCaveat extends ExtractCaveat<\n ControllerCaveatSpecification,\n CaveatType\n >,\n >(targetCaveatType: CaveatType, mutator: CaveatMutator<TargetCaveat>): void {\n if (Object.keys(this.state.subjects).length === 0) {\n return;\n }\n\n this.update((draftState) => {\n Object.values(draftState.subjects).forEach((subject) => {\n Object.values(subject.permissions).forEach((permission) => {\n const { caveats } = permission;\n const targetCaveat = caveats?.find(\n ({ type }) => type === targetCaveatType,\n );\n if (!targetCaveat) {\n return;\n }\n\n // The mutator may modify the caveat value in place, and must always\n // return a valid mutation result.\n const mutatorResult = mutator(targetCaveat.value);\n switch (mutatorResult.operation) {\n case CaveatMutatorOperation.noop:\n break;\n\n case CaveatMutatorOperation.updateValue:\n // Typecast: `Mutable` is used here to assign to a readonly\n // property. `targetConstraint` should already be mutable because\n // it's part of a draft, but for some reason it's not. We can't\n // use the more-correct `Draft` type here either because it\n // results in an error.\n (targetCaveat as Mutable<CaveatConstraint, 'value'>).value =\n mutatorResult.value;\n\n this.validateCaveat(\n targetCaveat,\n subject.origin,\n permission.parentCapability,\n );\n break;\n\n case CaveatMutatorOperation.deleteCaveat:\n this.deleteCaveat(permission, targetCaveatType, subject.origin);\n break;\n\n case CaveatMutatorOperation.revokePermission:\n this.deletePermission(\n draftState.subjects,\n subject.origin,\n permission.parentCapability,\n );\n break;\n\n default: {\n // This type check ensures that the switch statement is\n // exhaustive.\n const _exhaustiveCheck: never = mutatorResult;\n throw new Error(\n `Unrecognized mutation result: \"${\n (_exhaustiveCheck as any).operation\n }\"`,\n );\n }\n }\n });\n });\n });\n }\n\n /**\n * Removes the caveat of the specified type from the permission corresponding\n * to the given subject origin and target name.\n *\n * Throws an error if no such permission or caveat exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to remove.\n */\n removeCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(origin: OriginString, target: TargetName, caveatType: CaveatType): void {\n this.update((draftState) => {\n const permission = draftState.subjects[origin]?.permissions[target];\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n if (!permission.caveats) {\n throw new CaveatDoesNotExistError(origin, target, caveatType);\n }\n\n this.deleteCaveat(permission, caveatType, origin);\n });\n }\n\n /**\n * Deletes the specified caveat from the specified permission. If no caveats\n * remain after deletion, the permission's caveat property is set to `null`.\n * The permission is validated after being modified.\n *\n * Throws an error if the permission does not have a caveat with the specified\n * type.\n *\n * @param permission - The permission whose caveat to delete.\n * @param caveatType - The type of the caveat to delete.\n * @param origin - The origin the permission subject.\n */\n private deleteCaveat<\n CaveatType extends ExtractCaveats<ControllerCaveatSpecification>['type'],\n >(\n permission: Draft<PermissionConstraint>,\n caveatType: CaveatType,\n origin: OriginString,\n ): void {\n /* istanbul ignore if: not possible in our usage */\n if (!permission.caveats) {\n throw new CaveatDoesNotExistError(\n origin,\n permission.parentCapability,\n caveatType,\n );\n }\n\n const caveatIndex = permission.caveats.findIndex(\n (existingCaveat) => existingCaveat.type === caveatType,\n );\n\n if (caveatIndex === -1) {\n throw new CaveatDoesNotExistError(\n origin,\n permission.parentCapability,\n caveatType,\n );\n }\n\n if (permission.caveats.length === 1) {\n permission.caveats = null;\n } else {\n permission.caveats.splice(caveatIndex, 1);\n }\n\n this.validateModifiedPermission(permission, origin);\n }\n\n /**\n * Validates the specified modified permission. Should **always** be invoked\n * on a permission after its caveats have been modified.\n *\n * Just like {@link PermissionController.validatePermission}, except that the\n * corresponding target name and specification are retrieved first, and an\n * error is thrown if the target name does not exist.\n *\n * @param permission - The modified permission to validate.\n * @param origin - The origin associated with the permission.\n */\n private validateModifiedPermission(\n permission: Draft<PermissionConstraint>,\n origin: OriginString,\n ): void {\n /* istanbul ignore if: this should be impossible */\n if (!this.targetExists(permission.parentCapability)) {\n throw new Error(\n `Fatal: Existing permission target \"${permission.parentCapability}\" has no specification.`,\n );\n }\n\n this.validatePermission(\n this.getPermissionSpecification(permission.parentCapability),\n permission as PermissionConstraint,\n origin,\n );\n }\n\n /**\n * Verifies the existence the specified permission target, i.e. whether it has\n * a specification.\n *\n * @param target - The requested permission target.\n * @returns Whether the permission target exists.\n */\n private targetExists(\n target: string,\n ): target is ControllerPermissionSpecification['targetName'] {\n return hasProperty(this._permissionSpecifications, target);\n }\n\n /**\n * Grants _approved_ permissions to the specified subject. Every permission and\n * caveat is stringently validated – including by calling every specification\n * validator – and an error is thrown if any validation fails.\n *\n * ATTN: This method does **not** prompt the user for approval.\n *\n * @see {@link PermissionController.requestPermissions} For initiating a\n * permissions request requiring user approval.\n * @param options - Options bag.\n * @param options.approvedPermissions - The requested permissions approved by\n * the user.\n * @param options.requestData - Permission request data. Passed to permission\n * factory functions.\n * @param options.preserveExistingPermissions - Whether to preserve the\n * subject's existing permissions.\n * @param options.subject - The subject to grant permissions to.\n * @returns The granted permissions.\n */\n grantPermissions({\n approvedPermissions,\n requestData,\n preserveExistingPermissions = true,\n subject,\n }: {\n approvedPermissions: RequestedPermissions;\n subject: PermissionSubjectMetadata;\n preserveExistingPermissions?: boolean;\n requestData?: Record<string, unknown>;\n }): SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n > {\n const { origin } = subject;\n\n if (!origin || typeof origin !== 'string') {\n throw new InvalidSubjectIdentifierError(origin);\n }\n\n const permissions = (\n preserveExistingPermissions\n ? {\n ...this.getPermissions(origin),\n }\n : {}\n ) as SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >;\n\n for (const [requestedTarget, approvedPermission] of Object.entries(\n approvedPermissions,\n )) {\n if (!this.targetExists(requestedTarget)) {\n throw methodNotFound(requestedTarget);\n }\n\n if (\n approvedPermission.parentCapability !== undefined &&\n requestedTarget !== approvedPermission.parentCapability\n ) {\n throw new InvalidApprovedPermissionError(\n origin,\n requestedTarget,\n approvedPermission,\n );\n }\n\n // We have verified that the target exists, and reassign it to change its\n // type.\n const targetName = requestedTarget as ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'];\n const specification = this.getPermissionSpecification(targetName);\n\n // The requested caveats are validated here.\n const caveats = this.constructCaveats(\n origin,\n targetName,\n approvedPermission.caveats,\n );\n\n const permissionOptions = {\n caveats,\n invoker: origin,\n target: targetName,\n };\n\n let permission: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >;\n if (specification.factory) {\n permission = specification.factory(permissionOptions, requestData);\n\n // Full caveat and permission validation is performed here since the\n // factory function can arbitrarily modify the entire permission object,\n // including its caveats.\n this.validatePermission(specification, permission, origin);\n } else {\n permission = constructPermission(permissionOptions);\n\n // We do not need to validate caveats in this case, because the plain\n // permission constructor function does not modify the caveats, which\n // were already validated by `constructCaveats` above.\n this.validatePermission(specification, permission, origin, {\n invokePermissionValidator: true,\n performCaveatValidation: false,\n });\n }\n permissions[targetName] = permission;\n }\n\n this.setValidatedPermissions(origin, permissions);\n return permissions;\n }\n\n /**\n * Validates the specified permission by:\n * - Ensuring that if `subjectTypes` is specified, the subject requesting the permission is of a type in the list.\n * - Ensuring that its `caveats` property is either `null` or a non-empty array.\n * - Ensuring that it only includes caveats allowed by its specification.\n * - Ensuring that it includes no duplicate caveats (by caveat type).\n * - Validating each caveat object, if `performCaveatValidation` is `true`.\n * - Calling the validator of its specification, if one exists and `invokePermissionValidator` is `true`.\n *\n * An error is thrown if validation fails.\n *\n * @param specification - The specification of the permission.\n * @param permission - The permission to validate.\n * @param origin - The origin associated with the permission.\n * @param validationOptions - Validation options.\n * @param validationOptions.invokePermissionValidator - Whether to invoke the\n * permission's consumer-specified validator function, if any.\n * @param validationOptions.performCaveatValidation - Whether to invoke\n * {@link PermissionController.validateCaveat} on each of the permission's\n * caveats.\n */\n private validatePermission(\n specification: PermissionSpecificationConstraint,\n permission: PermissionConstraint,\n origin: OriginString,\n { invokePermissionValidator, performCaveatValidation } = {\n invokePermissionValidator: true,\n performCaveatValidation: true,\n },\n ): void {\n const { allowedCaveats, validator, targetName } = specification;\n\n if (\n specification.subjectTypes?.length &&\n specification.subjectTypes.length > 0\n ) {\n const metadata = this.messagingSystem.call(\n 'SubjectMetadataController:getSubjectMetadata',\n origin,\n );\n\n if (\n !metadata ||\n metadata.subjectType === null ||\n !specification.subjectTypes.includes(metadata.subjectType)\n ) {\n throw specification.permissionType === PermissionType.RestrictedMethod\n ? methodNotFound(targetName, { origin })\n : new EndowmentPermissionDoesNotExistError(targetName, origin);\n }\n }\n\n if (hasProperty(permission, 'caveats')) {\n const { caveats } = permission;\n\n if (caveats !== null && !(Array.isArray(caveats) && caveats.length > 0)) {\n throw new InvalidCaveatsPropertyError(origin, targetName, caveats);\n }\n\n const seenCaveatTypes = new Set<string>();\n caveats?.forEach((caveat) => {\n if (performCaveatValidation) {\n this.validateCaveat(caveat, origin, targetName);\n }\n\n if (!allowedCaveats?.includes(caveat.type)) {\n throw new ForbiddenCaveatError(caveat.type, origin, targetName);\n }\n\n if (seenCaveatTypes.has(caveat.type)) {\n throw new DuplicateCaveatError(caveat.type, origin, targetName);\n }\n seenCaveatTypes.add(caveat.type);\n });\n }\n\n if (invokePermissionValidator && validator) {\n validator(permission, origin, targetName);\n }\n }\n\n /**\n * Assigns the specified permissions to the subject with the given origin.\n * Overwrites all existing permissions, and creates a subject entry if it\n * doesn't already exist.\n *\n * ATTN: Assumes that the new permissions have been validated.\n *\n * @param origin - The origin of the grantee subject.\n * @param permissions - The new permissions for the grantee subject.\n */\n private setValidatedPermissions(\n origin: OriginString,\n permissions: Record<\n string,\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n ): void {\n this.update((draftState) => {\n if (!draftState.subjects[origin]) {\n draftState.subjects[origin] = { origin, permissions: {} };\n }\n\n draftState.subjects[origin].permissions = castDraft(permissions);\n });\n }\n\n /**\n * Validates the requested caveats for the permission of the specified\n * subject origin and target name and returns the validated caveat array.\n *\n * Throws an error if validation fails.\n *\n * @param origin - The origin of the permission subject.\n * @param target - The permission target name.\n * @param requestedCaveats - The requested caveats to construct.\n * @returns The constructed caveats.\n */\n private constructCaveats(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n requestedCaveats?: unknown[] | null,\n ): NonEmptyArray<ExtractCaveats<ControllerCaveatSpecification>> | undefined {\n const caveatArray = requestedCaveats?.map((requestedCaveat) => {\n this.validateCaveat(requestedCaveat, origin, target);\n\n // Reassign so that we have a fresh object.\n const { type, value } = requestedCaveat as CaveatConstraint;\n return { type, value } as ExtractCaveats<ControllerCaveatSpecification>;\n });\n\n return caveatArray && isNonEmptyArray(caveatArray)\n ? caveatArray\n : undefined;\n }\n\n /**\n * This methods validates that the specified caveat is an object with the\n * expected properties and types. It also ensures that a caveat specification\n * exists for the requested caveat type, and calls the specification\n * validator, if it exists, on the caveat object.\n *\n * Throws an error if validation fails.\n *\n * @param caveat - The caveat object to validate.\n * @param origin - The origin associated with the subject of the parent\n * permission.\n * @param target - The target name associated with the parent permission.\n */\n private validateCaveat(\n caveat: unknown,\n origin: OriginString,\n target: string,\n ): void {\n if (!isPlainObject(caveat)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new InvalidCaveatError(caveat, origin, target);\n }\n\n if (Object.keys(caveat).length !== 2) {\n throw new InvalidCaveatFieldsError(caveat, origin, target);\n }\n\n if (typeof caveat.type !== 'string') {\n throw new InvalidCaveatTypeError(caveat, origin, target);\n }\n\n const specification = this.getCaveatSpecification(caveat.type);\n if (!specification) {\n throw new UnrecognizedCaveatTypeError(caveat.type, origin, target);\n }\n\n if (!hasProperty(caveat, 'value') || caveat.value === undefined) {\n throw new CaveatMissingValueError(caveat, origin, target);\n }\n\n if (!isValidJson(caveat.value)) {\n throw new CaveatInvalidJsonError(caveat, origin, target);\n }\n\n // Typecast: TypeScript still believes that the caveat is a PlainObject.\n specification.validator?.(caveat as CaveatConstraint, origin, target);\n }\n\n /**\n * Initiates a permission request that requires user approval. This should\n * always be used to grant additional permissions to a subject, unless user\n * approval has been obtained through some other means.\n *\n * Permissions are validated at every step of the approval process, and this\n * method will reject if validation fails.\n *\n * @see {@link ApprovalController} For the user approval logic.\n * @see {@link PermissionController.acceptPermissionsRequest} For the method\n * that _accepts_ the request and resolves the user approval promise.\n * @see {@link PermissionController.rejectPermissionsRequest} For the method\n * that _rejects_ the request and the user approval promise.\n * @param subject - The grantee subject.\n * @param requestedPermissions - The requested permissions.\n * @param options - Additional options.\n * @param options.id - The id of the permissions request. Defaults to a unique\n * id.\n * @param options.preserveExistingPermissions - Whether to preserve the\n * subject's existing permissions. Defaults to `true`.\n * @returns The granted permissions and request metadata.\n */\n async requestPermissions(\n subject: PermissionSubjectMetadata,\n requestedPermissions: RequestedPermissions,\n options: {\n id?: string;\n preserveExistingPermissions?: boolean;\n } = {},\n ): Promise<\n [\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n { data?: Record<string, unknown>; id: string; origin: OriginString },\n ]\n > {\n const { origin } = subject;\n const { id = nanoid(), preserveExistingPermissions = true } = options;\n this.validateRequestedPermissions(origin, requestedPermissions);\n\n const metadata = {\n id,\n origin,\n };\n\n const permissionsRequest = {\n metadata,\n permissions: requestedPermissions,\n };\n\n const approvedRequest = await this.requestUserApproval(permissionsRequest);\n const { permissions: approvedPermissions, ...requestData } =\n approvedRequest;\n\n const sideEffects = this.getSideEffects(approvedPermissions);\n\n if (Object.values(sideEffects.permittedHandlers).length > 0) {\n const sideEffectsData = await this.executeSideEffects(\n sideEffects,\n approvedRequest,\n );\n const mappedData = Object.keys(sideEffects.permittedHandlers).reduce(\n (acc, permission, i) => ({ [permission]: sideEffectsData[i], ...acc }),\n {},\n );\n\n return [\n this.grantPermissions({\n subject,\n approvedPermissions,\n preserveExistingPermissions,\n requestData,\n }),\n { data: mappedData, ...metadata },\n ];\n }\n\n return [\n this.grantPermissions({\n subject,\n approvedPermissions,\n preserveExistingPermissions,\n requestData,\n }),\n metadata,\n ];\n }\n\n /**\n * Validates requested permissions. Throws if validation fails.\n *\n * This method ensures that the requested permissions are a properly\n * formatted {@link RequestedPermissions} object, and performs the same\n * validation as {@link PermissionController.grantPermissions}, except that\n * consumer-specified permission validator functions are not called, since\n * they are only called on fully constructed, approved permissions that are\n * otherwise completely valid.\n *\n * Unrecognzied properties on requested permissions are ignored.\n *\n * @param origin - The origin of the grantee subject.\n * @param requestedPermissions - The requested permissions.\n */\n private validateRequestedPermissions(\n origin: OriginString,\n requestedPermissions: unknown,\n ): void {\n if (!isPlainObject(requestedPermissions)) {\n throw invalidParams({\n message: `Requested permissions for origin \"${origin}\" is not a plain object.`,\n data: { origin, requestedPermissions },\n });\n }\n\n if (Object.keys(requestedPermissions).length === 0) {\n throw invalidParams({\n message: `Permissions request for origin \"${origin}\" contains no permissions.`,\n data: { requestedPermissions },\n });\n }\n\n for (const targetName of Object.keys(requestedPermissions)) {\n const permission = requestedPermissions[targetName];\n\n if (!this.targetExists(targetName)) {\n throw methodNotFound(targetName, { origin, requestedPermissions });\n }\n\n if (\n !isPlainObject(permission) ||\n (permission.parentCapability !== undefined &&\n targetName !== permission.parentCapability)\n ) {\n throw invalidParams({\n message: `Permissions request for origin \"${origin}\" contains invalid requested permission(s).`,\n data: { origin, requestedPermissions },\n });\n }\n\n // Here we validate the permission without invoking its validator, if any.\n // The validator will be invoked after the permission has been approved.\n this.validatePermission(\n this.getPermissionSpecification(targetName),\n // Typecast: The permission is still a \"PlainObject\" here.\n permission as PermissionConstraint,\n origin,\n { invokePermissionValidator: false, performCaveatValidation: true },\n );\n }\n }\n\n /**\n * Adds a request to the {@link ApprovalController} using the\n * {@link AddApprovalRequest} action. Also validates the resulting approved\n * permissions request, and throws an error if validation fails.\n *\n * @param permissionsRequest - The permissions request object.\n * @returns The approved permissions request object.\n */\n private async requestUserApproval(permissionsRequest: PermissionsRequest) {\n const { origin, id } = permissionsRequest.metadata;\n const approvedRequest = await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin,\n requestData: permissionsRequest,\n type: MethodNames.requestPermissions,\n },\n true,\n );\n\n this.validateApprovedPermissions(approvedRequest, { id, origin });\n return approvedRequest as PermissionsRequest;\n }\n\n /**\n * Reunites all the side-effects (onPermitted and onFailure) of the requested permissions inside a record of arrays.\n *\n * @param permissions - The approved permissions.\n * @returns The {@link SideEffects} object containing the handlers arrays.\n */\n private getSideEffects(permissions: RequestedPermissions) {\n return Object.keys(permissions).reduce<SideEffects>(\n (sideEffectList, targetName) => {\n if (this.targetExists(targetName)) {\n const specification = this.getPermissionSpecification(targetName);\n\n if (specification.sideEffect) {\n sideEffectList.permittedHandlers[targetName] =\n specification.sideEffect.onPermitted;\n\n if (specification.sideEffect.onFailure) {\n sideEffectList.failureHandlers[targetName] =\n specification.sideEffect.onFailure;\n }\n }\n }\n return sideEffectList;\n },\n { permittedHandlers: {}, failureHandlers: {} },\n );\n }\n\n /**\n * Executes the side-effects of the approved permissions while handling the errors if any.\n * It will pass an instance of the {@link messagingSystem} and the request data associated with the permission request to the handlers through its params.\n *\n * @param sideEffects - the side-effect record created by {@link getSideEffects}\n * @param requestData - the permissions requestData.\n * @returns the value returned by all the `onPermitted` handlers in an array.\n */\n private async executeSideEffects(\n sideEffects: SideEffects,\n requestData: PermissionsRequest,\n ) {\n const { permittedHandlers, failureHandlers } = sideEffects;\n const params = {\n requestData,\n messagingSystem: this.messagingSystem,\n };\n\n const promiseResults = await Promise.allSettled(\n Object.values(permittedHandlers).map((permittedHandler) =>\n permittedHandler(params),\n ),\n );\n\n // lib.es2020.promise.d.ts does not export its types so we're using a simple type.\n const rejectedHandlers = promiseResults.filter(\n (promise) => promise.status === 'rejected',\n ) as { status: 'rejected'; reason: Error }[];\n\n if (rejectedHandlers.length > 0) {\n const failureHandlersList = Object.values(failureHandlers);\n if (failureHandlersList.length > 0) {\n try {\n await Promise.all(\n failureHandlersList.map((failureHandler) => failureHandler(params)),\n );\n } catch (error) {\n throw internalError('Unexpected error in side-effects', { error });\n }\n }\n const reasons = rejectedHandlers.map((handler) => handler.reason);\n\n reasons.forEach((reason) => {\n console.error(reason);\n });\n\n throw reasons.length > 1\n ? internalError(\n 'Multiple errors occurred during side-effects execution',\n { errors: reasons },\n )\n : reasons[0];\n }\n\n // lib.es2020.promise.d.ts does not export its types so we're using a simple type.\n return (promiseResults as { status: 'fulfilled'; value: unknown }[]).map(\n ({ value }) => value,\n );\n }\n\n /**\n * Validates an approved {@link PermissionsRequest} object. The approved\n * request must have the required `metadata` and `permissions` properties,\n * the `id` and `origin` of the `metadata` must match the original request\n * metadata, and the requested permissions must be valid per\n * {@link PermissionController.validateRequestedPermissions}. Any extra\n * metadata properties are ignored.\n *\n * An error is thrown if validation fails.\n *\n * @param approvedRequest - The approved permissions request object.\n * @param originalMetadata - The original request metadata.\n */\n private validateApprovedPermissions(\n approvedRequest: unknown,\n originalMetadata: PermissionsRequestMetadata,\n ) {\n const { id, origin } = originalMetadata;\n\n if (\n !isPlainObject(approvedRequest) ||\n !isPlainObject(approvedRequest.metadata)\n ) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" is invalid.`,\n { data: { approvedRequest } },\n );\n }\n\n const {\n metadata: { id: newId, origin: newOrigin },\n permissions,\n } = approvedRequest;\n\n if (newId !== id) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" mutated its id.`,\n { originalId: id, mutatedId: newId },\n );\n }\n\n if (newOrigin !== origin) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" mutated its origin.`,\n { originalOrigin: origin, mutatedOrigin: newOrigin },\n );\n }\n\n try {\n this.validateRequestedPermissions(origin, permissions);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n // Re-throw as an internal error; we should never receive invalid approved\n // permissions.\n throw internalError(\n `Invalid approved permissions request: ${error.message}`,\n error.data,\n );\n }\n throw internalError('Unrecognized error type', { error });\n }\n }\n\n /**\n * Accepts a permissions request created by\n * {@link PermissionController.requestPermissions}.\n *\n * @param request - The permissions request.\n */\n async acceptPermissionsRequest(request: PermissionsRequest): Promise<void> {\n const { id } = request.metadata;\n\n if (!this.hasApprovalRequest({ id })) {\n throw new PermissionsRequestNotFoundError(id);\n }\n\n if (Object.keys(request.permissions).length === 0) {\n this._rejectPermissionsRequest(\n id,\n invalidParams({\n message: 'Must request at least one permission.',\n }),\n );\n return;\n }\n\n try {\n this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n request,\n );\n } catch (error) {\n // If accepting unexpectedly fails, reject the request and re-throw the\n // error\n this._rejectPermissionsRequest(id, error);\n throw error;\n }\n }\n\n /**\n * Rejects a permissions request created by\n * {@link PermissionController.requestPermissions}.\n *\n * @param id - The id of the request to be rejected.\n */\n async rejectPermissionsRequest(id: string): Promise<void> {\n if (!this.hasApprovalRequest({ id })) {\n throw new PermissionsRequestNotFoundError(id);\n }\n\n this._rejectPermissionsRequest(id, userRejectedRequest());\n }\n\n /**\n * Checks whether the {@link ApprovalController} has a particular permissions\n * request.\n *\n * @see {@link PermissionController.acceptPermissionsRequest} and\n * {@link PermissionController.rejectPermissionsRequest} for usage.\n * @param options - The {@link HasApprovalRequest} options.\n * @param options.id - The id of the approval request to check for.\n * @returns Whether the specified request exists.\n */\n private hasApprovalRequest(options: { id: string }): boolean {\n return this.messagingSystem.call(\n 'ApprovalController:hasRequest',\n // Typecast: For some reason, the type here expects all of the possible\n // HasApprovalRequest options to be specified, when they're actually all\n // optional. Passing just the id is definitely valid, so we just cast it.\n options as any,\n );\n }\n\n /**\n * Rejects the permissions request with the specified id, with the specified\n * error as the reason. This method is effectively a wrapper around a\n * messenger call for the `ApprovalController:rejectRequest` action.\n *\n * @see {@link PermissionController.acceptPermissionsRequest} and\n * {@link PermissionController.rejectPermissionsRequest} for usage.\n * @param id - The id of the request to reject.\n * @param error - The error associated with the rejection.\n * @returns Nothing\n */\n private _rejectPermissionsRequest(id: string, error: unknown): void {\n return this.messagingSystem.call(\n 'ApprovalController:rejectRequest',\n id,\n error,\n );\n }\n\n /**\n * Gets the subject's endowments per the specified endowment permission.\n * Throws if the subject does not have the required permission or if the\n * permission is not an endowment permission.\n *\n * @param origin - The origin of the subject whose endowments to retrieve.\n * @param targetName - The name of the endowment permission. This must be a\n * valid permission target name.\n * @param requestData - Additional data associated with the request, if any.\n * Forwarded to the endowment getter function for the permission.\n * @returns The endowments, if any.\n */\n async getEndowments(\n origin: string,\n targetName: ExtractEndowmentPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n requestData?: unknown,\n ): Promise<Json> {\n if (!this.hasPermission(origin, targetName)) {\n throw unauthorized({ data: { origin, targetName } });\n }\n\n return this.getTypedPermissionSpecification(\n PermissionType.Endowment,\n targetName,\n origin,\n ).endowmentGetter({ origin, requestData });\n }\n\n /**\n * Executes a restricted method as the subject with the given origin.\n * The specified params, if any, will be passed to the method implementation.\n *\n * ATTN: Great caution should be exercised in the use of this method.\n * Methods that cause side effects or affect application state should\n * be avoided.\n *\n * This method will first attempt to retrieve the requested restricted method\n * implementation, throwing if it does not exist. The method will then be\n * invoked as though the subject with the specified origin had invoked it with\n * the specified parameters. This means that any existing caveats will be\n * applied to the restricted method, and this method will throw if the\n * restricted method or its caveat decorators throw.\n *\n * In addition, this method will throw if the subject does not have a\n * permission for the specified restricted method.\n *\n * @param origin - The origin of the subject to execute the method on behalf\n * of.\n * @param targetName - The name of the method to execute. This must be a valid\n * permission target name.\n * @param params - The parameters to pass to the method implementation.\n * @returns The result of the executed method.\n */\n async executeRestrictedMethod(\n origin: OriginString,\n targetName: ExtractRestrictedMethodPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n params?: RestrictedMethodParameters,\n ): Promise<Json> {\n // Throws if the method does not exist\n const methodImplementation = this.getRestrictedMethod(targetName, origin);\n\n const result = await this._executeRestrictedMethod(\n methodImplementation,\n { origin },\n targetName,\n params,\n );\n\n if (result === undefined) {\n throw new Error(\n `Internal request for method \"${targetName}\" as origin \"${origin}\" returned no result.`,\n );\n }\n\n return result;\n }\n\n /**\n * An internal method used in the controller's `json-rpc-engine` middleware\n * and {@link PermissionController.executeRestrictedMethod}. Calls the\n * specified restricted method implementation after decorating it with the\n * caveats of its permission. Throws if the subject does not have the\n * requisite permission.\n *\n * ATTN: Parameter validation is the responsibility of the caller, or\n * the restricted method implementation in the case of `params`.\n *\n * @see {@link PermissionController.executeRestrictedMethod} and\n * {@link PermissionController.createPermissionMiddleware} for usage.\n * @param methodImplementation - The implementation of the method to call.\n * @param subject - Metadata about the subject that made the request.\n * @param method - The method name\n * @param params - Params needed for executing the restricted method\n * @returns The result of the restricted method implementation\n */\n private _executeRestrictedMethod(\n methodImplementation: RestrictedMethod<RestrictedMethodParameters, Json>,\n subject: PermissionSubjectMetadata,\n method: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n params: RestrictedMethodParameters = [],\n ): ReturnType<RestrictedMethod<RestrictedMethodParameters, Json>> {\n const { origin } = subject;\n\n const permission = this.getPermission(origin, method);\n if (!permission) {\n throw unauthorized({ data: { origin, method } });\n }\n\n return decorateWithCaveats(\n methodImplementation,\n permission,\n this._caveatSpecifications,\n )({ method, params, context: { origin } });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PermissionController.js","sourceRoot":"","sources":["../src/PermissionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,+DAA2D;AAE3D,iEAIoC;AACpC,qDAAoD;AACpD,2CAA8C;AAE9C,4EAA4C;AAC5C,iCAA8C;AAC9C,mCAAgC;AAUhC,qCAGkB;AAClB,qCAwBkB;AAiBlB,6CAKsB;AACtB,mEAAyE;AAEzE,mCAAsC;AAuCtC;;GAEG;AACH,MAAM,cAAc,GAAG,sBAAsB,CAAC;AA4C9C;;;;;GAKG;AACH,SAAS,gBAAgB;IACvB,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,EAEpD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe;IACtB,OAAO,EAAE,QAAQ,EAAE,EAAE,EAA2C,CAAC;AACnE,CAAC;AAuLD;;GAEG;AACH,IAAY,sBAKX;AALD,WAAY,sBAAsB;IAChC,mEAAI,CAAA;IACJ,iFAAW,CAAA;IACX,mFAAY,CAAA;IACZ,2FAAgB,CAAA;AAClB,CAAC,EALW,sBAAsB,GAAtB,8BAAsB,KAAtB,8BAAsB,QAKjC;AAkHD;;;;;;;;;;;;GAYG;AACH,MAAa,oBAGX,SAAQ,gCAST;IAgCC;;;;;;;;;;;;;;;;OAgBG;IACH,YACE,OAGC;QAED,MAAM,EACJ,oBAAoB,EACpB,wBAAwB,EACxB,mBAAmB,EACnB,SAAS,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CAAC,qBAAqB,CAC3B,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7C,CAAC;CACF;AAl1DD,oDAk1DC","sourcesContent":["/* eslint-enable @typescript-eslint/no-unused-vars */\nimport type {\n AcceptRequest as AcceptApprovalRequest,\n AddApprovalRequest,\n HasApprovalRequest,\n RejectRequest as RejectApprovalRequest,\n} from '@metamask/approval-controller';\nimport type {\n StateMetadata,\n RestrictedControllerMessenger,\n ActionConstraint,\n EventConstraint,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { NonEmptyArray } from '@metamask/controller-utils';\nimport {\n isNonEmptyArray,\n isPlainObject,\n isValidJson,\n} from '@metamask/controller-utils';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport { hasProperty } from '@metamask/utils';\nimport type { Json, Mutable } from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\nimport { castDraft, type Draft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport type {\n CaveatConstraint,\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n ExtractCaveat,\n ExtractCaveats,\n ExtractCaveatValue,\n} from './Caveat';\nimport {\n decorateWithCaveats,\n isRestrictedMethodCaveatSpecification,\n} from './Caveat';\nimport {\n CaveatAlreadyExistsError,\n CaveatDoesNotExistError,\n CaveatInvalidJsonError,\n CaveatMissingValueError,\n CaveatSpecificationMismatchError,\n DuplicateCaveatError,\n EndowmentPermissionDoesNotExistError,\n ForbiddenCaveatError,\n internalError,\n InvalidApprovedPermissionError,\n InvalidCaveatError,\n InvalidCaveatFieldsError,\n InvalidCaveatsPropertyError,\n InvalidCaveatTypeError,\n invalidParams,\n InvalidSubjectIdentifierError,\n methodNotFound,\n PermissionDoesNotExistError,\n PermissionsRequestNotFoundError,\n unauthorized,\n UnrecognizedCaveatTypeError,\n UnrecognizedSubjectError,\n userRejectedRequest,\n} from './errors';\nimport type {\n EndowmentSpecificationConstraint,\n ExtractAllowedCaveatTypes,\n ExtractPermissionSpecification,\n OriginString,\n PermissionConstraint,\n PermissionSpecificationConstraint,\n PermissionSpecificationMap,\n RequestedPermissions,\n RestrictedMethod,\n RestrictedMethodParameters,\n RestrictedMethodSpecificationConstraint,\n SideEffectHandler,\n ValidPermission,\n ValidPermissionSpecification,\n} from './Permission';\nimport {\n constructPermission,\n findCaveat,\n hasSpecificationType,\n PermissionType,\n} from './Permission';\nimport { getPermissionMiddlewareFactory } from './permission-middleware';\nimport type { GetSubjectMetadata } from './SubjectMetadataController';\nimport { MethodNames } from './utils';\n\n/**\n * Metadata associated with {@link PermissionController} subjects.\n */\nexport type PermissionSubjectMetadata = {\n origin: OriginString;\n};\n\n/**\n * Metadata associated with permission requests.\n */\nexport type PermissionsRequestMetadata = PermissionSubjectMetadata & {\n id: string;\n};\n\n/**\n * Used for prompting the user about a proposed new permission.\n * Includes information about the grantee subject, requested permissions, and\n * any additional information added by the consumer.\n *\n * All properties except `permissions` are passed to any factories found for\n * the requested permissions.\n */\nexport type PermissionsRequest = {\n metadata: PermissionsRequestMetadata;\n permissions: RequestedPermissions;\n [key: string]: Json;\n};\n\nexport type SideEffects = {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n permittedHandlers: Record<string, SideEffectHandler<any, any>>;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n failureHandlers: Record<string, SideEffectHandler<any, any>>;\n};\n\n/**\n * The name of the {@link PermissionController}.\n */\nconst controllerName = 'PermissionController';\n\n/**\n * Permissions associated with a {@link PermissionController} subject.\n */\nexport type SubjectPermissions<Permission extends PermissionConstraint> =\n Record<Permission['parentCapability'], Permission>;\n\n/**\n * Permissions and metadata associated with a {@link PermissionController}\n * subject.\n */\nexport type PermissionSubjectEntry<\n SubjectPermission extends PermissionConstraint,\n> = {\n origin: SubjectPermission['invoker'];\n permissions: SubjectPermissions<SubjectPermission>;\n};\n\n/**\n * All subjects of a {@link PermissionController}.\n *\n * @template SubjectPermission - The permissions of the subject.\n */\nexport type PermissionControllerSubjects<\n SubjectPermission extends PermissionConstraint,\n> = Record<\n SubjectPermission['invoker'],\n PermissionSubjectEntry<SubjectPermission>\n>;\n\n// TODO:TS4.4 Enable compiler flags to forbid unchecked member access\n/**\n * The state of a {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n */\nexport type PermissionControllerState<Permission> =\n Permission extends PermissionConstraint\n ? {\n subjects: PermissionControllerSubjects<Permission>;\n }\n : never;\n\n/**\n * Get the state metadata of the {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n * @returns The state metadata\n */\nfunction getStateMetadata<Permission extends PermissionConstraint>() {\n return { subjects: { anonymous: true, persist: true } } as StateMetadata<\n PermissionControllerState<Permission>\n >;\n}\n\n/**\n * Get the default state of the {@link PermissionController}.\n *\n * @template Permission - The controller's permission type union.\n * @returns The default state of the controller\n */\nfunction getDefaultState<Permission extends PermissionConstraint>() {\n return { subjects: {} } as PermissionControllerState<Permission>;\n}\n\n/**\n * Gets the state of the {@link PermissionController}.\n */\nexport type GetPermissionControllerState = ControllerGetStateAction<\n typeof controllerName,\n PermissionControllerState<PermissionConstraint>\n>;\n\n/**\n * Gets the names of all subjects from the {@link PermissionController}.\n */\nexport type GetSubjects = {\n type: `${typeof controllerName}:getSubjectNames`;\n handler: () => (keyof PermissionControllerSubjects<PermissionConstraint>)[];\n};\n\n/**\n * Gets the permissions for specified subject\n */\nexport type GetPermissions = {\n type: `${typeof controllerName}:getPermissions`;\n handler: GenericPermissionController['getPermissions'];\n};\n\n/**\n * Checks whether the specified subject has any permissions.\n */\nexport type HasPermissions = {\n type: `${typeof controllerName}:hasPermissions`;\n handler: GenericPermissionController['hasPermissions'];\n};\n\n/**\n * Checks whether the specified subject has a specific permission.\n */\nexport type HasPermission = {\n type: `${typeof controllerName}:hasPermission`;\n handler: GenericPermissionController['hasPermission'];\n};\n\n/**\n * Directly grants given permissions for a specificed origin without requesting user approval\n */\nexport type GrantPermissions = {\n type: `${typeof controllerName}:grantPermissions`;\n handler: GenericPermissionController['grantPermissions'];\n};\n\n/**\n * Requests given permissions for a specified origin\n */\nexport type RequestPermissions = {\n type: `${typeof controllerName}:requestPermissions`;\n handler: GenericPermissionController['requestPermissions'];\n};\n\n/**\n * Removes the specified permissions for each origin.\n */\nexport type RevokePermissions = {\n type: `${typeof controllerName}:revokePermissions`;\n handler: GenericPermissionController['revokePermissions'];\n};\n\n/**\n * Removes all permissions for a given origin\n */\nexport type RevokeAllPermissions = {\n type: `${typeof controllerName}:revokeAllPermissions`;\n handler: GenericPermissionController['revokeAllPermissions'];\n};\n\n/**\n * Revokes all permissions corresponding to the specified target for all subjects.\n * Does nothing if no subjects or no such permission exists.\n */\nexport type RevokePermissionForAllSubjects = {\n type: `${typeof controllerName}:revokePermissionForAllSubjects`;\n handler: GenericPermissionController['revokePermissionForAllSubjects'];\n};\n\n/**\n * Updates a caveat value for a specified caveat type belonging to a specific target and origin.\n */\nexport type UpdateCaveat = {\n type: `${typeof controllerName}:updateCaveat`;\n handler: GenericPermissionController['updateCaveat'];\n};\n\n/**\n * Clears all permissions from the {@link PermissionController}.\n */\nexport type ClearPermissions = {\n type: `${typeof controllerName}:clearPermissions`;\n handler: () => void;\n};\n\n/**\n * Gets the endowments for the given subject and permission.\n */\nexport type GetEndowments = {\n type: `${typeof controllerName}:getEndowments`;\n handler: GenericPermissionController['getEndowments'];\n};\n\n/**\n * The {@link ControllerMessenger} actions of the {@link PermissionController}.\n */\nexport type PermissionControllerActions =\n | ClearPermissions\n | GetEndowments\n | GetPermissionControllerState\n | GetSubjects\n | GetPermissions\n | HasPermission\n | HasPermissions\n | GrantPermissions\n | RequestPermissions\n | RevokeAllPermissions\n | RevokePermissionForAllSubjects\n | RevokePermissions\n | UpdateCaveat;\n\n/**\n * The generic state change event of the {@link PermissionController}.\n */\nexport type PermissionControllerStateChange = ControllerStateChangeEvent<\n typeof controllerName,\n PermissionControllerState<PermissionConstraint>\n>;\n\n/**\n * The {@link ControllerMessenger} events of the {@link PermissionController}.\n *\n * The permission controller only emits its generic state change events.\n * Consumers should use selector subscriptions to subscribe to relevant\n * substate.\n */\nexport type PermissionControllerEvents = PermissionControllerStateChange;\n\n/**\n * The external {@link ControllerMessenger} actions available to the\n * {@link PermissionController}.\n */\ntype AllowedActions =\n | AddApprovalRequest\n | HasApprovalRequest\n | AcceptApprovalRequest\n | RejectApprovalRequest\n | GetSubjectMetadata;\n\n/**\n * The messenger of the {@link PermissionController}.\n */\nexport type PermissionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n PermissionControllerActions | AllowedActions,\n PermissionControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nexport type SideEffectMessenger<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = RestrictedControllerMessenger<\n typeof controllerName,\n Actions,\n Events,\n string,\n never\n>;\n\n/**\n * A generic {@link PermissionController}.\n */\nexport type GenericPermissionController = PermissionController<\n PermissionSpecificationConstraint,\n CaveatSpecificationConstraint\n>;\n\n/**\n * Describes the possible results of a {@link CaveatMutator} function.\n */\nexport enum CaveatMutatorOperation {\n noop,\n updateValue,\n deleteCaveat,\n revokePermission,\n}\n\n/**\n * Given a caveat value, returns a {@link CaveatMutatorOperation} and, optionally,\n * a new caveat value.\n *\n * @see {@link PermissionController.updatePermissionsByCaveat} for more details.\n * @template Caveat - The caveat type for which this mutator is intended.\n * @param caveatValue - The existing value of the caveat being mutated.\n * @returns A tuple of the mutation result and, optionally, the new caveat\n * value.\n */\nexport type CaveatMutator<TargetCaveat extends CaveatConstraint> = (\n caveatValue: TargetCaveat['value'],\n) => CaveatMutatorResult;\n\ntype CaveatMutatorResult =\n | Readonly<{\n operation: CaveatMutatorOperation.updateValue;\n value: CaveatConstraint['value'];\n }>\n | Readonly<{\n operation: Exclude<\n CaveatMutatorOperation,\n CaveatMutatorOperation.updateValue\n >;\n }>;\n\n/**\n * Extracts the permission(s) specified by the given permission and caveat\n * specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ControllerPermissionSpecification extends ValidPermissionSpecification<ControllerPermissionSpecification>\n ? ValidPermission<\n ControllerPermissionSpecification['targetName'],\n ExtractCaveats<ControllerCaveatSpecification>\n >\n : never;\n\n/**\n * Extracts the restricted method permission(s) specified by the given\n * permission and caveat specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractRestrictedMethodPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ExtractPermission<\n Extract<\n ControllerPermissionSpecification,\n RestrictedMethodSpecificationConstraint\n >,\n ControllerCaveatSpecification\n>;\n\n/**\n * Extracts the endowment permission(s) specified by the given permission and\n * caveat specifications.\n *\n * @template ControllerPermissionSpecification - The permission specification(s)\n * to extract from.\n * @template ControllerCaveatSpecification - The caveat specification(s) to\n * extract from. Necessary because {@link Permission} has a generic parameter\n * that describes the allowed caveats for the permission.\n */\nexport type ExtractEndowmentPermission<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = ExtractPermission<\n Extract<ControllerPermissionSpecification, EndowmentSpecificationConstraint>,\n ControllerCaveatSpecification\n>;\n\n/**\n * Options for the {@link PermissionController} constructor.\n *\n * @template ControllerPermissionSpecification - A union of the types of all\n * permission specifications available to the controller. Any referenced caveats\n * must be included in the controller's caveat specifications.\n * @template ControllerCaveatSpecification - A union of the types of all\n * caveat specifications available to the controller.\n */\nexport type PermissionControllerOptions<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> = {\n messenger: PermissionControllerMessenger;\n caveatSpecifications: CaveatSpecificationMap<ControllerCaveatSpecification>;\n permissionSpecifications: PermissionSpecificationMap<ControllerPermissionSpecification>;\n unrestrictedMethods: readonly string[];\n state?: Partial<\n PermissionControllerState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n >;\n};\n\n/**\n * The permission controller. See the [Architecture](../ARCHITECTURE.md)\n * document for details.\n *\n * Assumes the existence of an {@link ApprovalController} reachable via the\n * {@link ControllerMessenger}.\n *\n * @template ControllerPermissionSpecification - A union of the types of all\n * permission specifications available to the controller. Any referenced caveats\n * must be included in the controller's caveat specifications.\n * @template ControllerCaveatSpecification - A union of the types of all\n * caveat specifications available to the controller.\n */\nexport class PermissionController<\n ControllerPermissionSpecification extends PermissionSpecificationConstraint,\n ControllerCaveatSpecification extends CaveatSpecificationConstraint,\n> extends BaseController<\n typeof controllerName,\n PermissionControllerState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n PermissionControllerMessenger\n> {\n private readonly _caveatSpecifications: Readonly<\n CaveatSpecificationMap<ControllerCaveatSpecification>\n >;\n\n private readonly _permissionSpecifications: Readonly<\n PermissionSpecificationMap<ControllerPermissionSpecification>\n >;\n\n private readonly _unrestrictedMethods: ReadonlySet<string>;\n\n /**\n * The names of all JSON-RPC methods that will be ignored by the controller.\n *\n * @returns The names of all unrestricted JSON-RPC methods\n */\n public get unrestrictedMethods(): ReadonlySet<string> {\n return this._unrestrictedMethods;\n }\n\n /**\n * Returns a `json-rpc-engine` middleware function factory, so that the rules\n * described by the state of this controller can be applied to incoming\n * JSON-RPC requests.\n *\n * The middleware **must** be added in the correct place in the middleware\n * stack in order for it to work. See the README for an example.\n */\n public createPermissionMiddleware: ReturnType<\n typeof getPermissionMiddlewareFactory\n >;\n\n /**\n * Constructs the PermissionController.\n *\n * @param options - Permission controller options.\n * @param options.caveatSpecifications - The specifications of all caveats\n * available to the controller. See {@link CaveatSpecificationMap} and the\n * documentation for more details.\n * @param options.permissionSpecifications - The specifications of all\n * permissions available to the controller. See\n * {@link PermissionSpecificationMap} and the README for more details.\n * @param options.unrestrictedMethods - The callable names of all JSON-RPC\n * methods ignored by the new controller.\n * @param options.messenger - The controller messenger. See\n * {@link BaseController} for more information.\n * @param options.state - Existing state to hydrate the controller with at\n * initialization.\n */\n constructor(\n options: PermissionControllerOptions<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >,\n ) {\n const {\n caveatSpecifications,\n permissionSpecifications,\n unrestrictedMethods,\n messenger,\n state = {},\n } = options;\n\n super({\n name: controllerName,\n metadata:\n getStateMetadata<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n messenger,\n state: {\n ...getDefaultState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n ...state,\n },\n });\n\n this._unrestrictedMethods = new Set(unrestrictedMethods);\n this._caveatSpecifications = deepFreeze({ ...caveatSpecifications });\n\n this.validatePermissionSpecifications(\n permissionSpecifications,\n this._caveatSpecifications,\n );\n\n this._permissionSpecifications = deepFreeze({\n ...permissionSpecifications,\n });\n\n this.registerMessageHandlers();\n this.createPermissionMiddleware = getPermissionMiddlewareFactory({\n executeRestrictedMethod: this._executeRestrictedMethod.bind(this),\n getRestrictedMethod: this.getRestrictedMethod.bind(this),\n isUnrestrictedMethod: this.unrestrictedMethods.has.bind(\n this.unrestrictedMethods,\n ),\n });\n }\n\n /**\n * Gets a permission specification.\n *\n * @param targetName - The name of the permission specification to get.\n * @returns The permission specification with the specified target name.\n */\n private getPermissionSpecification<\n TargetName extends ControllerPermissionSpecification['targetName'],\n >(\n targetName: TargetName,\n ): ExtractPermissionSpecification<\n ControllerPermissionSpecification,\n TargetName\n > {\n return this._permissionSpecifications[targetName];\n }\n\n /**\n * Gets a caveat specification.\n *\n * @param caveatType - The type of the caveat specification to get.\n * @returns The caveat specification with the specified type.\n */\n private getCaveatSpecification<\n CaveatType extends ControllerCaveatSpecification['type'],\n >(caveatType: CaveatType) {\n return this._caveatSpecifications[caveatType];\n }\n\n /**\n * Constructor helper for validating permission specifications.\n *\n * Throws an error if validation fails.\n *\n * @param permissionSpecifications - The permission specifications passed to\n * this controller's constructor.\n * @param caveatSpecifications - The caveat specifications passed to this\n * controller.\n */\n private validatePermissionSpecifications(\n permissionSpecifications: PermissionSpecificationMap<ControllerPermissionSpecification>,\n caveatSpecifications: CaveatSpecificationMap<ControllerCaveatSpecification>,\n ) {\n Object.entries<ControllerPermissionSpecification>(\n permissionSpecifications,\n ).forEach(\n ([\n targetName,\n { permissionType, targetName: innerTargetName, allowedCaveats },\n ]) => {\n if (!permissionType || !hasProperty(PermissionType, permissionType)) {\n throw new Error(`Invalid permission type: \"${permissionType}\"`);\n }\n\n if (!targetName) {\n throw new Error(`Invalid permission target name: \"${targetName}\"`);\n }\n\n if (targetName !== innerTargetName) {\n throw new Error(\n `Invalid permission specification: target name \"${targetName}\" must match specification.targetName value \"${innerTargetName}\".`,\n );\n }\n\n if (allowedCaveats) {\n allowedCaveats.forEach((caveatType) => {\n if (!hasProperty(caveatSpecifications, caveatType)) {\n throw new UnrecognizedCaveatTypeError(caveatType);\n }\n\n const specification =\n caveatSpecifications[\n caveatType as ControllerCaveatSpecification['type']\n ];\n const isRestrictedMethodCaveat =\n isRestrictedMethodCaveatSpecification(specification);\n\n if (\n (permissionType === PermissionType.RestrictedMethod &&\n !isRestrictedMethodCaveat) ||\n (permissionType === PermissionType.Endowment &&\n isRestrictedMethodCaveat)\n ) {\n throw new CaveatSpecificationMismatchError(\n specification,\n permissionType,\n );\n }\n });\n }\n },\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:clearPermissions` as const,\n () => this.clearState(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getEndowments` as const,\n (origin: string, targetName: string, requestData?: unknown) =>\n this.getEndowments(origin, targetName, requestData),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSubjectNames` as const,\n () => this.getSubjectNames(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getPermissions` as const,\n (origin: OriginString) => this.getPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:hasPermission` as const,\n (origin: OriginString, targetName: string) =>\n this.hasPermission(origin, targetName),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:hasPermissions` as const,\n (origin: OriginString) => this.hasPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:grantPermissions` as const,\n this.grantPermissions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:requestPermissions` as const,\n (subject: PermissionSubjectMetadata, permissions: RequestedPermissions) =>\n this.requestPermissions(subject, permissions),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokeAllPermissions` as const,\n (origin: OriginString) => this.revokeAllPermissions(origin),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokePermissionForAllSubjects` as const,\n (\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ) => this.revokePermissionForAllSubjects(target),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:revokePermissions` as const,\n this.revokePermissions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateCaveat` as const,\n (origin, target, caveatType, caveatValue) => {\n this.updateCaveat(\n origin,\n target,\n caveatType as ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n caveatValue,\n );\n },\n );\n }\n\n /**\n * Clears the state of the controller.\n */\n clearState(): void {\n this.update((_draftState) => {\n return {\n ...getDefaultState<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >(),\n };\n });\n }\n\n /**\n * Gets the permission specification corresponding to the given permission\n * type and target name. Throws an error if the target name does not\n * correspond to a permission, or if the specification is not of the\n * given permission type.\n *\n * @template Type - The type of the permission specification to get.\n * @param permissionType - The type of the permission specification to get.\n * @param targetName - The name of the permission whose specification to get.\n * @param requestingOrigin - The origin of the requesting subject, if any.\n * Will be added to any thrown errors.\n * @returns The specification object corresponding to the given type and\n * target name.\n */\n private getTypedPermissionSpecification<Type extends PermissionType>(\n permissionType: Type,\n targetName: string,\n requestingOrigin?: string,\n ): ControllerPermissionSpecification & { permissionType: Type } {\n const failureError =\n permissionType === PermissionType.RestrictedMethod\n ? methodNotFound(\n targetName,\n requestingOrigin ? { origin: requestingOrigin } : undefined,\n )\n : new EndowmentPermissionDoesNotExistError(\n targetName,\n requestingOrigin,\n );\n\n if (!this.targetExists(targetName)) {\n throw failureError;\n }\n\n const specification = this.getPermissionSpecification(targetName);\n if (!hasSpecificationType(specification, permissionType)) {\n throw failureError;\n }\n\n return specification;\n }\n\n /**\n * Gets the implementation of the specified restricted method.\n *\n * A JSON-RPC error is thrown if the method does not exist.\n *\n * @see {@link PermissionController.executeRestrictedMethod} and\n * {@link PermissionController.createPermissionMiddleware} for internal usage.\n * @param method - The name of the restricted method.\n * @param origin - The origin associated with the request for the restricted\n * method, if any.\n * @returns The restricted method implementation.\n */\n getRestrictedMethod(\n method: string,\n origin?: string,\n ): RestrictedMethod<RestrictedMethodParameters, Json> {\n return this.getTypedPermissionSpecification(\n PermissionType.RestrictedMethod,\n method,\n origin,\n ).methodImplementation;\n }\n\n /**\n * Gets a list of all origins of subjects.\n *\n * @returns The origins (i.e. IDs) of all subjects.\n */\n getSubjectNames(): OriginString[] {\n return Object.keys(this.state.subjects);\n }\n\n /**\n * Gets the permission for the specified target of the subject corresponding\n * to the specified origin.\n *\n * @param origin - The origin of the subject.\n * @param targetName - The method name as invoked by a third party (i.e., not\n * a method key).\n * @returns The permission if it exists, or undefined otherwise.\n */\n getPermission<\n SubjectPermission extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >,\n >(\n origin: OriginString,\n targetName: SubjectPermission['parentCapability'],\n ): SubjectPermission | undefined {\n return this.state.subjects[origin]?.permissions[targetName] as\n | SubjectPermission\n | undefined;\n }\n\n /**\n * Gets all permissions for the specified subject, if any.\n *\n * @param origin - The origin of the subject.\n * @returns The permissions of the subject, if any.\n */\n getPermissions(\n origin: OriginString,\n ):\n | SubjectPermissions<\n ValidPermission<string, ExtractCaveats<ControllerCaveatSpecification>>\n >\n | undefined {\n return this.state.subjects[origin]?.permissions;\n }\n\n /**\n * Checks whether the subject with the specified origin has the specified\n * permission.\n *\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @returns Whether the subject has the permission.\n */\n hasPermission(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): boolean {\n return Boolean(this.getPermission(origin, target));\n }\n\n /**\n * Checks whether the subject with the specified origin has any permissions.\n * Use this if you want to know if a subject \"exists\".\n *\n * @param origin - The origin of the subject to check.\n * @returns Whether the subject has any permissions.\n */\n hasPermissions(origin: OriginString): boolean {\n return Boolean(this.state.subjects[origin]);\n }\n\n /**\n * Revokes all permissions from the specified origin.\n *\n * Throws an error of the origin has no permissions.\n *\n * @param origin - The origin whose permissions to revoke.\n */\n revokeAllPermissions(origin: OriginString): void {\n this.update((draftState) => {\n if (!draftState.subjects[origin]) {\n throw new UnrecognizedSubjectError(origin);\n }\n delete draftState.subjects[origin];\n });\n }\n\n /**\n * Revokes the specified permission from the subject with the specified\n * origin.\n *\n * Throws an error if the subject or the permission does not exist.\n *\n * @param origin - The origin of the subject whose permission to revoke.\n * @param target - The target name of the permission to revoke.\n */\n revokePermission(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n this.revokePermissions({ [origin]: [target] });\n }\n\n /**\n * Revokes the specified permissions from the specified subjects.\n *\n * Throws an error if any of the subjects or permissions do not exist.\n *\n * @param subjectsAndPermissions - An object mapping subject origins\n * to arrays of permission target names to revoke.\n */\n revokePermissions(\n subjectsAndPermissions: Record<\n OriginString,\n NonEmptyArray<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability']\n >\n >,\n ): void {\n this.update((draftState) => {\n Object.keys(subjectsAndPermissions).forEach((origin) => {\n if (!hasProperty(draftState.subjects, origin)) {\n throw new UnrecognizedSubjectError(origin);\n }\n\n subjectsAndPermissions[origin].forEach((target) => {\n const { permissions } = draftState.subjects[origin];\n if (!hasProperty(permissions as Record<string, unknown>, target)) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n this.deletePermission(draftState.subjects, origin, target);\n });\n });\n });\n }\n\n /**\n * Revokes all permissions corresponding to the specified target for all subjects.\n * Does nothing if no subjects or no such permission exists.\n *\n * @param target - The name of the target to revoke all permissions for.\n */\n revokePermissionForAllSubjects(\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n if (this.getSubjectNames().length === 0) {\n return;\n }\n\n this.update((draftState) => {\n Object.entries(draftState.subjects).forEach(([origin, subject]) => {\n const { permissions } = subject;\n\n if (hasProperty(permissions as Record<string, unknown>, target)) {\n this.deletePermission(draftState.subjects, origin, target);\n }\n });\n });\n }\n\n /**\n * Deletes the permission identified by the given origin and target. If the\n * permission is the single remaining permission of its subject, the subject\n * is also deleted.\n *\n * @param subjects - The draft permission controller subjects.\n * @param origin - The origin of the subject associated with the permission\n * to delete.\n * @param target - The target name of the permission to delete.\n */\n private deletePermission(\n subjects: Draft<PermissionControllerSubjects<PermissionConstraint>>,\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n ): void {\n const { permissions } = subjects[origin];\n if (Object.keys(permissions).length > 1) {\n delete permissions[target];\n } else {\n delete subjects[origin];\n }\n }\n\n /**\n * Checks whether the permission of the subject corresponding to the given\n * origin has a caveat of the specified type.\n *\n * Throws an error if the subject does not have a permission with the\n * specified target name.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to check for.\n * @returns Whether the permission has the specified caveat.\n */\n hasCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(origin: OriginString, target: TargetName, caveatType: CaveatType): boolean {\n return Boolean(this.getCaveat(origin, target, caveatType));\n }\n\n /**\n * Gets the caveat of the specified type, if any, for the permission of\n * the subject corresponding to the given origin.\n *\n * Throws an error if the subject does not have a permission with the\n * specified target name.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to get.\n * @returns The caveat, or `undefined` if no such caveat exists.\n */\n getCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n ): ExtractCaveat<ControllerCaveatSpecification, CaveatType> | undefined {\n const permission = this.getPermission(origin, target);\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n return findCaveat(permission, caveatType) as\n | ExtractCaveat<ControllerCaveatSpecification, CaveatType>\n | undefined;\n }\n\n /**\n * Adds a caveat of the specified type, with the specified caveat value, to\n * the permission corresponding to the given subject origin and permission\n * target.\n *\n * For modifying existing caveats, use\n * {@link PermissionController.updateCaveat}.\n *\n * Throws an error if no such permission exists, or if the caveat already\n * exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to add.\n * @param caveatValue - The value of the caveat to add.\n */\n addCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>,\n ): void {\n if (this.hasCaveat(origin, target, caveatType)) {\n throw new CaveatAlreadyExistsError(origin, target, caveatType);\n }\n\n this.setCaveat(origin, target, caveatType, caveatValue);\n }\n\n /**\n * Updates the value of the caveat of the specified type belonging to the\n * permission corresponding to the given subject origin and permission\n * target.\n *\n * For adding new caveats, use\n * {@link PermissionController.addCaveat}.\n *\n * Throws an error if no such permission or caveat exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to update.\n * @param caveatValue - The new value of the caveat.\n */\n updateCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n CaveatValue extends ExtractCaveatValue<\n ControllerCaveatSpecification,\n CaveatType\n >,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: CaveatValue,\n ): void {\n if (!this.hasCaveat(origin, target, caveatType)) {\n throw new CaveatDoesNotExistError(origin, target, caveatType);\n }\n\n this.setCaveat(origin, target, caveatType, caveatValue);\n }\n\n /**\n * Sets the specified caveat on the specified permission. Overwrites existing\n * caveats of the same type in-place (preserving array order), and adds the\n * caveat to the end of the array otherwise.\n *\n * Throws an error if the permission does not exist or fails to validate after\n * its caveats have been modified.\n *\n * @see {@link PermissionController.addCaveat}\n * @see {@link PermissionController.updateCaveat}\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to set.\n * @param caveatValue - The value of the caveat to set.\n */\n private setCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(\n origin: OriginString,\n target: TargetName,\n caveatType: CaveatType,\n caveatValue: ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>,\n ): void {\n this.update((draftState) => {\n const subject = draftState.subjects[origin];\n\n // Unreachable because `hasCaveat` is always called before this, and it\n // throws if permissions are missing. TypeScript needs this, however.\n /* istanbul ignore if */\n if (!subject) {\n throw new UnrecognizedSubjectError(origin);\n }\n\n const permission = subject.permissions[target];\n\n /* istanbul ignore if: practically impossible, but TypeScript wants it */\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n const caveat = {\n type: caveatType,\n value: caveatValue,\n };\n this.validateCaveat(caveat, origin, target);\n\n if (permission.caveats) {\n const caveatIndex = permission.caveats.findIndex(\n (existingCaveat) => existingCaveat.type === caveat.type,\n );\n\n if (caveatIndex === -1) {\n permission.caveats.push(caveat);\n } else {\n permission.caveats.splice(caveatIndex, 1, caveat);\n }\n } else {\n // Typecast: At this point, we don't know if the specific permission\n // is allowed to have caveats, but it should be impossible to call\n // this method for a permission that may not have any caveats.\n // If all else fails, the permission validator is also called.\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n permission.caveats = [caveat] as any;\n }\n\n this.validateModifiedPermission(permission, origin);\n });\n }\n\n /**\n * Updates all caveats with the specified type for all subjects and\n * permissions by applying the specified mutator function to them.\n *\n * ATTN: Permissions can be revoked entirely by the action of this method,\n * read on for details.\n *\n * Caveat mutators are functions that receive a caveat value and return a\n * tuple consisting of a {@link CaveatMutatorOperation} and, optionally, a new\n * value to update the existing caveat with.\n *\n * For each caveat, depending on the mutator result, this method will:\n * - Do nothing ({@link CaveatMutatorOperation.noop})\n * - Update the value of the caveat ({@link CaveatMutatorOperation.updateValue}). The caveat specification validator, if any, will be called after updating the value.\n * - Delete the caveat ({@link CaveatMutatorOperation.deleteCaveat}). The permission specification validator, if any, will be called after deleting the caveat.\n * - Revoke the parent permission ({@link CaveatMutatorOperation.revokePermission})\n *\n * This method throws if the validation of any caveat or permission fails.\n *\n * @param targetCaveatType - The type of the caveats to update.\n * @param mutator - The mutator function which will be applied to all caveat\n * values.\n */\n updatePermissionsByCaveat<\n CaveatType extends ExtractCaveats<ControllerCaveatSpecification>['type'],\n TargetCaveat extends ExtractCaveat<\n ControllerCaveatSpecification,\n CaveatType\n >,\n >(targetCaveatType: CaveatType, mutator: CaveatMutator<TargetCaveat>): void {\n if (Object.keys(this.state.subjects).length === 0) {\n return;\n }\n\n this.update((draftState) => {\n Object.values(draftState.subjects).forEach((subject) => {\n Object.values(subject.permissions).forEach((permission) => {\n const { caveats } = permission;\n const targetCaveat = caveats?.find(\n ({ type }) => type === targetCaveatType,\n );\n if (!targetCaveat) {\n return;\n }\n\n // The mutator may modify the caveat value in place, and must always\n // return a valid mutation result.\n const mutatorResult = mutator(targetCaveat.value);\n switch (mutatorResult.operation) {\n case CaveatMutatorOperation.noop:\n break;\n\n case CaveatMutatorOperation.updateValue:\n // Typecast: `Mutable` is used here to assign to a readonly\n // property. `targetConstraint` should already be mutable because\n // it's part of a draft, but for some reason it's not. We can't\n // use the more-correct `Draft` type here either because it\n // results in an error.\n (targetCaveat as Mutable<CaveatConstraint, 'value'>).value =\n mutatorResult.value;\n\n this.validateCaveat(\n targetCaveat,\n subject.origin,\n permission.parentCapability,\n );\n break;\n\n case CaveatMutatorOperation.deleteCaveat:\n this.deleteCaveat(permission, targetCaveatType, subject.origin);\n break;\n\n case CaveatMutatorOperation.revokePermission:\n this.deletePermission(\n draftState.subjects,\n subject.origin,\n permission.parentCapability,\n );\n break;\n\n default: {\n // This type check ensures that the switch statement is\n // exhaustive.\n const _exhaustiveCheck: never = mutatorResult;\n throw new Error(\n `Unrecognized mutation result: \"${\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (_exhaustiveCheck as any).operation\n }\"`,\n );\n }\n }\n });\n });\n });\n }\n\n /**\n * Removes the caveat of the specified type from the permission corresponding\n * to the given subject origin and target name.\n *\n * Throws an error if no such permission or caveat exists.\n *\n * @template TargetName - The permission target name. Should be inferred.\n * @template CaveatType - The valid caveat types for the permission. Should\n * be inferred.\n * @param origin - The origin of the subject.\n * @param target - The target name of the permission.\n * @param caveatType - The type of the caveat to remove.\n */\n removeCaveat<\n TargetName extends ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>,\n >(origin: OriginString, target: TargetName, caveatType: CaveatType): void {\n this.update((draftState) => {\n const permission = draftState.subjects[origin]?.permissions[target];\n if (!permission) {\n throw new PermissionDoesNotExistError(origin, target);\n }\n\n if (!permission.caveats) {\n throw new CaveatDoesNotExistError(origin, target, caveatType);\n }\n\n this.deleteCaveat(permission, caveatType, origin);\n });\n }\n\n /**\n * Deletes the specified caveat from the specified permission. If no caveats\n * remain after deletion, the permission's caveat property is set to `null`.\n * The permission is validated after being modified.\n *\n * Throws an error if the permission does not have a caveat with the specified\n * type.\n *\n * @param permission - The permission whose caveat to delete.\n * @param caveatType - The type of the caveat to delete.\n * @param origin - The origin the permission subject.\n */\n private deleteCaveat<\n CaveatType extends ExtractCaveats<ControllerCaveatSpecification>['type'],\n >(\n permission: Draft<PermissionConstraint>,\n caveatType: CaveatType,\n origin: OriginString,\n ): void {\n /* istanbul ignore if: not possible in our usage */\n if (!permission.caveats) {\n throw new CaveatDoesNotExistError(\n origin,\n permission.parentCapability,\n caveatType,\n );\n }\n\n const caveatIndex = permission.caveats.findIndex(\n (existingCaveat) => existingCaveat.type === caveatType,\n );\n\n if (caveatIndex === -1) {\n throw new CaveatDoesNotExistError(\n origin,\n permission.parentCapability,\n caveatType,\n );\n }\n\n if (permission.caveats.length === 1) {\n permission.caveats = null;\n } else {\n permission.caveats.splice(caveatIndex, 1);\n }\n\n this.validateModifiedPermission(permission, origin);\n }\n\n /**\n * Validates the specified modified permission. Should **always** be invoked\n * on a permission after its caveats have been modified.\n *\n * Just like {@link PermissionController.validatePermission}, except that the\n * corresponding target name and specification are retrieved first, and an\n * error is thrown if the target name does not exist.\n *\n * @param permission - The modified permission to validate.\n * @param origin - The origin associated with the permission.\n */\n private validateModifiedPermission(\n permission: Draft<PermissionConstraint>,\n origin: OriginString,\n ): void {\n /* istanbul ignore if: this should be impossible */\n if (!this.targetExists(permission.parentCapability)) {\n throw new Error(\n `Fatal: Existing permission target \"${permission.parentCapability}\" has no specification.`,\n );\n }\n\n this.validatePermission(\n this.getPermissionSpecification(permission.parentCapability),\n permission as PermissionConstraint,\n origin,\n );\n }\n\n /**\n * Verifies the existence the specified permission target, i.e. whether it has\n * a specification.\n *\n * @param target - The requested permission target.\n * @returns Whether the permission target exists.\n */\n private targetExists(\n target: string,\n ): target is ControllerPermissionSpecification['targetName'] {\n return hasProperty(this._permissionSpecifications, target);\n }\n\n /**\n * Grants _approved_ permissions to the specified subject. Every permission and\n * caveat is stringently validated – including by calling every specification\n * validator – and an error is thrown if any validation fails.\n *\n * ATTN: This method does **not** prompt the user for approval.\n *\n * @see {@link PermissionController.requestPermissions} For initiating a\n * permissions request requiring user approval.\n * @param options - Options bag.\n * @param options.approvedPermissions - The requested permissions approved by\n * the user.\n * @param options.requestData - Permission request data. Passed to permission\n * factory functions.\n * @param options.preserveExistingPermissions - Whether to preserve the\n * subject's existing permissions.\n * @param options.subject - The subject to grant permissions to.\n * @returns The granted permissions.\n */\n grantPermissions({\n approvedPermissions,\n requestData,\n preserveExistingPermissions = true,\n subject,\n }: {\n approvedPermissions: RequestedPermissions;\n subject: PermissionSubjectMetadata;\n preserveExistingPermissions?: boolean;\n requestData?: Record<string, unknown>;\n }): SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n > {\n const { origin } = subject;\n\n if (!origin || typeof origin !== 'string') {\n throw new InvalidSubjectIdentifierError(origin);\n }\n\n const permissions = (\n preserveExistingPermissions\n ? {\n ...this.getPermissions(origin),\n }\n : {}\n ) as SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >;\n\n for (const [requestedTarget, approvedPermission] of Object.entries(\n approvedPermissions,\n )) {\n if (!this.targetExists(requestedTarget)) {\n throw methodNotFound(requestedTarget);\n }\n\n if (\n approvedPermission.parentCapability !== undefined &&\n requestedTarget !== approvedPermission.parentCapability\n ) {\n throw new InvalidApprovedPermissionError(\n origin,\n requestedTarget,\n approvedPermission,\n );\n }\n\n // We have verified that the target exists, and reassign it to change its\n // type.\n const targetName = requestedTarget as ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'];\n const specification = this.getPermissionSpecification(targetName);\n\n // The requested caveats are validated here.\n const caveats = this.constructCaveats(\n origin,\n targetName,\n approvedPermission.caveats,\n );\n\n const permissionOptions = {\n caveats,\n invoker: origin,\n target: targetName,\n };\n\n let permission: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >;\n if (specification.factory) {\n permission = specification.factory(permissionOptions, requestData);\n\n // Full caveat and permission validation is performed here since the\n // factory function can arbitrarily modify the entire permission object,\n // including its caveats.\n this.validatePermission(specification, permission, origin);\n } else {\n permission = constructPermission(permissionOptions);\n\n // We do not need to validate caveats in this case, because the plain\n // permission constructor function does not modify the caveats, which\n // were already validated by `constructCaveats` above.\n this.validatePermission(specification, permission, origin, {\n invokePermissionValidator: true,\n performCaveatValidation: false,\n });\n }\n permissions[targetName] = permission;\n }\n\n this.setValidatedPermissions(origin, permissions);\n return permissions;\n }\n\n /**\n * Validates the specified permission by:\n * - Ensuring that if `subjectTypes` is specified, the subject requesting the permission is of a type in the list.\n * - Ensuring that its `caveats` property is either `null` or a non-empty array.\n * - Ensuring that it only includes caveats allowed by its specification.\n * - Ensuring that it includes no duplicate caveats (by caveat type).\n * - Validating each caveat object, if `performCaveatValidation` is `true`.\n * - Calling the validator of its specification, if one exists and `invokePermissionValidator` is `true`.\n *\n * An error is thrown if validation fails.\n *\n * @param specification - The specification of the permission.\n * @param permission - The permission to validate.\n * @param origin - The origin associated with the permission.\n * @param validationOptions - Validation options.\n * @param validationOptions.invokePermissionValidator - Whether to invoke the\n * permission's consumer-specified validator function, if any.\n * @param validationOptions.performCaveatValidation - Whether to invoke\n * {@link PermissionController.validateCaveat} on each of the permission's\n * caveats.\n */\n private validatePermission(\n specification: PermissionSpecificationConstraint,\n permission: PermissionConstraint,\n origin: OriginString,\n { invokePermissionValidator, performCaveatValidation } = {\n invokePermissionValidator: true,\n performCaveatValidation: true,\n },\n ): void {\n const { allowedCaveats, validator, targetName } = specification;\n\n if (\n specification.subjectTypes?.length &&\n specification.subjectTypes.length > 0\n ) {\n const metadata = this.messagingSystem.call(\n 'SubjectMetadataController:getSubjectMetadata',\n origin,\n );\n\n if (\n !metadata ||\n metadata.subjectType === null ||\n !specification.subjectTypes.includes(metadata.subjectType)\n ) {\n throw specification.permissionType === PermissionType.RestrictedMethod\n ? methodNotFound(targetName, { origin })\n : new EndowmentPermissionDoesNotExistError(targetName, origin);\n }\n }\n\n if (hasProperty(permission, 'caveats')) {\n const { caveats } = permission;\n\n if (caveats !== null && !(Array.isArray(caveats) && caveats.length > 0)) {\n throw new InvalidCaveatsPropertyError(origin, targetName, caveats);\n }\n\n const seenCaveatTypes = new Set<string>();\n caveats?.forEach((caveat) => {\n if (performCaveatValidation) {\n this.validateCaveat(caveat, origin, targetName);\n }\n\n if (!allowedCaveats?.includes(caveat.type)) {\n throw new ForbiddenCaveatError(caveat.type, origin, targetName);\n }\n\n if (seenCaveatTypes.has(caveat.type)) {\n throw new DuplicateCaveatError(caveat.type, origin, targetName);\n }\n seenCaveatTypes.add(caveat.type);\n });\n }\n\n if (invokePermissionValidator && validator) {\n validator(permission, origin, targetName);\n }\n }\n\n /**\n * Assigns the specified permissions to the subject with the given origin.\n * Overwrites all existing permissions, and creates a subject entry if it\n * doesn't already exist.\n *\n * ATTN: Assumes that the new permissions have been validated.\n *\n * @param origin - The origin of the grantee subject.\n * @param permissions - The new permissions for the grantee subject.\n */\n private setValidatedPermissions(\n origin: OriginString,\n permissions: Record<\n string,\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n ): void {\n this.update((draftState) => {\n if (!draftState.subjects[origin]) {\n draftState.subjects[origin] = { origin, permissions: {} };\n }\n\n draftState.subjects[origin].permissions = castDraft(permissions);\n });\n }\n\n /**\n * Validates the requested caveats for the permission of the specified\n * subject origin and target name and returns the validated caveat array.\n *\n * Throws an error if validation fails.\n *\n * @param origin - The origin of the permission subject.\n * @param target - The permission target name.\n * @param requestedCaveats - The requested caveats to construct.\n * @returns The constructed caveats.\n */\n private constructCaveats(\n origin: OriginString,\n target: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n requestedCaveats?: unknown[] | null,\n ): NonEmptyArray<ExtractCaveats<ControllerCaveatSpecification>> | undefined {\n const caveatArray = requestedCaveats?.map((requestedCaveat) => {\n this.validateCaveat(requestedCaveat, origin, target);\n\n // Reassign so that we have a fresh object.\n const { type, value } = requestedCaveat as CaveatConstraint;\n return { type, value } as ExtractCaveats<ControllerCaveatSpecification>;\n });\n\n return caveatArray && isNonEmptyArray(caveatArray)\n ? caveatArray\n : undefined;\n }\n\n /**\n * This methods validates that the specified caveat is an object with the\n * expected properties and types. It also ensures that a caveat specification\n * exists for the requested caveat type, and calls the specification\n * validator, if it exists, on the caveat object.\n *\n * Throws an error if validation fails.\n *\n * @param caveat - The caveat object to validate.\n * @param origin - The origin associated with the subject of the parent\n * permission.\n * @param target - The target name associated with the parent permission.\n */\n private validateCaveat(\n caveat: unknown,\n origin: OriginString,\n target: string,\n ): void {\n if (!isPlainObject(caveat)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new InvalidCaveatError(caveat, origin, target);\n }\n\n if (Object.keys(caveat).length !== 2) {\n throw new InvalidCaveatFieldsError(caveat, origin, target);\n }\n\n if (typeof caveat.type !== 'string') {\n throw new InvalidCaveatTypeError(caveat, origin, target);\n }\n\n const specification = this.getCaveatSpecification(caveat.type);\n if (!specification) {\n throw new UnrecognizedCaveatTypeError(caveat.type, origin, target);\n }\n\n if (!hasProperty(caveat, 'value') || caveat.value === undefined) {\n throw new CaveatMissingValueError(caveat, origin, target);\n }\n\n if (!isValidJson(caveat.value)) {\n throw new CaveatInvalidJsonError(caveat, origin, target);\n }\n\n // Typecast: TypeScript still believes that the caveat is a PlainObject.\n specification.validator?.(caveat as CaveatConstraint, origin, target);\n }\n\n /**\n * Initiates a permission request that requires user approval. This should\n * always be used to grant additional permissions to a subject, unless user\n * approval has been obtained through some other means.\n *\n * Permissions are validated at every step of the approval process, and this\n * method will reject if validation fails.\n *\n * @see {@link ApprovalController} For the user approval logic.\n * @see {@link PermissionController.acceptPermissionsRequest} For the method\n * that _accepts_ the request and resolves the user approval promise.\n * @see {@link PermissionController.rejectPermissionsRequest} For the method\n * that _rejects_ the request and the user approval promise.\n * @param subject - The grantee subject.\n * @param requestedPermissions - The requested permissions.\n * @param options - Additional options.\n * @param options.id - The id of the permissions request. Defaults to a unique\n * id.\n * @param options.preserveExistingPermissions - Whether to preserve the\n * subject's existing permissions. Defaults to `true`.\n * @returns The granted permissions and request metadata.\n */\n async requestPermissions(\n subject: PermissionSubjectMetadata,\n requestedPermissions: RequestedPermissions,\n options: {\n id?: string;\n preserveExistingPermissions?: boolean;\n } = {},\n ): Promise<\n [\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >,\n { data?: Record<string, unknown>; id: string; origin: OriginString },\n ]\n > {\n const { origin } = subject;\n const { id = nanoid(), preserveExistingPermissions = true } = options;\n this.validateRequestedPermissions(origin, requestedPermissions);\n\n const metadata = {\n id,\n origin,\n };\n\n const permissionsRequest = {\n metadata,\n permissions: requestedPermissions,\n };\n\n const approvedRequest = await this.requestUserApproval(permissionsRequest);\n const { permissions: approvedPermissions, ...requestData } =\n approvedRequest;\n\n const sideEffects = this.getSideEffects(approvedPermissions);\n\n if (Object.values(sideEffects.permittedHandlers).length > 0) {\n const sideEffectsData = await this.executeSideEffects(\n sideEffects,\n approvedRequest,\n );\n const mappedData = Object.keys(sideEffects.permittedHandlers).reduce(\n (acc, permission, i) => ({ [permission]: sideEffectsData[i], ...acc }),\n {},\n );\n\n return [\n this.grantPermissions({\n subject,\n approvedPermissions,\n preserveExistingPermissions,\n requestData,\n }),\n { data: mappedData, ...metadata },\n ];\n }\n\n return [\n this.grantPermissions({\n subject,\n approvedPermissions,\n preserveExistingPermissions,\n requestData,\n }),\n metadata,\n ];\n }\n\n /**\n * Validates requested permissions. Throws if validation fails.\n *\n * This method ensures that the requested permissions are a properly\n * formatted {@link RequestedPermissions} object, and performs the same\n * validation as {@link PermissionController.grantPermissions}, except that\n * consumer-specified permission validator functions are not called, since\n * they are only called on fully constructed, approved permissions that are\n * otherwise completely valid.\n *\n * Unrecognzied properties on requested permissions are ignored.\n *\n * @param origin - The origin of the grantee subject.\n * @param requestedPermissions - The requested permissions.\n */\n private validateRequestedPermissions(\n origin: OriginString,\n requestedPermissions: unknown,\n ): void {\n if (!isPlainObject(requestedPermissions)) {\n throw invalidParams({\n message: `Requested permissions for origin \"${origin}\" is not a plain object.`,\n data: { origin, requestedPermissions },\n });\n }\n\n if (Object.keys(requestedPermissions).length === 0) {\n throw invalidParams({\n message: `Permissions request for origin \"${origin}\" contains no permissions.`,\n data: { requestedPermissions },\n });\n }\n\n for (const targetName of Object.keys(requestedPermissions)) {\n const permission = requestedPermissions[targetName];\n\n if (!this.targetExists(targetName)) {\n throw methodNotFound(targetName, { origin, requestedPermissions });\n }\n\n if (\n !isPlainObject(permission) ||\n (permission.parentCapability !== undefined &&\n targetName !== permission.parentCapability)\n ) {\n throw invalidParams({\n message: `Permissions request for origin \"${origin}\" contains invalid requested permission(s).`,\n data: { origin, requestedPermissions },\n });\n }\n\n // Here we validate the permission without invoking its validator, if any.\n // The validator will be invoked after the permission has been approved.\n this.validatePermission(\n this.getPermissionSpecification(targetName),\n // Typecast: The permission is still a \"PlainObject\" here.\n permission as PermissionConstraint,\n origin,\n { invokePermissionValidator: false, performCaveatValidation: true },\n );\n }\n }\n\n /**\n * Adds a request to the {@link ApprovalController} using the\n * {@link AddApprovalRequest} action. Also validates the resulting approved\n * permissions request, and throws an error if validation fails.\n *\n * @param permissionsRequest - The permissions request object.\n * @returns The approved permissions request object.\n */\n private async requestUserApproval(permissionsRequest: PermissionsRequest) {\n const { origin, id } = permissionsRequest.metadata;\n const approvedRequest = await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin,\n requestData: permissionsRequest,\n type: MethodNames.requestPermissions,\n },\n true,\n );\n\n this.validateApprovedPermissions(approvedRequest, { id, origin });\n return approvedRequest as PermissionsRequest;\n }\n\n /**\n * Reunites all the side-effects (onPermitted and onFailure) of the requested permissions inside a record of arrays.\n *\n * @param permissions - The approved permissions.\n * @returns The {@link SideEffects} object containing the handlers arrays.\n */\n private getSideEffects(permissions: RequestedPermissions) {\n return Object.keys(permissions).reduce<SideEffects>(\n (sideEffectList, targetName) => {\n if (this.targetExists(targetName)) {\n const specification = this.getPermissionSpecification(targetName);\n\n if (specification.sideEffect) {\n sideEffectList.permittedHandlers[targetName] =\n specification.sideEffect.onPermitted;\n\n if (specification.sideEffect.onFailure) {\n sideEffectList.failureHandlers[targetName] =\n specification.sideEffect.onFailure;\n }\n }\n }\n return sideEffectList;\n },\n { permittedHandlers: {}, failureHandlers: {} },\n );\n }\n\n /**\n * Executes the side-effects of the approved permissions while handling the errors if any.\n * It will pass an instance of the {@link messagingSystem} and the request data associated with the permission request to the handlers through its params.\n *\n * @param sideEffects - the side-effect record created by {@link getSideEffects}\n * @param requestData - the permissions requestData.\n * @returns the value returned by all the `onPermitted` handlers in an array.\n */\n private async executeSideEffects(\n sideEffects: SideEffects,\n requestData: PermissionsRequest,\n ) {\n const { permittedHandlers, failureHandlers } = sideEffects;\n const params = {\n requestData,\n messagingSystem: this.messagingSystem,\n };\n\n const promiseResults = await Promise.allSettled(\n Object.values(permittedHandlers).map((permittedHandler) =>\n permittedHandler(params),\n ),\n );\n\n // lib.es2020.promise.d.ts does not export its types so we're using a simple type.\n const rejectedHandlers = promiseResults.filter(\n (promise) => promise.status === 'rejected',\n ) as { status: 'rejected'; reason: Error }[];\n\n if (rejectedHandlers.length > 0) {\n const failureHandlersList = Object.values(failureHandlers);\n if (failureHandlersList.length > 0) {\n try {\n await Promise.all(\n failureHandlersList.map((failureHandler) => failureHandler(params)),\n );\n } catch (error) {\n throw internalError('Unexpected error in side-effects', { error });\n }\n }\n const reasons = rejectedHandlers.map((handler) => handler.reason);\n\n reasons.forEach((reason) => {\n console.error(reason);\n });\n\n throw reasons.length > 1\n ? internalError(\n 'Multiple errors occurred during side-effects execution',\n { errors: reasons },\n )\n : reasons[0];\n }\n\n // lib.es2020.promise.d.ts does not export its types so we're using a simple type.\n return (promiseResults as { status: 'fulfilled'; value: unknown }[]).map(\n ({ value }) => value,\n );\n }\n\n /**\n * Validates an approved {@link PermissionsRequest} object. The approved\n * request must have the required `metadata` and `permissions` properties,\n * the `id` and `origin` of the `metadata` must match the original request\n * metadata, and the requested permissions must be valid per\n * {@link PermissionController.validateRequestedPermissions}. Any extra\n * metadata properties are ignored.\n *\n * An error is thrown if validation fails.\n *\n * @param approvedRequest - The approved permissions request object.\n * @param originalMetadata - The original request metadata.\n */\n private validateApprovedPermissions(\n approvedRequest: unknown,\n originalMetadata: PermissionsRequestMetadata,\n ) {\n const { id, origin } = originalMetadata;\n\n if (\n !isPlainObject(approvedRequest) ||\n !isPlainObject(approvedRequest.metadata)\n ) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" is invalid.`,\n { data: { approvedRequest } },\n );\n }\n\n const {\n metadata: { id: newId, origin: newOrigin },\n permissions,\n } = approvedRequest;\n\n if (newId !== id) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" mutated its id.`,\n { originalId: id, mutatedId: newId },\n );\n }\n\n if (newOrigin !== origin) {\n throw internalError(\n `Approved permissions request for subject \"${origin}\" mutated its origin.`,\n { originalOrigin: origin, mutatedOrigin: newOrigin },\n );\n }\n\n try {\n this.validateRequestedPermissions(origin, permissions);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n // Re-throw as an internal error; we should never receive invalid approved\n // permissions.\n throw internalError(\n `Invalid approved permissions request: ${error.message}`,\n error.data,\n );\n }\n throw internalError('Unrecognized error type', { error });\n }\n }\n\n /**\n * Accepts a permissions request created by\n * {@link PermissionController.requestPermissions}.\n *\n * @param request - The permissions request.\n */\n async acceptPermissionsRequest(request: PermissionsRequest): Promise<void> {\n const { id } = request.metadata;\n\n if (!this.hasApprovalRequest({ id })) {\n throw new PermissionsRequestNotFoundError(id);\n }\n\n if (Object.keys(request.permissions).length === 0) {\n this._rejectPermissionsRequest(\n id,\n invalidParams({\n message: 'Must request at least one permission.',\n }),\n );\n return;\n }\n\n try {\n this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n request,\n );\n } catch (error) {\n // If accepting unexpectedly fails, reject the request and re-throw the\n // error\n this._rejectPermissionsRequest(id, error);\n throw error;\n }\n }\n\n /**\n * Rejects a permissions request created by\n * {@link PermissionController.requestPermissions}.\n *\n * @param id - The id of the request to be rejected.\n */\n async rejectPermissionsRequest(id: string): Promise<void> {\n if (!this.hasApprovalRequest({ id })) {\n throw new PermissionsRequestNotFoundError(id);\n }\n\n this._rejectPermissionsRequest(id, userRejectedRequest());\n }\n\n /**\n * Checks whether the {@link ApprovalController} has a particular permissions\n * request.\n *\n * @see {@link PermissionController.acceptPermissionsRequest} and\n * {@link PermissionController.rejectPermissionsRequest} for usage.\n * @param options - The {@link HasApprovalRequest} options.\n * @param options.id - The id of the approval request to check for.\n * @returns Whether the specified request exists.\n */\n private hasApprovalRequest(options: { id: string }): boolean {\n return this.messagingSystem.call(\n 'ApprovalController:hasRequest',\n // Typecast: For some reason, the type here expects all of the possible\n // HasApprovalRequest options to be specified, when they're actually all\n // optional. Passing just the id is definitely valid, so we just cast it.\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options as any,\n );\n }\n\n /**\n * Rejects the permissions request with the specified id, with the specified\n * error as the reason. This method is effectively a wrapper around a\n * messenger call for the `ApprovalController:rejectRequest` action.\n *\n * @see {@link PermissionController.acceptPermissionsRequest} and\n * {@link PermissionController.rejectPermissionsRequest} for usage.\n * @param id - The id of the request to reject.\n * @param error - The error associated with the rejection.\n * @returns Nothing\n */\n private _rejectPermissionsRequest(id: string, error: unknown): void {\n return this.messagingSystem.call(\n 'ApprovalController:rejectRequest',\n id,\n error,\n );\n }\n\n /**\n * Gets the subject's endowments per the specified endowment permission.\n * Throws if the subject does not have the required permission or if the\n * permission is not an endowment permission.\n *\n * @param origin - The origin of the subject whose endowments to retrieve.\n * @param targetName - The name of the endowment permission. This must be a\n * valid permission target name.\n * @param requestData - Additional data associated with the request, if any.\n * Forwarded to the endowment getter function for the permission.\n * @returns The endowments, if any.\n */\n async getEndowments(\n origin: string,\n targetName: ExtractEndowmentPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n requestData?: unknown,\n ): Promise<Json> {\n if (!this.hasPermission(origin, targetName)) {\n throw unauthorized({ data: { origin, targetName } });\n }\n\n return this.getTypedPermissionSpecification(\n PermissionType.Endowment,\n targetName,\n origin,\n ).endowmentGetter({ origin, requestData });\n }\n\n /**\n * Executes a restricted method as the subject with the given origin.\n * The specified params, if any, will be passed to the method implementation.\n *\n * ATTN: Great caution should be exercised in the use of this method.\n * Methods that cause side effects or affect application state should\n * be avoided.\n *\n * This method will first attempt to retrieve the requested restricted method\n * implementation, throwing if it does not exist. The method will then be\n * invoked as though the subject with the specified origin had invoked it with\n * the specified parameters. This means that any existing caveats will be\n * applied to the restricted method, and this method will throw if the\n * restricted method or its caveat decorators throw.\n *\n * In addition, this method will throw if the subject does not have a\n * permission for the specified restricted method.\n *\n * @param origin - The origin of the subject to execute the method on behalf\n * of.\n * @param targetName - The name of the method to execute. This must be a valid\n * permission target name.\n * @param params - The parameters to pass to the method implementation.\n * @returns The result of the executed method.\n */\n async executeRestrictedMethod(\n origin: OriginString,\n targetName: ExtractRestrictedMethodPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n params?: RestrictedMethodParameters,\n ): Promise<Json> {\n // Throws if the method does not exist\n const methodImplementation = this.getRestrictedMethod(targetName, origin);\n\n const result = await this._executeRestrictedMethod(\n methodImplementation,\n { origin },\n targetName,\n params,\n );\n\n if (result === undefined) {\n throw new Error(\n `Internal request for method \"${targetName}\" as origin \"${origin}\" returned no result.`,\n );\n }\n\n return result;\n }\n\n /**\n * An internal method used in the controller's `json-rpc-engine` middleware\n * and {@link PermissionController.executeRestrictedMethod}. Calls the\n * specified restricted method implementation after decorating it with the\n * caveats of its permission. Throws if the subject does not have the\n * requisite permission.\n *\n * ATTN: Parameter validation is the responsibility of the caller, or\n * the restricted method implementation in the case of `params`.\n *\n * @see {@link PermissionController.executeRestrictedMethod} and\n * {@link PermissionController.createPermissionMiddleware} for usage.\n * @param methodImplementation - The implementation of the method to call.\n * @param subject - Metadata about the subject that made the request.\n * @param method - The method name\n * @param params - Params needed for executing the restricted method\n * @returns The result of the restricted method implementation\n */\n private _executeRestrictedMethod(\n methodImplementation: RestrictedMethod<RestrictedMethodParameters, Json>,\n subject: PermissionSubjectMetadata,\n method: ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >['parentCapability'],\n params: RestrictedMethodParameters = [],\n ): ReturnType<RestrictedMethod<RestrictedMethodParameters, Json>> {\n const { origin } = subject;\n\n const permission = this.getPermission(origin, method);\n if (!permission) {\n throw unauthorized({ data: { origin, method } });\n }\n\n return decorateWithCaveats(\n methodImplementation,\n permission,\n this._caveatSpecifications,\n )({ method, params, context: { origin } });\n }\n}\n"]}
|
|
@@ -36,7 +36,11 @@ export declare type GetSubjectMetadata = {
|
|
|
36
36
|
type: `${typeof controllerName}:getSubjectMetadata`;
|
|
37
37
|
handler: (origin: SubjectOrigin) => SubjectMetadata | undefined;
|
|
38
38
|
};
|
|
39
|
-
export declare type
|
|
39
|
+
export declare type AddSubjectMetadata = {
|
|
40
|
+
type: `${typeof controllerName}:addSubjectMetadata`;
|
|
41
|
+
handler: (metadata: SubjectMetadataToAdd) => void;
|
|
42
|
+
};
|
|
43
|
+
export declare type SubjectMetadataControllerActions = GetSubjectMetadataState | GetSubjectMetadata | AddSubjectMetadata;
|
|
40
44
|
export declare type SubjectMetadataStateChange = ControllerStateChangeEvent<typeof controllerName, SubjectMetadataControllerState>;
|
|
41
45
|
export declare type SubjectMetadataControllerEvents = SubjectMetadataStateChange;
|
|
42
46
|
declare type AllowedActions = HasPermissions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubjectMetadataController.d.ts","sourceRoot":"","sources":["../src/SubjectMetadataController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,K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B,kBAAkB,CAAC;AAEvB,oBAAY,0BAA0B,GAAG,0BAA0B,CACjE,OAAO,cAAc,EACrB,8BAA8B,CAC/B,CAAC;AAEF,oBAAY,+BAA+B,GAAG,0BAA0B,CAAC;AAEzE,aAAK,cAAc,GAAG,cAAc,CAAC;AAErC,oBAAY,kCAAkC,GAAG,6BAA6B,CAC5E,OAAO,cAAc,EACrB,gCAAgC,GAAG,cAAc,EACjD,+BAA+B,EAC/B,cAAc,CAAC,MAAM,CAAC,EACtB,KAAK,CACN,CAAC;AAEF,aAAK,gCAAgC,GAAG;IACtC,SAAS,EAAE,kCAAkC,CAAC;IAC9C,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;CACjD,CAAC;AAEF;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,cAAc,CAC3D,OAAO,cAAc,EACrB,8BAA8B,EAC9B,kCAAkC,CACnC;IACC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAE3C,OAAO,CAAC,QAAQ,CAAC,iDAAiD,CAAc;IAEhF,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAgD;gBAE1E,EACV,SAAS,EACT,iBAAiB,EACjB,KAAU,GACX,EAAE,gCAAgC;IAmCnC;;;OAGG;IACH,UAAU,IAAI,IAAI;IAOlB;;;;;;;;;;;OAWG;IACH,kBAAkB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,IAAI;IA4CxD;;;;;OAKG;IACH,kBAAkB,CAAC,MAAM,EAAE,aAAa,GAAG,eAAe,GAAG,SAAS;IAItE;;OAEG;IACH,iBAAiB,IAAI,IAAI;IAYzB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,MAAM,CAAC,eAAe;CAiB/B"}
|
|
@@ -43,6 +43,7 @@ class SubjectMetadataController extends base_controller_1.BaseController {
|
|
|
43
43
|
this.subjectCacheLimit = subjectCacheLimit;
|
|
44
44
|
this.subjectsWithoutPermissionsEncounteredSinceStartup = new Set();
|
|
45
45
|
this.messagingSystem.registerActionHandler(`${this.name}:getSubjectMetadata`, this.getSubjectMetadata.bind(this));
|
|
46
|
+
this.messagingSystem.registerActionHandler(`${this.name}:addSubjectMetadata`, this.addSubjectMetadata.bind(this));
|
|
46
47
|
}
|
|
47
48
|
/**
|
|
48
49
|
* Clears the state of this controller. Also resets the cache of subjects
|
|
@@ -85,6 +86,8 @@ class SubjectMetadataController extends base_controller_1.BaseController {
|
|
|
85
86
|
this.subjectsWithoutPermissionsEncounteredSinceStartup.add(origin);
|
|
86
87
|
this.update((draftState) => {
|
|
87
88
|
// Typecast: ts(2589)
|
|
89
|
+
// TODO: Replace `any` with type
|
|
90
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
88
91
|
draftState.subjectMetadata[origin] = newMetadata;
|
|
89
92
|
if (typeof originToForget === 'string') {
|
|
90
93
|
delete draftState.subjectMetadata[originToForget];
|
|
@@ -107,6 +110,8 @@ class SubjectMetadataController extends base_controller_1.BaseController {
|
|
|
107
110
|
this.update((draftState) => {
|
|
108
111
|
return SubjectMetadataController.getTrimmedState(
|
|
109
112
|
// Typecast: ts(2589)
|
|
113
|
+
// TODO: Replace `any` with type
|
|
114
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
110
115
|
draftState, this.subjectHasPermissions);
|
|
111
116
|
});
|
|
112
117
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubjectMetadataController.js","sourceRoot":"","sources":["../src/SubjectMetadataController.ts"],"names":[],"mappings":";;;AAKA,+DAA2D;AAS3D,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAInD;;;GAGG;AACH,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,sCAAuB,CAAA;IACvB,oCAAqB,CAAA;IACrB,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;IACnB,4BAAa,CAAA;AACf,CAAC,EANW,WAAW,GAAX,mBAAW,KAAX,mBAAW,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IAED;;OAEG;IACH,iBAAiB;QACf,IAAI,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE;YACzB,OAAO,yBAAyB,CAAC,eAAe;YAC9C,qBAAqB;YACrB,UAAiB,EACjB,IAAI,CAAC,qBAAqB,CAC3B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;OAYG;IACK,MAAM,CAAC,eAAe,CAC5B,KAA8C,EAC9C,cAAkE;QAElE,MAAM,EAAE,eAAe,GAAG,EAAE,EAAE,GAAG,KAAK,CAAC;QAEvC,OAAO;YACL,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,CAElD,CAAC,kBAAkB,EAAE,MAAM,EAAE,EAAE;gBAC/B,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE;oBAC1B,kBAAkB,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;iBACtD;gBACD,OAAO,kBAAkB,CAAC;YAC5B,CAAC,EAAE,EAAE,CAAC;SACP,CAAC;IACJ,CAAC;CACF;AAnKD,8DAmKC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GenericPermissionController,\n HasPermissions,\n PermissionSubjectMetadata,\n} from './PermissionController';\n\nconst controllerName = 'SubjectMetadataController';\n\ntype SubjectOrigin = string;\n\n/**\n * The different kinds of subjects that MetaMask may interact with, including\n * third parties and itself (e.g., when the background communicated with the UI).\n */\nexport enum SubjectType {\n Extension = 'extension',\n Internal = 'internal',\n Unknown = 'unknown',\n Website = 'website',\n Snap = 'snap',\n}\n\nexport type SubjectMetadata = PermissionSubjectMetadata & {\n [key: string]: Json;\n // TODO:TS4.4 make optional\n name: string | null;\n subjectType: SubjectType | null;\n extensionId: string | null;\n iconUrl: string | null;\n};\n\ntype SubjectMetadataToAdd = PermissionSubjectMetadata & {\n name?: string | null;\n subjectType?: SubjectType | null;\n extensionId?: string | null;\n iconUrl?: string | null;\n} & Record<string, Json>;\n\nexport type SubjectMetadataControllerState = {\n subjectMetadata: Record<SubjectOrigin, SubjectMetadata>;\n};\n\nconst stateMetadata = {\n subjectMetadata: { persist: true, anonymous: false },\n};\n\nconst defaultState: SubjectMetadataControllerState = {\n subjectMetadata: {},\n};\n\nexport type GetSubjectMetadataState = ControllerGetStateAction<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type GetSubjectMetadata = {\n type: `${typeof controllerName}:getSubjectMetadata`;\n handler: (origin: SubjectOrigin) => SubjectMetadata | undefined;\n};\n\nexport type SubjectMetadataControllerActions =\n | GetSubjectMetadataState\n | GetSubjectMetadata;\n\nexport type SubjectMetadataStateChange = ControllerStateChangeEvent<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type SubjectMetadataControllerEvents = SubjectMetadataStateChange;\n\ntype AllowedActions = HasPermissions;\n\nexport type SubjectMetadataControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SubjectMetadataControllerActions | AllowedActions,\n SubjectMetadataControllerEvents,\n AllowedActions['type'],\n never\n>;\n\ntype SubjectMetadataControllerOptions = {\n messenger: SubjectMetadataControllerMessenger;\n subjectCacheLimit: number;\n state?: Partial<SubjectMetadataControllerState>;\n};\n\n/**\n * A controller for storing metadata associated with permission subjects. More\n * or less, a cache.\n */\nexport class SubjectMetadataController extends BaseController<\n typeof controllerName,\n SubjectMetadataControllerState,\n SubjectMetadataControllerMessenger\n> {\n private readonly subjectCacheLimit: number;\n\n private readonly subjectsWithoutPermissionsEncounteredSinceStartup: Set<string>;\n\n private readonly subjectHasPermissions: GenericPermissionController['hasPermissions'];\n\n constructor({\n messenger,\n subjectCacheLimit,\n state = {},\n }: SubjectMetadataControllerOptions) {\n if (!Number.isInteger(subjectCacheLimit) || subjectCacheLimit < 1) {\n throw new Error(\n `subjectCacheLimit must be a positive integer. Received: \"${subjectCacheLimit}\"`,\n );\n }\n\n const hasPermissions = (origin: string) => {\n return messenger.call('PermissionController:hasPermissions', origin);\n };\n\n super({\n name: controllerName,\n metadata: stateMetadata,\n messenger,\n state: {\n ...SubjectMetadataController.getTrimmedState(state, hasPermissions),\n },\n });\n\n this.subjectHasPermissions = hasPermissions;\n this.subjectCacheLimit = subjectCacheLimit;\n this.subjectsWithoutPermissionsEncounteredSinceStartup = new Set();\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getSubjectMetadata`,\n this.getSubjectMetadata.bind(this),\n );\n }\n\n /**\n * Clears the state of this controller. Also resets the cache of subjects\n * encountered since startup, so as to not prematurely reach the cache limit.\n */\n clearState(): void {\n this.subjectsWithoutPermissionsEncounteredSinceStartup.clear();\n this.update((_draftState) => {\n return { ...defaultState };\n });\n }\n\n /**\n * Stores domain metadata for the given origin (subject). Deletes metadata for\n * subjects without permissions in a FIFO manner once more than\n * {@link SubjectMetadataController.subjectCacheLimit} distinct origins have\n * been added since boot.\n *\n * In order to prevent a degraded user experience,\n * metadata is never deleted for subjects with permissions, since metadata\n * cannot yet be requested on demand.\n *\n * @param metadata - The subject metadata to store.\n */\n addSubjectMetadata(metadata: SubjectMetadataToAdd): void {\n const { origin } = metadata;\n const newMetadata: SubjectMetadata = {\n ...metadata,\n extensionId: metadata.extensionId || null,\n iconUrl: metadata.iconUrl || null,\n name: metadata.name || null,\n subjectType: metadata.subjectType || null,\n };\n\n let originToForget: string | null = null;\n // We only delete the oldest encountered subject from the cache, again to\n // ensure that the user's experience isn't degraded by missing icons etc.\n if (\n this.subjectsWithoutPermissionsEncounteredSinceStartup.size >=\n this.subjectCacheLimit\n ) {\n const cachedOrigin =\n this.subjectsWithoutPermissionsEncounteredSinceStartup\n .values()\n .next().value;\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.delete(\n cachedOrigin,\n );\n\n if (!this.subjectHasPermissions(cachedOrigin)) {\n originToForget = cachedOrigin;\n }\n }\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.add(origin);\n\n this.update((draftState) => {\n // Typecast: ts(2589)\n draftState.subjectMetadata[origin] = newMetadata as any;\n if (typeof originToForget === 'string') {\n delete draftState.subjectMetadata[originToForget];\n }\n });\n }\n\n /**\n * Gets the subject metadata for the given origin, if any.\n *\n * @param origin - The origin for which to get the subject metadata.\n * @returns The subject metadata, if any, or `undefined` otherwise.\n */\n getSubjectMetadata(origin: SubjectOrigin): SubjectMetadata | undefined {\n return this.state.subjectMetadata[origin];\n }\n\n /**\n * Deletes all subjects without permissions from the controller's state.\n */\n trimMetadataState(): void {\n this.update((draftState) => {\n return SubjectMetadataController.getTrimmedState(\n // Typecast: ts(2589)\n draftState as any,\n this.subjectHasPermissions,\n );\n });\n }\n\n /**\n * Returns a new state object that only includes subjects with permissions.\n * This method is static because we want to call it in the constructor, before\n * the controller's state is initialized.\n *\n * @param state - The state object to trim.\n * @param hasPermissions - A function that returns a boolean indicating\n * whether a particular subject (identified by its origin) has any\n * permissions.\n * @returns The new state object. If the specified `state` object has no\n * subject metadata, the returned object will be equivalent to the default\n * state of this controller.\n */\n private static getTrimmedState(\n state: Partial<SubjectMetadataControllerState>,\n hasPermissions: SubjectMetadataController['subjectHasPermissions'],\n ): SubjectMetadataControllerState {\n const { subjectMetadata = {} } = state;\n\n return {\n subjectMetadata: Object.keys(subjectMetadata).reduce<\n Record<SubjectOrigin, SubjectMetadata>\n >((newSubjectMetadata, origin) => {\n if (hasPermissions(origin)) {\n newSubjectMetadata[origin] = subjectMetadata[origin];\n }\n return newSubjectMetadata;\n }, {}),\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubjectMetadataController.js","sourceRoot":"","sources":["../src/SubjectMetadataController.ts"],"names":[],"mappings":";;;AAKA,+DAA2D;AAS3D,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAInD;;;GAGG;AACH,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,sCAAuB,CAAA;IACvB,oCA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AC,MAAM,CAAC,GAAG,WAAkB,CAAC;YACxD,IAAI,OAAO,cAAc,KAAK,QAAQ,EAAE;gBACtC,OAAO,UAAU,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC;aACnD;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,kBAAkB,CAAC,MAAqB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IAED;;OAEG;IACH,iBAAiB;QACf,IAAI,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE;YACzB,OAAO,yBAAyB,CAAC,eAAe;YAC9C,qBAAqB;YACrB,gCAAgC;YAChC,8DAA8D;YAC9D,UAAiB,EACjB,IAAI,CAAC,qBAAqB,CAC3B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;OAYG;IACK,MAAM,CAAC,eAAe,CAC5B,KAA8C,EAC9C,cAAkE;QAElE,MAAM,EAAE,eAAe,GAAG,EAAE,EAAE,GAAG,KAAK,CAAC;QAEvC,OAAO;YACL,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,CAElD,CAAC,kBAAkB,EAAE,MAAM,EAAE,EAAE;gBAC/B,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE;oBAC1B,kBAAkB,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;iBACtD;gBACD,OAAO,kBAAkB,CAAC;YAC5B,CAAC,EAAE,EAAE,CAAC;SACP,CAAC;IACJ,CAAC;CACF;AA5KD,8DA4KC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GenericPermissionController,\n HasPermissions,\n PermissionSubjectMetadata,\n} from './PermissionController';\n\nconst controllerName = 'SubjectMetadataController';\n\ntype SubjectOrigin = string;\n\n/**\n * The different kinds of subjects that MetaMask may interact with, including\n * third parties and itself (e.g., when the background communicated with the UI).\n */\nexport enum SubjectType {\n Extension = 'extension',\n Internal = 'internal',\n Unknown = 'unknown',\n Website = 'website',\n Snap = 'snap',\n}\n\nexport type SubjectMetadata = PermissionSubjectMetadata & {\n [key: string]: Json;\n // TODO:TS4.4 make optional\n name: string | null;\n subjectType: SubjectType | null;\n extensionId: string | null;\n iconUrl: string | null;\n};\n\ntype SubjectMetadataToAdd = PermissionSubjectMetadata & {\n name?: string | null;\n subjectType?: SubjectType | null;\n extensionId?: string | null;\n iconUrl?: string | null;\n} & Record<string, Json>;\n\nexport type SubjectMetadataControllerState = {\n subjectMetadata: Record<SubjectOrigin, SubjectMetadata>;\n};\n\nconst stateMetadata = {\n subjectMetadata: { persist: true, anonymous: false },\n};\n\nconst defaultState: SubjectMetadataControllerState = {\n subjectMetadata: {},\n};\n\nexport type GetSubjectMetadataState = ControllerGetStateAction<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type GetSubjectMetadata = {\n type: `${typeof controllerName}:getSubjectMetadata`;\n handler: (origin: SubjectOrigin) => SubjectMetadata | undefined;\n};\n\nexport type AddSubjectMetadata = {\n type: `${typeof controllerName}:addSubjectMetadata`;\n handler: (metadata: SubjectMetadataToAdd) => void;\n};\n\nexport type SubjectMetadataControllerActions =\n | GetSubjectMetadataState\n | GetSubjectMetadata\n | AddSubjectMetadata;\n\nexport type SubjectMetadataStateChange = ControllerStateChangeEvent<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type SubjectMetadataControllerEvents = SubjectMetadataStateChange;\n\ntype AllowedActions = HasPermissions;\n\nexport type SubjectMetadataControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SubjectMetadataControllerActions | AllowedActions,\n SubjectMetadataControllerEvents,\n AllowedActions['type'],\n never\n>;\n\ntype SubjectMetadataControllerOptions = {\n messenger: SubjectMetadataControllerMessenger;\n subjectCacheLimit: number;\n state?: Partial<SubjectMetadataControllerState>;\n};\n\n/**\n * A controller for storing metadata associated with permission subjects. More\n * or less, a cache.\n */\nexport class SubjectMetadataController extends BaseController<\n typeof controllerName,\n SubjectMetadataControllerState,\n SubjectMetadataControllerMessenger\n> {\n private readonly subjectCacheLimit: number;\n\n private readonly subjectsWithoutPermissionsEncounteredSinceStartup: Set<string>;\n\n private readonly subjectHasPermissions: GenericPermissionController['hasPermissions'];\n\n constructor({\n messenger,\n subjectCacheLimit,\n state = {},\n }: SubjectMetadataControllerOptions) {\n if (!Number.isInteger(subjectCacheLimit) || subjectCacheLimit < 1) {\n throw new Error(\n `subjectCacheLimit must be a positive integer. Received: \"${subjectCacheLimit}\"`,\n );\n }\n\n const hasPermissions = (origin: string) => {\n return messenger.call('PermissionController:hasPermissions', origin);\n };\n\n super({\n name: controllerName,\n metadata: stateMetadata,\n messenger,\n state: {\n ...SubjectMetadataController.getTrimmedState(state, hasPermissions),\n },\n });\n\n this.subjectHasPermissions = hasPermissions;\n this.subjectCacheLimit = subjectCacheLimit;\n this.subjectsWithoutPermissionsEncounteredSinceStartup = new Set();\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getSubjectMetadata`,\n this.getSubjectMetadata.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:addSubjectMetadata`,\n this.addSubjectMetadata.bind(this),\n );\n }\n\n /**\n * Clears the state of this controller. Also resets the cache of subjects\n * encountered since startup, so as to not prematurely reach the cache limit.\n */\n clearState(): void {\n this.subjectsWithoutPermissionsEncounteredSinceStartup.clear();\n this.update((_draftState) => {\n return { ...defaultState };\n });\n }\n\n /**\n * Stores domain metadata for the given origin (subject). Deletes metadata for\n * subjects without permissions in a FIFO manner once more than\n * {@link SubjectMetadataController.subjectCacheLimit} distinct origins have\n * been added since boot.\n *\n * In order to prevent a degraded user experience,\n * metadata is never deleted for subjects with permissions, since metadata\n * cannot yet be requested on demand.\n *\n * @param metadata - The subject metadata to store.\n */\n addSubjectMetadata(metadata: SubjectMetadataToAdd): void {\n const { origin } = metadata;\n const newMetadata: SubjectMetadata = {\n ...metadata,\n extensionId: metadata.extensionId || null,\n iconUrl: metadata.iconUrl || null,\n name: metadata.name || null,\n subjectType: metadata.subjectType || null,\n };\n\n let originToForget: string | null = null;\n // We only delete the oldest encountered subject from the cache, again to\n // ensure that the user's experience isn't degraded by missing icons etc.\n if (\n this.subjectsWithoutPermissionsEncounteredSinceStartup.size >=\n this.subjectCacheLimit\n ) {\n const cachedOrigin =\n this.subjectsWithoutPermissionsEncounteredSinceStartup\n .values()\n .next().value;\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.delete(\n cachedOrigin,\n );\n\n if (!this.subjectHasPermissions(cachedOrigin)) {\n originToForget = cachedOrigin;\n }\n }\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.add(origin);\n\n this.update((draftState) => {\n // Typecast: ts(2589)\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n draftState.subjectMetadata[origin] = newMetadata as any;\n if (typeof originToForget === 'string') {\n delete draftState.subjectMetadata[originToForget];\n }\n });\n }\n\n /**\n * Gets the subject metadata for the given origin, if any.\n *\n * @param origin - The origin for which to get the subject metadata.\n * @returns The subject metadata, if any, or `undefined` otherwise.\n */\n getSubjectMetadata(origin: SubjectOrigin): SubjectMetadata | undefined {\n return this.state.subjectMetadata[origin];\n }\n\n /**\n * Deletes all subjects without permissions from the controller's state.\n */\n trimMetadataState(): void {\n this.update((draftState) => {\n return SubjectMetadataController.getTrimmedState(\n // Typecast: ts(2589)\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n draftState as any,\n this.subjectHasPermissions,\n );\n });\n }\n\n /**\n * Returns a new state object that only includes subjects with permissions.\n * This method is static because we want to call it in the constructor, before\n * the controller's state is initialized.\n *\n * @param state - The state object to trim.\n * @param hasPermissions - A function that returns a boolean indicating\n * whether a particular subject (identified by its origin) has any\n * permissions.\n * @returns The new state object. If the specified `state` object has no\n * subject metadata, the returned object will be equivalent to the default\n * state of this controller.\n */\n private static getTrimmedState(\n state: Partial<SubjectMetadataControllerState>,\n hasPermissions: SubjectMetadataController['subjectHasPermissions'],\n ): SubjectMetadataControllerState {\n const { subjectMetadata = {} } = state;\n\n return {\n subjectMetadata: Object.keys(subjectMetadata).reduce<\n Record<SubjectOrigin, SubjectMetadata>\n >((newSubjectMetadata, origin) => {\n if (hasPermissions(origin)) {\n newSubjectMetadata[origin] = subjectMetadata[origin];\n }\n return newSubjectMetadata;\n }, {}),\n };\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/permission-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "7.1.0",
|
|
4
4
|
"description": "Mediates access to JSON-RPC methods, used to interact with pieces of the MetaMask stack, via middleware for json-rpc-engine",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"build:docs": "typedoc",
|
|
25
|
+
"changelog:update": "../../scripts/update-changelog.sh @metamask/permission-controller",
|
|
25
26
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/permission-controller",
|
|
26
27
|
"publish:preview": "yarn npm publish --tag preview",
|
|
27
28
|
"test": "jest --reporters=jest-silent-reporter",
|
|
@@ -30,10 +31,9 @@
|
|
|
30
31
|
"test:watch": "jest --watch"
|
|
31
32
|
},
|
|
32
33
|
"dependencies": {
|
|
33
|
-
"@metamask/
|
|
34
|
-
"@metamask/
|
|
35
|
-
"@metamask/
|
|
36
|
-
"@metamask/json-rpc-engine": "^7.3.0",
|
|
34
|
+
"@metamask/base-controller": "^4.0.1",
|
|
35
|
+
"@metamask/controller-utils": "^8.0.1",
|
|
36
|
+
"@metamask/json-rpc-engine": "^7.3.1",
|
|
37
37
|
"@metamask/rpc-errors": "^6.1.0",
|
|
38
38
|
"@metamask/utils": "^8.2.0",
|
|
39
39
|
"@types/deep-freeze-strict": "^1.1.0",
|
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
"nanoid": "^3.1.31"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@metamask/
|
|
45
|
+
"@metamask/approval-controller": "^5.1.1",
|
|
46
|
+
"@metamask/auto-changelog": "^3.4.4",
|
|
46
47
|
"@types/jest": "^27.4.1",
|
|
47
48
|
"deepmerge": "^4.2.2",
|
|
48
49
|
"jest": "^27.5.1",
|
|
@@ -52,7 +53,7 @@
|
|
|
52
53
|
"typescript": "~4.8.4"
|
|
53
54
|
},
|
|
54
55
|
"peerDependencies": {
|
|
55
|
-
"@metamask/approval-controller": "^5.
|
|
56
|
+
"@metamask/approval-controller": "^5.1.1"
|
|
56
57
|
},
|
|
57
58
|
"engines": {
|
|
58
59
|
"node": ">=16.0.0"
|