@metamask/permission-controller 13.1.1 → 14.1.0

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