@metamask/permission-controller 8.0.1 → 9.0.0

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