@metamask/permission-controller 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [6.0.0]
10
+ ### Added
11
+ - Add new handler to `permissionRpcMethods.handlers` for `wallet_revokePermissions` RPC method ([#1889](https://github.com/MetaMask/core/pull/1889))
12
+
13
+ ### Changed
14
+ - **BREAKING:** Bump `@metamask/base-controller` to ^4.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
15
+ - This is breaking because the type of the `messenger` has backward-incompatible changes. See the changelog for this package for more.
16
+ - **BREAKING:** Update `PermittedRpcMethodHooks` type so it must support signature for `wallet_revokePermission` hook ([#1889](https://github.com/MetaMask/core/pull/1889))
17
+ - Bump `@metamask/approval-controller` to ^5.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
18
+ - Bump `@metamask/controller-utils` to ^6.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
19
+
20
+ ## [5.0.1]
21
+ ### Changed
22
+ - Bump `@metamask/json-rpc-engine` from `^7.1.0` to `^7.2.0` ([#1895](https://github.com/MetaMask/core/pull/1895))
23
+ - Bump dependency on `@metamask/rpc-errors` to ^6.1.0 ([#1653](https://github.com/MetaMask/core/pull/1653))
24
+ - Bump dependency and peer dependency on `@metamask/approval-controller` to ^4.0.1
25
+ - Bump `@metamask/utils` from `8.1.0` to `8.2.0` ([#1957](https://github.com/MetaMask/core/pull/1957))
26
+ - Bump `@metamask/auto-changelog` from `^3.2.0` to `^3.4.3` ([#1870](https://github.com/MetaMask/core/pull/1870), [#1905](https://github.com/MetaMask/core/pull/1905), [#1997](https://github.com/MetaMask/core/pull/1997))
27
+
9
28
  ## [5.0.0]
10
29
  ### Changed
11
30
  - **BREAKING:** Remove `undefined` from RestrictedMethodParameters type union and from type parameter for RestrictedMethodOptions ([#1749])(https://github.com/MetaMask/core/pull/1749))
@@ -94,7 +113,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
94
113
 
95
114
  All changes listed after this point were applied to this package following the monorepo conversion.
96
115
 
97
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@5.0.0...HEAD
116
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@6.0.0...HEAD
117
+ [6.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@5.0.1...@metamask/permission-controller@6.0.0
118
+ [5.0.1]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@5.0.0...@metamask/permission-controller@5.0.1
98
119
  [5.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@4.1.2...@metamask/permission-controller@5.0.0
99
120
  [4.1.2]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@4.1.1...@metamask/permission-controller@4.1.2
100
121
  [4.1.1]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@4.1.0...@metamask/permission-controller@4.1.1
@@ -1,9 +1,8 @@
1
1
  import type { AcceptRequest as AcceptApprovalRequest, AddApprovalRequest, HasApprovalRequest, RejectRequest as RejectApprovalRequest } from '@metamask/approval-controller';
2
- import type { RestrictedControllerMessenger, ActionConstraint, EventConstraint } from '@metamask/base-controller';
3
- import { BaseControllerV2 } from '@metamask/base-controller';
2
+ import type { RestrictedControllerMessenger, ActionConstraint, EventConstraint, ControllerGetStateAction, ControllerStateChangeEvent } from '@metamask/base-controller';
3
+ import { BaseController } from '@metamask/base-controller';
4
4
  import type { NonEmptyArray } from '@metamask/controller-utils';
5
5
  import type { Json } from '@metamask/utils';
6
- import type { Patch } from 'immer';
7
6
  import type { CaveatConstraint, CaveatSpecificationConstraint, CaveatSpecificationMap, ExtractCaveat, ExtractCaveats, ExtractCaveatValue } from './Caveat';
8
7
  import type { EndowmentSpecificationConstraint, ExtractAllowedCaveatTypes, OriginString, PermissionConstraint, PermissionSpecificationConstraint, PermissionSpecificationMap, RequestedPermissions, RestrictedMethod, RestrictedMethodParameters, RestrictedMethodSpecificationConstraint, SideEffectHandler, ValidPermission, ValidPermissionSpecification } from './Permission';
9
8
  import { getPermissionMiddlewareFactory } from './permission-middleware';
@@ -70,10 +69,7 @@ export declare type PermissionControllerState<Permission> = Permission extends P
70
69
  /**
71
70
  * Gets the state of the {@link PermissionController}.
72
71
  */
73
- export declare type GetPermissionControllerState = {
74
- type: `${typeof controllerName}:getState`;
75
- handler: () => PermissionControllerState<PermissionConstraint>;
76
- };
72
+ export declare type GetPermissionControllerState = ControllerGetStateAction<typeof controllerName, PermissionControllerState<PermissionConstraint>>;
77
73
  /**
78
74
  * Gets the names of all subjects from the {@link PermissionController}.
79
75
  */
@@ -166,10 +162,7 @@ export declare type PermissionControllerActions = ClearPermissions | GetEndowmen
166
162
  /**
167
163
  * The generic state change event of the {@link PermissionController}.
168
164
  */
169
- export declare type PermissionControllerStateChange = {
170
- type: `${typeof controllerName}:stateChange`;
171
- payload: [PermissionControllerState<PermissionConstraint>, Patch[]];
172
- };
165
+ export declare type PermissionControllerStateChange = ControllerStateChangeEvent<typeof controllerName, PermissionControllerState<PermissionConstraint>>;
173
166
  /**
174
167
  * The {@link ControllerMessenger} events of the {@link PermissionController}.
175
168
  *
@@ -280,7 +273,7 @@ export declare type PermissionControllerOptions<ControllerPermissionSpecificatio
280
273
  * @template ControllerCaveatSpecification - A union of the types of all
281
274
  * caveat specifications available to the controller.
282
275
  */
283
- export declare class PermissionController<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> extends BaseControllerV2<typeof controllerName, PermissionControllerState<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>, PermissionControllerMessenger> {
276
+ export declare class PermissionController<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> extends BaseController<typeof controllerName, PermissionControllerState<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>, PermissionControllerMessenger> {
284
277
  private readonly _caveatSpecifications;
285
278
  private readonly _permissionSpecifications;
286
279
  private readonly _unrestrictedMethods;
@@ -312,7 +305,7 @@ export declare class PermissionController<ControllerPermissionSpecification exte
312
305
  * @param options.unrestrictedMethods - The callable names of all JSON-RPC
313
306
  * methods ignored by the new controller.
314
307
  * @param options.messenger - The controller messenger. See
315
- * {@link BaseControllerV2} for more information.
308
+ * {@link BaseController} for more information.
316
309
  * @param options.state - Existing state to hydrate the controller with at
317
310
  * initialization.
318
311
  */
@@ -1 +1 @@
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,EAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAQhE,OAAO,KAAK,EAAE,IAAI,EAAW,MAAM,iBAAiB,CAAC;AAGrD,OAAO,KAAK,EAAS,KAAK,EAAE,MAAM,OAAO,CAAC;AAG1C,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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;;;;OAcG;IACH,OAAO,CAAC,4BAA4B;IAgDpC;;;;;;;OAOG;YACW,mBAAmB;IAiBjC;;;;;OAKG;IACH,OAAO,CAAC,cAAc;IAsBtB;;;;;;;OAOG;YACW,kBAAkB;IAoDhC;;;;;;;;;;;;OAYG;IACH,OAAO,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;IAU1B;;;;;;;;;;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"}
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,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ACjC,6BAA6B,CAC9B,CAAC,kBAAkB,CAAC,EACrB,MAAM,CAAC,EAAE,0BAA0B,GAClC,OAAO,CAAC,IAAI,CAAC;IAoBhB;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,wBAAwB;CAsBjC"}
@@ -81,7 +81,7 @@ var CaveatMutatorOperation;
81
81
  * @template ControllerCaveatSpecification - A union of the types of all
82
82
  * caveat specifications available to the controller.
83
83
  */
84
- class PermissionController extends base_controller_1.BaseControllerV2 {
84
+ class PermissionController extends base_controller_1.BaseController {
85
85
  /**
86
86
  * Constructs the PermissionController.
87
87
  *
@@ -95,7 +95,7 @@ class PermissionController extends base_controller_1.BaseControllerV2 {
95
95
  * @param options.unrestrictedMethods - The callable names of all JSON-RPC
96
96
  * methods ignored by the new controller.
97
97
  * @param options.messenger - The controller messenger. See
98
- * {@link BaseControllerV2} for more information.
98
+ * {@link BaseController} for more information.
99
99
  * @param options.state - Existing state to hydrate the controller with at
100
100
  * initialization.
101
101
  */
@@ -1 +1 @@
1
- {"version":3,"file":"PermissionController.js","sourceRoot":"","sources":["../src/PermissionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,+DAA6D;AAE7D,iEAIoC;AACpC,qDAAoD;AACpD,2CAA8C;AAE9C,4EAA4C;AAC5C,iCAAkC;AAElC,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;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I,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACtD,IAAI,CAAC,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} from '@metamask/base-controller';\nimport { BaseControllerV2 } 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 } from 'immer';\nimport type { Draft, Patch } 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 = {\n type: `${typeof controllerName}:getState`;\n handler: () => 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 = {\n type: `${typeof controllerName}:stateChange`;\n payload: [PermissionControllerState<PermissionConstraint>, Patch[]];\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 BaseControllerV2<\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 BaseControllerV2} 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;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,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,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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,7 +1,6 @@
1
- import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
- import { BaseControllerV2 } from '@metamask/base-controller';
1
+ import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
2
+ import { BaseController } from '@metamask/base-controller';
3
3
  import type { Json } from '@metamask/utils';
4
- import type { Patch } from 'immer';
5
4
  import type { HasPermissions, PermissionSubjectMetadata } from './PermissionController';
6
5
  declare const controllerName = "SubjectMetadataController";
7
6
  declare type SubjectOrigin = string;
@@ -32,19 +31,13 @@ declare type SubjectMetadataToAdd = PermissionSubjectMetadata & {
32
31
  export declare type SubjectMetadataControllerState = {
33
32
  subjectMetadata: Record<SubjectOrigin, SubjectMetadata>;
34
33
  };
35
- export declare type GetSubjectMetadataState = {
36
- type: `${typeof controllerName}:getState`;
37
- handler: () => SubjectMetadataControllerState;
38
- };
34
+ export declare type GetSubjectMetadataState = ControllerGetStateAction<typeof controllerName, SubjectMetadataControllerState>;
39
35
  export declare type GetSubjectMetadata = {
40
36
  type: `${typeof controllerName}:getSubjectMetadata`;
41
37
  handler: (origin: SubjectOrigin) => SubjectMetadata | undefined;
42
38
  };
43
39
  export declare type SubjectMetadataControllerActions = GetSubjectMetadataState | GetSubjectMetadata;
44
- export declare type SubjectMetadataStateChange = {
45
- type: `${typeof controllerName}:stateChange`;
46
- payload: [SubjectMetadataControllerState, Patch[]];
47
- };
40
+ export declare type SubjectMetadataStateChange = ControllerStateChangeEvent<typeof controllerName, SubjectMetadataControllerState>;
48
41
  export declare type SubjectMetadataControllerEvents = SubjectMetadataStateChange;
49
42
  declare type AllowedActions = HasPermissions;
50
43
  export declare type SubjectMetadataControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SubjectMetadataControllerActions | AllowedActions, SubjectMetadataControllerEvents, AllowedActions['type'], never>;
@@ -57,7 +50,7 @@ declare type SubjectMetadataControllerOptions = {
57
50
  * A controller for storing metadata associated with permission subjects. More
58
51
  * or less, a cache.
59
52
  */
60
- export declare class SubjectMetadataController extends BaseControllerV2<typeof controllerName, SubjectMetadataControllerState, SubjectMetadataControllerMessenger> {
53
+ export declare class SubjectMetadataController extends BaseController<typeof controllerName, SubjectMetadataControllerState, SubjectMetadataControllerMessenger> {
61
54
  private readonly subjectCacheLimit;
62
55
  private readonly subjectsWithoutPermissionsEncounteredSinceStartup;
63
56
  private readonly subjectHasPermissions;
@@ -1 +1 @@
1
- {"version":3,"file":"SubjectMetadataController.d.ts","sourceRoot":"","sources":["../src/SubjectMetadataController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAEnC,OAAO,KAAK,EAEV,cAAc,EACd,yBAAyB,EAC1B,MAAM,wBAAwB,CAAC;AAEhC,QAAA,MAAM,cAAc,8BAA8B,CAAC;AAEnD,aAAK,aAAa,GAAG,MAAM,CAAC;AAE5B;;;GAGG;AACH,oBAAY,WAAW;IACrB,SAAS,cAAc;IACvB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,IAAI,SAAS;CACd;AAED,oBAAY,eAAe,GAAG,yBAAyB,GAAG;IACxD,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAEpB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,WAAW,EAAE,WAAW,GAAG,IAAI,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB,CAAC;AAEF,aAAK,oBAAoB,GAAG,yBAAy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,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;IA8BnC;;;OAGG;IACH,UAAU,IAAI,IAAI;IAOlB;;;;;;;;;;;OAWG;IACH,kBAAkB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,IAAI;IA0CxD;;;;;OAKG;IACH,kBAAkB,CAAC,MAAM,EAAE,aAAa,GAAG,eAAe,GAAG,SAAS;IAItE;;OAEG;IACH,iBAAiB,IAAI,IAAI;IAUzB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,MAAM,CAAC,eAAe;CAiB/B"}
@@ -25,7 +25,7 @@ const defaultState = {
25
25
  * A controller for storing metadata associated with permission subjects. More
26
26
  * or less, a cache.
27
27
  */
28
- class SubjectMetadataController extends base_controller_1.BaseControllerV2 {
28
+ class SubjectMetadataController extends base_controller_1.BaseController {
29
29
  constructor({ messenger, subjectCacheLimit, state = {}, }) {
30
30
  if (!Number.isInteger(subjectCacheLimit) || subjectCacheLimit < 1) {
31
31
  throw new Error(`subjectCacheLimit must be a positive integer. Received: "${subjectCacheLimit}"`);
@@ -1 +1 @@
1
- {"version":3,"file":"SubjectMetadataController.js","sourceRoot":"","sources":["../src/SubjectMetadataController.ts"],"names":[],"mappings":";;;AACA,+DAA6D;AAU7D,MAAM,cAAc,GAAG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tC,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,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 { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport type { Json } from '@metamask/utils';\nimport type { Patch } from 'immer';\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 = {\n type: `${typeof controllerName}:getState`;\n handler: () => 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 = {\n type: `${typeof controllerName}:stateChange`;\n payload: [SubjectMetadataControllerState, Patch[]];\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 BaseControllerV2<\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,oCAAqB,CAAA;IACrB,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;IACnB,4BAAa,CAAA;AACf,CAAC,EANW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAMtB;AAsBD,MAAM,aAAa,GAAG;IACpB,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACrD,CAAC;AAEF,MAAM,YAAY,GAAmC;IACnD,eAAe,EAAE,EAAE;CACpB,CAAC;AAuCF;;;GAGG;AACH,MAAa,yBAA0B,SAAQ,gCAI9C;IAOC,YAAY,EACV,SAAS,EACT,iBAAiB,EACjB,KAAK,GAAG,EAAE,GACuB;QACjC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,GAAG,CAAC,EAAE;YACjE,MAAM,IAAI,KAAK,CACb,4DAA4D,iBAAiB,GAAG,CACjF,CAAC;SACH;QAED,MAAM,cAAc,GAAG,CAAC,MAAc,EAAE,EAAE;YACxC,OAAO,SAAS,CAAC,IAAI,CAAC,qCAAqC,EAAE,MAAM,CAAC,CAAC;QACvE,CAAC,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,aAAa;YACvB,SAAS;YACT,KAAK,oBACA,yBAAyB,CAAC,eAAe,CAAC,KAAK,EAAE,cAAc,CAAC,CACpE;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,qBAAqB,GAAG,cAAc,CAAC;QAC5C,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,iDAAiD,GAAG,IAAI,GAAG,EAAE,C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,qBAAqB;YACrB,UAAU,CAAC,eAAe,CAAC,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,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,5 +1,8 @@
1
1
  import type { GetPermissionsHooks } from './getPermissions';
2
2
  import type { RequestPermissionsHooks } from './requestPermissions';
3
- export declare type PermittedRpcMethodHooks = RequestPermissionsHooks & GetPermissionsHooks;
4
- export declare const handlers: readonly [import("..").PermittedHandlerExport<RequestPermissionsHooks, [import("..").RequestedPermissions], import("..").PermissionConstraint[]>, import("..").PermittedHandlerExport<GetPermissionsHooks, [], import("..").PermissionConstraint[]>];
3
+ import type { RevokePermissionsHooks } from './revokePermissions';
4
+ export declare type PermittedRpcMethodHooks = RequestPermissionsHooks & GetPermissionsHooks & RevokePermissionsHooks;
5
+ export declare const handlers: readonly [import("..").PermittedHandlerExport<RequestPermissionsHooks, [import("..").RequestedPermissions], import("..").PermissionConstraint[]>, import("..").PermittedHandlerExport<GetPermissionsHooks, [], import("..").PermissionConstraint[]>, import("..").PermittedHandlerExport<RevokePermissionsHooks, {
6
+ [x: string]: import("@metamask/utils").Json;
7
+ }, null>];
5
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rpc-methods/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAE5D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAGpE,oBAAY,uBAAuB,GAAG,uBAAuB,GAC3D,mBAAmB,CAAC;AAEtB,eAAO,MAAM,QAAQ,sPAGX,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rpc-methods/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAE5D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAGlE,oBAAY,uBAAuB,GAAG,uBAAuB,GAC3D,mBAAmB,GACnB,sBAAsB,CAAC;AAEzB,eAAO,MAAM,QAAQ;;SAIX,CAAC"}
@@ -3,8 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handlers = void 0;
4
4
  const getPermissions_1 = require("./getPermissions");
5
5
  const requestPermissions_1 = require("./requestPermissions");
6
+ const revokePermissions_1 = require("./revokePermissions");
6
7
  exports.handlers = [
7
8
  requestPermissions_1.requestPermissionsHandler,
8
9
  getPermissions_1.getPermissionsHandler,
10
+ revokePermissions_1.revokePermissionsHandler,
9
11
  ];
10
12
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/rpc-methods/index.ts"],"names":[],"mappings":";;;AACA,qDAAyD;AAEzD,6DAAiE;AAKpD,QAAA,QAAQ,GAAG;IACtB,8CAAyB;IACzB,sCAAqB;CACb,CAAC","sourcesContent":["import type { GetPermissionsHooks } from './getPermissions';\nimport { getPermissionsHandler } from './getPermissions';\nimport type { RequestPermissionsHooks } from './requestPermissions';\nimport { requestPermissionsHandler } from './requestPermissions';\n\nexport type PermittedRpcMethodHooks = RequestPermissionsHooks &\n GetPermissionsHooks;\n\nexport const handlers = [\n requestPermissionsHandler,\n getPermissionsHandler,\n] as const;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/rpc-methods/index.ts"],"names":[],"mappings":";;;AACA,qDAAyD;AAEzD,6DAAiE;AAEjE,2DAA+D;AAMlD,QAAA,QAAQ,GAAG;IACtB,8CAAyB;IACzB,sCAAqB;IACrB,4CAAwB;CAChB,CAAC","sourcesContent":["import type { GetPermissionsHooks } from './getPermissions';\nimport { getPermissionsHandler } from './getPermissions';\nimport type { RequestPermissionsHooks } from './requestPermissions';\nimport { requestPermissionsHandler } from './requestPermissions';\nimport type { RevokePermissionsHooks } from './revokePermissions';\nimport { revokePermissionsHandler } from './revokePermissions';\n\nexport type PermittedRpcMethodHooks = RequestPermissionsHooks &\n GetPermissionsHooks &\n RevokePermissionsHooks;\n\nexport const handlers = [\n requestPermissionsHandler,\n getPermissionsHandler,\n revokePermissionsHandler,\n] as const;\n"]}
@@ -0,0 +1,11 @@
1
+ import { type Json, type NonEmptyArray } from '@metamask/utils';
2
+ import type { PermissionConstraint } from '../Permission';
3
+ import type { PermittedHandlerExport } from '../utils';
4
+ export declare const revokePermissionsHandler: PermittedHandlerExport<RevokePermissionsHooks, RevokePermissionArgs, null>;
5
+ declare type RevokePermissionArgs = Record<PermissionConstraint['parentCapability'], Json>;
6
+ declare type RevokePermissions = (permissions: NonEmptyArray<PermissionConstraint['parentCapability']>) => void;
7
+ export declare type RevokePermissionsHooks = {
8
+ revokePermissionsForOrigin: RevokePermissions;
9
+ };
10
+ export {};
11
+ //# sourceMappingURL=revokePermissions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revokePermissions.d.ts","sourceRoot":"","sources":["../../src/rpc-methods/revokePermissions.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,IAAI,EAET,KAAK,aAAa,EAEnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAGvD,eAAO,MAAM,wBAAwB,EAAE,sBAAsB,CAC3D,sBAAsB,EACtB,oBAAoB,EACpB,IAAI,CAOL,CAAC;AAEF,aAAK,oBAAoB,GAAG,MAAM,CAChC,oBAAoB,CAAC,kBAAkB,CAAC,EACxC,IAAI,CACL,CAAC;AAEF,aAAK,iBAAiB,GAAG,CACvB,WAAW,EAAE,aAAa,CAAC,oBAAoB,CAAC,kBAAkB,CAAC,CAAC,KACjE,IAAI,CAAC;AAEV,oBAAY,sBAAsB,GAAG;IACnC,0BAA0B,EAAE,iBAAiB,CAAC;CAC/C,CAAC"}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.revokePermissionsHandler = void 0;
13
+ const utils_1 = require("@metamask/utils");
14
+ const errors_1 = require("../errors");
15
+ const utils_2 = require("../utils");
16
+ exports.revokePermissionsHandler = {
17
+ methodNames: [utils_2.MethodNames.revokePermissions],
18
+ implementation: revokePermissionsImplementation,
19
+ hookNames: {
20
+ revokePermissionsForOrigin: true,
21
+ },
22
+ };
23
+ /**
24
+ * Revoke Permissions implementation to be used in JsonRpcEngine middleware.
25
+ *
26
+ * @param req - The JsonRpcEngine request
27
+ * @param res - The JsonRpcEngine result object
28
+ * @param _next - JsonRpcEngine next() callback - unused
29
+ * @param end - JsonRpcEngine end() callback
30
+ * @param options - Method hooks passed to the method implementation
31
+ * @param options.revokePermissionsForOrigin - A hook that revokes given permission keys for an origin
32
+ * @returns A promise that resolves to nothing
33
+ */
34
+ function revokePermissionsImplementation(req, res, _next, end, { revokePermissionsForOrigin }) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ const { params } = req;
37
+ const param = params === null || params === void 0 ? void 0 : params[0];
38
+ if (!param) {
39
+ return end((0, errors_1.invalidParams)({ data: { request: req } }));
40
+ }
41
+ // For now, this API revokes the entire permission key
42
+ // even if caveats are specified.
43
+ const permissionKeys = Object.keys(param);
44
+ if (!(0, utils_1.isNonEmptyArray)(permissionKeys)) {
45
+ return end((0, errors_1.invalidParams)({ data: { request: req } }));
46
+ }
47
+ revokePermissionsForOrigin(permissionKeys);
48
+ res.result = null;
49
+ return end();
50
+ });
51
+ }
52
+ //# sourceMappingURL=revokePermissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revokePermissions.js","sourceRoot":"","sources":["../../src/rpc-methods/revokePermissions.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2CAMyB;AAEzB,sCAA0C;AAG1C,oCAAuC;AAE1B,QAAA,wBAAwB,GAIjC;IACF,WAAW,EAAE,CAAC,mBAAW,CAAC,iBAAiB,CAAC;IAC5C,cAAc,EAAE,+BAA+B;IAC/C,SAAS,EAAE;QACT,0BAA0B,EAAE,IAAI;KACjC;CACF,CAAC;AAeF;;;;;;;;;;GAUG;AACH,SAAe,+BAA+B,CAC5C,GAAyC,EACzC,GAAiC,EACjC,KAAc,EACd,GAA6B,EAC7B,EAAE,0BAA0B,EAA0B;;QAEtD,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;QAEvB,MAAM,KAAK,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAG,CAAC,CAAC,CAAC;QAE1B,IAAI,CAAC,KAAK,EAAE;YACV,OAAO,GAAG,CAAC,IAAA,sBAAa,EAAC,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;SACvD;QAED,sDAAsD;QACtD,iCAAiC;QACjC,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAE1C,IAAI,CAAC,IAAA,uBAAe,EAAC,cAAc,CAAC,EAAE;YACpC,OAAO,GAAG,CAAC,IAAA,sBAAa,EAAC,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;SACvD;QAED,0BAA0B,CAAC,cAAc,CAAC,CAAC;QAE3C,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC;QAElB,OAAO,GAAG,EAAE,CAAC;IACf,CAAC;CAAA","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport {\n isNonEmptyArray,\n type Json,\n type JsonRpcRequest,\n type NonEmptyArray,\n type PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { invalidParams } from '../errors';\nimport type { PermissionConstraint } from '../Permission';\nimport type { PermittedHandlerExport } from '../utils';\nimport { MethodNames } from '../utils';\n\nexport const revokePermissionsHandler: PermittedHandlerExport<\n RevokePermissionsHooks,\n RevokePermissionArgs,\n null\n> = {\n methodNames: [MethodNames.revokePermissions],\n implementation: revokePermissionsImplementation,\n hookNames: {\n revokePermissionsForOrigin: true,\n },\n};\n\ntype RevokePermissionArgs = Record<\n PermissionConstraint['parentCapability'],\n Json\n>;\n\ntype RevokePermissions = (\n permissions: NonEmptyArray<PermissionConstraint['parentCapability']>,\n) => void;\n\nexport type RevokePermissionsHooks = {\n revokePermissionsForOrigin: RevokePermissions;\n};\n\n/**\n * Revoke Permissions implementation to be used in JsonRpcEngine middleware.\n *\n * @param req - The JsonRpcEngine request\n * @param res - The JsonRpcEngine result object\n * @param _next - JsonRpcEngine next() callback - unused\n * @param end - JsonRpcEngine end() callback\n * @param options - Method hooks passed to the method implementation\n * @param options.revokePermissionsForOrigin - A hook that revokes given permission keys for an origin\n * @returns A promise that resolves to nothing\n */\nasync function revokePermissionsImplementation(\n req: JsonRpcRequest<RevokePermissionArgs>,\n res: PendingJsonRpcResponse<null>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { revokePermissionsForOrigin }: RevokePermissionsHooks,\n): Promise<void> {\n const { params } = req;\n\n const param = params?.[0];\n\n if (!param) {\n return end(invalidParams({ data: { request: req } }));\n }\n\n // For now, this API revokes the entire permission key\n // even if caveats are specified.\n const permissionKeys = Object.keys(param);\n\n if (!isNonEmptyArray(permissionKeys)) {\n return end(invalidParams({ data: { request: req } }));\n }\n\n revokePermissionsForOrigin(permissionKeys);\n\n res.result = null;\n\n return end();\n}\n"]}
package/dist/utils.d.ts CHANGED
@@ -4,7 +4,8 @@ import type { CaveatSpecificationConstraint, CaveatSpecificationMap } from './Ca
4
4
  import type { PermissionSpecificationConstraint, PermissionSpecificationMap } from './Permission';
5
5
  export declare enum MethodNames {
6
6
  requestPermissions = "wallet_requestPermissions",
7
- getPermissions = "wallet_getPermissions"
7
+ getPermissions = "wallet_getPermissions",
8
+ revokePermissions = "wallet_revokePermissions"
8
9
  }
9
10
  /**
10
11
  * Utility type for extracting a union of all individual caveat or permission
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACV,6BAA6B,EAC7B,sBAAsB,EACvB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EACV,iCAAiC,EACjC,0BAA0B,EAC3B,MAAM,cAAc,CAAC;AAEtB,oBAAY,WAAW;IACrB,kBAAkB,8BAA8B;IAChD,cAAc,0BAA0B;CACzC;AAED;;;;;;;GAOG;AACH,oBAAY,qBAAqB,CAC/B,iBAAiB,SACb,sBAAsB,CAAC,6BAA6B,CAAC,GACrD,0BAA0B,CAAC,iCAAiC,CAAC,IAC/D,iBAAiB,CAAC,MAAM,iBAAiB,CAAC,CAAC;AAE/C;;GAEG;AACH,oBAAY,yBAAyB,CACnC,CAAC,EACD,CAAC,SAAS,aAAa,EACvB,CAAC,SAAS,IAAI,IACZ,CACF,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,EACtB,GAAG,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAC9B,IAAI,EAAE,yBAAyB,EAC/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,cAAc,CAAC,CAAC,CAAC,EACtB,GAAG,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAC9B,IAAI,EAAE,yBAAyB,EAC/B,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,CAAC,KACL,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B;;;;;GAKG;AACH,oBAAY,SAAS,CAAC,CAAC,IAAI;KACxB,QAAQ,IAAI,MAAM,CAAC,GAAG,IAAI;CAC5B,CAAC;AAEF;;GAEG;AACH,oBAAY,sBAAsB,CAChC,CAAC,EACD,CAAC,SAAS,aAAa,EACvB,CAAC,SAAS,IAAI,IACZ;IACF,cAAc,EAAE,yBAAyB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnD,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB,CAAC"}
package/dist/utils.js CHANGED
@@ -5,5 +5,6 @@ var MethodNames;
5
5
  (function (MethodNames) {
6
6
  MethodNames["requestPermissions"] = "wallet_requestPermissions";
7
7
  MethodNames["getPermissions"] = "wallet_getPermissions";
8
+ MethodNames["revokePermissions"] = "wallet_revokePermissions";
8
9
  })(MethodNames = exports.MethodNames || (exports.MethodNames = {}));
9
10
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAoBA,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,+DAAgD,CAAA;IAChD,uDAAwC,CAAA;AAC1C,CAAC,EAHW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAGtB","sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n} from './Caveat';\nimport type {\n PermissionSpecificationConstraint,\n PermissionSpecificationMap,\n} from './Permission';\n\nexport enum MethodNames {\n requestPermissions = 'wallet_requestPermissions',\n getPermissions = 'wallet_getPermissions',\n}\n\n/**\n * Utility type for extracting a union of all individual caveat or permission\n * specification types from a {@link CaveatSpecificationMap} or\n * {@link PermissionSpecificationMap}.\n *\n * @template SpecificationsMap - The caveat or permission specifications map\n * whose specification type union to extract.\n */\nexport type ExtractSpecifications<\n SpecificationsMap extends\n | CaveatSpecificationMap<CaveatSpecificationConstraint>\n | PermissionSpecificationMap<PermissionSpecificationConstraint>,\n> = SpecificationsMap[keyof SpecificationsMap];\n\n/**\n * A middleware function for handling a permitted method.\n */\nexport type HandlerMiddlewareFunction<\n T,\n U extends JsonRpcParams,\n V extends Json,\n> = (\n req: JsonRpcRequest<U>,\n res: PendingJsonRpcResponse<V>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: T,\n) => void | Promise<void>;\n\n/**\n * We use a mapped object type in order to create a type that requires the\n * presence of the names of all hooks for the given handler.\n * This can then be used to select only the necessary hooks whenever a method\n * is called for purposes of POLA.\n */\nexport type HookNames<T> = {\n [Property in keyof T]: true;\n};\n\n/**\n * A handler for a permitted method.\n */\nexport type PermittedHandlerExport<\n T,\n U extends JsonRpcParams,\n V extends Json,\n> = {\n implementation: HandlerMiddlewareFunction<T, U, V>;\n hookNames: HookNames<T>;\n methodNames: string[];\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAoBA,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,+DAAgD,CAAA;IAChD,uDAAwC,CAAA;IACxC,6DAA8C,CAAA;AAChD,CAAC,EAJW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAItB","sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n} from './Caveat';\nimport type {\n PermissionSpecificationConstraint,\n PermissionSpecificationMap,\n} from './Permission';\n\nexport enum MethodNames {\n requestPermissions = 'wallet_requestPermissions',\n getPermissions = 'wallet_getPermissions',\n revokePermissions = 'wallet_revokePermissions',\n}\n\n/**\n * Utility type for extracting a union of all individual caveat or permission\n * specification types from a {@link CaveatSpecificationMap} or\n * {@link PermissionSpecificationMap}.\n *\n * @template SpecificationsMap - The caveat or permission specifications map\n * whose specification type union to extract.\n */\nexport type ExtractSpecifications<\n SpecificationsMap extends\n | CaveatSpecificationMap<CaveatSpecificationConstraint>\n | PermissionSpecificationMap<PermissionSpecificationConstraint>,\n> = SpecificationsMap[keyof SpecificationsMap];\n\n/**\n * A middleware function for handling a permitted method.\n */\nexport type HandlerMiddlewareFunction<\n T,\n U extends JsonRpcParams,\n V extends Json,\n> = (\n req: JsonRpcRequest<U>,\n res: PendingJsonRpcResponse<V>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: T,\n) => void | Promise<void>;\n\n/**\n * We use a mapped object type in order to create a type that requires the\n * presence of the names of all hooks for the given handler.\n * This can then be used to select only the necessary hooks whenever a method\n * is called for purposes of POLA.\n */\nexport type HookNames<T> = {\n [Property in keyof T]: true;\n};\n\n/**\n * A handler for a permitted method.\n */\nexport type PermittedHandlerExport<\n T,\n U extends JsonRpcParams,\n V extends Json,\n> = {\n implementation: HandlerMiddlewareFunction<T, U, V>;\n hookNames: HookNames<T>;\n methodNames: string[];\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/permission-controller",
3
- "version": "5.0.0",
3
+ "version": "6.0.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",
@@ -24,24 +24,25 @@
24
24
  "build:docs": "typedoc",
25
25
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/permission-controller",
26
26
  "publish:preview": "yarn npm publish --tag preview",
27
- "test": "jest",
27
+ "test": "jest --reporters=jest-silent-reporter",
28
28
  "test:clean": "jest --clearCache",
29
+ "test:verbose": "jest --verbose",
29
30
  "test:watch": "jest --watch"
30
31
  },
31
32
  "dependencies": {
32
- "@metamask/approval-controller": "^4.0.0",
33
- "@metamask/base-controller": "^3.2.3",
34
- "@metamask/controller-utils": "^5.0.2",
35
- "@metamask/json-rpc-engine": "^7.1.1",
36
- "@metamask/rpc-errors": "^6.0.0",
37
- "@metamask/utils": "^8.1.0",
33
+ "@metamask/approval-controller": "^5.0.0",
34
+ "@metamask/base-controller": "^4.0.0",
35
+ "@metamask/controller-utils": "^6.0.0",
36
+ "@metamask/json-rpc-engine": "^7.3.0",
37
+ "@metamask/rpc-errors": "^6.1.0",
38
+ "@metamask/utils": "^8.2.0",
38
39
  "@types/deep-freeze-strict": "^1.1.0",
39
40
  "deep-freeze-strict": "^1.1.1",
40
41
  "immer": "^9.0.6",
41
42
  "nanoid": "^3.1.31"
42
43
  },
43
44
  "devDependencies": {
44
- "@metamask/auto-changelog": "^3.1.0",
45
+ "@metamask/auto-changelog": "^3.4.3",
45
46
  "@types/jest": "^27.4.1",
46
47
  "deepmerge": "^4.2.2",
47
48
  "jest": "^27.5.1",
@@ -51,7 +52,7 @@
51
52
  "typescript": "~4.8.4"
52
53
  },
53
54
  "peerDependencies": {
54
- "@metamask/approval-controller": "^4.0.0"
55
+ "@metamask/approval-controller": "^5.0.0"
55
56
  },
56
57
  "engines": {
57
58
  "node": ">=16.0.0"