@metamask/permission-controller 1.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.
@@ -0,0 +1,870 @@
1
+ import { Patch } from 'immer';
2
+ import { AcceptRequest as AcceptApprovalRequest, AddApprovalRequest, HasApprovalRequest, RejectRequest as RejectApprovalRequest } from '@metamask/approval-controller';
3
+ import { BaseControllerV2, RestrictedControllerMessenger } from '@metamask/base-controller';
4
+ import { Json, NonEmptyArray } from '@metamask/controller-utils';
5
+ import { CaveatConstraint, CaveatSpecificationConstraint, CaveatSpecificationMap, ExtractCaveat, ExtractCaveats, ExtractCaveatValue } from './Caveat';
6
+ import { EndowmentSpecificationConstraint, ExtractAllowedCaveatTypes, OriginString, PermissionConstraint, PermissionSpecificationConstraint, PermissionSpecificationMap, RequestedPermissions, RestrictedMethod, RestrictedMethodParameters, RestrictedMethodSpecificationConstraint, ValidPermission, ValidPermissionSpecification } from './Permission';
7
+ import { getPermissionMiddlewareFactory } from './permission-middleware';
8
+ /**
9
+ * Metadata associated with {@link PermissionController} subjects.
10
+ */
11
+ export declare type PermissionSubjectMetadata = {
12
+ origin: OriginString;
13
+ };
14
+ /**
15
+ * Metadata associated with permission requests.
16
+ */
17
+ export declare type PermissionsRequestMetadata = PermissionSubjectMetadata & {
18
+ id: string;
19
+ };
20
+ /**
21
+ * Used for prompting the user about a proposed new permission.
22
+ * Includes information about the grantee subject, requested permissions, and
23
+ * any additional information added by the consumer.
24
+ *
25
+ * All properties except `permissions` are passed to any factories found for
26
+ * the requested permissions.
27
+ */
28
+ export declare type PermissionsRequest = {
29
+ metadata: PermissionsRequestMetadata;
30
+ permissions: RequestedPermissions;
31
+ [key: string]: Json;
32
+ };
33
+ /**
34
+ * The name of the {@link PermissionController}.
35
+ */
36
+ declare const controllerName = "PermissionController";
37
+ /**
38
+ * Permissions associated with a {@link PermissionController} subject.
39
+ */
40
+ export declare type SubjectPermissions<Permission extends PermissionConstraint> = Record<Permission['parentCapability'], Permission>;
41
+ /**
42
+ * Permissions and metadata associated with a {@link PermissionController}
43
+ * subject.
44
+ */
45
+ export declare type PermissionSubjectEntry<SubjectPermission extends PermissionConstraint> = {
46
+ origin: SubjectPermission['invoker'];
47
+ permissions: SubjectPermissions<SubjectPermission>;
48
+ };
49
+ /**
50
+ * All subjects of a {@link PermissionController}.
51
+ *
52
+ * @template SubjectPermission - The permissions of the subject.
53
+ */
54
+ export declare type PermissionControllerSubjects<SubjectPermission extends PermissionConstraint> = Record<SubjectPermission['invoker'], PermissionSubjectEntry<SubjectPermission>>;
55
+ /**
56
+ * The state of a {@link PermissionController}.
57
+ *
58
+ * @template Permission - The controller's permission type union.
59
+ */
60
+ export declare type PermissionControllerState<Permission> = Permission extends PermissionConstraint ? {
61
+ subjects: PermissionControllerSubjects<Permission>;
62
+ } : never;
63
+ /**
64
+ * Gets the state of the {@link PermissionController}.
65
+ */
66
+ export declare type GetPermissionControllerState = {
67
+ type: `${typeof controllerName}:getState`;
68
+ handler: () => PermissionControllerState<PermissionConstraint>;
69
+ };
70
+ /**
71
+ * Gets the names of all subjects from the {@link PermissionController}.
72
+ */
73
+ export declare type GetSubjects = {
74
+ type: `${typeof controllerName}:getSubjectNames`;
75
+ handler: () => (keyof PermissionControllerSubjects<PermissionConstraint>)[];
76
+ };
77
+ /**
78
+ * Gets the permissions for specified subject
79
+ */
80
+ export declare type GetPermissions = {
81
+ type: `${typeof controllerName}:getPermissions`;
82
+ handler: GenericPermissionController['getPermissions'];
83
+ };
84
+ /**
85
+ * Checks whether the specified subject has any permissions.
86
+ */
87
+ export declare type HasPermissions = {
88
+ type: `${typeof controllerName}:hasPermissions`;
89
+ handler: GenericPermissionController['hasPermissions'];
90
+ };
91
+ /**
92
+ * Checks whether the specified subject has a specific permission.
93
+ */
94
+ export declare type HasPermission = {
95
+ type: `${typeof controllerName}:hasPermission`;
96
+ handler: GenericPermissionController['hasPermission'];
97
+ };
98
+ /**
99
+ * Directly grants given permissions for a specificed origin without requesting user approval
100
+ */
101
+ export declare type GrantPermissions = {
102
+ type: `${typeof controllerName}:grantPermissions`;
103
+ handler: GenericPermissionController['grantPermissions'];
104
+ };
105
+ /**
106
+ * Requests given permissions for a specified origin
107
+ */
108
+ export declare type RequestPermissions = {
109
+ type: `${typeof controllerName}:requestPermissions`;
110
+ handler: GenericPermissionController['requestPermissions'];
111
+ };
112
+ /**
113
+ * Removes the specified permissions for each origin.
114
+ */
115
+ export declare type RevokePermissions = {
116
+ type: `${typeof controllerName}:revokePermissions`;
117
+ handler: GenericPermissionController['revokePermissions'];
118
+ };
119
+ /**
120
+ * Removes all permissions for a given origin
121
+ */
122
+ export declare type RevokeAllPermissions = {
123
+ type: `${typeof controllerName}:revokeAllPermissions`;
124
+ handler: GenericPermissionController['revokeAllPermissions'];
125
+ };
126
+ /**
127
+ * Revokes all permissions corresponding to the specified target for all subjects.
128
+ * Does nothing if no subjects or no such permission exists.
129
+ */
130
+ export declare type RevokePermissionForAllSubjects = {
131
+ type: `${typeof controllerName}:revokePermissionForAllSubjects`;
132
+ handler: GenericPermissionController['revokePermissionForAllSubjects'];
133
+ };
134
+ /**
135
+ * Clears all permissions from the {@link PermissionController}.
136
+ */
137
+ export declare type ClearPermissions = {
138
+ type: `${typeof controllerName}:clearPermissions`;
139
+ handler: () => void;
140
+ };
141
+ /**
142
+ * Gets the endowments for the given subject and permission.
143
+ */
144
+ export declare type GetEndowments = {
145
+ type: `${typeof controllerName}:getEndowments`;
146
+ handler: GenericPermissionController['getEndowments'];
147
+ };
148
+ /**
149
+ * The {@link ControllerMessenger} actions of the {@link PermissionController}.
150
+ */
151
+ export declare type PermissionControllerActions = ClearPermissions | GetEndowments | GetPermissionControllerState | GetSubjects | GetPermissions | HasPermission | HasPermissions | GrantPermissions | RequestPermissions | RevokeAllPermissions | RevokePermissionForAllSubjects | RevokePermissions;
152
+ /**
153
+ * The generic state change event of the {@link PermissionController}.
154
+ */
155
+ export declare type PermissionControllerStateChange = {
156
+ type: `${typeof controllerName}:stateChange`;
157
+ payload: [PermissionControllerState<PermissionConstraint>, Patch[]];
158
+ };
159
+ /**
160
+ * The {@link ControllerMessenger} events of the {@link PermissionController}.
161
+ *
162
+ * The permission controller only emits its generic state change events.
163
+ * Consumers should use selector subscriptions to subscribe to relevant
164
+ * substate.
165
+ */
166
+ export declare type PermissionControllerEvents = PermissionControllerStateChange;
167
+ /**
168
+ * The external {@link ControllerMessenger} actions available to the
169
+ * {@link PermissionController}.
170
+ */
171
+ declare type AllowedActions = AddApprovalRequest | HasApprovalRequest | AcceptApprovalRequest | RejectApprovalRequest;
172
+ /**
173
+ * The messenger of the {@link PermissionController}.
174
+ */
175
+ export declare type PermissionControllerMessenger = RestrictedControllerMessenger<typeof controllerName, PermissionControllerActions | AllowedActions, PermissionControllerEvents, AllowedActions['type'], never>;
176
+ /**
177
+ * A generic {@link PermissionController}.
178
+ */
179
+ export declare type GenericPermissionController = PermissionController<PermissionSpecificationConstraint, CaveatSpecificationConstraint>;
180
+ /**
181
+ * Describes the possible results of a {@link CaveatMutator} function.
182
+ */
183
+ export declare enum CaveatMutatorOperation {
184
+ noop = 0,
185
+ updateValue = 1,
186
+ deleteCaveat = 2,
187
+ revokePermission = 3
188
+ }
189
+ /**
190
+ * Given a caveat value, returns a {@link CaveatMutatorOperation} and, optionally,
191
+ * a new caveat value.
192
+ *
193
+ * @see {@link PermissionController.updatePermissionsByCaveat} for more details.
194
+ * @template Caveat - The caveat type for which this mutator is intended.
195
+ * @param caveatValue - The existing value of the caveat being mutated.
196
+ * @returns A tuple of the mutation result and, optionally, the new caveat
197
+ * value.
198
+ */
199
+ export declare type CaveatMutator<TargetCaveat extends CaveatConstraint> = (caveatValue: TargetCaveat['value']) => CaveatMutatorResult;
200
+ declare type CaveatMutatorResult = Readonly<{
201
+ operation: CaveatMutatorOperation.updateValue;
202
+ value: CaveatConstraint['value'];
203
+ }> | Readonly<{
204
+ operation: Exclude<CaveatMutatorOperation, CaveatMutatorOperation.updateValue>;
205
+ }>;
206
+ /**
207
+ * Extracts the permission(s) specified by the given permission and caveat
208
+ * specifications.
209
+ *
210
+ * @template ControllerPermissionSpecification - The permission specification(s)
211
+ * to extract from.
212
+ * @template ControllerCaveatSpecification - The caveat specification(s) to
213
+ * extract from. Necessary because {@link Permission} has a generic parameter
214
+ * that describes the allowed caveats for the permission.
215
+ */
216
+ export declare type ExtractPermission<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> = ControllerPermissionSpecification extends ValidPermissionSpecification<ControllerPermissionSpecification> ? ValidPermission<ControllerPermissionSpecification['targetKey'], ExtractCaveats<ControllerCaveatSpecification>> : never;
217
+ /**
218
+ * Extracts the restricted method permission(s) specified by the given
219
+ * permission and caveat specifications.
220
+ *
221
+ * @template ControllerPermissionSpecification - The permission specification(s)
222
+ * to extract from.
223
+ * @template ControllerCaveatSpecification - The caveat specification(s) to
224
+ * extract from. Necessary because {@link Permission} has a generic parameter
225
+ * that describes the allowed caveats for the permission.
226
+ */
227
+ export declare type ExtractRestrictedMethodPermission<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> = ExtractPermission<Extract<ControllerPermissionSpecification, RestrictedMethodSpecificationConstraint>, ControllerCaveatSpecification>;
228
+ /**
229
+ * Extracts the endowment permission(s) specified by the given permission and
230
+ * caveat specifications.
231
+ *
232
+ * @template ControllerPermissionSpecification - The permission specification(s)
233
+ * to extract from.
234
+ * @template ControllerCaveatSpecification - The caveat specification(s) to
235
+ * extract from. Necessary because {@link Permission} has a generic parameter
236
+ * that describes the allowed caveats for the permission.
237
+ */
238
+ export declare type ExtractEndowmentPermission<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> = ExtractPermission<Extract<ControllerPermissionSpecification, EndowmentSpecificationConstraint>, ControllerCaveatSpecification>;
239
+ /**
240
+ * Options for the {@link PermissionController} constructor.
241
+ *
242
+ * @template ControllerPermissionSpecification - A union of the types of all
243
+ * permission specifications available to the controller. Any referenced caveats
244
+ * must be included in the controller's caveat specifications.
245
+ * @template ControllerCaveatSpecification - A union of the types of all
246
+ * caveat specifications available to the controller.
247
+ */
248
+ export declare type PermissionControllerOptions<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> = {
249
+ messenger: PermissionControllerMessenger;
250
+ caveatSpecifications: CaveatSpecificationMap<ControllerCaveatSpecification>;
251
+ permissionSpecifications: PermissionSpecificationMap<ControllerPermissionSpecification>;
252
+ unrestrictedMethods: string[];
253
+ state?: Partial<PermissionControllerState<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>>;
254
+ };
255
+ /**
256
+ * The permission controller. See the [Architecture](../ARCHITECTURE.md)
257
+ * document for details.
258
+ *
259
+ * Assumes the existence of an {@link ApprovalController} reachable via the
260
+ * {@link ControllerMessenger}.
261
+ *
262
+ * @template ControllerPermissionSpecification - A union of the types of all
263
+ * permission specifications available to the controller. Any referenced caveats
264
+ * must be included in the controller's caveat specifications.
265
+ * @template ControllerCaveatSpecification - A union of the types of all
266
+ * caveat specifications available to the controller.
267
+ */
268
+ export declare class PermissionController<ControllerPermissionSpecification extends PermissionSpecificationConstraint, ControllerCaveatSpecification extends CaveatSpecificationConstraint> extends BaseControllerV2<typeof controllerName, PermissionControllerState<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>, PermissionControllerMessenger> {
269
+ private readonly _caveatSpecifications;
270
+ private readonly _permissionSpecifications;
271
+ private readonly _unrestrictedMethods;
272
+ /**
273
+ * The names of all JSON-RPC methods that will be ignored by the controller.
274
+ *
275
+ * @returns The names of all unrestricted JSON-RPC methods
276
+ */
277
+ get unrestrictedMethods(): ReadonlySet<string>;
278
+ /**
279
+ * Returns a `json-rpc-engine` middleware function factory, so that the rules
280
+ * described by the state of this controller can be applied to incoming
281
+ * JSON-RPC requests.
282
+ *
283
+ * The middleware **must** be added in the correct place in the middleware
284
+ * stack in order for it to work. See the README for an example.
285
+ */
286
+ createPermissionMiddleware: ReturnType<typeof getPermissionMiddlewareFactory>;
287
+ /**
288
+ * Constructs the PermissionController.
289
+ *
290
+ * @param options - Permission controller options.
291
+ * @param options.caveatSpecifications - The specifications of all caveats
292
+ * available to the controller. See {@link CaveatSpecificationMap} and the
293
+ * documentation for more details.
294
+ * @param options.permissionSpecifications - The specifications of all
295
+ * permissions available to the controller. See
296
+ * {@link PermissionSpecificationMap} and the README for more details.
297
+ * @param options.unrestrictedMethods - The callable names of all JSON-RPC
298
+ * methods ignored by the new controller.
299
+ * @param options.messenger - The controller messenger. See
300
+ * {@link BaseControllerV2} for more information.
301
+ * @param options.state - Existing state to hydrate the controller with at
302
+ * initialization.
303
+ */
304
+ constructor(options: PermissionControllerOptions<ControllerPermissionSpecification, ControllerCaveatSpecification>);
305
+ /**
306
+ * Gets a permission specification.
307
+ *
308
+ * @param targetKey - The target key of the permission specification to get.
309
+ * @returns The permission specification with the specified target key.
310
+ */
311
+ private getPermissionSpecification;
312
+ /**
313
+ * Gets a caveat specification.
314
+ *
315
+ * @param caveatType - The type of the caveat specification to get.
316
+ * @returns The caveat specification with the specified type.
317
+ */
318
+ private getCaveatSpecification;
319
+ /**
320
+ * Constructor helper for validating permission specifications. This is
321
+ * intended to prevent the use of invalid target keys which, while impossible
322
+ * to add in TypeScript, could rather easily occur in plain JavaScript.
323
+ *
324
+ * Throws an error if validation fails.
325
+ *
326
+ * @param permissionSpecifications - The permission specifications passed to
327
+ * this controller's constructor.
328
+ * @param caveatSpecifications - The caveat specifications passed to this
329
+ * controller.
330
+ */
331
+ private validatePermissionSpecifications;
332
+ /**
333
+ * Constructor helper for registering the controller's messaging system
334
+ * actions.
335
+ */
336
+ private registerMessageHandlers;
337
+ /**
338
+ * Clears the state of the controller.
339
+ */
340
+ clearState(): void;
341
+ /**
342
+ * Gets the permission specification corresponding to the given permission
343
+ * type and target name. Throws an error if the target name does not
344
+ * correspond to a permission, or if the specification is not of the
345
+ * given permission type.
346
+ *
347
+ * @template Type - The type of the permission specification to get.
348
+ * @param permissionType - The type of the permission specification to get.
349
+ * @param targetName - The name of the permission whose specification to get.
350
+ * @param requestingOrigin - The origin of the requesting subject, if any.
351
+ * Will be added to any thrown errors.
352
+ * @returns The specification object corresponding to the given type and
353
+ * target name.
354
+ */
355
+ private getTypedPermissionSpecification;
356
+ /**
357
+ * Gets the implementation of the specified restricted method.
358
+ *
359
+ * A JSON-RPC error is thrown if the method does not exist.
360
+ *
361
+ * @see {@link PermissionController.executeRestrictedMethod} and
362
+ * {@link PermissionController.createPermissionMiddleware} for internal usage.
363
+ * @param method - The name of the restricted method.
364
+ * @param origin - The origin associated with the request for the restricted
365
+ * method, if any.
366
+ * @returns The restricted method implementation.
367
+ */
368
+ getRestrictedMethod(method: string, origin?: string): RestrictedMethod<RestrictedMethodParameters, Json>;
369
+ /**
370
+ * Gets a list of all origins of subjects.
371
+ *
372
+ * @returns The origins (i.e. IDs) of all subjects.
373
+ */
374
+ getSubjectNames(): OriginString[];
375
+ /**
376
+ * Gets the permission for the specified target of the subject corresponding
377
+ * to the specified origin.
378
+ *
379
+ * @param origin - The origin of the subject.
380
+ * @param targetName - The method name as invoked by a third party (i.e., not
381
+ * a method key).
382
+ * @returns The permission if it exists, or undefined otherwise.
383
+ */
384
+ getPermission<SubjectPermission extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>(origin: OriginString, targetName: SubjectPermission['parentCapability']): SubjectPermission | undefined;
385
+ /**
386
+ * Gets all permissions for the specified subject, if any.
387
+ *
388
+ * @param origin - The origin of the subject.
389
+ * @returns The permissions of the subject, if any.
390
+ */
391
+ getPermissions(origin: OriginString): SubjectPermissions<ValidPermission<string, ExtractCaveats<ControllerCaveatSpecification>>> | undefined;
392
+ /**
393
+ * Checks whether the subject with the specified origin has the specified
394
+ * permission.
395
+ *
396
+ * @param origin - The origin of the subject.
397
+ * @param target - The target name of the permission.
398
+ * @returns Whether the subject has the permission.
399
+ */
400
+ hasPermission(origin: OriginString, target: ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability']): boolean;
401
+ /**
402
+ * Checks whether the subject with the specified origin has any permissions.
403
+ * Use this if you want to know if a subject "exists".
404
+ *
405
+ * @param origin - The origin of the subject to check.
406
+ * @returns Whether the subject has any permissions.
407
+ */
408
+ hasPermissions(origin: OriginString): boolean;
409
+ /**
410
+ * Revokes all permissions from the specified origin.
411
+ *
412
+ * Throws an error of the origin has no permissions.
413
+ *
414
+ * @param origin - The origin whose permissions to revoke.
415
+ */
416
+ revokeAllPermissions(origin: OriginString): void;
417
+ /**
418
+ * Revokes the specified permission from the subject with the specified
419
+ * origin.
420
+ *
421
+ * Throws an error if the subject or the permission does not exist.
422
+ *
423
+ * @param origin - The origin of the subject whose permission to revoke.
424
+ * @param target - The target name of the permission to revoke.
425
+ */
426
+ revokePermission(origin: OriginString, target: ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability']): void;
427
+ /**
428
+ * Revokes the specified permissions from the specified subjects.
429
+ *
430
+ * Throws an error if any of the subjects or permissions do not exist.
431
+ *
432
+ * @param subjectsAndPermissions - An object mapping subject origins
433
+ * to arrays of permission target names to revoke.
434
+ */
435
+ revokePermissions(subjectsAndPermissions: Record<OriginString, NonEmptyArray<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability']>>): void;
436
+ /**
437
+ * Revokes all permissions corresponding to the specified target for all subjects.
438
+ * Does nothing if no subjects or no such permission exists.
439
+ *
440
+ * @param target - The name of the target to revoke all permissions for.
441
+ */
442
+ revokePermissionForAllSubjects(target: ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability']): void;
443
+ /**
444
+ * Deletes the permission identified by the given origin and target. If the
445
+ * permission is the single remaining permission of its subject, the subject
446
+ * is also deleted.
447
+ *
448
+ * @param subjects - The draft permission controller subjects.
449
+ * @param origin - The origin of the subject associated with the permission
450
+ * to delete.
451
+ * @param target - The target name of the permission to delete.
452
+ */
453
+ private deletePermission;
454
+ /**
455
+ * Checks whether the permission of the subject corresponding to the given
456
+ * origin has a caveat of the specified type.
457
+ *
458
+ * Throws an error if the subject does not have a permission with the
459
+ * specified target name.
460
+ *
461
+ * @template TargetName - The permission target name. Should be inferred.
462
+ * @template CaveatType - The valid caveat types for the permission. Should
463
+ * be inferred.
464
+ * @param origin - The origin of the subject.
465
+ * @param target - The target name of the permission.
466
+ * @param caveatType - The type of the caveat to check for.
467
+ * @returns Whether the permission has the specified caveat.
468
+ */
469
+ hasCaveat<TargetName extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>>(origin: OriginString, target: TargetName, caveatType: CaveatType): boolean;
470
+ /**
471
+ * Gets the caveat of the specified type, if any, for the permission of
472
+ * the subject corresponding to the given origin.
473
+ *
474
+ * Throws an error if the subject does not have a permission with the
475
+ * specified target name.
476
+ *
477
+ * @template TargetName - The permission target name. Should be inferred.
478
+ * @template CaveatType - The valid caveat types for the permission. Should
479
+ * be inferred.
480
+ * @param origin - The origin of the subject.
481
+ * @param target - The target name of the permission.
482
+ * @param caveatType - The type of the caveat to get.
483
+ * @returns The caveat, or `undefined` if no such caveat exists.
484
+ */
485
+ getCaveat<TargetName extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>>(origin: OriginString, target: TargetName, caveatType: CaveatType): ExtractCaveat<ControllerCaveatSpecification, CaveatType> | undefined;
486
+ /**
487
+ * Adds a caveat of the specified type, with the specified caveat value, to
488
+ * the permission corresponding to the given subject origin and permission
489
+ * target.
490
+ *
491
+ * For modifying existing caveats, use
492
+ * {@link PermissionController.updateCaveat}.
493
+ *
494
+ * Throws an error if no such permission exists, or if the caveat already
495
+ * exists.
496
+ *
497
+ * @template TargetName - The permission target name. Should be inferred.
498
+ * @template CaveatType - The valid caveat types for the permission. Should
499
+ * be inferred.
500
+ * @param origin - The origin of the subject.
501
+ * @param target - The target name of the permission.
502
+ * @param caveatType - The type of the caveat to add.
503
+ * @param caveatValue - The value of the caveat to add.
504
+ */
505
+ addCaveat<TargetName extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>>(origin: OriginString, target: TargetName, caveatType: CaveatType, caveatValue: ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>): void;
506
+ /**
507
+ * Updates the value of the caveat of the specified type belonging to the
508
+ * permission corresponding to the given subject origin and permission
509
+ * target.
510
+ *
511
+ * For adding new caveats, use
512
+ * {@link PermissionController.addCaveat}.
513
+ *
514
+ * Throws an error if no such permission or caveat exists.
515
+ *
516
+ * @template TargetName - The permission target name. Should be inferred.
517
+ * @template CaveatType - The valid caveat types for the permission. Should
518
+ * be inferred.
519
+ * @param origin - The origin of the subject.
520
+ * @param target - The target name of the permission.
521
+ * @param caveatType - The type of the caveat to update.
522
+ * @param caveatValue - The new value of the caveat.
523
+ */
524
+ updateCaveat<TargetName extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>, CaveatValue extends ExtractCaveatValue<ControllerCaveatSpecification, CaveatType>>(origin: OriginString, target: TargetName, caveatType: CaveatType, caveatValue: CaveatValue): void;
525
+ /**
526
+ * Sets the specified caveat on the specified permission. Overwrites existing
527
+ * caveats of the same type in-place (preserving array order), and adds the
528
+ * caveat to the end of the array otherwise.
529
+ *
530
+ * Throws an error if the permission does not exist or fails to validate after
531
+ * its caveats have been modified.
532
+ *
533
+ * @see {@link PermissionController.addCaveat}
534
+ * @see {@link PermissionController.updateCaveat}
535
+ * @template TargetName - The permission target name. Should be inferred.
536
+ * @template CaveatType - The valid caveat types for the permission. Should
537
+ * be inferred.
538
+ * @param origin - The origin of the subject.
539
+ * @param target - The target name of the permission.
540
+ * @param caveatType - The type of the caveat to set.
541
+ * @param caveatValue - The value of the caveat to set.
542
+ */
543
+ private setCaveat;
544
+ /**
545
+ * Updates all caveats with the specified type for all subjects and
546
+ * permissions by applying the specified mutator function to them.
547
+ *
548
+ * ATTN: Permissions can be revoked entirely by the action of this method,
549
+ * read on for details.
550
+ *
551
+ * Caveat mutators are functions that receive a caveat value and return a
552
+ * tuple consisting of a {@link CaveatMutatorOperation} and, optionally, a new
553
+ * value to update the existing caveat with.
554
+ *
555
+ * For each caveat, depending on the mutator result, this method will:
556
+ * - Do nothing ({@link CaveatMutatorOperation.noop})
557
+ * - Update the value of the caveat ({@link CaveatMutatorOperation.updateValue}). The caveat specification validator, if any, will be called after updating the value.
558
+ * - Delete the caveat ({@link CaveatMutatorOperation.deleteCaveat}). The permission specification validator, if any, will be called after deleting the caveat.
559
+ * - Revoke the parent permission ({@link CaveatMutatorOperation.revokePermission})
560
+ *
561
+ * This method throws if the validation of any caveat or permission fails.
562
+ *
563
+ * @param targetCaveatType - The type of the caveats to update.
564
+ * @param mutator - The mutator function which will be applied to all caveat
565
+ * values.
566
+ */
567
+ updatePermissionsByCaveat<CaveatType extends ExtractCaveats<ControllerCaveatSpecification>['type'], TargetCaveat extends ExtractCaveat<ControllerCaveatSpecification, CaveatType>>(targetCaveatType: CaveatType, mutator: CaveatMutator<TargetCaveat>): void;
568
+ /**
569
+ * Removes the caveat of the specified type from the permission corresponding
570
+ * to the given subject origin and target name.
571
+ *
572
+ * Throws an error if no such permission or caveat exists.
573
+ *
574
+ * @template TargetName - The permission target name. Should be inferred.
575
+ * @template CaveatType - The valid caveat types for the permission. Should
576
+ * be inferred.
577
+ * @param origin - The origin of the subject.
578
+ * @param target - The target name of the permission.
579
+ * @param caveatType - The type of the caveat to remove.
580
+ */
581
+ removeCaveat<TargetName extends ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], CaveatType extends ExtractAllowedCaveatTypes<ControllerPermissionSpecification>>(origin: OriginString, target: TargetName, caveatType: CaveatType): void;
582
+ /**
583
+ * Deletes the specified caveat from the specified permission. If no caveats
584
+ * remain after deletion, the permission's caveat property is set to `null`.
585
+ * The permission is validated after being modified.
586
+ *
587
+ * Throws an error if the permission does not have a caveat with the specified
588
+ * type.
589
+ *
590
+ * @param permission - The permission whose caveat to delete.
591
+ * @param caveatType - The type of the caveat to delete.
592
+ * @param origin - The origin the permission subject.
593
+ * @param target - The name of the permission target.
594
+ */
595
+ private deleteCaveat;
596
+ /**
597
+ * Validates the specified modified permission. Should **always** be invoked
598
+ * on a permission after its caveats have been modified.
599
+ *
600
+ * Just like {@link PermissionController.validatePermission}, except that the
601
+ * corresponding target key and specification are retrieved first, and an
602
+ * error is thrown if the target key does not exist.
603
+ *
604
+ * @param permission - The modified permission to validate.
605
+ * @param origin - The origin associated with the permission.
606
+ * @param targetName - The target name name of the permission.
607
+ */
608
+ private validateModifiedPermission;
609
+ /**
610
+ * Gets the key for the specified permission target.
611
+ *
612
+ * Used to support our namespaced permission target feature, which is used
613
+ * to implement namespaced restricted JSON-RPC methods.
614
+ *
615
+ * @param target - The requested permission target.
616
+ * @returns The internal key of the permission target.
617
+ */
618
+ private getTargetKey;
619
+ /**
620
+ * Grants _approved_ permissions to the specified subject. Every permission and
621
+ * caveat is stringently validated – including by calling every specification
622
+ * validator – and an error is thrown if any validation fails.
623
+ *
624
+ * ATTN: This method does **not** prompt the user for approval.
625
+ *
626
+ * @see {@link PermissionController.requestPermissions} For initiating a
627
+ * permissions request requiring user approval.
628
+ * @param options - Options bag.
629
+ * @param options.approvedPermissions - The requested permissions approved by
630
+ * the user.
631
+ * @param options.requestData - Permission request data. Passed to permission
632
+ * factory functions.
633
+ * @param options.preserveExistingPermissions - Whether to preserve the
634
+ * subject's existing permissions.
635
+ * @param options.subject - The subject to grant permissions to.
636
+ * @returns The granted permissions.
637
+ */
638
+ grantPermissions({ approvedPermissions, requestData, preserveExistingPermissions, subject, }: {
639
+ approvedPermissions: RequestedPermissions;
640
+ subject: PermissionSubjectMetadata;
641
+ preserveExistingPermissions?: boolean;
642
+ requestData?: Record<string, unknown>;
643
+ }): SubjectPermissions<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>;
644
+ /**
645
+ * Validates the specified permission by:
646
+ * - Ensuring that its `caveats` property is either `null` or a non-empty array.
647
+ * - Ensuring that it only includes caveats allowed by its specification.
648
+ * - Ensuring that it includes no duplicate caveats (by caveat type).
649
+ * - Validating each caveat object, if `performCaveatValidation` is `true`.
650
+ * - Calling the validator of its specification, if one exists and `invokePermissionValidator` is `true`.
651
+ *
652
+ * An error is thrown if validation fails.
653
+ *
654
+ * @param specification - The specification of the permission.
655
+ * @param permission - The permission to validate.
656
+ * @param origin - The origin associated with the permission.
657
+ * @param targetName - The target name of the permission.
658
+ * @param validationOptions - Validation options.
659
+ * @param validationOptions.invokePermissionValidator - Whether to invoke the
660
+ * permission's consumer-specified validator function, if any.
661
+ * @param validationOptions.performCaveatValidation - Whether to invoke
662
+ * {@link PermissionController.validateCaveat} on each of the permission's
663
+ * caveats.
664
+ */
665
+ private validatePermission;
666
+ /**
667
+ * Assigns the specified permissions to the subject with the given origin.
668
+ * Overwrites all existing permissions, and creates a subject entry if it
669
+ * doesn't already exist.
670
+ *
671
+ * ATTN: Assumes that the new permissions have been validated.
672
+ *
673
+ * @param origin - The origin of the grantee subject.
674
+ * @param permissions - The new permissions for the grantee subject.
675
+ */
676
+ private setValidatedPermissions;
677
+ /**
678
+ * Validates the requested caveats for the permission of the specified
679
+ * subject origin and target name and returns the validated caveat array.
680
+ *
681
+ * Throws an error if validation fails.
682
+ *
683
+ * @param origin - The origin of the permission subject.
684
+ * @param target - The permission target name.
685
+ * @param requestedCaveats - The requested caveats to construct.
686
+ * @returns The constructed caveats.
687
+ */
688
+ private constructCaveats;
689
+ /**
690
+ * This methods validates that the specified caveat is an object with the
691
+ * expected properties and types. It also ensures that a caveat specification
692
+ * exists for the requested caveat type, and calls the specification
693
+ * validator, if it exists, on the caveat object.
694
+ *
695
+ * Throws an error if validation fails.
696
+ *
697
+ * @param caveat - The caveat object to validate.
698
+ * @param origin - The origin associated with the subject of the parent
699
+ * permission.
700
+ * @param target - The target name associated with the parent permission.
701
+ */
702
+ private validateCaveat;
703
+ /**
704
+ * Initiates a permission request that requires user approval. This should
705
+ * always be used to grant additional permissions to a subject, unless user
706
+ * approval has been obtained through some other means.
707
+ *
708
+ * Permissions are validated at every step of the approval process, and this
709
+ * method will reject if validation fails.
710
+ *
711
+ * @see {@link ApprovalController} For the user approval logic.
712
+ * @see {@link PermissionController.acceptPermissionsRequest} For the method
713
+ * that _accepts_ the request and resolves the user approval promise.
714
+ * @see {@link PermissionController.rejectPermissionsRequest} For the method
715
+ * that _rejects_ the request and the user approval promise.
716
+ * @param subject - The grantee subject.
717
+ * @param requestedPermissions - The requested permissions.
718
+ * @param options - Additional options.
719
+ * @param options.id - The id of the permissions request. Defaults to a unique
720
+ * id.
721
+ * @param options.preserveExistingPermissions - Whether to preserve the
722
+ * subject's existing permissions. Defaults to `true`.
723
+ * @returns The granted permissions and request metadata.
724
+ */
725
+ requestPermissions(subject: PermissionSubjectMetadata, requestedPermissions: RequestedPermissions, options?: {
726
+ id?: string;
727
+ preserveExistingPermissions?: boolean;
728
+ }): Promise<[
729
+ SubjectPermissions<ExtractPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>>,
730
+ {
731
+ id: string;
732
+ origin: OriginString;
733
+ }
734
+ ]>;
735
+ /**
736
+ * Validates requested permissions. Throws if validation fails.
737
+ *
738
+ * This method ensures that the requested permissions are a properly
739
+ * formatted {@link RequestedPermissions} object, and performs the same
740
+ * validation as {@link PermissionController.grantPermissions}, except that
741
+ * consumer-specified permission validator functions are not called, since
742
+ * they are only called on fully constructed, approved permissions that are
743
+ * otherwise completely valid.
744
+ *
745
+ * Unrecognzied properties on requested permissions are ignored.
746
+ *
747
+ * @param origin - The origin of the grantee subject.
748
+ * @param requestedPermissions - The requested permissions.
749
+ */
750
+ private validateRequestedPermissions;
751
+ /**
752
+ * Adds a request to the {@link ApprovalController} using the
753
+ * {@link AddApprovalRequest} action. Also validates the resulting approved
754
+ * permissions request, and throws an error if validation fails.
755
+ *
756
+ * @param permissionsRequest - The permissions request object.
757
+ * @returns The approved permissions request object.
758
+ */
759
+ private requestUserApproval;
760
+ /**
761
+ * Validates an approved {@link PermissionsRequest} object. The approved
762
+ * request must have the required `metadata` and `permissions` properties,
763
+ * the `id` and `origin` of the `metadata` must match the original request
764
+ * metadata, and the requested permissions must be valid per
765
+ * {@link PermissionController.validateRequestedPermissions}. Any extra
766
+ * metadata properties are ignored.
767
+ *
768
+ * An error is thrown if validation fails.
769
+ *
770
+ * @param approvedRequest - The approved permissions request object.
771
+ * @param originalMetadata - The original request metadata.
772
+ */
773
+ private validateApprovedPermissions;
774
+ /**
775
+ * Accepts a permissions request created by
776
+ * {@link PermissionController.requestPermissions}.
777
+ *
778
+ * @param request - The permissions request.
779
+ */
780
+ acceptPermissionsRequest(request: PermissionsRequest): Promise<void>;
781
+ /**
782
+ * Rejects a permissions request created by
783
+ * {@link PermissionController.requestPermissions}.
784
+ *
785
+ * @param id - The id of the request to be rejected.
786
+ */
787
+ rejectPermissionsRequest(id: string): Promise<void>;
788
+ /**
789
+ * Checks whether the {@link ApprovalController} has a particular permissions
790
+ * request.
791
+ *
792
+ * @see {@link PermissionController.acceptPermissionsRequest} and
793
+ * {@link PermissionController.rejectPermissionsRequest} for usage.
794
+ * @param options - The {@link HasApprovalRequest} options.
795
+ * @param options.id - The id of the approval request to check for.
796
+ * @returns Whether the specified request exists.
797
+ */
798
+ private hasApprovalRequest;
799
+ /**
800
+ * Rejects the permissions request with the specified id, with the specified
801
+ * error as the reason. This method is effectively a wrapper around a
802
+ * messenger call for the `ApprovalController:rejectRequest` action.
803
+ *
804
+ * @see {@link PermissionController.acceptPermissionsRequest} and
805
+ * {@link PermissionController.rejectPermissionsRequest} for usage.
806
+ * @param id - The id of the request to reject.
807
+ * @param error - The error associated with the rejection.
808
+ * @returns Nothing
809
+ */
810
+ private _rejectPermissionsRequest;
811
+ /**
812
+ * Gets the subject's endowments per the specified endowment permission.
813
+ * Throws if the subject does not have the required permission or if the
814
+ * permission is not an endowment permission.
815
+ *
816
+ * @param origin - The origin of the subject whose endowments to retrieve.
817
+ * @param targetName - The name of the endowment permission. This must be a
818
+ * valid permission target name.
819
+ * @param requestData - Additional data associated with the request, if any.
820
+ * Forwarded to the endowment getter function for the permission.
821
+ * @returns The endowments, if any.
822
+ */
823
+ getEndowments(origin: string, targetName: ExtractEndowmentPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], requestData?: unknown): Promise<Json>;
824
+ /**
825
+ * Executes a restricted method as the subject with the given origin.
826
+ * The specified params, if any, will be passed to the method implementation.
827
+ *
828
+ * ATTN: Great caution should be exercised in the use of this method.
829
+ * Methods that cause side effects or affect application state should
830
+ * be avoided.
831
+ *
832
+ * This method will first attempt to retrieve the requested restricted method
833
+ * implementation, throwing if it does not exist. The method will then be
834
+ * invoked as though the subject with the specified origin had invoked it with
835
+ * the specified parameters. This means that any existing caveats will be
836
+ * applied to the restricted method, and this method will throw if the
837
+ * restricted method or its caveat decorators throw.
838
+ *
839
+ * In addition, this method will throw if the subject does not have a
840
+ * permission for the specified restricted method.
841
+ *
842
+ * @param origin - The origin of the subject to execute the method on behalf
843
+ * of.
844
+ * @param targetName - The name of the method to execute. This must be a valid
845
+ * permission target name.
846
+ * @param params - The parameters to pass to the method implementation.
847
+ * @returns The result of the executed method.
848
+ */
849
+ executeRestrictedMethod(origin: OriginString, targetName: ExtractRestrictedMethodPermission<ControllerPermissionSpecification, ControllerCaveatSpecification>['parentCapability'], params?: RestrictedMethodParameters): Promise<Json>;
850
+ /**
851
+ * An internal method used in the controller's `json-rpc-engine` middleware
852
+ * and {@link PermissionController.executeRestrictedMethod}. Calls the
853
+ * specified restricted method implementation after decorating it with the
854
+ * caveats of its permission. Throws if the subject does not have the
855
+ * requisite permission.
856
+ *
857
+ * ATTN: Parameter validation is the responsibility of the caller, or
858
+ * the restricted method implementation in the case of `params`.
859
+ *
860
+ * @see {@link PermissionController.executeRestrictedMethod} and
861
+ * {@link PermissionController.createPermissionMiddleware} for usage.
862
+ * @param methodImplementation - The implementation of the method to call.
863
+ * @param subject - Metadata about the subject that made the request.
864
+ * @param method - The method name
865
+ * @param params - Params needed for executing the restricted method
866
+ * @returns The result of the restricted method implementation
867
+ */
868
+ private _executeRestrictedMethod;
869
+ }
870
+ export {};