-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpermissionRequestLifecycleOrchestrator.ts
More file actions
281 lines (247 loc) · 8.1 KB
/
Copy pathpermissionRequestLifecycleOrchestrator.ts
File metadata and controls
281 lines (247 loc) · 8.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import type {
AccountMeta,
PermissionRequest,
PermissionResponse,
} from '@metamask/7715-permissions-shared/types';
import type { Delegation } from '@metamask/delegation-core';
import {
createTimestampTerms,
encodeDelegations,
ROOT_AUTHORITY,
} from '@metamask/delegation-core';
import { bytesToHex, numberToHex } from '@metamask/utils';
import type { AccountController } from '../accountController';
import { getChainMetadata } from './chainMetadata';
import type { ConfirmationDialogFactory } from './confirmationFactory';
import type {
BaseContext,
DeepRequired,
LifecycleOrchestrationHandlers,
PermissionRequestResult,
} from './types';
/**
* Orchestrator for the permission request lifecycle.
* Orchestrates the lifecycle of permission requests, confirmation dialogs, and delegation creation.
*/
export class PermissionRequestLifecycleOrchestrator {
readonly #accountController: AccountController;
readonly #confirmationDialogFactory: ConfirmationDialogFactory;
constructor({
accountController,
confirmationDialogFactory,
}: {
accountController: AccountController;
confirmationDialogFactory: ConfirmationDialogFactory;
}) {
this.#accountController = accountController;
this.#confirmationDialogFactory = confirmationDialogFactory;
}
/**
* Orchestrates the permission request lifecycle.
* @param origin - The origin of the permission request.
* @param permissionRequest - The permission request to orchestrate.
* @param lifecycleHandlers - The lifecycle handlers to call during orchestration.
* @returns The permission response.
*/
async orchestrate<
TRequest extends PermissionRequest,
TContext extends BaseContext,
TMetadata extends object,
TPermission extends TRequest['permission'],
TPopulatedPermission extends DeepRequired<TPermission>,
>(
origin: string,
permissionRequest: PermissionRequest,
lifecycleHandlers: LifecycleOrchestrationHandlers<
TRequest,
TContext,
TMetadata,
TPermission,
TPopulatedPermission
>,
): Promise<PermissionRequestResult> {
const isAdjustmentAllowed = permissionRequest.isAdjustmentAllowed ?? true;
const validatedPermissionRequest =
lifecycleHandlers.parseAndValidatePermission(permissionRequest);
const chainId = parseInt(permissionRequest.chainId, 16);
let context = await lifecycleHandlers.buildContext(
validatedPermissionRequest,
);
const createUiContent = async () => {
const metadata = await lifecycleHandlers.deriveMetadata({ context });
return await lifecycleHandlers.createConfirmationContent({
context,
metadata,
origin,
chainId,
});
};
const confirmationDialog =
this.#confirmationDialogFactory.createConfirmation({
ui: await createUiContent(),
});
const interfaceId = await confirmationDialog.createInterface();
if (lifecycleHandlers.onConfirmationCreated) {
const updateContext = async ({
updatedContext,
}: {
updatedContext: TContext;
}) => {
if (!isAdjustmentAllowed) {
throw new Error('Adjustment is not allowed');
}
context = updatedContext;
await confirmationDialog.updateContent({ ui: await createUiContent() });
};
lifecycleHandlers.onConfirmationCreated({
interfaceId,
updateContext,
initialContext: context,
});
}
try {
const decision = await confirmationDialog.awaitUserDecision();
if (decision.isConfirmationGranted) {
const response = await this.#resolveResponse({
originalRequest: validatedPermissionRequest,
modifiedContext: context,
lifecycleHandlers,
isAdjustmentAllowed,
chainId,
});
return {
approved: true,
response,
};
}
return {
approved: false,
reason: 'Permission request denied',
};
} finally {
if (lifecycleHandlers.onConfirmationResolved) {
lifecycleHandlers.onConfirmationResolved();
}
}
}
/**
* Resolves a permission request into a final permission response.
* @private
* @template TRequest - Type of permission request
* @template TContext - Type of context for the permission request.
* @template TMetadata - Type of metadata associated with the permission request.
* @template TPermission - Type of permission being requested.
* @template TPopulatedPermission - Type of fully populated permission with all required fields.
* @param params - Parameters for resolving the response.
* @param params.originalRequest - The original unmodified permission request.
* @param params.modifiedContext - The possibly modified context after user interaction.
* @param params.lifecycleHandlers - Handlers for the permission lifecycle.
* @param params.isAdjustmentAllowed - Whether the permission can be adjusted.
* @param params.chainId - The chain ID for the permission.
* @returns The resolved permission response.
*/
async #resolveResponse<
TRequest extends PermissionRequest,
TContext extends BaseContext,
TMetadata extends object,
TPermission extends TRequest['permission'],
TPopulatedPermission extends DeepRequired<TPermission>,
>({
originalRequest,
modifiedContext,
lifecycleHandlers,
isAdjustmentAllowed,
chainId,
}: {
originalRequest: TRequest;
modifiedContext: TContext;
isAdjustmentAllowed: boolean;
chainId: number;
lifecycleHandlers: LifecycleOrchestrationHandlers<
TRequest,
TContext,
TMetadata,
TPermission,
TPopulatedPermission
>;
}): Promise<PermissionResponse> {
// apply the changes made to the context to the request
const resolvedRequest = await lifecycleHandlers.applyContext({
context: modifiedContext,
originalRequest,
});
// populate optional values of the permission
const populatedPermission = await lifecycleHandlers.populatePermission({
permission: resolvedRequest.permission as TPermission,
});
// the actual permission being granted
const grantedPermissionRequest = {
...resolvedRequest,
permission: populatedPermission,
isAdjustmentAllowed,
};
const [address, accountMetadata] = await Promise.all([
this.#accountController.getAccountAddress({
chainId,
}),
this.#accountController.getAccountMetadata({
chainId,
}),
]);
const { contracts } = getChainMetadata({ chainId });
const {
enforcers: { TimestampEnforcer },
delegationManager,
} = contracts;
const caveats = await lifecycleHandlers.createPermissionCaveats({
permission: populatedPermission,
contracts,
});
const timestampAfterThreshold = 0;
const timestampBeforeThreshold = grantedPermissionRequest.expiry;
caveats.push({
enforcer: TimestampEnforcer,
terms: createTimestampTerms({
timestampAfterThreshold,
timestampBeforeThreshold,
}),
args: '0x',
});
// eslint-disable-next-line no-restricted-globals
const saltBytes = crypto.getRandomValues(new Uint8Array(32));
const salt = bytesToHex(saltBytes);
const delegation = {
delegate: grantedPermissionRequest.signer.data.address,
authority: ROOT_AUTHORITY,
delegator: address,
caveats,
salt: BigInt(salt),
} as const;
const signedDelegation: Delegation =
await this.#accountController.signDelegation({
chainId,
delegation,
});
const context = encodeDelegations([signedDelegation], { out: 'hex' });
const accountMeta: AccountMeta[] =
accountMetadata.factory && accountMetadata.factoryData
? [
{
factory: accountMetadata.factory,
factoryData: accountMetadata.factoryData,
},
]
: [];
const response: PermissionResponse = {
...grantedPermissionRequest,
chainId: numberToHex(chainId),
address,
accountMeta,
context,
signerMeta: {
delegationManager,
},
};
return response;
}
}