@metamask/permission-controller 11.0.0 → 11.0.2

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 (185) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/dist/Caveat.cjs +48 -0
  3. package/dist/Caveat.cjs.map +1 -0
  4. package/dist/{types/Caveat.d.ts → Caveat.d.cts} +3 -3
  5. package/dist/Caveat.d.cts.map +1 -0
  6. package/dist/Caveat.d.mts +210 -0
  7. package/dist/Caveat.d.mts.map +1 -0
  8. package/dist/Caveat.mjs +42 -11
  9. package/dist/Caveat.mjs.map +1 -1
  10. package/dist/Permission.cjs +65 -0
  11. package/dist/Permission.cjs.map +1 -0
  12. package/dist/{types/Permission.d.ts → Permission.d.cts} +7 -7
  13. package/dist/Permission.d.cts.map +1 -0
  14. package/dist/Permission.d.mts +417 -0
  15. package/dist/Permission.d.mts.map +1 -0
  16. package/dist/Permission.mjs +58 -13
  17. package/dist/Permission.mjs.map +1 -1
  18. package/dist/PermissionController.cjs +1481 -0
  19. package/dist/{chunk-COGJLF22.mjs.map → PermissionController.cjs.map} +1 -1
  20. package/dist/{types/PermissionController.d.ts → PermissionController.d.cts} +10 -10
  21. package/dist/PermissionController.d.cts.map +1 -0
  22. package/dist/PermissionController.d.mts +986 -0
  23. package/dist/PermissionController.d.mts.map +1 -0
  24. package/dist/PermissionController.mjs +1479 -13
  25. package/dist/PermissionController.mjs.map +1 -1
  26. package/dist/SubjectMetadataController.cjs +152 -0
  27. package/dist/SubjectMetadataController.cjs.map +1 -0
  28. package/dist/{types/SubjectMetadataController.d.ts → SubjectMetadataController.d.cts} +5 -5
  29. package/dist/SubjectMetadataController.d.cts.map +1 -0
  30. package/dist/SubjectMetadataController.d.mts +107 -0
  31. package/dist/SubjectMetadataController.d.mts.map +1 -0
  32. package/dist/SubjectMetadataController.mjs +146 -8
  33. package/dist/SubjectMetadataController.mjs.map +1 -1
  34. package/dist/errors.cjs +217 -0
  35. package/dist/errors.cjs.map +1 -0
  36. package/dist/{types/errors.d.ts → errors.d.cts} +6 -6
  37. package/dist/errors.d.cts.map +1 -0
  38. package/dist/errors.d.mts +185 -0
  39. package/dist/errors.d.mts.map +1 -0
  40. package/dist/errors.mjs +187 -57
  41. package/dist/errors.mjs.map +1 -1
  42. package/dist/index.cjs +38 -0
  43. package/dist/index.cjs.map +1 -0
  44. package/dist/index.d.cts +9 -0
  45. package/dist/index.d.cts.map +1 -0
  46. package/dist/index.d.mts +9 -0
  47. package/dist/index.d.mts.map +1 -0
  48. package/dist/index.mjs +7 -97
  49. package/dist/index.mjs.map +1 -1
  50. package/dist/permission-middleware.cjs +55 -0
  51. package/dist/permission-middleware.cjs.map +1 -0
  52. package/dist/{types/permission-middleware.d.ts → permission-middleware.d.cts} +4 -4
  53. package/dist/permission-middleware.d.cts.map +1 -0
  54. package/dist/permission-middleware.d.mts +33 -0
  55. package/dist/permission-middleware.d.mts.map +1 -0
  56. package/dist/permission-middleware.mjs +50 -8
  57. package/dist/permission-middleware.mjs.map +1 -1
  58. package/dist/rpc-methods/getPermissions.cjs +27 -0
  59. package/dist/rpc-methods/getPermissions.cjs.map +1 -0
  60. package/dist/rpc-methods/getPermissions.d.cts +9 -0
  61. package/dist/rpc-methods/getPermissions.d.cts.map +1 -0
  62. package/dist/rpc-methods/getPermissions.d.mts +9 -0
  63. package/dist/rpc-methods/getPermissions.d.mts.map +1 -0
  64. package/dist/rpc-methods/getPermissions.mjs +22 -7
  65. package/dist/rpc-methods/getPermissions.mjs.map +1 -1
  66. package/dist/rpc-methods/index.cjs +12 -0
  67. package/dist/rpc-methods/index.cjs.map +1 -0
  68. package/dist/rpc-methods/index.d.cts +6 -0
  69. package/dist/rpc-methods/index.d.cts.map +1 -0
  70. package/dist/rpc-methods/index.d.mts +6 -0
  71. package/dist/rpc-methods/index.d.mts.map +1 -0
  72. package/dist/rpc-methods/index.mjs +8 -12
  73. package/dist/rpc-methods/index.mjs.map +1 -1
  74. package/dist/rpc-methods/requestPermissions.cjs +36 -0
  75. package/dist/rpc-methods/requestPermissions.cjs.map +1 -0
  76. package/dist/{types/rpc-methods/requestPermissions.d.ts → rpc-methods/requestPermissions.d.cts} +3 -3
  77. package/dist/rpc-methods/requestPermissions.d.cts.map +1 -0
  78. package/dist/rpc-methods/requestPermissions.d.mts +17 -0
  79. package/dist/rpc-methods/requestPermissions.d.mts.map +1 -0
  80. package/dist/rpc-methods/requestPermissions.mjs +31 -8
  81. package/dist/rpc-methods/requestPermissions.mjs.map +1 -1
  82. package/dist/rpc-methods/revokePermissions.cjs +41 -0
  83. package/dist/rpc-methods/revokePermissions.cjs.map +1 -0
  84. package/dist/{types/rpc-methods/revokePermissions.d.ts → rpc-methods/revokePermissions.d.cts} +4 -4
  85. package/dist/rpc-methods/revokePermissions.d.cts.map +1 -0
  86. package/dist/rpc-methods/revokePermissions.d.mts +11 -0
  87. package/dist/rpc-methods/revokePermissions.d.mts.map +1 -0
  88. package/dist/rpc-methods/revokePermissions.mjs +36 -8
  89. package/dist/rpc-methods/revokePermissions.mjs.map +1 -1
  90. package/dist/utils.cjs +44 -0
  91. package/dist/utils.cjs.map +1 -0
  92. package/dist/{types/utils.d.ts → utils.d.cts} +5 -5
  93. package/dist/utils.d.cts.map +1 -0
  94. package/dist/utils.d.mts +57 -0
  95. package/dist/utils.d.mts.map +1 -0
  96. package/dist/utils.mjs +39 -9
  97. package/dist/utils.mjs.map +1 -1
  98. package/package.json +18 -12
  99. package/dist/Caveat.js +0 -12
  100. package/dist/Caveat.js.map +0 -1
  101. package/dist/Permission.js +0 -14
  102. package/dist/Permission.js.map +0 -1
  103. package/dist/PermissionController.js +0 -15
  104. package/dist/PermissionController.js.map +0 -1
  105. package/dist/SubjectMetadataController.js +0 -10
  106. package/dist/SubjectMetadataController.js.map +0 -1
  107. package/dist/chunk-2L4QPE5A.mjs +0 -25
  108. package/dist/chunk-2L4QPE5A.mjs.map +0 -1
  109. package/dist/chunk-3WWJKO7P.mjs +0 -37
  110. package/dist/chunk-3WWJKO7P.mjs.map +0 -1
  111. package/dist/chunk-3YOPLPVY.js +0 -37
  112. package/dist/chunk-3YOPLPVY.js.map +0 -1
  113. package/dist/chunk-42QSJHWO.mjs +0 -155
  114. package/dist/chunk-42QSJHWO.mjs.map +0 -1
  115. package/dist/chunk-4FMYQC3Y.mjs +0 -29
  116. package/dist/chunk-4FMYQC3Y.mjs.map +0 -1
  117. package/dist/chunk-4NAVRO44.mjs +0 -35
  118. package/dist/chunk-4NAVRO44.mjs.map +0 -1
  119. package/dist/chunk-5RFW5THA.mjs +0 -17
  120. package/dist/chunk-5RFW5THA.mjs.map +0 -1
  121. package/dist/chunk-6PXDVUYM.js +0 -29
  122. package/dist/chunk-6PXDVUYM.js.map +0 -1
  123. package/dist/chunk-74H4CVH7.mjs +0 -34
  124. package/dist/chunk-74H4CVH7.mjs.map +0 -1
  125. package/dist/chunk-7A3VYLCK.js +0 -30
  126. package/dist/chunk-7A3VYLCK.js.map +0 -1
  127. package/dist/chunk-B6PDRQ7N.js +0 -1679
  128. package/dist/chunk-B6PDRQ7N.js.map +0 -1
  129. package/dist/chunk-COGJLF22.mjs +0 -1679
  130. package/dist/chunk-F5TBMVWC.js +0 -46
  131. package/dist/chunk-F5TBMVWC.js.map +0 -1
  132. package/dist/chunk-FYADAA2G.js +0 -220
  133. package/dist/chunk-FYADAA2G.js.map +0 -1
  134. package/dist/chunk-G4BWJ7EA.mjs +0 -220
  135. package/dist/chunk-G4BWJ7EA.mjs.map +0 -1
  136. package/dist/chunk-HYMS7IGB.mjs +0 -31
  137. package/dist/chunk-HYMS7IGB.mjs.map +0 -1
  138. package/dist/chunk-I62TTXZ6.mjs +0 -46
  139. package/dist/chunk-I62TTXZ6.mjs.map +0 -1
  140. package/dist/chunk-OCLNDUYO.mjs +0 -30
  141. package/dist/chunk-OCLNDUYO.mjs.map +0 -1
  142. package/dist/chunk-VBIZGGQL.js +0 -17
  143. package/dist/chunk-VBIZGGQL.js.map +0 -1
  144. package/dist/chunk-VQPP5PWS.js +0 -35
  145. package/dist/chunk-VQPP5PWS.js.map +0 -1
  146. package/dist/chunk-VSDHL2GQ.js +0 -155
  147. package/dist/chunk-VSDHL2GQ.js.map +0 -1
  148. package/dist/chunk-X4ZAW4QR.js +0 -34
  149. package/dist/chunk-X4ZAW4QR.js.map +0 -1
  150. package/dist/chunk-Z2XKIXLS.js +0 -25
  151. package/dist/chunk-Z2XKIXLS.js.map +0 -1
  152. package/dist/chunk-ZH4MLSXX.js +0 -31
  153. package/dist/chunk-ZH4MLSXX.js.map +0 -1
  154. package/dist/errors.js +0 -58
  155. package/dist/errors.js.map +0 -1
  156. package/dist/index.js +0 -98
  157. package/dist/index.js.map +0 -1
  158. package/dist/permission-middleware.js +0 -9
  159. package/dist/permission-middleware.js.map +0 -1
  160. package/dist/rpc-methods/getPermissions.js +0 -9
  161. package/dist/rpc-methods/getPermissions.js.map +0 -1
  162. package/dist/rpc-methods/index.js +0 -13
  163. package/dist/rpc-methods/index.js.map +0 -1
  164. package/dist/rpc-methods/requestPermissions.js +0 -10
  165. package/dist/rpc-methods/requestPermissions.js.map +0 -1
  166. package/dist/rpc-methods/revokePermissions.js +0 -10
  167. package/dist/rpc-methods/revokePermissions.js.map +0 -1
  168. package/dist/tsconfig.build.tsbuildinfo +0 -1
  169. package/dist/types/Caveat.d.ts.map +0 -1
  170. package/dist/types/Permission.d.ts.map +0 -1
  171. package/dist/types/PermissionController.d.ts.map +0 -1
  172. package/dist/types/SubjectMetadataController.d.ts.map +0 -1
  173. package/dist/types/errors.d.ts.map +0 -1
  174. package/dist/types/index.d.ts +0 -9
  175. package/dist/types/index.d.ts.map +0 -1
  176. package/dist/types/permission-middleware.d.ts.map +0 -1
  177. package/dist/types/rpc-methods/getPermissions.d.ts +0 -9
  178. package/dist/types/rpc-methods/getPermissions.d.ts.map +0 -1
  179. package/dist/types/rpc-methods/index.d.ts +0 -6
  180. package/dist/types/rpc-methods/index.d.ts.map +0 -1
  181. package/dist/types/rpc-methods/requestPermissions.d.ts.map +0 -1
  182. package/dist/types/rpc-methods/revokePermissions.d.ts.map +0 -1
  183. package/dist/types/utils.d.ts.map +0 -1
  184. package/dist/utils.js +0 -10
  185. package/dist/utils.js.map +0 -1
@@ -0,0 +1,1481 @@
1
+ "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ var _PermissionController_instances, _PermissionController_expectGetCaveatMerger, _PermissionController_applyGrantedPermissions, _PermissionController_mergeIncrementalPermissions, _PermissionController_mergePermission, _PermissionController_mergeCaveat, _PermissionController_handleApprovedPermissions;
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PermissionController = exports.CaveatMutatorOperation = void 0;
13
+ const base_controller_1 = require("@metamask/base-controller");
14
+ const controller_utils_1 = require("@metamask/controller-utils");
15
+ const rpc_errors_1 = require("@metamask/rpc-errors");
16
+ const utils_1 = require("@metamask/utils");
17
+ const deep_freeze_strict_1 = __importDefault(require("deep-freeze-strict"));
18
+ const immer_1 = require("immer");
19
+ const nanoid_1 = require("nanoid");
20
+ const Caveat_1 = require("./Caveat.cjs");
21
+ const errors_1 = require("./errors.cjs");
22
+ const Permission_1 = require("./Permission.cjs");
23
+ const permission_middleware_1 = require("./permission-middleware.cjs");
24
+ const utils_2 = require("./utils.cjs");
25
+ /**
26
+ * The name of the {@link PermissionController}.
27
+ */
28
+ const controllerName = 'PermissionController';
29
+ /**
30
+ * Get the state metadata of the {@link PermissionController}.
31
+ *
32
+ * @template Permission - The controller's permission type union.
33
+ * @returns The state metadata
34
+ */
35
+ function getStateMetadata() {
36
+ return { subjects: { anonymous: true, persist: true } };
37
+ }
38
+ /**
39
+ * Get the default state of the {@link PermissionController}.
40
+ *
41
+ * @template Permission - The controller's permission type union.
42
+ * @returns The default state of the controller
43
+ */
44
+ function getDefaultState() {
45
+ return { subjects: {} };
46
+ }
47
+ /**
48
+ * Describes the possible results of a {@link CaveatMutator} function.
49
+ */
50
+ var CaveatMutatorOperation;
51
+ (function (CaveatMutatorOperation) {
52
+ CaveatMutatorOperation[CaveatMutatorOperation["Noop"] = 0] = "Noop";
53
+ CaveatMutatorOperation[CaveatMutatorOperation["UpdateValue"] = 1] = "UpdateValue";
54
+ CaveatMutatorOperation[CaveatMutatorOperation["DeleteCaveat"] = 2] = "DeleteCaveat";
55
+ CaveatMutatorOperation[CaveatMutatorOperation["RevokePermission"] = 3] = "RevokePermission";
56
+ })(CaveatMutatorOperation || (exports.CaveatMutatorOperation = CaveatMutatorOperation = {}));
57
+ /**
58
+ * The permission controller. See the [Architecture](../ARCHITECTURE.md)
59
+ * document for details.
60
+ *
61
+ * Assumes the existence of an {@link ApprovalController} reachable via the
62
+ * {@link ControllerMessenger}.
63
+ *
64
+ * @template ControllerPermissionSpecification - A union of the types of all
65
+ * permission specifications available to the controller. Any referenced caveats
66
+ * must be included in the controller's caveat specifications.
67
+ * @template ControllerCaveatSpecification - A union of the types of all
68
+ * caveat specifications available to the controller.
69
+ */
70
+ class PermissionController extends base_controller_1.BaseController {
71
+ /**
72
+ * The names of all JSON-RPC methods that will be ignored by the controller.
73
+ *
74
+ * @returns The names of all unrestricted JSON-RPC methods
75
+ */
76
+ get unrestrictedMethods() {
77
+ return this._unrestrictedMethods;
78
+ }
79
+ /**
80
+ * Constructs the PermissionController.
81
+ *
82
+ * @param options - Permission controller options.
83
+ * @param options.caveatSpecifications - The specifications of all caveats
84
+ * available to the controller. See {@link CaveatSpecificationMap} and the
85
+ * documentation for more details.
86
+ * @param options.permissionSpecifications - The specifications of all
87
+ * permissions available to the controller. See
88
+ * {@link PermissionSpecificationMap} and the README for more details.
89
+ * @param options.unrestrictedMethods - The callable names of all JSON-RPC
90
+ * methods ignored by the new controller.
91
+ * @param options.messenger - The controller messenger. See
92
+ * {@link BaseController} for more information.
93
+ * @param options.state - Existing state to hydrate the controller with at
94
+ * initialization.
95
+ */
96
+ constructor(options) {
97
+ const { caveatSpecifications, permissionSpecifications, unrestrictedMethods, messenger, state = {}, } = options;
98
+ super({
99
+ name: controllerName,
100
+ metadata: getStateMetadata(),
101
+ messenger,
102
+ state: {
103
+ ...getDefaultState(),
104
+ ...state,
105
+ },
106
+ });
107
+ _PermissionController_instances.add(this);
108
+ this._unrestrictedMethods = new Set(unrestrictedMethods);
109
+ this._caveatSpecifications = (0, deep_freeze_strict_1.default)({ ...caveatSpecifications });
110
+ this.validatePermissionSpecifications(permissionSpecifications, this._caveatSpecifications);
111
+ this._permissionSpecifications = (0, deep_freeze_strict_1.default)({
112
+ ...permissionSpecifications,
113
+ });
114
+ this.registerMessageHandlers();
115
+ this.createPermissionMiddleware = (0, permission_middleware_1.getPermissionMiddlewareFactory)({
116
+ executeRestrictedMethod: this._executeRestrictedMethod.bind(this),
117
+ getRestrictedMethod: this.getRestrictedMethod.bind(this),
118
+ isUnrestrictedMethod: this.unrestrictedMethods.has.bind(this.unrestrictedMethods),
119
+ });
120
+ }
121
+ /**
122
+ * Gets a permission specification.
123
+ *
124
+ * @param targetName - The name of the permission specification to get.
125
+ * @returns The permission specification with the specified target name.
126
+ */
127
+ getPermissionSpecification(targetName) {
128
+ return this._permissionSpecifications[targetName];
129
+ }
130
+ /**
131
+ * Gets a caveat specification.
132
+ *
133
+ * @param caveatType - The type of the caveat specification to get.
134
+ * @returns The caveat specification with the specified type.
135
+ */
136
+ getCaveatSpecification(caveatType) {
137
+ return this._caveatSpecifications[caveatType];
138
+ }
139
+ /**
140
+ * Constructor helper for validating permission specifications.
141
+ *
142
+ * Throws an error if validation fails.
143
+ *
144
+ * @param permissionSpecifications - The permission specifications passed to
145
+ * this controller's constructor.
146
+ * @param caveatSpecifications - The caveat specifications passed to this
147
+ * controller.
148
+ */
149
+ validatePermissionSpecifications(permissionSpecifications, caveatSpecifications) {
150
+ Object.entries(permissionSpecifications).forEach(([targetName, { permissionType, targetName: innerTargetName, allowedCaveats },]) => {
151
+ if (!permissionType || !(0, utils_1.hasProperty)(Permission_1.PermissionType, permissionType)) {
152
+ throw new Error(`Invalid permission type: "${permissionType}"`);
153
+ }
154
+ if (!targetName) {
155
+ throw new Error(`Invalid permission target name: "${targetName}"`);
156
+ }
157
+ if (targetName !== innerTargetName) {
158
+ throw new Error(`Invalid permission specification: target name "${targetName}" must match specification.targetName value "${innerTargetName}".`);
159
+ }
160
+ if (allowedCaveats) {
161
+ allowedCaveats.forEach((caveatType) => {
162
+ if (!(0, utils_1.hasProperty)(caveatSpecifications, caveatType)) {
163
+ throw new errors_1.UnrecognizedCaveatTypeError(caveatType);
164
+ }
165
+ const specification = caveatSpecifications[caveatType];
166
+ const isRestrictedMethodCaveat = (0, Caveat_1.isRestrictedMethodCaveatSpecification)(specification);
167
+ if ((permissionType === Permission_1.PermissionType.RestrictedMethod &&
168
+ !isRestrictedMethodCaveat) ||
169
+ (permissionType === Permission_1.PermissionType.Endowment &&
170
+ isRestrictedMethodCaveat)) {
171
+ throw new errors_1.CaveatSpecificationMismatchError(specification, permissionType);
172
+ }
173
+ });
174
+ }
175
+ });
176
+ }
177
+ /**
178
+ * Constructor helper for registering the controller's messaging system
179
+ * actions.
180
+ */
181
+ registerMessageHandlers() {
182
+ this.messagingSystem.registerActionHandler(`${controllerName}:clearPermissions`, () => this.clearState());
183
+ this.messagingSystem.registerActionHandler(`${controllerName}:getEndowments`, (origin, targetName, requestData) => this.getEndowments(origin, targetName, requestData));
184
+ this.messagingSystem.registerActionHandler(`${controllerName}:getSubjectNames`, () => this.getSubjectNames());
185
+ this.messagingSystem.registerActionHandler(`${controllerName}:getPermissions`, (origin) => this.getPermissions(origin));
186
+ this.messagingSystem.registerActionHandler(`${controllerName}:hasPermission`, (origin, targetName) => this.hasPermission(origin, targetName));
187
+ this.messagingSystem.registerActionHandler(`${controllerName}:hasPermissions`, (origin) => this.hasPermissions(origin));
188
+ this.messagingSystem.registerActionHandler(`${controllerName}:grantPermissions`, this.grantPermissions.bind(this));
189
+ this.messagingSystem.registerActionHandler(`${controllerName}:grantPermissionsIncremental`, this.grantPermissionsIncremental.bind(this));
190
+ this.messagingSystem.registerActionHandler(`${controllerName}:requestPermissions`, (subject, permissions) => this.requestPermissions(subject, permissions));
191
+ this.messagingSystem.registerActionHandler(`${controllerName}:requestPermissionsIncremental`, (subject, permissions) => this.requestPermissionsIncremental(subject, permissions));
192
+ this.messagingSystem.registerActionHandler(`${controllerName}:revokeAllPermissions`, (origin) => this.revokeAllPermissions(origin));
193
+ this.messagingSystem.registerActionHandler(`${controllerName}:revokePermissionForAllSubjects`, (target) => this.revokePermissionForAllSubjects(target));
194
+ this.messagingSystem.registerActionHandler(`${controllerName}:revokePermissions`, this.revokePermissions.bind(this));
195
+ this.messagingSystem.registerActionHandler(`${controllerName}:updateCaveat`, (origin, target, caveatType, caveatValue) => {
196
+ this.updateCaveat(origin, target, caveatType, caveatValue);
197
+ });
198
+ }
199
+ /**
200
+ * Clears the state of the controller.
201
+ */
202
+ clearState() {
203
+ this.update((_draftState) => {
204
+ return {
205
+ ...getDefaultState(),
206
+ };
207
+ });
208
+ }
209
+ /**
210
+ * Gets the permission specification corresponding to the given permission
211
+ * type and target name. Throws an error if the target name does not
212
+ * correspond to a permission, or if the specification is not of the
213
+ * given permission type.
214
+ *
215
+ * @template Type - The type of the permission specification to get.
216
+ * @param permissionType - The type of the permission specification to get.
217
+ * @param targetName - The name of the permission whose specification to get.
218
+ * @param requestingOrigin - The origin of the requesting subject, if any.
219
+ * Will be added to any thrown errors.
220
+ * @returns The specification object corresponding to the given type and
221
+ * target name.
222
+ */
223
+ getTypedPermissionSpecification(permissionType, targetName, requestingOrigin) {
224
+ const failureError = permissionType === Permission_1.PermissionType.RestrictedMethod
225
+ ? (0, errors_1.methodNotFound)(targetName, requestingOrigin ? { origin: requestingOrigin } : undefined)
226
+ : new errors_1.EndowmentPermissionDoesNotExistError(targetName, requestingOrigin);
227
+ if (!this.targetExists(targetName)) {
228
+ throw failureError;
229
+ }
230
+ const specification = this.getPermissionSpecification(targetName);
231
+ if (!(0, Permission_1.hasSpecificationType)(specification, permissionType)) {
232
+ throw failureError;
233
+ }
234
+ return specification;
235
+ }
236
+ /**
237
+ * Gets the implementation of the specified restricted method.
238
+ *
239
+ * A JSON-RPC error is thrown if the method does not exist.
240
+ *
241
+ * @see {@link PermissionController.executeRestrictedMethod} and
242
+ * {@link PermissionController.createPermissionMiddleware} for internal usage.
243
+ * @param method - The name of the restricted method.
244
+ * @param origin - The origin associated with the request for the restricted
245
+ * method, if any.
246
+ * @returns The restricted method implementation.
247
+ */
248
+ getRestrictedMethod(method, origin) {
249
+ return this.getTypedPermissionSpecification(Permission_1.PermissionType.RestrictedMethod, method, origin).methodImplementation;
250
+ }
251
+ /**
252
+ * Gets a list of all origins of subjects.
253
+ *
254
+ * @returns The origins (i.e. IDs) of all subjects.
255
+ */
256
+ getSubjectNames() {
257
+ return Object.keys(this.state.subjects);
258
+ }
259
+ /**
260
+ * Gets the permission for the specified target of the subject corresponding
261
+ * to the specified origin.
262
+ *
263
+ * @param origin - The origin of the subject.
264
+ * @param targetName - The method name as invoked by a third party (i.e., not
265
+ * a method key).
266
+ * @returns The permission if it exists, or undefined otherwise.
267
+ */
268
+ getPermission(origin, targetName) {
269
+ return this.state.subjects[origin]?.permissions[targetName];
270
+ }
271
+ /**
272
+ * Gets all permissions for the specified subject, if any.
273
+ *
274
+ * @param origin - The origin of the subject.
275
+ * @returns The permissions of the subject, if any.
276
+ */
277
+ getPermissions(origin) {
278
+ return this.state.subjects[origin]?.permissions;
279
+ }
280
+ /**
281
+ * Checks whether the subject with the specified origin has the specified
282
+ * permission.
283
+ *
284
+ * @param origin - The origin of the subject.
285
+ * @param target - The target name of the permission.
286
+ * @returns Whether the subject has the permission.
287
+ */
288
+ hasPermission(origin, target) {
289
+ return Boolean(this.getPermission(origin, target));
290
+ }
291
+ /**
292
+ * Checks whether the subject with the specified origin has any permissions.
293
+ * Use this if you want to know if a subject "exists".
294
+ *
295
+ * @param origin - The origin of the subject to check.
296
+ * @returns Whether the subject has any permissions.
297
+ */
298
+ hasPermissions(origin) {
299
+ return Boolean(this.state.subjects[origin]);
300
+ }
301
+ /**
302
+ * Revokes all permissions from the specified origin.
303
+ *
304
+ * Throws an error of the origin has no permissions.
305
+ *
306
+ * @param origin - The origin whose permissions to revoke.
307
+ */
308
+ revokeAllPermissions(origin) {
309
+ this.update((draftState) => {
310
+ if (!draftState.subjects[origin]) {
311
+ throw new errors_1.UnrecognizedSubjectError(origin);
312
+ }
313
+ delete draftState.subjects[origin];
314
+ });
315
+ }
316
+ /**
317
+ * Revokes the specified permission from the subject with the specified
318
+ * origin.
319
+ *
320
+ * Throws an error if the subject or the permission does not exist.
321
+ *
322
+ * @param origin - The origin of the subject whose permission to revoke.
323
+ * @param target - The target name of the permission to revoke.
324
+ */
325
+ revokePermission(origin, target) {
326
+ this.revokePermissions({ [origin]: [target] });
327
+ }
328
+ /**
329
+ * Revokes the specified permissions from the specified subjects.
330
+ *
331
+ * Throws an error if any of the subjects or permissions do not exist.
332
+ *
333
+ * @param subjectsAndPermissions - An object mapping subject origins
334
+ * to arrays of permission target names to revoke.
335
+ */
336
+ revokePermissions(subjectsAndPermissions) {
337
+ this.update((draftState) => {
338
+ Object.keys(subjectsAndPermissions).forEach((origin) => {
339
+ if (!(0, utils_1.hasProperty)(draftState.subjects, origin)) {
340
+ throw new errors_1.UnrecognizedSubjectError(origin);
341
+ }
342
+ subjectsAndPermissions[origin].forEach((target) => {
343
+ const { permissions } = draftState.subjects[origin];
344
+ if (!(0, utils_1.hasProperty)(permissions, target)) {
345
+ throw new errors_1.PermissionDoesNotExistError(origin, target);
346
+ }
347
+ this.deletePermission(draftState.subjects, origin, target);
348
+ });
349
+ });
350
+ });
351
+ }
352
+ /**
353
+ * Revokes all permissions corresponding to the specified target for all subjects.
354
+ * Does nothing if no subjects or no such permission exists.
355
+ *
356
+ * @param target - The name of the target to revoke all permissions for.
357
+ */
358
+ revokePermissionForAllSubjects(target) {
359
+ if (this.getSubjectNames().length === 0) {
360
+ return;
361
+ }
362
+ this.update((draftState) => {
363
+ Object.entries(draftState.subjects).forEach(([origin, subject]) => {
364
+ const { permissions } = subject;
365
+ if ((0, utils_1.hasProperty)(permissions, target)) {
366
+ this.deletePermission(draftState.subjects, origin, target);
367
+ }
368
+ });
369
+ });
370
+ }
371
+ /**
372
+ * Deletes the permission identified by the given origin and target. If the
373
+ * permission is the single remaining permission of its subject, the subject
374
+ * is also deleted.
375
+ *
376
+ * @param subjects - The draft permission controller subjects.
377
+ * @param origin - The origin of the subject associated with the permission
378
+ * to delete.
379
+ * @param target - The target name of the permission to delete.
380
+ */
381
+ deletePermission(subjects, origin, target) {
382
+ const { permissions } = subjects[origin];
383
+ if (Object.keys(permissions).length > 1) {
384
+ delete permissions[target];
385
+ }
386
+ else {
387
+ delete subjects[origin];
388
+ }
389
+ }
390
+ /**
391
+ * Checks whether the permission of the subject corresponding to the given
392
+ * origin has a caveat of the specified type.
393
+ *
394
+ * Throws an error if the subject does not have a permission with the
395
+ * specified target name.
396
+ *
397
+ * @template TargetName - The permission target name. Should be inferred.
398
+ * @template CaveatType - The valid caveat types for the permission. Should
399
+ * be inferred.
400
+ * @param origin - The origin of the subject.
401
+ * @param target - The target name of the permission.
402
+ * @param caveatType - The type of the caveat to check for.
403
+ * @returns Whether the permission has the specified caveat.
404
+ */
405
+ hasCaveat(origin, target, caveatType) {
406
+ return Boolean(this.getCaveat(origin, target, caveatType));
407
+ }
408
+ /**
409
+ * Gets the caveat of the specified type, if any, for the permission of
410
+ * the subject corresponding to the given origin.
411
+ *
412
+ * Throws an error if the subject does not have a permission with the
413
+ * specified target name.
414
+ *
415
+ * @template TargetName - The permission target name. Should be inferred.
416
+ * @template CaveatType - The valid caveat types for the permission. Should
417
+ * be inferred.
418
+ * @param origin - The origin of the subject.
419
+ * @param target - The target name of the permission.
420
+ * @param caveatType - The type of the caveat to get.
421
+ * @returns The caveat, or `undefined` if no such caveat exists.
422
+ */
423
+ getCaveat(origin, target, caveatType) {
424
+ const permission = this.getPermission(origin, target);
425
+ if (!permission) {
426
+ throw new errors_1.PermissionDoesNotExistError(origin, target);
427
+ }
428
+ return (0, Permission_1.findCaveat)(permission, caveatType);
429
+ }
430
+ /**
431
+ * Adds a caveat of the specified type, with the specified caveat value, to
432
+ * the permission corresponding to the given subject origin and permission
433
+ * target.
434
+ *
435
+ * For modifying existing caveats, use
436
+ * {@link PermissionController.updateCaveat}.
437
+ *
438
+ * Throws an error if no such permission exists, or if the caveat already
439
+ * exists.
440
+ *
441
+ * @template TargetName - The permission target name. Should be inferred.
442
+ * @template CaveatType - The valid caveat types for the permission. Should
443
+ * be inferred.
444
+ * @param origin - The origin of the subject.
445
+ * @param target - The target name of the permission.
446
+ * @param caveatType - The type of the caveat to add.
447
+ * @param caveatValue - The value of the caveat to add.
448
+ */
449
+ addCaveat(origin, target, caveatType, caveatValue) {
450
+ if (this.hasCaveat(origin, target, caveatType)) {
451
+ throw new errors_1.CaveatAlreadyExistsError(origin, target, caveatType);
452
+ }
453
+ this.setCaveat(origin, target, caveatType, caveatValue);
454
+ }
455
+ /**
456
+ * Updates the value of the caveat of the specified type belonging to the
457
+ * permission corresponding to the given subject origin and permission
458
+ * target.
459
+ *
460
+ * For adding new caveats, use
461
+ * {@link PermissionController.addCaveat}.
462
+ *
463
+ * Throws an error if no such permission or caveat exists.
464
+ *
465
+ * @template TargetName - The permission target name. Should be inferred.
466
+ * @template CaveatType - The valid caveat types for the permission. Should
467
+ * be inferred.
468
+ * @param origin - The origin of the subject.
469
+ * @param target - The target name of the permission.
470
+ * @param caveatType - The type of the caveat to update.
471
+ * @param caveatValue - The new value of the caveat.
472
+ */
473
+ updateCaveat(origin, target, caveatType, caveatValue) {
474
+ if (!this.hasCaveat(origin, target, caveatType)) {
475
+ throw new errors_1.CaveatDoesNotExistError(origin, target, caveatType);
476
+ }
477
+ this.setCaveat(origin, target, caveatType, caveatValue);
478
+ }
479
+ /**
480
+ * Sets the specified caveat on the specified permission. Overwrites existing
481
+ * caveats of the same type in-place (preserving array order), and adds the
482
+ * caveat to the end of the array otherwise.
483
+ *
484
+ * Throws an error if the permission does not exist or fails to validate after
485
+ * its caveats have been modified.
486
+ *
487
+ * @see {@link PermissionController.addCaveat}
488
+ * @see {@link PermissionController.updateCaveat}
489
+ * @template TargetName - The permission target name. Should be inferred.
490
+ * @template CaveatType - The valid caveat types for the permission. Should
491
+ * be inferred.
492
+ * @param origin - The origin of the subject.
493
+ * @param target - The target name of the permission.
494
+ * @param caveatType - The type of the caveat to set.
495
+ * @param caveatValue - The value of the caveat to set.
496
+ */
497
+ setCaveat(origin, target, caveatType, caveatValue) {
498
+ this.update((draftState) => {
499
+ const subject = draftState.subjects[origin];
500
+ // Unreachable because `hasCaveat` is always called before this, and it
501
+ // throws if permissions are missing. TypeScript needs this, however.
502
+ /* istanbul ignore if */
503
+ if (!subject) {
504
+ throw new errors_1.UnrecognizedSubjectError(origin);
505
+ }
506
+ const permission = subject.permissions[target];
507
+ /* istanbul ignore if: practically impossible, but TypeScript wants it */
508
+ if (!permission) {
509
+ throw new errors_1.PermissionDoesNotExistError(origin, target);
510
+ }
511
+ const caveat = {
512
+ type: caveatType,
513
+ value: caveatValue,
514
+ };
515
+ this.validateCaveat(caveat, origin, target);
516
+ if (permission.caveats) {
517
+ const caveatIndex = permission.caveats.findIndex((existingCaveat) => existingCaveat.type === caveat.type);
518
+ if (caveatIndex === -1) {
519
+ permission.caveats.push(caveat);
520
+ }
521
+ else {
522
+ permission.caveats.splice(caveatIndex, 1, caveat);
523
+ }
524
+ }
525
+ else {
526
+ // At this point, we don't know if the specific permission is allowed
527
+ // to have caveats, but it should be impossible to call this method
528
+ // for a permission that may not have any caveats. If all else fails,
529
+ // the permission validator is also called.
530
+ // @ts-expect-error See above comment
531
+ permission.caveats = [caveat];
532
+ }
533
+ this.validateModifiedPermission(permission, origin);
534
+ });
535
+ }
536
+ /**
537
+ * Updates all caveats with the specified type for all subjects and
538
+ * permissions by applying the specified mutator function to them.
539
+ *
540
+ * ATTN: Permissions can be revoked entirely by the action of this method,
541
+ * read on for details.
542
+ *
543
+ * Caveat mutators are functions that receive a caveat value and return a
544
+ * tuple consisting of a {@link CaveatMutatorOperation} and, optionally, a new
545
+ * value to update the existing caveat with.
546
+ *
547
+ * For each caveat, depending on the mutator result, this method will:
548
+ * - Do nothing ({@link CaveatMutatorOperation.Noop})
549
+ * - Update the value of the caveat ({@link CaveatMutatorOperation.UpdateValue}). The caveat specification validator, if any, will be called after updating the value.
550
+ * - Delete the caveat ({@link CaveatMutatorOperation.DeleteCaveat}). The permission specification validator, if any, will be called after deleting the caveat.
551
+ * - Revoke the parent permission ({@link CaveatMutatorOperation.RevokePermission})
552
+ *
553
+ * This method throws if the validation of any caveat or permission fails.
554
+ *
555
+ * @param targetCaveatType - The type of the caveats to update.
556
+ * @param mutator - The mutator function which will be applied to all caveat
557
+ * values.
558
+ */
559
+ updatePermissionsByCaveat(targetCaveatType, mutator) {
560
+ if (Object.keys(this.state.subjects).length === 0) {
561
+ return;
562
+ }
563
+ this.update((draftState) => {
564
+ Object.values(draftState.subjects).forEach((subject) => {
565
+ Object.values(subject.permissions).forEach((permission) => {
566
+ const { caveats } = permission;
567
+ const targetCaveat = caveats?.find(({ type }) => type === targetCaveatType);
568
+ if (!targetCaveat) {
569
+ return;
570
+ }
571
+ // The mutator may modify the caveat value in place, and must always
572
+ // return a valid mutation result.
573
+ const mutatorResult = mutator(targetCaveat.value);
574
+ const { operation } = mutatorResult;
575
+ switch (operation) {
576
+ case CaveatMutatorOperation.Noop:
577
+ break;
578
+ case CaveatMutatorOperation.UpdateValue:
579
+ // Typecast: `Mutable` is used here to assign to a readonly
580
+ // property. `targetConstraint` should already be mutable because
581
+ // it's part of a draft, but for some reason it's not. We can't
582
+ // use the more-correct `Draft` type here either because it
583
+ // results in an error.
584
+ targetCaveat.value =
585
+ mutatorResult.value;
586
+ this.validateCaveat(targetCaveat, subject.origin, permission.parentCapability);
587
+ break;
588
+ case CaveatMutatorOperation.DeleteCaveat:
589
+ this.deleteCaveat(permission, targetCaveatType, subject.origin);
590
+ break;
591
+ case CaveatMutatorOperation.RevokePermission:
592
+ this.deletePermission(draftState.subjects, subject.origin, permission.parentCapability);
593
+ break;
594
+ default: {
595
+ // Overriding as `never` is the expected result of exhaustiveness checking,
596
+ // and is intended to represent unchecked exception cases.
597
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
598
+ throw new Error(`Unrecognized mutation result: "${operation}"`);
599
+ }
600
+ }
601
+ });
602
+ });
603
+ });
604
+ }
605
+ /**
606
+ * Removes the caveat of the specified type from the permission corresponding
607
+ * to the given subject origin and target name.
608
+ *
609
+ * Throws an error if no such permission or caveat exists.
610
+ *
611
+ * @template TargetName - The permission target name. Should be inferred.
612
+ * @template CaveatType - The valid caveat types for the permission. Should
613
+ * be inferred.
614
+ * @param origin - The origin of the subject.
615
+ * @param target - The target name of the permission.
616
+ * @param caveatType - The type of the caveat to remove.
617
+ */
618
+ removeCaveat(origin, target, caveatType) {
619
+ this.update((draftState) => {
620
+ const permission = draftState.subjects[origin]?.permissions[target];
621
+ if (!permission) {
622
+ throw new errors_1.PermissionDoesNotExistError(origin, target);
623
+ }
624
+ if (!permission.caveats) {
625
+ throw new errors_1.CaveatDoesNotExistError(origin, target, caveatType);
626
+ }
627
+ this.deleteCaveat(permission, caveatType, origin);
628
+ });
629
+ }
630
+ /**
631
+ * Deletes the specified caveat from the specified permission. If no caveats
632
+ * remain after deletion, the permission's caveat property is set to `null`.
633
+ * The permission is validated after being modified.
634
+ *
635
+ * Throws an error if the permission does not have a caveat with the specified
636
+ * type.
637
+ *
638
+ * @param permission - The permission whose caveat to delete.
639
+ * @param caveatType - The type of the caveat to delete.
640
+ * @param origin - The origin the permission subject.
641
+ */
642
+ deleteCaveat(permission, caveatType, origin) {
643
+ /* istanbul ignore if: not possible in our usage */
644
+ if (!permission.caveats) {
645
+ throw new errors_1.CaveatDoesNotExistError(origin, permission.parentCapability, caveatType);
646
+ }
647
+ const caveatIndex = permission.caveats.findIndex((existingCaveat) => existingCaveat.type === caveatType);
648
+ if (caveatIndex === -1) {
649
+ throw new errors_1.CaveatDoesNotExistError(origin, permission.parentCapability, caveatType);
650
+ }
651
+ if (permission.caveats.length === 1) {
652
+ permission.caveats = null;
653
+ }
654
+ else {
655
+ permission.caveats.splice(caveatIndex, 1);
656
+ }
657
+ this.validateModifiedPermission(permission, origin);
658
+ }
659
+ /**
660
+ * Validates the specified modified permission. Should **always** be invoked
661
+ * on a permission after its caveats have been modified.
662
+ *
663
+ * Just like {@link PermissionController.validatePermission}, except that the
664
+ * corresponding target name and specification are retrieved first, and an
665
+ * error is thrown if the target name does not exist.
666
+ *
667
+ * @param permission - The modified permission to validate.
668
+ * @param origin - The origin associated with the permission.
669
+ */
670
+ validateModifiedPermission(permission, origin) {
671
+ /* istanbul ignore if: this should be impossible */
672
+ if (!this.targetExists(permission.parentCapability)) {
673
+ throw new Error(`Fatal: Existing permission target "${permission.parentCapability}" has no specification.`);
674
+ }
675
+ this.validatePermission(this.getPermissionSpecification(permission.parentCapability), permission, origin);
676
+ }
677
+ /**
678
+ * Verifies the existence the specified permission target, i.e. whether it has
679
+ * a specification.
680
+ *
681
+ * @param target - The requested permission target.
682
+ * @returns Whether the permission target exists.
683
+ */
684
+ targetExists(target) {
685
+ return (0, utils_1.hasProperty)(this._permissionSpecifications, target);
686
+ }
687
+ /**
688
+ * Grants _approved_ permissions to the specified subject. Every permission and
689
+ * caveat is stringently validated—including by calling their specification
690
+ * validators—and an error is thrown if validation fails.
691
+ *
692
+ * ATTN: This method does **not** prompt the user for approval. User consent must
693
+ * first be obtained through some other means.
694
+ *
695
+ * @see {@link PermissionController.requestPermissions} For initiating a
696
+ * permissions request requiring user approval.
697
+ * @param options - Options bag.
698
+ * @param options.approvedPermissions - The requested permissions approved by
699
+ * the user.
700
+ * @param options.requestData - Permission request data. Passed to permission
701
+ * factory functions.
702
+ * @param options.preserveExistingPermissions - Whether to preserve the
703
+ * subject's existing permissions.
704
+ * @param options.subject - The subject to grant permissions to.
705
+ * @returns The subject's new permission state. It may or may not have changed.
706
+ */
707
+ grantPermissions({ approvedPermissions, requestData, preserveExistingPermissions = true, subject, }) {
708
+ return __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_applyGrantedPermissions).call(this, {
709
+ approvedPermissions,
710
+ subject,
711
+ mergePermissions: false,
712
+ preserveExistingPermissions,
713
+ requestData,
714
+ });
715
+ }
716
+ /**
717
+ * Incrementally grants _approved_ permissions to the specified subject. Every
718
+ * permission and caveat is stringently validated—including by calling their
719
+ * specification validators—and an error is thrown if validation fails.
720
+ *
721
+ * ATTN: This method does **not** prompt the user for approval. User consent must
722
+ * first be obtained through some other means.
723
+ *
724
+ * @see {@link PermissionController.requestPermissionsIncremental} For initiating
725
+ * an incremental permissions request requiring user approval.
726
+ * @param options - Options bag.
727
+ * @param options.approvedPermissions - The requested permissions approved by
728
+ * the user.
729
+ * @param options.requestData - Permission request data. Passed to permission
730
+ * factory functions.
731
+ * @param options.subject - The subject to grant permissions to.
732
+ * @returns The subject's new permission state. It may or may not have changed.
733
+ */
734
+ grantPermissionsIncremental({ approvedPermissions, requestData, subject, }) {
735
+ return __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_applyGrantedPermissions).call(this, {
736
+ approvedPermissions,
737
+ subject,
738
+ mergePermissions: true,
739
+ preserveExistingPermissions: true,
740
+ requestData,
741
+ });
742
+ }
743
+ /**
744
+ * Validates the specified permission by:
745
+ * - Ensuring that if `subjectTypes` is specified, the subject requesting the permission is of a type in the list.
746
+ * - Ensuring that its `caveats` property is either `null` or a non-empty array.
747
+ * - Ensuring that it only includes caveats allowed by its specification.
748
+ * - Ensuring that it includes no duplicate caveats (by caveat type).
749
+ * - Validating each caveat object, if `performCaveatValidation` is `true`.
750
+ * - Calling the validator of its specification, if one exists and `invokePermissionValidator` is `true`.
751
+ *
752
+ * An error is thrown if validation fails.
753
+ *
754
+ * @param specification - The specification of the permission.
755
+ * @param permission - The permission to validate.
756
+ * @param origin - The origin associated with the permission.
757
+ * @param validationOptions - Validation options.
758
+ * @param validationOptions.invokePermissionValidator - Whether to invoke the
759
+ * permission's consumer-specified validator function, if any.
760
+ * @param validationOptions.performCaveatValidation - Whether to invoke
761
+ * {@link PermissionController.validateCaveat} on each of the permission's
762
+ * caveats.
763
+ */
764
+ validatePermission(specification, permission, origin, { invokePermissionValidator, performCaveatValidation } = {
765
+ invokePermissionValidator: true,
766
+ performCaveatValidation: true,
767
+ }) {
768
+ const { allowedCaveats, validator, targetName } = specification;
769
+ if (specification.subjectTypes?.length &&
770
+ specification.subjectTypes.length > 0) {
771
+ const metadata = this.messagingSystem.call('SubjectMetadataController:getSubjectMetadata', origin);
772
+ if (!metadata ||
773
+ metadata.subjectType === null ||
774
+ !specification.subjectTypes.includes(metadata.subjectType)) {
775
+ throw specification.permissionType === Permission_1.PermissionType.RestrictedMethod
776
+ ? (0, errors_1.methodNotFound)(targetName, { origin })
777
+ : new errors_1.EndowmentPermissionDoesNotExistError(targetName, origin);
778
+ }
779
+ }
780
+ if ((0, utils_1.hasProperty)(permission, 'caveats')) {
781
+ const { caveats } = permission;
782
+ if (caveats !== null && !(Array.isArray(caveats) && caveats.length > 0)) {
783
+ throw new errors_1.InvalidCaveatsPropertyError(origin, targetName, caveats);
784
+ }
785
+ const seenCaveatTypes = new Set();
786
+ caveats?.forEach((caveat) => {
787
+ if (performCaveatValidation) {
788
+ this.validateCaveat(caveat, origin, targetName);
789
+ }
790
+ if (!allowedCaveats?.includes(caveat.type)) {
791
+ throw new errors_1.ForbiddenCaveatError(caveat.type, origin, targetName);
792
+ }
793
+ if (seenCaveatTypes.has(caveat.type)) {
794
+ throw new errors_1.DuplicateCaveatError(caveat.type, origin, targetName);
795
+ }
796
+ seenCaveatTypes.add(caveat.type);
797
+ });
798
+ }
799
+ if (invokePermissionValidator && validator) {
800
+ validator(permission, origin, targetName);
801
+ }
802
+ }
803
+ /**
804
+ * Assigns the specified permissions to the subject with the given origin.
805
+ * Overwrites all existing permissions, and creates a subject entry if it
806
+ * doesn't already exist.
807
+ *
808
+ * ATTN: Assumes that the new permissions have been validated.
809
+ *
810
+ * @param origin - The origin of the grantee subject.
811
+ * @param permissions - The new permissions for the grantee subject.
812
+ */
813
+ setValidatedPermissions(origin, permissions) {
814
+ this.update((draftState) => {
815
+ if (!draftState.subjects[origin]) {
816
+ draftState.subjects[origin] = { origin, permissions: {} };
817
+ }
818
+ draftState.subjects[origin].permissions = (0, immer_1.castDraft)(permissions);
819
+ });
820
+ }
821
+ /**
822
+ * Validates the requested caveats for the permission of the specified
823
+ * subject origin and target name and returns the validated caveat array.
824
+ *
825
+ * Throws an error if validation fails.
826
+ *
827
+ * @param origin - The origin of the permission subject.
828
+ * @param target - The permission target name.
829
+ * @param requestedCaveats - The requested caveats to construct.
830
+ * @returns The constructed caveats.
831
+ */
832
+ constructCaveats(origin, target, requestedCaveats) {
833
+ const caveatArray = requestedCaveats?.map((requestedCaveat) => {
834
+ this.validateCaveat(requestedCaveat, origin, target);
835
+ // Reassign so that we have a fresh object.
836
+ const { type, value } = requestedCaveat;
837
+ return { type, value };
838
+ });
839
+ return caveatArray && (0, controller_utils_1.isNonEmptyArray)(caveatArray)
840
+ ? caveatArray
841
+ : undefined;
842
+ }
843
+ /**
844
+ * This methods validates that the specified caveat is an object with the
845
+ * expected properties and types. It also ensures that a caveat specification
846
+ * exists for the requested caveat type, and calls the specification
847
+ * validator, if it exists, on the caveat object.
848
+ *
849
+ * Throws an error if validation fails.
850
+ *
851
+ * @param caveat - The caveat object to validate.
852
+ * @param origin - The origin associated with the subject of the parent
853
+ * permission.
854
+ * @param target - The target name associated with the parent permission.
855
+ */
856
+ validateCaveat(caveat, origin, target) {
857
+ if (!(0, controller_utils_1.isPlainObject)(caveat)) {
858
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
859
+ throw new errors_1.InvalidCaveatError(caveat, origin, target);
860
+ }
861
+ if (Object.keys(caveat).length !== 2) {
862
+ throw new errors_1.InvalidCaveatFieldsError(caveat, origin, target);
863
+ }
864
+ if (typeof caveat.type !== 'string') {
865
+ throw new errors_1.InvalidCaveatTypeError(caveat, origin, target);
866
+ }
867
+ const specification = this.getCaveatSpecification(caveat.type);
868
+ if (!specification) {
869
+ throw new errors_1.UnrecognizedCaveatTypeError(caveat.type, origin, target);
870
+ }
871
+ if (!(0, utils_1.hasProperty)(caveat, 'value') || caveat.value === undefined) {
872
+ throw new errors_1.CaveatMissingValueError(caveat, origin, target);
873
+ }
874
+ if (!(0, controller_utils_1.isValidJson)(caveat.value)) {
875
+ throw new errors_1.CaveatInvalidJsonError(caveat, origin, target);
876
+ }
877
+ // Typecast: TypeScript still believes that the caveat is a PlainObject.
878
+ specification.validator?.(caveat, origin, target);
879
+ }
880
+ /**
881
+ * Initiates a permission request that requires user approval.
882
+ *
883
+ * Either this or {@link PermissionController.requestPermissionsIncremental}
884
+ * should always be used to grant additional permissions to a subject,
885
+ * unless user approval has been obtained through some other means.
886
+ *
887
+ * Permissions are validated at every step of the approval process, and this
888
+ * method will reject if validation fails.
889
+ *
890
+ * @see {@link ApprovalController} For the user approval logic.
891
+ * @see {@link PermissionController.acceptPermissionsRequest} For the method
892
+ * that _accepts_ the request and resolves the user approval promise.
893
+ * @see {@link PermissionController.rejectPermissionsRequest} For the method
894
+ * that _rejects_ the request and the user approval promise.
895
+ * @param subject - The grantee subject.
896
+ * @param requestedPermissions - The requested permissions.
897
+ * @param options - Additional options.
898
+ * @param options.id - The id of the permissions request. Defaults to a unique
899
+ * id.
900
+ * @param options.preserveExistingPermissions - Whether to preserve the
901
+ * subject's existing permissions. Defaults to `true`.
902
+ * @param options.metadata - Additional metadata about the permission request.
903
+ * @returns The granted permissions and request metadata.
904
+ */
905
+ async requestPermissions(subject, requestedPermissions, options = {}) {
906
+ const { origin } = subject;
907
+ const { id = (0, nanoid_1.nanoid)(), preserveExistingPermissions = true } = options;
908
+ this.validateRequestedPermissions(origin, requestedPermissions);
909
+ const metadata = {
910
+ ...options.metadata,
911
+ id,
912
+ origin,
913
+ };
914
+ const permissionsRequest = {
915
+ metadata,
916
+ permissions: requestedPermissions,
917
+ };
918
+ const approvedRequest = await this.requestUserApproval(permissionsRequest);
919
+ return await __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_handleApprovedPermissions).call(this, {
920
+ subject,
921
+ metadata,
922
+ preserveExistingPermissions,
923
+ approvedRequest,
924
+ });
925
+ }
926
+ /**
927
+ * Initiates an incremental permission request that prompts for user approval.
928
+ * Incremental permission requests allow the caller to replace existing and/or
929
+ * add brand new permissions and caveats for the specified subject.
930
+ *
931
+ * Incremental permission request are merged with the subject's existing permissions
932
+ * through a right-biased union, where the incremental permission are the right-hand
933
+ * side of the merger. If both sides of the merger specify the same caveats for a
934
+ * given permission, the caveats are merged using their specification's caveat value
935
+ * merger property.
936
+ *
937
+ * Either this or {@link PermissionController.requestPermissions} should
938
+ * always be used to grant additional permissions to a subject, unless user
939
+ * approval has been obtained through some other means.
940
+ *
941
+ * Permissions are validated at every step of the approval process, and this
942
+ * method will reject if validation fails.
943
+ *
944
+ * @see {@link ApprovalController} For the user approval logic.
945
+ * @see {@link PermissionController.acceptPermissionsRequest} For the method
946
+ * that _accepts_ the request and resolves the user approval promise.
947
+ * @see {@link PermissionController.rejectPermissionsRequest} For the method
948
+ * that _rejects_ the request and the user approval promise.
949
+ * @param subject - The grantee subject.
950
+ * @param requestedPermissions - The requested permissions.
951
+ * @param options - Additional options.
952
+ * @param options.id - The id of the permissions request. Defaults to a unique
953
+ * id.
954
+ * @param options.metadata - Additional metadata about the permission request.
955
+ * @returns The granted permissions and request metadata.
956
+ */
957
+ async requestPermissionsIncremental(subject, requestedPermissions, options = {}) {
958
+ const { origin } = subject;
959
+ const { id = (0, nanoid_1.nanoid)() } = options;
960
+ this.validateRequestedPermissions(origin, requestedPermissions);
961
+ const currentPermissions = this.getPermissions(origin) ?? {};
962
+ const [newPermissions, permissionDiffMap] = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_mergeIncrementalPermissions).call(this, currentPermissions, requestedPermissions);
963
+ // The second undefined check is just for type narrowing purposes. These values
964
+ // will always be jointly defined or undefined.
965
+ if (newPermissions === undefined || permissionDiffMap === undefined) {
966
+ return [];
967
+ }
968
+ try {
969
+ // It does not spark joy to run this validation again after the merger operation.
970
+ // But, optimizing this procedure is probably not worth it, especially considering
971
+ // that the worst-case scenario for validation degrades to the below function call.
972
+ this.validateRequestedPermissions(origin, newPermissions);
973
+ }
974
+ catch (error) {
975
+ if (error instanceof Error) {
976
+ throw new errors_1.InvalidMergedPermissionsError(origin, error, permissionDiffMap);
977
+ }
978
+ /* istanbul ignore next: This should be impossible */
979
+ throw (0, errors_1.internalError)('Unrecognized error type', { error });
980
+ }
981
+ const metadata = {
982
+ ...options.metadata,
983
+ id,
984
+ origin,
985
+ };
986
+ const permissionsRequest = {
987
+ metadata,
988
+ permissions: newPermissions,
989
+ diff: {
990
+ currentPermissions,
991
+ permissionDiffMap,
992
+ },
993
+ };
994
+ const approvedRequest = await this.requestUserApproval(permissionsRequest);
995
+ return await __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_handleApprovedPermissions).call(this, {
996
+ subject,
997
+ metadata,
998
+ preserveExistingPermissions: false,
999
+ approvedRequest,
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Validates requested permissions. Throws if validation fails.
1004
+ *
1005
+ * This method ensures that the requested permissions are a properly
1006
+ * formatted {@link RequestedPermissions} object, and performs the same
1007
+ * validation as {@link PermissionController.grantPermissions}, except that
1008
+ * consumer-specified permission validator functions are not called, since
1009
+ * they are only called on fully constructed, approved permissions that are
1010
+ * otherwise completely valid.
1011
+ *
1012
+ * Unrecognzied properties on requested permissions are ignored.
1013
+ *
1014
+ * @param origin - The origin of the grantee subject.
1015
+ * @param requestedPermissions - The requested permissions.
1016
+ */
1017
+ validateRequestedPermissions(origin, requestedPermissions) {
1018
+ if (!(0, controller_utils_1.isPlainObject)(requestedPermissions)) {
1019
+ throw (0, errors_1.invalidParams)({
1020
+ message: `Requested permissions for origin "${origin}" is not a plain object.`,
1021
+ data: { origin, requestedPermissions },
1022
+ });
1023
+ }
1024
+ if (Object.keys(requestedPermissions).length === 0) {
1025
+ throw (0, errors_1.invalidParams)({
1026
+ message: `Permissions request for origin "${origin}" contains no permissions.`,
1027
+ data: { requestedPermissions },
1028
+ });
1029
+ }
1030
+ for (const targetName of Object.keys(requestedPermissions)) {
1031
+ const permission = requestedPermissions[targetName];
1032
+ if (!this.targetExists(targetName)) {
1033
+ throw (0, errors_1.methodNotFound)(targetName, { origin, requestedPermissions });
1034
+ }
1035
+ if (!(0, controller_utils_1.isPlainObject)(permission) ||
1036
+ (permission.parentCapability !== undefined &&
1037
+ targetName !== permission.parentCapability)) {
1038
+ throw (0, errors_1.invalidParams)({
1039
+ message: `Permissions request for origin "${origin}" contains invalid requested permission(s).`,
1040
+ data: { origin, requestedPermissions },
1041
+ });
1042
+ }
1043
+ // Here we validate the permission without invoking its validator, if any.
1044
+ // The validator will be invoked after the permission has been approved.
1045
+ this.validatePermission(this.getPermissionSpecification(targetName),
1046
+ // Typecast: The permission is still a "PlainObject" here.
1047
+ permission, origin, { invokePermissionValidator: false, performCaveatValidation: true });
1048
+ }
1049
+ }
1050
+ /**
1051
+ * Adds a request to the {@link ApprovalController} using the
1052
+ * {@link AddApprovalRequest} action. Also validates the resulting approved
1053
+ * permissions request, and throws an error if validation fails.
1054
+ *
1055
+ * @param permissionsRequest - The permissions request object.
1056
+ * @returns The approved permissions request object.
1057
+ */
1058
+ async requestUserApproval(permissionsRequest) {
1059
+ const { origin, id } = permissionsRequest.metadata;
1060
+ const approvedRequest = await this.messagingSystem.call('ApprovalController:addRequest', {
1061
+ id,
1062
+ origin,
1063
+ requestData: permissionsRequest,
1064
+ type: utils_2.MethodNames.RequestPermissions,
1065
+ }, true);
1066
+ this.validateApprovedPermissions(approvedRequest, { id, origin });
1067
+ return approvedRequest;
1068
+ }
1069
+ /**
1070
+ * Reunites all the side-effects (onPermitted and onFailure) of the requested permissions inside a record of arrays.
1071
+ *
1072
+ * @param permissions - The approved permissions.
1073
+ * @returns The {@link SideEffects} object containing the handlers arrays.
1074
+ */
1075
+ getSideEffects(permissions) {
1076
+ return Object.keys(permissions).reduce((sideEffectList, targetName) => {
1077
+ if (this.targetExists(targetName)) {
1078
+ const specification = this.getPermissionSpecification(targetName);
1079
+ if (specification.sideEffect) {
1080
+ sideEffectList.permittedHandlers[targetName] =
1081
+ specification.sideEffect.onPermitted;
1082
+ if (specification.sideEffect.onFailure) {
1083
+ sideEffectList.failureHandlers[targetName] =
1084
+ specification.sideEffect.onFailure;
1085
+ }
1086
+ }
1087
+ }
1088
+ return sideEffectList;
1089
+ }, { permittedHandlers: {}, failureHandlers: {} });
1090
+ }
1091
+ /**
1092
+ * Executes the side-effects of the approved permissions while handling the errors if any.
1093
+ * It will pass an instance of the {@link messagingSystem} and the request data associated with the permission request to the handlers through its params.
1094
+ *
1095
+ * @param sideEffects - the side-effect record created by {@link getSideEffects}
1096
+ * @param requestData - the permissions requestData.
1097
+ * @returns the value returned by all the `onPermitted` handlers in an array.
1098
+ */
1099
+ async executeSideEffects(sideEffects, requestData) {
1100
+ const { permittedHandlers, failureHandlers } = sideEffects;
1101
+ const params = {
1102
+ requestData,
1103
+ messagingSystem: this.messagingSystem,
1104
+ };
1105
+ const promiseResults = await Promise.allSettled(Object.values(permittedHandlers).map((permittedHandler) => permittedHandler(params)));
1106
+ // lib.es2020.promise.d.ts does not export its types so we're using a simple type.
1107
+ const rejectedHandlers = promiseResults.filter((promise) => promise.status === 'rejected');
1108
+ if (rejectedHandlers.length > 0) {
1109
+ const failureHandlersList = Object.values(failureHandlers);
1110
+ if (failureHandlersList.length > 0) {
1111
+ try {
1112
+ await Promise.all(failureHandlersList.map((failureHandler) => failureHandler(params)));
1113
+ }
1114
+ catch (error) {
1115
+ throw (0, errors_1.internalError)('Unexpected error in side-effects', { error });
1116
+ }
1117
+ }
1118
+ const reasons = rejectedHandlers.map((handler) => handler.reason);
1119
+ reasons.forEach((reason) => {
1120
+ console.error(reason);
1121
+ });
1122
+ throw reasons.length > 1
1123
+ ? (0, errors_1.internalError)('Multiple errors occurred during side-effects execution', { errors: reasons })
1124
+ : reasons[0];
1125
+ }
1126
+ // lib.es2020.promise.d.ts does not export its types so we're using a simple type.
1127
+ return promiseResults.map(({ value }) => value);
1128
+ }
1129
+ /**
1130
+ * Validates an approved {@link PermissionsRequest} object. The approved
1131
+ * request must have the required `metadata` and `permissions` properties,
1132
+ * the `id` and `origin` of the `metadata` must match the original request
1133
+ * metadata, and the requested permissions must be valid per
1134
+ * {@link PermissionController.validateRequestedPermissions}. Any extra
1135
+ * metadata properties are ignored.
1136
+ *
1137
+ * An error is thrown if validation fails.
1138
+ *
1139
+ * @param approvedRequest - The approved permissions request object.
1140
+ * @param originalMetadata - The original request metadata.
1141
+ */
1142
+ validateApprovedPermissions(approvedRequest, originalMetadata) {
1143
+ const { id, origin } = originalMetadata;
1144
+ if (!(0, controller_utils_1.isPlainObject)(approvedRequest) ||
1145
+ !(0, controller_utils_1.isPlainObject)(approvedRequest.metadata)) {
1146
+ throw (0, errors_1.internalError)(`Approved permissions request for subject "${origin}" is invalid.`, { data: { approvedRequest } });
1147
+ }
1148
+ const { metadata: { id: newId, origin: newOrigin }, permissions, } = approvedRequest;
1149
+ if (newId !== id) {
1150
+ throw (0, errors_1.internalError)(`Approved permissions request for subject "${origin}" mutated its id.`, { originalId: id, mutatedId: newId });
1151
+ }
1152
+ if (newOrigin !== origin) {
1153
+ throw (0, errors_1.internalError)(`Approved permissions request for subject "${origin}" mutated its origin.`, { originalOrigin: origin, mutatedOrigin: newOrigin });
1154
+ }
1155
+ try {
1156
+ this.validateRequestedPermissions(origin, permissions);
1157
+ }
1158
+ catch (error) {
1159
+ if (error instanceof Error) {
1160
+ // Re-throw as an internal error; we should never receive invalid approved
1161
+ // permissions.
1162
+ throw (0, errors_1.internalError)(`Invalid approved permissions request: ${error.message}`, error instanceof rpc_errors_1.JsonRpcError ? error.data : undefined);
1163
+ }
1164
+ /* istanbul ignore next: This should be impossible */
1165
+ throw (0, errors_1.internalError)('Unrecognized error type', { error });
1166
+ }
1167
+ }
1168
+ /**
1169
+ * Accepts a permissions request created by
1170
+ * {@link PermissionController.requestPermissions}.
1171
+ *
1172
+ * @param request - The permissions request.
1173
+ */
1174
+ async acceptPermissionsRequest(request) {
1175
+ const { id } = request.metadata;
1176
+ if (!this.hasApprovalRequest({ id })) {
1177
+ throw new errors_1.PermissionsRequestNotFoundError(id);
1178
+ }
1179
+ if (Object.keys(request.permissions).length === 0) {
1180
+ this._rejectPermissionsRequest(id, (0, errors_1.invalidParams)({
1181
+ message: 'Must request at least one permission.',
1182
+ }));
1183
+ return;
1184
+ }
1185
+ try {
1186
+ await this.messagingSystem.call('ApprovalController:acceptRequest', id, request);
1187
+ }
1188
+ catch (error) {
1189
+ // If accepting unexpectedly fails, reject the request and re-throw the
1190
+ // error
1191
+ this._rejectPermissionsRequest(id, error);
1192
+ throw error;
1193
+ }
1194
+ }
1195
+ /**
1196
+ * Rejects a permissions request created by
1197
+ * {@link PermissionController.requestPermissions}.
1198
+ *
1199
+ * @param id - The id of the request to be rejected.
1200
+ */
1201
+ async rejectPermissionsRequest(id) {
1202
+ if (!this.hasApprovalRequest({ id })) {
1203
+ throw new errors_1.PermissionsRequestNotFoundError(id);
1204
+ }
1205
+ this._rejectPermissionsRequest(id, (0, errors_1.userRejectedRequest)());
1206
+ }
1207
+ /**
1208
+ * Checks whether the {@link ApprovalController} has a particular permissions
1209
+ * request.
1210
+ *
1211
+ * @see {@link PermissionController.acceptPermissionsRequest} and
1212
+ * {@link PermissionController.rejectPermissionsRequest} for usage.
1213
+ * @param options - The {@link HasApprovalRequest} options.
1214
+ * @param options.id - The id of the approval request to check for.
1215
+ * @returns Whether the specified request exists.
1216
+ */
1217
+ hasApprovalRequest(options) {
1218
+ return this.messagingSystem.call('ApprovalController:hasRequest', options);
1219
+ }
1220
+ /**
1221
+ * Rejects the permissions request with the specified id, with the specified
1222
+ * error as the reason. This method is effectively a wrapper around a
1223
+ * messenger call for the `ApprovalController:rejectRequest` action.
1224
+ *
1225
+ * @see {@link PermissionController.acceptPermissionsRequest} and
1226
+ * {@link PermissionController.rejectPermissionsRequest} for usage.
1227
+ * @param id - The id of the request to reject.
1228
+ * @param error - The error associated with the rejection.
1229
+ * @returns Nothing
1230
+ */
1231
+ _rejectPermissionsRequest(id, error) {
1232
+ return this.messagingSystem.call('ApprovalController:rejectRequest', id, error);
1233
+ }
1234
+ /**
1235
+ * Gets the subject's endowments per the specified endowment permission.
1236
+ * Throws if the subject does not have the required permission or if the
1237
+ * permission is not an endowment permission.
1238
+ *
1239
+ * @param origin - The origin of the subject whose endowments to retrieve.
1240
+ * @param targetName - The name of the endowment permission. This must be a
1241
+ * valid permission target name.
1242
+ * @param requestData - Additional data associated with the request, if any.
1243
+ * Forwarded to the endowment getter function for the permission.
1244
+ * @returns The endowments, if any.
1245
+ */
1246
+ async getEndowments(origin, targetName, requestData) {
1247
+ if (!this.hasPermission(origin, targetName)) {
1248
+ throw (0, errors_1.unauthorized)({ data: { origin, targetName } });
1249
+ }
1250
+ return this.getTypedPermissionSpecification(Permission_1.PermissionType.Endowment, targetName, origin).endowmentGetter({ origin, requestData });
1251
+ }
1252
+ /**
1253
+ * Executes a restricted method as the subject with the given origin.
1254
+ * The specified params, if any, will be passed to the method implementation.
1255
+ *
1256
+ * ATTN: Great caution should be exercised in the use of this method.
1257
+ * Methods that cause side effects or affect application state should
1258
+ * be avoided.
1259
+ *
1260
+ * This method will first attempt to retrieve the requested restricted method
1261
+ * implementation, throwing if it does not exist. The method will then be
1262
+ * invoked as though the subject with the specified origin had invoked it with
1263
+ * the specified parameters. This means that any existing caveats will be
1264
+ * applied to the restricted method, and this method will throw if the
1265
+ * restricted method or its caveat decorators throw.
1266
+ *
1267
+ * In addition, this method will throw if the subject does not have a
1268
+ * permission for the specified restricted method.
1269
+ *
1270
+ * @param origin - The origin of the subject to execute the method on behalf
1271
+ * of.
1272
+ * @param targetName - The name of the method to execute. This must be a valid
1273
+ * permission target name.
1274
+ * @param params - The parameters to pass to the method implementation.
1275
+ * @returns The result of the executed method.
1276
+ */
1277
+ async executeRestrictedMethod(origin, targetName, params) {
1278
+ // Throws if the method does not exist
1279
+ const methodImplementation = this.getRestrictedMethod(targetName, origin);
1280
+ const result = await this._executeRestrictedMethod(methodImplementation, { origin }, targetName, params);
1281
+ if (result === undefined) {
1282
+ throw new Error(`Internal request for method "${targetName}" as origin "${origin}" returned no result.`);
1283
+ }
1284
+ return result;
1285
+ }
1286
+ /**
1287
+ * An internal method used in the controller's `json-rpc-engine` middleware
1288
+ * and {@link PermissionController.executeRestrictedMethod}. Calls the
1289
+ * specified restricted method implementation after decorating it with the
1290
+ * caveats of its permission. Throws if the subject does not have the
1291
+ * requisite permission.
1292
+ *
1293
+ * ATTN: Parameter validation is the responsibility of the caller, or
1294
+ * the restricted method implementation in the case of `params`.
1295
+ *
1296
+ * @see {@link PermissionController.executeRestrictedMethod} and
1297
+ * {@link PermissionController.createPermissionMiddleware} for usage.
1298
+ * @param methodImplementation - The implementation of the method to call.
1299
+ * @param subject - Metadata about the subject that made the request.
1300
+ * @param method - The method name
1301
+ * @param params - Params needed for executing the restricted method
1302
+ * @returns The result of the restricted method implementation
1303
+ */
1304
+ _executeRestrictedMethod(methodImplementation, subject, method, params = []) {
1305
+ const { origin } = subject;
1306
+ const permission = this.getPermission(origin, method);
1307
+ if (!permission) {
1308
+ throw (0, errors_1.unauthorized)({ data: { origin, method } });
1309
+ }
1310
+ return (0, Caveat_1.decorateWithCaveats)(methodImplementation, permission, this._caveatSpecifications)({ method, params, context: { origin } });
1311
+ }
1312
+ }
1313
+ exports.PermissionController = PermissionController;
1314
+ _PermissionController_instances = new WeakSet(), _PermissionController_expectGetCaveatMerger = function _PermissionController_expectGetCaveatMerger(caveatType) {
1315
+ const { merger } = this.getCaveatSpecification(caveatType);
1316
+ if (merger === undefined) {
1317
+ throw new errors_1.CaveatMergerDoesNotExistError(caveatType);
1318
+ }
1319
+ return merger;
1320
+ }, _PermissionController_applyGrantedPermissions = function _PermissionController_applyGrantedPermissions({ approvedPermissions, subject, mergePermissions, preserveExistingPermissions, requestData, }) {
1321
+ const { origin } = subject;
1322
+ if (!origin || typeof origin !== 'string') {
1323
+ throw new errors_1.InvalidSubjectIdentifierError(origin);
1324
+ }
1325
+ const permissions = (preserveExistingPermissions
1326
+ ? {
1327
+ ...this.getPermissions(origin),
1328
+ }
1329
+ : {});
1330
+ for (const [requestedTarget, approvedPermission] of Object.entries(approvedPermissions)) {
1331
+ if (!this.targetExists(requestedTarget)) {
1332
+ throw (0, errors_1.methodNotFound)(requestedTarget);
1333
+ }
1334
+ if (approvedPermission.parentCapability !== undefined &&
1335
+ requestedTarget !== approvedPermission.parentCapability) {
1336
+ throw new errors_1.InvalidApprovedPermissionError(origin, requestedTarget, approvedPermission);
1337
+ }
1338
+ // We have verified that the target exists, and reassign it to change its
1339
+ // type.
1340
+ const targetName = requestedTarget;
1341
+ const specification = this.getPermissionSpecification(targetName);
1342
+ // The requested caveats are validated here.
1343
+ const caveats = this.constructCaveats(origin, targetName, approvedPermission.caveats);
1344
+ const permissionOptions = {
1345
+ caveats,
1346
+ invoker: origin,
1347
+ target: targetName,
1348
+ };
1349
+ let permission;
1350
+ let performCaveatValidation = true;
1351
+ if (specification.factory) {
1352
+ permission = specification.factory(permissionOptions, requestData);
1353
+ }
1354
+ else {
1355
+ permission = (0, Permission_1.constructPermission)(permissionOptions);
1356
+ // We do not need to validate caveats in this case, because the plain
1357
+ // permission constructor function does not modify the caveats, which
1358
+ // were already validated by `constructCaveats` above.
1359
+ performCaveatValidation = false;
1360
+ }
1361
+ if (mergePermissions) {
1362
+ permission = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_mergePermission).call(this, permissions[targetName], permission)[0];
1363
+ }
1364
+ this.validatePermission(specification, permission, origin, {
1365
+ invokePermissionValidator: true,
1366
+ performCaveatValidation,
1367
+ });
1368
+ permissions[targetName] = permission;
1369
+ }
1370
+ this.setValidatedPermissions(origin, permissions);
1371
+ return permissions;
1372
+ }, _PermissionController_mergeIncrementalPermissions = function _PermissionController_mergeIncrementalPermissions(existingPermissions, incrementalRequestedPermissions) {
1373
+ const permissionDiffMap = {};
1374
+ // Use immer's produce as a convenience for calculating the new permissions
1375
+ // without mutating the existing permissions or committing the results to state.
1376
+ const newPermissions = (0, immer_1.produce)(existingPermissions, (draftExistingPermissions) => {
1377
+ const leftPermissions = draftExistingPermissions;
1378
+ Object.entries(incrementalRequestedPermissions).forEach(([targetName, rightPermission]) => {
1379
+ const leftPermission = leftPermissions[targetName];
1380
+ const [newPermission, caveatsDiff] = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_mergePermission).call(this, leftPermission ?? {}, rightPermission);
1381
+ if (leftPermission === undefined ||
1382
+ Object.keys(caveatsDiff).length > 0) {
1383
+ leftPermissions[targetName] = newPermission;
1384
+ permissionDiffMap[targetName] = caveatsDiff;
1385
+ }
1386
+ // Otherwise, leave the left permission as-is; its authority has
1387
+ // not changed.
1388
+ });
1389
+ });
1390
+ if (Object.keys(permissionDiffMap).length === 0) {
1391
+ return [];
1392
+ }
1393
+ return [newPermissions, permissionDiffMap];
1394
+ }, _PermissionController_mergePermission = function _PermissionController_mergePermission(leftPermission, rightPermission) {
1395
+ const { caveatPairs, leftUniqueCaveats, rightUniqueCaveats } = (0, utils_2.collectUniqueAndPairedCaveats)(leftPermission, rightPermission);
1396
+ const [mergedCaveats, caveatDiffMap] = caveatPairs.reduce(([caveats, diffMap], [leftCaveat, rightCaveat]) => {
1397
+ const [newCaveat, diff] = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_mergeCaveat).call(this, leftCaveat, rightCaveat);
1398
+ if (newCaveat !== undefined && diff !== undefined) {
1399
+ caveats.push(newCaveat);
1400
+ diffMap[newCaveat.type] = diff;
1401
+ }
1402
+ else {
1403
+ caveats.push(leftCaveat);
1404
+ }
1405
+ return [caveats, diffMap];
1406
+ }, [[], {}]);
1407
+ const mergedRightUniqueCaveats = rightUniqueCaveats.map((caveat) => {
1408
+ const [newCaveat, diff] = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_mergeCaveat).call(this, undefined, caveat);
1409
+ caveatDiffMap[newCaveat.type] = diff;
1410
+ return newCaveat;
1411
+ });
1412
+ const allCaveats = [
1413
+ ...mergedCaveats,
1414
+ ...leftUniqueCaveats,
1415
+ ...mergedRightUniqueCaveats,
1416
+ ];
1417
+ const newPermission = {
1418
+ ...leftPermission,
1419
+ ...rightPermission,
1420
+ ...(allCaveats.length > 0
1421
+ ? { caveats: allCaveats }
1422
+ : {}),
1423
+ };
1424
+ return [newPermission, caveatDiffMap];
1425
+ }, _PermissionController_mergeCaveat = function _PermissionController_mergeCaveat(leftCaveat, rightCaveat) {
1426
+ /* istanbul ignore if: This should be impossible */
1427
+ if (leftCaveat !== undefined && leftCaveat.type !== rightCaveat.type) {
1428
+ throw new errors_1.CaveatMergeTypeMismatchError(leftCaveat.type, rightCaveat.type);
1429
+ }
1430
+ const merger = __classPrivateFieldGet(this, _PermissionController_instances, "m", _PermissionController_expectGetCaveatMerger).call(this, rightCaveat.type);
1431
+ if (leftCaveat === undefined) {
1432
+ return [
1433
+ {
1434
+ ...rightCaveat,
1435
+ },
1436
+ rightCaveat.value,
1437
+ ];
1438
+ }
1439
+ const [newValue, diff] = merger(leftCaveat.value, rightCaveat.value);
1440
+ return newValue !== undefined && diff !== undefined
1441
+ ? [
1442
+ {
1443
+ type: rightCaveat.type,
1444
+ value: newValue,
1445
+ },
1446
+ diff,
1447
+ ]
1448
+ : [];
1449
+ }, _PermissionController_handleApprovedPermissions =
1450
+ /**
1451
+ * Accepts a permissions request that has been approved by the user. This
1452
+ * method should be called after the user has approved the request and the
1453
+ * {@link ApprovalController} has resolved the user approval promise.
1454
+ *
1455
+ * @param options - Options bag.
1456
+ * @param options.subject - The subject to grant permissions to.
1457
+ * @param options.metadata - The metadata of the approved permissions request.
1458
+ * @param options.preserveExistingPermissions - Whether to preserve the
1459
+ * subject's existing permissions.
1460
+ * @param options.approvedRequest - The approved permissions request to handle.
1461
+ * @returns The granted permissions and request metadata.
1462
+ */
1463
+ async function _PermissionController_handleApprovedPermissions({ subject, metadata, preserveExistingPermissions, approvedRequest, }) {
1464
+ const { permissions: approvedPermissions, ...requestData } = approvedRequest;
1465
+ const approvedMetadata = { ...metadata };
1466
+ const sideEffects = this.getSideEffects(approvedPermissions);
1467
+ if (Object.values(sideEffects.permittedHandlers).length > 0) {
1468
+ const sideEffectsData = await this.executeSideEffects(sideEffects, approvedRequest);
1469
+ approvedMetadata.data = Object.keys(sideEffects.permittedHandlers).reduce((acc, permission, i) => ({ [permission]: sideEffectsData[i], ...acc }), {});
1470
+ }
1471
+ return [
1472
+ this.grantPermissions({
1473
+ subject,
1474
+ approvedPermissions,
1475
+ preserveExistingPermissions,
1476
+ requestData,
1477
+ }),
1478
+ approvedMetadata,
1479
+ ];
1480
+ };
1481
+ //# sourceMappingURL=PermissionController.cjs.map