@metamask/permission-controller 10.0.0 → 10.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/Caveat.js +3 -3
  3. package/dist/Caveat.mjs +2 -2
  4. package/dist/PermissionController.js +6 -6
  5. package/dist/PermissionController.mjs +5 -5
  6. package/dist/SubjectMetadataController.js +2 -2
  7. package/dist/SubjectMetadataController.mjs +1 -1
  8. package/dist/{chunk-3X6WO7UG.js → chunk-4YXP3WEE.js} +1 -1
  9. package/dist/{chunk-3X6WO7UG.js.map → chunk-4YXP3WEE.js.map} +1 -1
  10. package/dist/{chunk-RXC2KFRK.mjs → chunk-5NYMBY4A.mjs} +2 -2
  11. package/dist/{chunk-GHOOCGN3.js → chunk-6UCIDD5V.js} +4 -4
  12. package/dist/{chunk-RJKSCKTD.mjs → chunk-6V5UTS24.mjs} +2 -2
  13. package/dist/{chunk-4B6NOD2D.mjs → chunk-7WEYLBME.mjs} +7 -5
  14. package/dist/chunk-7WEYLBME.mjs.map +1 -0
  15. package/dist/{chunk-DV74ZDGD.js → chunk-AQ46ICF5.js} +5 -5
  16. package/dist/{chunk-RKDXFKNN.js → chunk-D7PWCWCC.js} +4 -4
  17. package/dist/{chunk-Y6GRGXOL.mjs → chunk-FVYYHAVF.mjs} +2 -2
  18. package/dist/{chunk-XM622CMP.js → chunk-HZPWUOQB.js} +3 -3
  19. package/dist/{chunk-C73QV75D.js → chunk-IPKS33XA.js} +5 -1
  20. package/dist/chunk-IPKS33XA.js.map +1 -0
  21. package/dist/{chunk-VM4LI55W.js → chunk-M5GM7UFU.js} +3 -3
  22. package/dist/{chunk-TBOKQ5NP.mjs → chunk-NOB77ENO.mjs} +3 -3
  23. package/dist/{chunk-I3DJ23QH.js → chunk-R56CBYD3.js} +61 -59
  24. package/dist/chunk-R56CBYD3.js.map +1 -0
  25. package/dist/{chunk-DUZPZORW.mjs → chunk-SKKQZ5E6.mjs} +2 -2
  26. package/dist/{chunk-W4CPVA4J.mjs → chunk-SPOFDHOW.mjs} +5 -1
  27. package/dist/chunk-SPOFDHOW.mjs.map +1 -0
  28. package/dist/{chunk-PTE4672I.js → chunk-TAK6LXU6.js} +1 -1
  29. package/dist/chunk-TAK6LXU6.js.map +1 -0
  30. package/dist/{chunk-AZUM6CBY.mjs → chunk-VHHS2FJX.mjs} +1 -1
  31. package/dist/chunk-VHHS2FJX.mjs.map +1 -0
  32. package/dist/{chunk-3R56AY2L.mjs → chunk-ZTBBRCDR.mjs} +1 -1
  33. package/dist/chunk-ZTBBRCDR.mjs.map +1 -0
  34. package/dist/errors.js +2 -2
  35. package/dist/errors.mjs +1 -1
  36. package/dist/index.js +10 -10
  37. package/dist/index.mjs +9 -9
  38. package/dist/permission-middleware.js +3 -3
  39. package/dist/permission-middleware.mjs +2 -2
  40. package/dist/rpc-methods/getPermissions.js +1 -1
  41. package/dist/rpc-methods/getPermissions.mjs +1 -1
  42. package/dist/rpc-methods/index.js +6 -6
  43. package/dist/rpc-methods/index.mjs +5 -5
  44. package/dist/rpc-methods/requestPermissions.js +4 -4
  45. package/dist/rpc-methods/requestPermissions.mjs +3 -3
  46. package/dist/rpc-methods/revokePermissions.js +4 -4
  47. package/dist/rpc-methods/revokePermissions.mjs +3 -3
  48. package/dist/tsconfig.build.tsbuildinfo +1 -1
  49. package/dist/types/PermissionController.d.ts.map +1 -1
  50. package/dist/types/SubjectMetadataController.d.ts.map +1 -1
  51. package/dist/types/errors.d.ts.map +1 -1
  52. package/dist/types/utils.d.ts.map +1 -1
  53. package/dist/utils.js +2 -2
  54. package/dist/utils.mjs +1 -1
  55. package/package.json +7 -7
  56. package/dist/chunk-3R56AY2L.mjs.map +0 -1
  57. package/dist/chunk-4B6NOD2D.mjs.map +0 -1
  58. package/dist/chunk-AZUM6CBY.mjs.map +0 -1
  59. package/dist/chunk-C73QV75D.js.map +0 -1
  60. package/dist/chunk-I3DJ23QH.js.map +0 -1
  61. package/dist/chunk-PTE4672I.js.map +0 -1
  62. package/dist/chunk-W4CPVA4J.mjs.map +0 -1
  63. /package/dist/{chunk-RXC2KFRK.mjs.map → chunk-5NYMBY4A.mjs.map} +0 -0
  64. /package/dist/{chunk-GHOOCGN3.js.map → chunk-6UCIDD5V.js.map} +0 -0
  65. /package/dist/{chunk-RJKSCKTD.mjs.map → chunk-6V5UTS24.mjs.map} +0 -0
  66. /package/dist/{chunk-DV74ZDGD.js.map → chunk-AQ46ICF5.js.map} +0 -0
  67. /package/dist/{chunk-RKDXFKNN.js.map → chunk-D7PWCWCC.js.map} +0 -0
  68. /package/dist/{chunk-Y6GRGXOL.mjs.map → chunk-FVYYHAVF.mjs.map} +0 -0
  69. /package/dist/{chunk-XM622CMP.js.map → chunk-HZPWUOQB.js.map} +0 -0
  70. /package/dist/{chunk-VM4LI55W.js.map → chunk-M5GM7UFU.js.map} +0 -0
  71. /package/dist/{chunk-TBOKQ5NP.mjs.map → chunk-NOB77ENO.mjs.map} +0 -0
  72. /package/dist/{chunk-DUZPZORW.mjs.map → chunk-SKKQZ5E6.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [10.0.1]
11
+
12
+ ### Changed
13
+
14
+ - Bump `@metamask/rpc-errors` from `6.2.1` to `^6.3.1` ([#4516](https://github.com/MetaMask/core/pull/4516))
15
+ - Bump `@metamask/utils` from `^8.3.0` to `^9.0.0` ([#4516](https://github.com/MetaMask/core/pull/4516))
16
+ - Bump `@metamask/base-controller` to `^9.0.1` ([#4517](https://github.com/MetaMask/core/pull/4517))
17
+ - Bump `@metamask/controller-utils` to `^11.0.1` ([#4517](https://github.com/MetaMask/core/pull/4517))
18
+ - Bump `@metamask/json-rpc-engine` to `^9.0.1` ([#4517](https://github.com/MetaMask/core/pull/4517))
19
+
10
20
  ## [10.0.0]
11
21
 
12
22
  ### Changed
@@ -242,7 +252,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
242
252
 
243
253
  All changes listed after this point were applied to this package following the monorepo conversion.
244
254
 
245
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@10.0.0...HEAD
255
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@10.0.1...HEAD
256
+ [10.0.1]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@10.0.0...@metamask/permission-controller@10.0.1
246
257
  [10.0.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@9.1.1...@metamask/permission-controller@10.0.0
247
258
  [9.1.1]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@9.1.0...@metamask/permission-controller@9.1.1
248
259
  [9.1.0]: https://github.com/MetaMask/core/compare/@metamask/permission-controller@9.0.2...@metamask/permission-controller@9.1.0
package/dist/Caveat.js CHANGED
@@ -1,12 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkRKDXFKNNjs = require('./chunk-RKDXFKNN.js');
4
+ var _chunkD7PWCWCCjs = require('./chunk-D7PWCWCC.js');
5
5
  require('./chunk-ZH4MLSXX.js');
6
- require('./chunk-3X6WO7UG.js');
6
+ require('./chunk-4YXP3WEE.js');
7
7
  require('./chunk-Z2XKIXLS.js');
8
8
 
9
9
 
10
10
 
11
- exports.decorateWithCaveats = _chunkRKDXFKNNjs.decorateWithCaveats; exports.isRestrictedMethodCaveatSpecification = _chunkRKDXFKNNjs.isRestrictedMethodCaveatSpecification;
11
+ exports.decorateWithCaveats = _chunkD7PWCWCCjs.decorateWithCaveats; exports.isRestrictedMethodCaveatSpecification = _chunkD7PWCWCCjs.isRestrictedMethodCaveatSpecification;
12
12
  //# sourceMappingURL=Caveat.js.map
package/dist/Caveat.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  decorateWithCaveats,
3
3
  isRestrictedMethodCaveatSpecification
4
- } from "./chunk-RJKSCKTD.mjs";
4
+ } from "./chunk-6V5UTS24.mjs";
5
5
  import "./chunk-HYMS7IGB.mjs";
6
- import "./chunk-AZUM6CBY.mjs";
6
+ import "./chunk-VHHS2FJX.mjs";
7
7
  import "./chunk-2L4QPE5A.mjs";
8
8
  export {
9
9
  decorateWithCaveats,
@@ -1,15 +1,15 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkI3DJ23QHjs = require('./chunk-I3DJ23QH.js');
5
- require('./chunk-RKDXFKNN.js');
4
+ var _chunkR56CBYD3js = require('./chunk-R56CBYD3.js');
5
+ require('./chunk-D7PWCWCC.js');
6
6
  require('./chunk-ZH4MLSXX.js');
7
- require('./chunk-VM4LI55W.js');
8
- require('./chunk-3X6WO7UG.js');
9
- require('./chunk-PTE4672I.js');
7
+ require('./chunk-M5GM7UFU.js');
8
+ require('./chunk-4YXP3WEE.js');
9
+ require('./chunk-TAK6LXU6.js');
10
10
  require('./chunk-Z2XKIXLS.js');
11
11
 
12
12
 
13
13
 
14
- exports.CaveatMutatorOperation = _chunkI3DJ23QHjs.CaveatMutatorOperation; exports.PermissionController = _chunkI3DJ23QHjs.PermissionController;
14
+ exports.CaveatMutatorOperation = _chunkR56CBYD3js.CaveatMutatorOperation; exports.PermissionController = _chunkR56CBYD3js.PermissionController;
15
15
  //# sourceMappingURL=PermissionController.js.map
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  CaveatMutatorOperation,
3
3
  PermissionController
4
- } from "./chunk-4B6NOD2D.mjs";
5
- import "./chunk-RJKSCKTD.mjs";
4
+ } from "./chunk-7WEYLBME.mjs";
5
+ import "./chunk-6V5UTS24.mjs";
6
6
  import "./chunk-HYMS7IGB.mjs";
7
- import "./chunk-RXC2KFRK.mjs";
8
- import "./chunk-AZUM6CBY.mjs";
9
- import "./chunk-3R56AY2L.mjs";
7
+ import "./chunk-5NYMBY4A.mjs";
8
+ import "./chunk-VHHS2FJX.mjs";
9
+ import "./chunk-ZTBBRCDR.mjs";
10
10
  import "./chunk-2L4QPE5A.mjs";
11
11
  export {
12
12
  CaveatMutatorOperation,
@@ -1,10 +1,10 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkC73QV75Djs = require('./chunk-C73QV75D.js');
4
+ var _chunkIPKS33XAjs = require('./chunk-IPKS33XA.js');
5
5
  require('./chunk-Z2XKIXLS.js');
6
6
 
7
7
 
8
8
 
9
- exports.SubjectMetadataController = _chunkC73QV75Djs.SubjectMetadataController; exports.SubjectType = _chunkC73QV75Djs.SubjectType;
9
+ exports.SubjectMetadataController = _chunkIPKS33XAjs.SubjectMetadataController; exports.SubjectType = _chunkIPKS33XAjs.SubjectType;
10
10
  //# sourceMappingURL=SubjectMetadataController.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SubjectMetadataController,
3
3
  SubjectType
4
- } from "./chunk-W4CPVA4J.mjs";
4
+ } from "./chunk-SPOFDHOW.mjs";
5
5
  import "./chunk-2L4QPE5A.mjs";
6
6
  export {
7
7
  SubjectMetadataController,
@@ -215,4 +215,4 @@ var PermissionsRequestNotFoundError = class extends Error {
215
215
 
216
216
 
217
217
  exports.unauthorized = unauthorized; exports.methodNotFound = methodNotFound; exports.invalidParams = invalidParams; exports.userRejectedRequest = userRejectedRequest; exports.internalError = internalError; exports.InvalidSubjectIdentifierError = InvalidSubjectIdentifierError; exports.UnrecognizedSubjectError = UnrecognizedSubjectError; exports.CaveatMergerDoesNotExistError = CaveatMergerDoesNotExistError; exports.InvalidMergedPermissionsError = InvalidMergedPermissionsError; exports.InvalidApprovedPermissionError = InvalidApprovedPermissionError; exports.PermissionDoesNotExistError = PermissionDoesNotExistError; exports.EndowmentPermissionDoesNotExistError = EndowmentPermissionDoesNotExistError; exports.UnrecognizedCaveatTypeError = UnrecognizedCaveatTypeError; exports.InvalidCaveatsPropertyError = InvalidCaveatsPropertyError; exports.CaveatDoesNotExistError = CaveatDoesNotExistError; exports.CaveatAlreadyExistsError = CaveatAlreadyExistsError; exports.InvalidCaveatError = InvalidCaveatError; exports.InvalidCaveatTypeError = InvalidCaveatTypeError; exports.CaveatMissingValueError = CaveatMissingValueError; exports.CaveatInvalidJsonError = CaveatInvalidJsonError; exports.InvalidCaveatFieldsError = InvalidCaveatFieldsError; exports.ForbiddenCaveatError = ForbiddenCaveatError; exports.DuplicateCaveatError = DuplicateCaveatError; exports.CaveatMergeTypeMismatchError = CaveatMergeTypeMismatchError; exports.CaveatSpecificationMismatchError = CaveatSpecificationMismatchError; exports.PermissionsRequestNotFoundError = PermissionsRequestNotFoundError;
218
- //# sourceMappingURL=chunk-3X6WO7UG.js.map
218
+ //# sourceMappingURL=chunk-4YXP3WEE.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAiBA,SAAS,aAAa,MAAuB;AAClD,SAAO,eAAe,aAAa;AAAA,IACjC,SACE;AAAA,IACF,MAAM,KAAK;AAAA,EACb,CAAC;AACH;AASO,SAAS,eAAe,QAAgB,MAA8B;AAC3E,QAAM,UAAU,eAAe,MAAM;AAErC,QAAM,OAAuD,EAAE,QAAQ;AACvE,MAAI,SAAS,QAAW;AACtB,SAAK,OAAO;AAAA,EACd;AACA,SAAO,UAAU,eAAe,IAAI;AACtC;AAaO,SAAS,cAAc,MAAwB;AACpD,SAAO,UAAU,cAAc;AAAA,IAC7B,MAAM,KAAK;AAAA,IACX,SAAS,KAAK;AAAA,EAChB,CAAC;AACH;AAQO,SAAS,oBACd,MACoB;AACpB,SAAO,eAAe,oBAAoB,EAAE,KAAK,CAAC;AACpD;AASO,SAAS,cACd,SACA,MACoB;AACpB,SAAO,UAAU,SAAS,EAAE,SAAS,KAAK,CAAC;AAC7C;AAEO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YA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E,QAAQ,QAAQ,OAAO;AAAA,EACvC;AACF;AAEO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAOlD,YAAY,QAAiC,QAAgB,QAAgB;AAC3E;AAAA,MACE,4CAA4C,OAAO,KAAK,MAAM,EAAE,MAAM;AAAA,IACxE;AACA,SAAK,OAAO,EAAE,QAAQ,QAAQ,OAAO;AAAA,EACvC;AACF;AAEO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAO9C,YAAY,YAAoB,QAAgB,YAAoB;AAClE;AAAA,MACE,2BAA2B,UAAU,mCAAmC,UAAU;AAAA,IACpF;AACA,SAAK,OAAO,EAAE,YAAY,QAAQ,QAAQ,WAAW;AAAA,EACvD;AACF;AAEO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAO9C,YAAY,YAAoB,QAAgB,YAAoB;AAClE;AAAA,MACE,2BAA2B,UAAU,wCAAwC,UAAU;AAAA,IACzF;AACA,SAAK,OAAO,EAAE,YAAY,QAAQ,QAAQ,WAAW;AAAA,EACvD;AACF;AAEO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAMtD,YAAY,gBAAwB,iBAAyB;AAC3D;AAAA,MACE,6CAA6C,cAAc,UAAU,eAAe;AAAA,IACtF;AACA,SAAK,OAAO,EAAE,gBAAgB,gBAAgB;AAAA,EAChD;AACF;AAEO,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAM1D,YACE,YACA,gBACA;AACA;AAAA,MACE,qEAAqE,cAAc;AAAA,IACrF;AACA,SAAK,OAAO,EAAE,YAAY,eAAe;AAAA,EAC3C;AACF;AAEO,IAAM,kCAAN,cAA8C,MAAM;AAAA,EACzD,YAAY,IAAY;AACtB,UAAM,gCAAgC,EAAE,cAAc;AAAA,EACxD;AACF","sourcesContent":["import type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport {\n errorCodes,\n providerErrors,\n rpcErrors,\n JsonRpcError,\n} from '@metamask/rpc-errors';\n\nimport type { CaveatConstraint } from './Caveat';\nimport type { PermissionType } from './Permission';\nimport type { PermissionDiffMap } from './PermissionController';\n\ntype UnauthorizedArg = {\n data?: Record<string, unknown>;\n message?: string;\n};\n\n/**\n * Utility function for building an \"unauthorized\" error.\n *\n * @param opts - Optional arguments that add extra context\n * @returns The built error\n */\nexport function unauthorized(opts: UnauthorizedArg) {\n return providerErrors.unauthorized({\n message:\n 'Unauthorized to perform action. Try requesting the required permission(s) first. For more information, see: https://docs.metamask.io/guide/rpc-api.html#permissions',\n data: opts.data,\n });\n}\n\n/**\n * Utility function for building a \"method not found\" error.\n *\n * @param method - The method in question.\n * @param data - Optional data for context.\n * @returns The built error\n */\nexport function methodNotFound(method: string, data?: DataWithOptionalCause) {\n const message = `The method \"${method}\" does not exist / is not available.`;\n\n const opts: Parameters<typeof rpcErrors.methodNotFound>[0] = { message };\n if (data !== undefined) {\n opts.data = data;\n }\n return rpcErrors.methodNotFound(opts);\n}\n\ntype InvalidParamsArg = {\n message?: string;\n data?: DataWithOptionalCause;\n};\n\n/**\n * Utility function for building an \"invalid params\" error.\n *\n * @param opts - Optional arguments that add extra context\n * @returns The built error\n */\nexport function invalidParams(opts: InvalidParamsArg) {\n return rpcErrors.invalidParams({\n data: opts.data,\n message: opts.message,\n });\n}\n\n/**\n * Utility function for building an \"user rejected request\" error.\n *\n * @param data - Optional data to add extra context\n * @returns The built error\n */\nexport function userRejectedRequest<Data extends Record<string, unknown>>(\n data?: Data,\n): JsonRpcError<Data> {\n return providerErrors.userRejectedRequest({ data });\n}\n\n/**\n * Utility function for building an internal error.\n *\n * @param message - The error message\n * @param data - Optional data to add extra context\n * @returns The built error\n */\nexport function internalError<Data extends Record<string, unknown>>(\n message: string,\n data?: Data,\n): JsonRpcError<Data> {\n return rpcErrors.internal({ message, data });\n}\n\nexport class InvalidSubjectIdentifierError extends Error {\n constructor(origin: unknown) {\n super(\n `Invalid subject identifier: \"${\n typeof origin === 'string' ? origin : typeof origin\n }\"`,\n );\n }\n}\n\nexport class UnrecognizedSubjectError extends Error {\n constructor(origin: string) {\n super(`Unrecognized subject: \"${origin}\" has no permissions.`);\n }\n}\n\nexport class CaveatMergerDoesNotExistError extends Error {\n constructor(caveatType: string) {\n super(`Caveat value merger does not exist for type: \"${caveatType}\"`);\n }\n}\n\nexport class InvalidMergedPermissionsError extends Error {\n public cause: Error;\n\n public data: {\n diff: PermissionDiffMap<string, CaveatConstraint>;\n };\n\n constructor(\n origin: string,\n cause: Error,\n diff: PermissionDiffMap<string, CaveatConstraint>,\n ) {\n super(\n `Invalid merged permissions for subject \"${origin}\":\\n${cause.message}`,\n );\n this.cause = cause;\n this.data = { diff };\n }\n}\n\nexport class InvalidApprovedPermissionError extends Error {\n public data: {\n origin: string;\n target: string;\n approvedPermission: Record<string, unknown>;\n };\n\n constructor(\n origin: string,\n target: string,\n approvedPermission: Record<string, unknown>,\n ) {\n super(\n `Invalid approved permission for origin \"${origin}\" and target \"${target}\".`,\n );\n this.data = { origin, target, approvedPermission };\n }\n}\nexport class PermissionDoesNotExistError extends Error {\n constructor(origin: string, target: string) {\n super(`Subject \"${origin}\" has no permission for \"${target}\".`);\n }\n}\n\nexport class EndowmentPermissionDoesNotExistError extends Error {\n public data?: { origin: string };\n\n constructor(target: string, origin?: string) {\n super(`Subject \"${origin}\" has no permission for \"${target}\".`);\n if (origin) {\n this.data = { origin };\n }\n }\n}\n\nexport class UnrecognizedCaveatTypeError extends Error {\n public data: {\n caveatType: string;\n origin?: string;\n target?: string;\n };\n\n constructor(caveatType: string);\n\n constructor(caveatType: string, origin: string, target: string);\n\n constructor(caveatType: string, origin?: string, target?: string) {\n super(`Unrecognized caveat type: \"${caveatType}\"`);\n this.data = { caveatType };\n if (origin !== undefined) {\n this.data.origin = origin;\n }\n\n if (target !== undefined) {\n this.data.target = target;\n }\n }\n}\n\nexport class InvalidCaveatsPropertyError extends Error {\n public data: { origin: string; target: string; caveatsProperty: unknown };\n\n constructor(origin: string, target: string, caveatsProperty: unknown) {\n super(\n `The \"caveats\" property of permission for \"${target}\" of subject \"${origin}\" is invalid. It must be a non-empty array if specified.`,\n );\n this.data = { origin, target, caveatsProperty };\n }\n}\n\nexport class CaveatDoesNotExistError extends Error {\n constructor(origin: string, target: string, caveatType: string) {\n super(\n `Permission for \"${target}\" of subject \"${origin}\" has no caveat of type \"${caveatType}\".`,\n );\n }\n}\n\nexport class CaveatAlreadyExistsError extends Error {\n constructor(origin: string, target: string, caveatType: string) {\n super(\n `Permission for \"${target}\" of subject \"${origin}\" already has a caveat of type \"${caveatType}\".`,\n );\n }\n}\n\nexport class InvalidCaveatError extends JsonRpcError<\n DataWithOptionalCause | undefined\n> {\n public override data: { origin: string; target: string };\n\n constructor(receivedCaveat: unknown, origin: string, target: string) {\n super(\n errorCodes.rpc.invalidParams,\n `Invalid caveat. Caveats must be plain objects.`,\n { receivedCaveat },\n );\n this.data = { origin, target };\n }\n}\n\nexport class InvalidCaveatTypeError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat types must be strings. Received: \"${typeof caveat.type}\"`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class CaveatMissingValueError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat is missing \"value\" field.`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class CaveatInvalidJsonError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat \"value\" is invalid JSON.`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class InvalidCaveatFieldsError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(\n `Caveat has unexpected number of fields: \"${Object.keys(caveat).length}\"`,\n );\n this.data = { caveat, origin, target };\n }\n}\n\nexport class ForbiddenCaveatError extends Error {\n public data: {\n caveatType: string;\n origin: string;\n target: string;\n };\n\n constructor(caveatType: string, origin: string, targetName: string) {\n super(\n `Permissions for target \"${targetName}\" may not have caveats of type \"${caveatType}\".`,\n );\n this.data = { caveatType, origin, target: targetName };\n }\n}\n\nexport class DuplicateCaveatError extends Error {\n public data: {\n caveatType: string;\n origin: string;\n target: string;\n };\n\n constructor(caveatType: string, origin: string, targetName: string) {\n super(\n `Permissions for target \"${targetName}\" contains multiple caveats of type \"${caveatType}\".`,\n );\n this.data = { caveatType, origin, target: targetName };\n }\n}\n\nexport class CaveatMergeTypeMismatchError extends Error {\n public data: {\n leftCaveatType: string;\n rightCaveatType: string;\n };\n\n constructor(leftCaveatType: string, rightCaveatType: string) {\n super(\n `Cannot merge caveats of different types: \"${leftCaveatType}\" and \"${rightCaveatType}\".`,\n );\n this.data = { leftCaveatType, rightCaveatType };\n }\n}\n\nexport class CaveatSpecificationMismatchError extends Error {\n public data: {\n caveatSpec: Record<string, unknown>;\n permissionType: PermissionType;\n };\n\n constructor(\n caveatSpec: Record<string, unknown>,\n permissionType: PermissionType,\n ) {\n super(\n `Caveat specification uses a mismatched type. Expected caveats for ${permissionType}`,\n );\n this.data = { caveatSpec, permissionType };\n }\n}\n\nexport class PermissionsRequestNotFoundError extends Error {\n constructor(id: string) {\n super(`Permissions request with id \"${id}\" not found.`);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAiBA,SAAS,aAAa,MAAuB;AAClD,SAAO,eAAe,aAAa;AAAA,IACjC,SACE;AAAA,IACF,MAAM,KAAK;AAAA,EACb,CAAC;AACH;AASO,SAAS,eAAe,QAAgB,MAA8B;AAC3E,QAAM,UAAU,eAAe,MAAM;AAErC,QAAM,OAAuD,EAAE,QAAQ;AACvE,MAAI,SAAS,QAAW;AACtB,SAAK,OAAO;AAAA,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YACA,gBACA;AACA;AAAA,MACE,qEAAqE,cAAc;AAAA,IACrF;AACA,SAAK,OAAO,EAAE,YAAY,eAAe;AAAA,EAC3C;AACF;AAEO,IAAM,kCAAN,cAA8C,MAAM;AAAA,EACzD,YAAY,IAAY;AACtB,UAAM,gCAAgC,EAAE,cAAc;AAAA,EACxD;AACF","sourcesContent":["import type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport {\n errorCodes,\n providerErrors,\n rpcErrors,\n JsonRpcError,\n} from '@metamask/rpc-errors';\n\nimport type { CaveatConstraint } from './Caveat';\nimport type { PermissionType } from './Permission';\nimport type { PermissionDiffMap } from './PermissionController';\n\ntype UnauthorizedArg = {\n data?: Record<string, unknown>;\n message?: string;\n};\n\n/**\n * Utility function for building an \"unauthorized\" error.\n *\n * @param opts - Optional arguments that add extra context\n * @returns The built error\n */\nexport function unauthorized(opts: UnauthorizedArg) {\n return providerErrors.unauthorized({\n message:\n 'Unauthorized to perform action. Try requesting the required permission(s) first. For more information, see: https://docs.metamask.io/guide/rpc-api.html#permissions',\n data: opts.data,\n });\n}\n\n/**\n * Utility function for building a \"method not found\" error.\n *\n * @param method - The method in question.\n * @param data - Optional data for context.\n * @returns The built error\n */\nexport function methodNotFound(method: string, data?: DataWithOptionalCause) {\n const message = `The method \"${method}\" does not exist / is not available.`;\n\n const opts: Parameters<typeof rpcErrors.methodNotFound>[0] = { message };\n if (data !== undefined) {\n opts.data = data;\n }\n return rpcErrors.methodNotFound(opts);\n}\n\ntype InvalidParamsArg = {\n message?: string;\n data?: DataWithOptionalCause;\n};\n\n/**\n * Utility function for building an \"invalid params\" error.\n *\n * @param opts - Optional arguments that add extra context\n * @returns The built error\n */\nexport function invalidParams(opts: InvalidParamsArg) {\n return rpcErrors.invalidParams({\n data: opts.data,\n message: opts.message,\n });\n}\n\n/**\n * Utility function for building an \"user rejected request\" error.\n *\n * @param data - Optional data to add extra context\n * @returns The built error\n */\nexport function userRejectedRequest<Data extends Record<string, unknown>>(\n data?: Data,\n): JsonRpcError<Data> {\n return providerErrors.userRejectedRequest({ data });\n}\n\n/**\n * Utility function for building an internal error.\n *\n * @param message - The error message\n * @param data - Optional data to add extra context\n * @returns The built error\n */\nexport function internalError<Data extends Record<string, unknown>>(\n message: string,\n data?: Data,\n): JsonRpcError<Data> {\n return rpcErrors.internal({ message, data });\n}\n\nexport class InvalidSubjectIdentifierError extends Error {\n constructor(origin: unknown) {\n super(\n `Invalid subject identifier: \"${\n typeof origin === 'string' ? origin : typeof origin\n }\"`,\n );\n }\n}\n\nexport class UnrecognizedSubjectError extends Error {\n constructor(origin: string) {\n super(`Unrecognized subject: \"${origin}\" has no permissions.`);\n }\n}\n\nexport class CaveatMergerDoesNotExistError extends Error {\n constructor(caveatType: string) {\n super(`Caveat value merger does not exist for type: \"${caveatType}\"`);\n }\n}\n\nexport class InvalidMergedPermissionsError extends Error {\n public cause: Error;\n\n public data: {\n diff: PermissionDiffMap<string, CaveatConstraint>;\n };\n\n constructor(\n origin: string,\n cause: Error,\n diff: PermissionDiffMap<string, CaveatConstraint>,\n ) {\n super(\n `Invalid merged permissions for subject \"${origin}\":\\n${cause.message}`,\n );\n this.cause = cause;\n this.data = { diff };\n }\n}\n\nexport class InvalidApprovedPermissionError extends Error {\n public data: {\n origin: string;\n target: string;\n approvedPermission: Record<string, unknown>;\n };\n\n constructor(\n origin: string,\n target: string,\n approvedPermission: Record<string, unknown>,\n ) {\n super(\n `Invalid approved permission for origin \"${origin}\" and target \"${target}\".`,\n );\n this.data = { origin, target, approvedPermission };\n }\n}\nexport class PermissionDoesNotExistError extends Error {\n constructor(origin: string, target: string) {\n super(`Subject \"${origin}\" has no permission for \"${target}\".`);\n }\n}\n\nexport class EndowmentPermissionDoesNotExistError extends Error {\n public data?: { origin: string };\n\n constructor(target: string, origin?: string) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n super(`Subject \"${origin}\" has no permission for \"${target}\".`);\n if (origin) {\n this.data = { origin };\n }\n }\n}\n\nexport class UnrecognizedCaveatTypeError extends Error {\n public data: {\n caveatType: string;\n origin?: string;\n target?: string;\n };\n\n constructor(caveatType: string);\n\n constructor(caveatType: string, origin: string, target: string);\n\n constructor(caveatType: string, origin?: string, target?: string) {\n super(`Unrecognized caveat type: \"${caveatType}\"`);\n this.data = { caveatType };\n if (origin !== undefined) {\n this.data.origin = origin;\n }\n\n if (target !== undefined) {\n this.data.target = target;\n }\n }\n}\n\nexport class InvalidCaveatsPropertyError extends Error {\n public data: { origin: string; target: string; caveatsProperty: unknown };\n\n constructor(origin: string, target: string, caveatsProperty: unknown) {\n super(\n `The \"caveats\" property of permission for \"${target}\" of subject \"${origin}\" is invalid. It must be a non-empty array if specified.`,\n );\n this.data = { origin, target, caveatsProperty };\n }\n}\n\nexport class CaveatDoesNotExistError extends Error {\n constructor(origin: string, target: string, caveatType: string) {\n super(\n `Permission for \"${target}\" of subject \"${origin}\" has no caveat of type \"${caveatType}\".`,\n );\n }\n}\n\nexport class CaveatAlreadyExistsError extends Error {\n constructor(origin: string, target: string, caveatType: string) {\n super(\n `Permission for \"${target}\" of subject \"${origin}\" already has a caveat of type \"${caveatType}\".`,\n );\n }\n}\n\nexport class InvalidCaveatError extends JsonRpcError<\n DataWithOptionalCause | undefined\n> {\n public override data: { origin: string; target: string };\n\n constructor(receivedCaveat: unknown, origin: string, target: string) {\n super(\n errorCodes.rpc.invalidParams,\n `Invalid caveat. Caveats must be plain objects.`,\n { receivedCaveat },\n );\n this.data = { origin, target };\n }\n}\n\nexport class InvalidCaveatTypeError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat types must be strings. Received: \"${typeof caveat.type}\"`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class CaveatMissingValueError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat is missing \"value\" field.`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class CaveatInvalidJsonError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(`Caveat \"value\" is invalid JSON.`);\n this.data = { caveat, origin, target };\n }\n}\n\nexport class InvalidCaveatFieldsError extends Error {\n public data: {\n caveat: Record<string, unknown>;\n origin: string;\n target: string;\n };\n\n constructor(caveat: Record<string, unknown>, origin: string, target: string) {\n super(\n `Caveat has unexpected number of fields: \"${Object.keys(caveat).length}\"`,\n );\n this.data = { caveat, origin, target };\n }\n}\n\nexport class ForbiddenCaveatError extends Error {\n public data: {\n caveatType: string;\n origin: string;\n target: string;\n };\n\n constructor(caveatType: string, origin: string, targetName: string) {\n super(\n `Permissions for target \"${targetName}\" may not have caveats of type \"${caveatType}\".`,\n );\n this.data = { caveatType, origin, target: targetName };\n }\n}\n\nexport class DuplicateCaveatError extends Error {\n public data: {\n caveatType: string;\n origin: string;\n target: string;\n };\n\n constructor(caveatType: string, origin: string, targetName: string) {\n super(\n `Permissions for target \"${targetName}\" contains multiple caveats of type \"${caveatType}\".`,\n );\n this.data = { caveatType, origin, target: targetName };\n }\n}\n\nexport class CaveatMergeTypeMismatchError extends Error {\n public data: {\n leftCaveatType: string;\n rightCaveatType: string;\n };\n\n constructor(leftCaveatType: string, rightCaveatType: string) {\n super(\n `Cannot merge caveats of different types: \"${leftCaveatType}\" and \"${rightCaveatType}\".`,\n );\n this.data = { leftCaveatType, rightCaveatType };\n }\n}\n\nexport class CaveatSpecificationMismatchError extends Error {\n public data: {\n caveatSpec: Record<string, unknown>;\n permissionType: PermissionType;\n };\n\n constructor(\n caveatSpec: Record<string, unknown>,\n permissionType: PermissionType,\n ) {\n super(\n `Caveat specification uses a mismatched type. Expected caveats for ${permissionType}`,\n );\n this.data = { caveatSpec, permissionType };\n }\n}\n\nexport class PermissionsRequestNotFoundError extends Error {\n constructor(id: string) {\n super(`Permissions request with id \"${id}\" not found.`);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  internalError
3
- } from "./chunk-AZUM6CBY.mjs";
3
+ } from "./chunk-VHHS2FJX.mjs";
4
4
 
5
5
  // src/permission-middleware.ts
6
6
  import { createAsyncMiddleware } from "@metamask/json-rpc-engine";
@@ -43,4 +43,4 @@ function getPermissionMiddlewareFactory({
43
43
  export {
44
44
  getPermissionMiddlewareFactory
45
45
  };
46
- //# sourceMappingURL=chunk-RXC2KFRK.mjs.map
46
+ //# sourceMappingURL=chunk-5NYMBY4A.mjs.map
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunk3X6WO7UGjs = require('./chunk-3X6WO7UG.js');
3
+ var _chunk4YXP3WEEjs = require('./chunk-4YXP3WEE.js');
4
4
 
5
5
  // src/rpc-methods/revokePermissions.ts
6
6
 
@@ -17,11 +17,11 @@ async function revokePermissionsImplementation(req, res, _next, end, { revokePer
17
17
  const { params } = req;
18
18
  const param = params?.[0];
19
19
  if (!param) {
20
- return end(_chunk3X6WO7UGjs.invalidParams.call(void 0, { data: { request: req } }));
20
+ return end(_chunk4YXP3WEEjs.invalidParams.call(void 0, { data: { request: req } }));
21
21
  }
22
22
  const permissionKeys = Object.keys(param);
23
23
  if (!_utils.isNonEmptyArray.call(void 0, permissionKeys)) {
24
- return end(_chunk3X6WO7UGjs.invalidParams.call(void 0, { data: { request: req } }));
24
+ return end(_chunk4YXP3WEEjs.invalidParams.call(void 0, { data: { request: req } }));
25
25
  }
26
26
  revokePermissionsForOrigin(permissionKeys);
27
27
  res.result = null;
@@ -31,4 +31,4 @@ async function revokePermissionsImplementation(req, res, _next, end, { revokePer
31
31
 
32
32
 
33
33
  exports.revokePermissionsHandler = revokePermissionsHandler;
34
- //# sourceMappingURL=chunk-GHOOCGN3.js.map
34
+ //# sourceMappingURL=chunk-6UCIDD5V.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  CaveatSpecificationMismatchError,
3
3
  UnrecognizedCaveatTypeError
4
- } from "./chunk-AZUM6CBY.mjs";
4
+ } from "./chunk-VHHS2FJX.mjs";
5
5
 
6
6
  // src/Caveat.ts
7
7
  import { hasProperty } from "@metamask/utils";
@@ -34,4 +34,4 @@ export {
34
34
  isRestrictedMethodCaveatSpecification,
35
35
  decorateWithCaveats
36
36
  };
37
- //# sourceMappingURL=chunk-RJKSCKTD.mjs.map
37
+ //# sourceMappingURL=chunk-6V5UTS24.mjs.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  decorateWithCaveats,
3
3
  isRestrictedMethodCaveatSpecification
4
- } from "./chunk-RJKSCKTD.mjs";
4
+ } from "./chunk-6V5UTS24.mjs";
5
5
  import {
6
6
  PermissionType,
7
7
  constructPermission,
@@ -10,7 +10,7 @@ import {
10
10
  } from "./chunk-HYMS7IGB.mjs";
11
11
  import {
12
12
  getPermissionMiddlewareFactory
13
- } from "./chunk-RXC2KFRK.mjs";
13
+ } from "./chunk-5NYMBY4A.mjs";
14
14
  import {
15
15
  CaveatAlreadyExistsError,
16
16
  CaveatDoesNotExistError,
@@ -38,10 +38,10 @@ import {
38
38
  methodNotFound,
39
39
  unauthorized,
40
40
  userRejectedRequest
41
- } from "./chunk-AZUM6CBY.mjs";
41
+ } from "./chunk-VHHS2FJX.mjs";
42
42
  import {
43
43
  collectUniqueAndPairedCaveats
44
- } from "./chunk-3R56AY2L.mjs";
44
+ } from "./chunk-ZTBBRCDR.mjs";
45
45
  import {
46
46
  __privateAdd,
47
47
  __privateMethod
@@ -150,6 +150,8 @@ var PermissionController = class extends BaseController {
150
150
  * @param rightCaveat - The right-hand caveat to merge.
151
151
  * @returns The merged caveat and the diff between the two caveats.
152
152
  */
153
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
154
+ // eslint-disable-next-line @typescript-eslint/naming-convention
153
155
  __privateAdd(this, _mergeCaveat);
154
156
  /**
155
157
  * Accepts a permissions request that has been approved by the user. This
@@ -1676,4 +1678,4 @@ export {
1676
1678
  CaveatMutatorOperation,
1677
1679
  PermissionController
1678
1680
  };
1679
- //# sourceMappingURL=chunk-4B6NOD2D.mjs.map
1681
+ //# sourceMappingURL=chunk-7WEYLBME.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/PermissionController.ts"],"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, produce as immerProduce, type Draft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport type {\n CaveatConstraint,\n CaveatDiffMap,\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n CaveatValueMerger,\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 CaveatMergerDoesNotExistError,\n CaveatMergeTypeMismatchError,\n CaveatMissingValueError,\n CaveatSpecificationMismatchError,\n DuplicateCaveatError,\n EndowmentPermissionDoesNotExistError,\n ForbiddenCaveatError,\n internalError,\n InvalidApprovedPermissionError,\n InvalidCaveatError,\n InvalidCaveatFieldsError,\n InvalidCaveatsPropertyError,\n InvalidCaveatTypeError,\n InvalidMergedPermissionsError,\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 { collectUniqueAndPairedCaveats, 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 [key: string]: Json;\n};\n\n/**\n * A diff produced by an incremental permissions request.\n */\nexport type PermissionDiffMap<\n TargetName extends string,\n AllowedCaveats extends CaveatConstraint,\n> = Record<TargetName, CaveatDiffMap<AllowedCaveats>>;\n\n/**\n * Used for prompting the user about a proposed new permission.\n * Includes information about the grantee subject, requested permissions, the\n * diff relative to the previously granted permissions (if relevant), and any\n * additional information added by the consumer.\n *\n * All properties except `diff` and `permissions` are passed to any factories\n * for the requested permissions.\n */\nexport type PermissionsRequest = {\n metadata: PermissionsRequestMetadata;\n permissions: RequestedPermissions;\n [key: string]: Json;\n} & {\n diff?: {\n currentPermissions: SubjectPermissions<PermissionConstraint>;\n permissionDiffMap: PermissionDiffMap<string, CaveatConstraint>;\n };\n};\n\n/**\n * Metadata associated with an approved permission request.\n */\ntype ApprovedPermissionsMetadata = {\n data?: Record<string, unknown>;\n id: string;\n origin: OriginString;\n};\n\nexport type SideEffects = {\n permittedHandlers: Record<\n string,\n SideEffectHandler<ActionConstraint, EventConstraint>\n >;\n failureHandlers: Record<\n string,\n SideEffectHandler<ActionConstraint, EventConstraint>\n >;\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/**\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 * Directly grants given permissions for a specificed origin without requesting user approval\n */\nexport type GrantPermissionsIncremental = {\n type: `${typeof controllerName}:grantPermissionsIncremental`;\n handler: GenericPermissionController['grantPermissionsIncremental'];\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 * Requests given permissions for a specified origin\n */\nexport type RequestPermissionsIncremental = {\n type: `${typeof controllerName}:requestPermissionsIncremental`;\n handler: GenericPermissionController['requestPermissionsIncremental'];\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 | GrantPermissionsIncremental\n | RequestPermissions\n | RequestPermissionsIncremental\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 | AllowedActions,\n Events,\n AllowedActions['type'] | Actions['type'],\n Events['type']\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n noop,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n updateValue,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n deleteCaveat,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype MergeCaveatResult<T extends CaveatConstraint | undefined> =\n T extends undefined\n ? [CaveatConstraint, CaveatConstraint['value']]\n : [CaveatConstraint, CaveatConstraint['value']] | [];\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 * Gets the merger function for the specified caveat. Throws if no\n * merger exists.\n *\n * @param caveatType - The type of the caveat whose merger to get.\n * @returns The caveat value merger function for the specified caveat type.\n */\n #expectGetCaveatMerger<\n CaveatType extends ControllerCaveatSpecification['type'],\n >(caveatType: CaveatType): CaveatValueMerger<Json> {\n const { merger } = this.getCaveatSpecification(caveatType);\n\n if (merger === undefined) {\n throw new CaveatMergerDoesNotExistError(caveatType);\n }\n return merger;\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}:grantPermissionsIncremental` as const,\n this.grantPermissionsIncremental.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}:requestPermissionsIncremental` as const,\n (subject: PermissionSubjectMetadata, permissions: RequestedPermissions) =>\n this.requestPermissionsIncremental(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 // At this point, we don't know if the specific permission is allowed\n // to have caveats, but it should be impossible to call this method\n // for a permission that may not have any caveats. If all else fails,\n // the permission validator is also called.\n // @ts-expect-error See above comment\n permission.caveats = [caveat];\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 const { operation } = mutatorResult;\n switch (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 // Overriding as `never` is the expected result of exhaustiveness checking,\n // and is intended to represent unchecked exception cases.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n throw new Error(`Unrecognized mutation result: \"${operation}\"`);\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 ControllerPermissionSpecification['targetName'],\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 their specification\n * validators—and an error is thrown if validation fails.\n *\n * ATTN: This method does **not** prompt the user for approval. User consent must\n * first be obtained through some other means.\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 subject's new permission state. It may or may not have changed.\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 }): Partial<\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n > {\n return this.#applyGrantedPermissions({\n approvedPermissions,\n subject,\n mergePermissions: false,\n preserveExistingPermissions,\n requestData,\n });\n }\n\n /**\n * Incrementally grants _approved_ permissions to the specified subject. Every\n * permission and caveat is stringently validated—including by calling their\n * specification validators—and an error is thrown if validation fails.\n *\n * ATTN: This method does **not** prompt the user for approval. User consent must\n * first be obtained through some other means.\n *\n * @see {@link PermissionController.requestPermissionsIncremental} For initiating\n * an incremental 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.subject - The subject to grant permissions to.\n * @returns The subject's new permission state. It may or may not have changed.\n */\n grantPermissionsIncremental({\n approvedPermissions,\n requestData,\n subject,\n }: {\n approvedPermissions: RequestedPermissions;\n subject: PermissionSubjectMetadata;\n requestData?: Record<string, unknown>;\n }): Partial<\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n > {\n return this.#applyGrantedPermissions({\n approvedPermissions,\n subject,\n mergePermissions: true,\n preserveExistingPermissions: true,\n requestData,\n });\n }\n\n #applyGrantedPermissions({\n approvedPermissions,\n subject,\n mergePermissions,\n preserveExistingPermissions,\n requestData,\n }: {\n approvedPermissions: RequestedPermissions;\n subject: PermissionSubjectMetadata;\n mergePermissions: boolean;\n preserveExistingPermissions: boolean;\n requestData?: Record<string, unknown>;\n }): Partial<\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\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 let performCaveatValidation = true;\n\n if (specification.factory) {\n permission = specification.factory(permissionOptions, requestData);\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 performCaveatValidation = false;\n }\n\n if (mergePermissions) {\n permission = this.#mergePermission(\n permissions[targetName],\n permission,\n )[0];\n }\n\n this.validatePermission(specification, permission, origin, {\n invokePermissionValidator: true,\n performCaveatValidation,\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.\n *\n * Either this or {@link PermissionController.requestPermissionsIncremental}\n * should always be used to grant additional permissions to a subject,\n * unless user 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 * @param options.metadata - Additional metadata about the permission request.\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 metadata?: Record<string, Json>;\n } = {},\n ): Promise<\n [\n Partial<\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n >,\n ApprovedPermissionsMetadata,\n ]\n > {\n const { origin } = subject;\n const { id = nanoid(), preserveExistingPermissions = true } = options;\n this.validateRequestedPermissions(origin, requestedPermissions);\n\n const metadata = {\n ...options.metadata,\n id,\n origin,\n };\n\n const permissionsRequest: PermissionsRequest = {\n metadata,\n permissions: requestedPermissions,\n };\n\n const approvedRequest = await this.requestUserApproval(permissionsRequest);\n return await this.#handleApprovedPermissions({\n subject,\n metadata,\n preserveExistingPermissions,\n approvedRequest,\n });\n }\n\n /**\n * Initiates an incremental permission request that prompts for user approval.\n * Incremental permission requests allow the caller to replace existing and/or\n * add brand new permissions and caveats for the specified subject.\n *\n * Incremental permission request are merged with the subject's existing permissions\n * through a right-biased union, where the incremental permission are the right-hand\n * side of the merger. If both sides of the merger specify the same caveats for a\n * given permission, the caveats are merged using their specification's caveat value\n * merger property.\n *\n * Either this or {@link PermissionController.requestPermissions} 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.metadata - Additional metadata about the permission request.\n * @returns The granted permissions and request metadata.\n */\n async requestPermissionsIncremental(\n subject: PermissionSubjectMetadata,\n requestedPermissions: RequestedPermissions,\n options: {\n id?: string;\n metadata?: Record<string, Json>;\n } = {},\n ): Promise<\n | [\n Partial<\n SubjectPermissions<\n ExtractPermission<\n ControllerPermissionSpecification,\n ControllerCaveatSpecification\n >\n >\n >,\n ApprovedPermissionsMetadata,\n ]\n | []\n > {\n const { origin } = subject;\n const { id = nanoid() } = options;\n this.validateRequestedPermissions(origin, requestedPermissions);\n\n const currentPermissions = this.getPermissions(origin) ?? {};\n const [newPermissions, permissionDiffMap] =\n this.#mergeIncrementalPermissions(\n currentPermissions,\n requestedPermissions,\n );\n\n // The second undefined check is just for type narrowing purposes. These values\n // will always be jointly defined or undefined.\n if (newPermissions === undefined || permissionDiffMap === undefined) {\n return [];\n }\n\n try {\n // It does not spark joy to run this validation again after the merger operation.\n // But, optimizing this procedure is probably not worth it, especially considering\n // that the worst-case scenario for validation degrades to the below function call.\n this.validateRequestedPermissions(origin, newPermissions);\n } catch (error) {\n if (error instanceof Error) {\n throw new InvalidMergedPermissionsError(\n origin,\n error,\n permissionDiffMap,\n );\n }\n /* istanbul ignore next: This should be impossible */\n throw internalError('Unrecognized error type', { error });\n }\n\n const metadata = {\n ...options.metadata,\n id,\n origin,\n };\n\n const permissionsRequest: PermissionsRequest = {\n metadata,\n permissions: newPermissions,\n diff: {\n currentPermissions,\n permissionDiffMap,\n },\n };\n\n const approvedRequest = await this.requestUserApproval(permissionsRequest);\n return await this.#handleApprovedPermissions({\n subject,\n metadata,\n preserveExistingPermissions: false,\n approvedRequest,\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 * Merges a set of incrementally requested permissions into the existing permissions of\n * the requesting subject. The merge is a right-biased union, where the existing\n * permissions are the left-hand side, and the incrementally requested permissions are\n * the right-hand side.\n *\n * @param existingPermissions - The subject's existing permissions.\n * @param incrementalRequestedPermissions - The requested permissions to merge.\n * @returns The merged permissions and the resulting diff.\n */\n #mergeIncrementalPermissions(\n existingPermissions: Exclude<\n ReturnType<typeof this.getPermissions>,\n undefined\n >,\n incrementalRequestedPermissions: RequestedPermissions,\n ):\n | [\n SubjectPermissions<\n ValidPermission<string, ExtractCaveats<ControllerCaveatSpecification>>\n >,\n PermissionDiffMap<string, CaveatConstraint>,\n ]\n | [] {\n const permissionDiffMap: PermissionDiffMap<string, CaveatConstraint> = {};\n\n // Use immer's produce as a convenience for calculating the new permissions\n // without mutating the existing permissions or committing the results to state.\n const newPermissions = immerProduce(\n existingPermissions,\n (draftExistingPermissions) => {\n const leftPermissions =\n draftExistingPermissions as RequestedPermissions;\n\n Object.entries(incrementalRequestedPermissions).forEach(\n ([targetName, rightPermission]) => {\n const leftPermission: Partial<PermissionConstraint> | undefined =\n leftPermissions[targetName];\n\n const [newPermission, caveatsDiff] = this.#mergePermission(\n leftPermission ?? {},\n rightPermission,\n );\n\n if (\n leftPermission === undefined ||\n Object.keys(caveatsDiff).length > 0\n ) {\n leftPermissions[targetName] = newPermission;\n permissionDiffMap[targetName] = caveatsDiff;\n }\n // Otherwise, leave the left permission as-is; its authority has\n // not changed.\n },\n );\n },\n );\n\n if (Object.keys(permissionDiffMap).length === 0) {\n return [];\n }\n return [newPermissions, permissionDiffMap];\n }\n\n /**\n * Performs a right-biased union between two permissions. The task of merging caveats\n * of the same type between the two permissions is delegated to the corresponding\n * caveat type's merger implementation.\n *\n * Throws if the left-hand and right-hand permissions both have a caveat whose\n * specification does not provide a caveat value merger function.\n *\n * @param leftPermission - The left-hand permission to merge.\n * @param rightPermission - The right-hand permission to merge.\n * @returns The merged permission.\n */\n #mergePermission<\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n T extends Partial<PermissionConstraint> | PermissionConstraint,\n >(\n leftPermission: T | undefined,\n rightPermission: T,\n ): [T, CaveatDiffMap<CaveatConstraint>] {\n const { caveatPairs, leftUniqueCaveats, rightUniqueCaveats } =\n collectUniqueAndPairedCaveats(leftPermission, rightPermission);\n\n const [mergedCaveats, caveatDiffMap] = caveatPairs.reduce(\n ([caveats, diffMap], [leftCaveat, rightCaveat]) => {\n const [newCaveat, diff] = this.#mergeCaveat(leftCaveat, rightCaveat);\n\n if (newCaveat !== undefined && diff !== undefined) {\n caveats.push(newCaveat);\n diffMap[newCaveat.type] = diff;\n } else {\n caveats.push(leftCaveat);\n }\n\n return [caveats, diffMap];\n },\n [[], {}] as [CaveatConstraint[], CaveatDiffMap<CaveatConstraint>],\n );\n\n const mergedRightUniqueCaveats = rightUniqueCaveats.map((caveat) => {\n const [newCaveat, diff] = this.#mergeCaveat(undefined, caveat);\n\n caveatDiffMap[newCaveat.type] = diff;\n return newCaveat;\n });\n\n const allCaveats = [\n ...mergedCaveats,\n ...leftUniqueCaveats,\n ...mergedRightUniqueCaveats,\n ];\n\n const newPermission = {\n ...leftPermission,\n ...rightPermission,\n ...(allCaveats.length > 0\n ? { caveats: allCaveats as NonEmptyArray<CaveatConstraint> }\n : {}),\n };\n\n return [newPermission, caveatDiffMap];\n }\n\n /**\n * Merges two caveats of the same type. The task of merging the values of the\n * two caveats is delegated to the corresponding caveat type's merger implementation.\n *\n * @param leftCaveat - The left-hand caveat to merge.\n * @param rightCaveat - The right-hand caveat to merge.\n * @returns The merged caveat and the diff between the two caveats.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n #mergeCaveat<T extends CaveatConstraint, U extends T | undefined>(\n leftCaveat: U,\n rightCaveat: T,\n ): MergeCaveatResult<U> {\n /* istanbul ignore if: This should be impossible */\n if (leftCaveat !== undefined && leftCaveat.type !== rightCaveat.type) {\n throw new CaveatMergeTypeMismatchError(leftCaveat.type, rightCaveat.type);\n }\n\n const merger = this.#expectGetCaveatMerger(rightCaveat.type);\n\n if (leftCaveat === undefined) {\n return [\n {\n ...rightCaveat,\n },\n rightCaveat.value,\n ];\n }\n\n const [newValue, diff] = merger(leftCaveat.value, rightCaveat.value);\n\n return newValue !== undefined && diff !== undefined\n ? [\n {\n type: rightCaveat.type,\n value: newValue,\n },\n diff,\n ]\n : ([] as MergeCaveatResult<U>);\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 * Accepts a permissions request that has been approved by the user. This\n * method should be called after the user has approved the request and the\n * {@link ApprovalController} has resolved the user approval promise.\n *\n * @param options - Options bag.\n * @param options.subject - The subject to grant permissions to.\n * @param options.metadata - The metadata of the approved permissions request.\n * @param options.preserveExistingPermissions - Whether to preserve the\n * subject's existing permissions.\n * @param options.approvedRequest - The approved permissions request to handle.\n * @returns The granted permissions and request metadata.\n */\n async #handleApprovedPermissions({\n subject,\n metadata,\n preserveExistingPermissions,\n approvedRequest,\n }: {\n subject: PermissionSubjectMetadata;\n metadata: PermissionsRequest['metadata'];\n preserveExistingPermissions: boolean;\n approvedRequest: PermissionsRequest;\n }): Promise<\n [ReturnType<typeof this.grantPermissions>, ApprovedPermissionsMetadata]\n > {\n const { permissions: approvedPermissions, ...requestData } =\n approvedRequest;\n const approvedMetadata: ApprovedPermissionsMetadata = { ...metadata };\n\n const sideEffects = this.getSideEffects(approvedPermissions);\n if (Object.values(sideEffects.permittedHandlers).length > 0) {\n const sideEffectsData = await this.executeSideEffects(\n sideEffects,\n approvedRequest,\n );\n\n approvedMetadata.data = Object.keys(sideEffects.permittedHandlers).reduce(\n (acc, permission, i) => ({ [permission]: sideEffectsData[i], ...acc }),\n {},\n );\n }\n\n return [\n this.grantPermissions({\n subject,\n approvedPermissions,\n preserveExistingPermissions,\n requestData,\n }),\n approvedMetadata,\n ];\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 Error) {\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 instanceof JsonRpcError ? error.data : undefined,\n );\n }\n /* istanbul ignore next: This should be impossible */\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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('ApprovalController:hasRequest', options);\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,sBAAsB;AAE/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB;AAE5B,OAAO,gBAAgB;AACvB,SAAS,WAAW,WAAW,oBAAgC;AAC/D,SAAS,cAAc;AAwIvB,IAAM,iBAAiB;AAiDvB,SAAS,mBAA4D;AACnE,SAAO,EAAE,UAAU,EAAE,WAAW,MAAM,SAAS,KAAK,EAAE;AAGxD;AAQA,SAAS,kBAA2D;AAClE,SAAO,EAAE,UAAU,CAAC,EAAE;AACxB;AA4MO,IAAK,yBAAL,kBAAKA,4BAAL;AAGL,EAAAA,gDAAA;AAGA,EAAAA,gDAAA;AAGA,EAAAA,gDAAA;AAGA,EAAAA,gDAAA;AAZU,SAAAA;AAAA,GAAA;AA9aZ;AAikBO,IAAM,uBAAN,cAGG,eASR;AAAA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