-
Notifications
You must be signed in to change notification settings - Fork 542
/
SnapController.ts
2479 lines (2192 loc) · 70.6 KB
/
SnapController.ts
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AddApprovalRequest } from '@metamask/approval-controller';
import {
BaseControllerV2 as BaseController,
RestrictedControllerMessenger,
} from '@metamask/base-controller';
import { encrypt, decrypt } from '@metamask/browser-passworder';
import {
Caveat,
GetEndowments,
GetPermissions,
GrantPermissions,
HasPermission,
HasPermissions,
PermissionConstraint,
PermissionsRequest,
RevokeAllPermissions,
RevokePermissionForAllSubjects,
RevokePermissions,
SubjectPermissions,
ValidPermission,
} from '@metamask/permission-controller';
import { caveatMappers } from '@metamask/rpc-methods';
import {
assertIsSnapManifest,
BlockedSnapInfo,
DEFAULT_ENDOWMENTS,
DEFAULT_REQUESTED_SNAP_VERSION,
fromEntries,
getSnapPermissionName,
getSnapPrefix,
gtVersion,
InstallSnapsResult,
isValidSemVerRange,
LOCALHOST_HOSTNAMES,
NpmSnapFileNames,
PersistedSnap,
ProcessSnapResult,
RequestedSnapPermissions,
resolveVersionRange,
satisfiesVersionRange,
SemVerRange,
Snap,
SnapId,
SnapIdPrefixes,
SnapManifest,
SnapPermissions,
SnapRpcHook,
SnapRpcHookArgs,
SnapStatus,
SnapStatusEvents,
SNAP_PREFIX,
SNAP_PREFIX_REGEX,
StatusContext,
StatusEvents,
StatusStates,
TruncatedSnap,
TruncatedSnapFields,
ValidatedSnapId,
validateSnapId,
validateSnapShasum,
} from '@metamask/snaps-utils';
import {
assert,
assertExhaustive,
Duration,
hasProperty,
inMilliseconds,
isNonEmptyArray,
isValidJson,
Json,
timeSince,
} from '@metamask/utils';
import { createMachine, interpret, StateMachine } from '@xstate/fsm';
import { ethErrors, serializeError } from 'eth-rpc-errors';
import type { Patch } from 'immer';
import { nanoid } from 'nanoid';
import { forceStrict, validateMachine } from '../fsm';
import {
ExecuteSnapAction,
ExecutionServiceEvents,
HandleRpcRequestAction,
SnapErrorJson,
TerminateAllSnapsAction,
TerminateSnapAction,
} from '../services/ExecutionService';
import { hasTimedOut, setDiff, withTimeout } from '../utils';
import { endowmentCaveatMappers, SnapEndowments } from './endowments';
import { RequestQueue } from './RequestQueue';
import { Timer } from './Timer';
import { fetchNpmSnap } from './utils';
export const controllerName = 'SnapController';
// TODO: Figure out how to name these
export const SNAP_APPROVAL_INSTALL = 'wallet_installSnap';
export const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';
const TRUNCATED_SNAP_PROPERTIES = new Set<TruncatedSnapFields>([
'initialPermissions',
'id',
'permissionName',
'version',
'enabled',
'blocked',
]);
export type PendingRequest = {
requestId: unknown;
timer: Timer;
};
/**
* A wrapper type for any data stored during runtime of Snaps.
* It is not persisted in state as it contains non-serializable data and is only relevant for the
* current session.
*/
export interface SnapRuntimeData {
/**
* A promise that resolves when the Snap has finished installing
*/
installPromise: null | Promise<PersistedSnap>;
/**
* A Unix timestamp for the last time the Snap received an RPC request
*/
lastRequest: null | number;
/**
* The current number of active references where this Snap is being used
*/
activeReferences: number;
/**
* The current pending inbound requests, meaning requests that are processed by snaps.
*/
pendingInboundRequests: PendingRequest[];
/**
* The current pending outbound requests, meaning requests made from snaps towards the MetaMask
* extension.
*/
pendingOutboundRequests: number;
/**
* RPC handler designated for the Snap
*/
rpcHandler: null | SnapRpcHook;
/**
* The finite state machine interpreter for possible states that the Snap can be in such as
* stopped, running, blocked
*
* @see {@link SnapController:constructor}
*/
interpreter: StateMachine.Service<StatusContext, StatusEvents, StatusStates>;
/**
* The snap source code
*/
sourceCode: null | string;
/**
* The snap state (encrypted)
*/
state: null | string;
}
export type SnapError = {
message: string;
code: number;
data?: Json;
};
/**
* The return type of {@link SnapController.fetchSnap} and its sibling methods.
*/
type FetchSnapResult = {
/**
* The manifest of the fetched Snap.
*/
manifest: SnapManifest;
/**
* The source code of the fetched Snap.
*/
sourceCode: string;
/**
* The raw XML content of the Snap's SVG icon, if any.
*/
svgIcon?: string;
};
// Types that probably should be defined elsewhere in prod
type CloseAllConnectionsFunction = (origin: string) => void;
type StoredSnaps = Record<SnapId, Snap>;
export type SnapControllerState = {
snaps: StoredSnaps;
// This type needs to be defined but is always empty in practice.
// eslint-disable-next-line @typescript-eslint/ban-types
snapStates: {};
snapErrors: {
[internalID: string]: SnapError & { internalID: string };
};
};
export type PersistedSnapControllerState = SnapControllerState & {
snaps: Record<SnapId, PersistedSnap>;
snapStates: Record<SnapId, string>;
};
// Controller Messenger Actions
/**
* Gets the specified Snap from state.
*/
export type GetSnap = {
type: `${typeof controllerName}:get`;
handler: SnapController['get'];
};
/**
* Handles sending an inbound request to a snap and returns its result.
*/
export type HandleSnapRequest = {
type: `${typeof controllerName}:handleRequest`;
handler: SnapController['handleRequest'];
};
/**
* Gets the specified Snap's persisted state.
*/
export type GetSnapState = {
type: `${typeof controllerName}:getSnapState`;
handler: SnapController['getSnapState'];
};
/**
* Checks if the specified snap exists in state.
*/
export type HasSnap = {
type: `${typeof controllerName}:has`;
handler: SnapController['has'];
};
/**
* Updates the specified Snap's persisted state.
*/
export type UpdateSnapState = {
type: `${typeof controllerName}:updateSnapState`;
handler: SnapController['updateSnapState'];
};
/**
* Clears the specified Snap's persisted state.
*/
export type ClearSnapState = {
type: `${typeof controllerName}:clearSnapState`;
handler: SnapController['clearSnapState'];
};
/**
* Checks all installed snaps against the blocklist.
*/
export type UpdateBlockedSnaps = {
type: `${typeof controllerName}:updateBlockedSnaps`;
handler: SnapController['updateBlockedSnaps'];
};
export type EnableSnap = {
type: `${typeof controllerName}:enable`;
handler: SnapController['enableSnap'];
};
export type DisableSnap = {
type: `${typeof controllerName}:disable`;
handler: SnapController['disableSnap'];
};
export type RemoveSnap = {
type: `${typeof controllerName}:remove`;
handler: SnapController['removeSnap'];
};
export type GetPermittedSnaps = {
type: `${typeof controllerName}:getPermitted`;
handler: SnapController['getPermittedSnaps'];
};
export type GetAllSnaps = {
type: `${typeof controllerName}:getAll`;
handler: SnapController['getAllSnaps'];
};
export type IncrementActiveReferences = {
type: `${typeof controllerName}:incrementActiveReferences`;
handler: SnapController['incrementActiveReferences'];
};
export type DecrementActiveReferences = {
type: `${typeof controllerName}:decrementActiveReferences`;
handler: SnapController['decrementActiveReferences'];
};
export type InstallSnaps = {
type: `${typeof controllerName}:install`;
handler: SnapController['installSnaps'];
};
export type RemoveSnapError = {
type: `${typeof controllerName}:removeSnapError`;
handler: SnapController['removeSnapError'];
};
export type SnapControllerActions =
| ClearSnapState
| GetSnap
| GetSnapState
| HandleSnapRequest
| HasSnap
| UpdateBlockedSnaps
| UpdateSnapState
| EnableSnap
| DisableSnap
| RemoveSnap
| GetPermittedSnaps
| InstallSnaps
| RemoveSnapError
| GetAllSnaps
| IncrementActiveReferences
| DecrementActiveReferences;
// Controller Messenger Events
export type SnapStateChange = {
type: `${typeof controllerName}:stateChange`;
payload: [SnapControllerState, Patch[]];
};
/**
* Emitted when a Snap has been added to state during installation.
*/
export type SnapAdded = {
type: `${typeof controllerName}:snapAdded`;
payload: [snap: Snap, svgIcon: string | undefined];
};
/**
* Emitted when an installed snap has been blocked.
*/
export type SnapBlocked = {
type: `${typeof controllerName}:snapBlocked`;
payload: [snapId: string, blockedSnapInfo: BlockedSnapInfo];
};
/**
* Emitted when a snap has been started after being added and authorized during
* installation.
*/
export type SnapInstalled = {
type: `${typeof controllerName}:snapInstalled`;
payload: [snap: TruncatedSnap];
};
/**
* Emitted when a snap is removed.
*/
export type SnapRemoved = {
type: `${typeof controllerName}:snapRemoved`;
payload: [snap: TruncatedSnap];
};
/**
* Emitted when an installed snap has been unblocked.
*/
export type SnapUnblocked = {
type: `${typeof controllerName}:snapUnblocked`;
payload: [snapId: string];
};
/**
* Emitted when a snap is updated.
*/
export type SnapUpdated = {
type: `${typeof controllerName}:snapUpdated`;
payload: [snap: TruncatedSnap, oldVersion: string];
};
/**
* Emitted when a Snap is terminated. This is different from the snap being
* stopped as it can also be triggered when a snap fails initialization.
*/
export type SnapTerminated = {
type: `${typeof controllerName}:snapTerminated`;
payload: [snap: TruncatedSnap];
};
export type SnapControllerEvents =
| SnapAdded
| SnapBlocked
| SnapInstalled
| SnapRemoved
| SnapStateChange
| SnapUnblocked
| SnapUpdated
| SnapTerminated;
export type AllowedActions =
| GetEndowments
| GetPermissions
| HasPermission
| HasPermissions
| RevokePermissions
| RevokeAllPermissions
| RevokePermissionForAllSubjects
| GrantPermissions
| AddApprovalRequest
| HandleRpcRequestAction
| ExecuteSnapAction
| TerminateAllSnapsAction
| TerminateSnapAction;
export type AllowedEvents = ExecutionServiceEvents;
type SnapControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
SnapControllerActions | AllowedActions,
SnapControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;
export enum AppKeyType {
StateEncryption = 'stateEncryption',
}
type GetAppKey = (subject: string, appKeyType: AppKeyType) => Promise<string>;
type FeatureFlags = {
/**
* We still need to implement new UI approval page in metamask-extension before we can allow
* DApps to update Snaps. After it's added, this flag can be removed.
*
* @see {SNAP_APPROVAL_UPDATE}
* @see {SnapController.processRequestedSnap}
*/
dappsCanUpdateSnaps?: true;
};
type SemVerVersion = string;
type SnapInfo = { version: SemVerVersion; shasum: string };
export type CheckSnapBlockListArg = Record<SnapId, SnapInfo>;
export type CheckSnapBlockListResult = Record<
SnapId,
| {
blocked: true;
reason?: string;
infoUrl?: string;
}
| { blocked: false }
>;
/**
* Checks whether a version of a snap is blocked.
*/
export type CheckSnapBlockList = (
snapsToCheck: CheckSnapBlockListArg,
) => Promise<CheckSnapBlockListResult>;
type SnapControllerArgs = {
/**
* A teardown function that allows the host to clean up its instrumentation
* for a running snap.
*/
closeAllConnections: CloseAllConnectionsFunction;
/**
* The names of endowment permissions whose values are the names of JavaScript
* APIs that will be added to the snap execution environment at runtime.
*/
environmentEndowmentPermissions: string[];
/**
* The function that will be used by the controller fo make network requests.
* Should be compatible with {@link fetch}.
*/
fetchFunction?: typeof fetch;
/**
* Flags that enable or disable features in the controller.
* See {@link FeatureFlags}.
*/
featureFlags: FeatureFlags;
/**
* A function to get an "app key" for a specific subject.
*/
getAppKey: GetAppKey;
/**
* How frequently to check whether a snap is idle.
*/
idleTimeCheckInterval?: number;
/**
* A function that checks whether the specified snap and version is blocked.
*/
checkBlockList: CheckSnapBlockList;
/**
* The maximum amount of time that a snap may be idle.
*/
maxIdleTime?: number;
/**
* The controller messenger.
*/
messenger: SnapControllerMessenger;
/**
* The maximum amount of time a snap may take to process an RPC request,
* unless it is permitted to take longer.
*/
maxRequestTime?: number;
/**
* The npm registry URL that will be used to fetch published snaps.
*/
npmRegistryUrl?: string;
/**
* Persisted state that will be used for rehydration.
*/
state?: PersistedSnapControllerState;
};
type AddSnapArgsBase = {
id: SnapId;
origin: string;
versionRange?: SemVerRange;
};
// A snap can either be added directly, with manifest and source code, or it
// can be fetched and then added.
type AddSnapArgs =
| AddSnapArgsBase
| (AddSnapArgsBase & {
manifest: SnapManifest;
sourceCode: string;
});
// When we set a snap, we need all required properties to be present and
// validated.
type SetSnapArgs = Omit<AddSnapArgs, 'id'> & {
id: ValidatedSnapId;
manifest: SnapManifest;
sourceCode: string;
svgIcon?: string;
};
const defaultState: SnapControllerState = {
snapErrors: {},
snaps: {},
snapStates: {},
};
/**
* Truncates the properties of a snap to only ones that are easily serializable.
*
* @param snap - The snap to truncate.
* @returns Object with serializable snap properties.
*/
function truncateSnap(snap: Snap): TruncatedSnap {
const truncatedSnap = Object.keys(snap).reduce<Partial<TruncatedSnap>>(
(serialized, key) => {
if (TRUNCATED_SNAP_PROPERTIES.has(key as any)) {
serialized[key as keyof TruncatedSnap] = snap[
key as keyof TruncatedSnap
] as any;
}
return serialized;
},
{},
);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return truncatedSnap as TruncatedSnap;
}
const name = 'SnapController';
/*
* A snap is initialized in three phases:
* - Add: Loads the snap from a remote source and parses it.
* - Authorize: Requests the snap's required permissions from the user.
* - Start: Initializes the snap in its SES realm with the authorized permissions.
*/
export class SnapController extends BaseController<
string,
SnapControllerState,
SnapControllerMessenger
> {
#closeAllConnections: CloseAllConnectionsFunction;
#environmentEndowmentPermissions: string[];
#featureFlags: FeatureFlags;
#fetchFunction: typeof fetch;
#idleTimeCheckInterval: number;
#checkSnapBlockList: CheckSnapBlockList;
#maxIdleTime: number;
// This property cannot be hash private yet because of tests.
private readonly maxRequestTime: number;
#npmRegistryUrl?: string;
// This property cannot be hash private yet because of tests.
private readonly snapsRuntimeData: Map<SnapId, SnapRuntimeData>;
#getAppKey: GetAppKey;
#timeoutForLastRequestStatus?: number;
#statusMachine!: StateMachine.Machine<
StatusContext,
StatusEvents,
StatusStates
>;
constructor({
closeAllConnections,
messenger,
state,
getAppKey,
environmentEndowmentPermissions = [],
npmRegistryUrl,
idleTimeCheckInterval = inMilliseconds(5, Duration.Second),
checkBlockList,
maxIdleTime = inMilliseconds(30, Duration.Second),
maxRequestTime = inMilliseconds(60, Duration.Second),
fetchFunction = globalThis.fetch.bind(globalThis),
featureFlags = {},
}: SnapControllerArgs) {
super({
messenger,
metadata: {
snapErrors: {
persist: false,
anonymous: false,
},
snapStates: {
persist: () => {
return Object.keys(this.state.snaps).reduce<
Record<string, string | null>
>((acc, cur) => {
acc[cur] = this.#getRuntimeExpect(cur).state;
return acc;
}, {});
},
anonymous: false,
},
snaps: {
persist: (snaps) => {
return Object.values(snaps)
.map((snap) => {
return {
...snap,
sourceCode: this.#getRuntimeExpect(snap.id).sourceCode,
// At the time state is rehydrated, no snap will be running.
status: SnapStatus.Stopped,
};
})
.reduce((memo: Record<string, Snap>, snap) => {
memo[snap.id] = snap;
return memo;
}, {});
},
anonymous: false,
},
},
name,
state: {
...defaultState,
...{
...state,
snaps: Object.values(state?.snaps ?? {}).reduce(
(memo: Record<string, Snap>, snap) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { sourceCode, ...rest } = snap;
memo[snap.id] = rest;
return memo;
},
{},
),
},
},
});
this.#closeAllConnections = closeAllConnections;
this.#environmentEndowmentPermissions = environmentEndowmentPermissions;
this.#featureFlags = featureFlags;
this.#fetchFunction = fetchFunction;
this.#getAppKey = getAppKey;
this.#idleTimeCheckInterval = idleTimeCheckInterval;
this.#checkSnapBlockList = checkBlockList;
this.#maxIdleTime = maxIdleTime;
this.maxRequestTime = maxRequestTime;
this.#npmRegistryUrl = npmRegistryUrl;
this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);
this._onOutboundRequest = this._onOutboundRequest.bind(this);
this._onOutboundResponse = this._onOutboundResponse.bind(this);
this.snapsRuntimeData = new Map();
this.#pollForLastRequestStatus();
/* eslint-disable @typescript-eslint/unbound-method */
this.messagingSystem.subscribe(
'ExecutionService:unhandledError',
this._onUnhandledSnapError,
);
this.messagingSystem.subscribe(
'ExecutionService:outboundRequest',
this._onOutboundRequest,
);
this.messagingSystem.subscribe(
'ExecutionService:outboundResponse',
this._onOutboundResponse,
);
/* eslint-enable @typescript-eslint/unbound-method */
this.#initializeStateMachine();
this.#registerMessageHandlers();
Object.values(state?.snaps ?? {}).forEach((snap) =>
this.#setupRuntime(snap.id, {
sourceCode: snap.sourceCode,
state: state?.snapStates?.[snap.id] ?? null,
}),
);
}
/**
* We track status of a Snap using a finite-state-machine.
* It keeps track of whether the snap is started / stopped / etc.
*
* @see {@link SnapController.transition} for interacting with the machine.
*/
// We initialize the machine in the instance because the status is currently tightly coupled
// with the SnapController - the guard checks for enabled status inside the SnapController state.
// In the future, side-effects could be added to the machine during transitions.
#initializeStateMachine() {
const disableGuard = ({ snapId }: StatusContext) => {
return this.getExpect(snapId).enabled;
};
const statusConfig: StateMachine.Config<
StatusContext,
StatusEvents,
StatusStates
> = {
initial: SnapStatus.Installing,
states: {
[SnapStatus.Installing]: {
on: {
[SnapStatusEvents.Start]: {
target: SnapStatus.Running,
cond: disableGuard,
},
},
},
[SnapStatus.Updating]: {
on: {
[SnapStatusEvents.Start]: {
target: SnapStatus.Running,
cond: disableGuard,
},
},
},
[SnapStatus.Running]: {
on: {
[SnapStatusEvents.Stop]: SnapStatus.Stopped,
[SnapStatusEvents.Crash]: SnapStatus.Crashed,
},
},
[SnapStatus.Stopped]: {
on: {
[SnapStatusEvents.Start]: {
target: SnapStatus.Running,
cond: disableGuard,
},
[SnapStatusEvents.Update]: SnapStatus.Updating,
},
},
[SnapStatus.Crashed]: {
on: {
[SnapStatusEvents.Start]: {
target: SnapStatus.Running,
cond: disableGuard,
},
},
},
},
};
this.#statusMachine = createMachine(statusConfig);
validateMachine(this.#statusMachine);
}
/**
* Constructor helper for registering the controller's messaging system
* actions.
*/
#registerMessageHandlers(): void {
this.messagingSystem.registerActionHandler(
`${controllerName}:clearSnapState`,
(...args) => this.clearSnapState(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:get`,
(...args) => this.get(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:getSnapState`,
async (...args) => this.getSnapState(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:handleRequest`,
async (...args) => this.handleRequest(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:has`,
(...args) => this.has(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:updateBlockedSnaps`,
async () => this.updateBlockedSnaps(),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:updateSnapState`,
async (...args) => this.updateSnapState(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:enable`,
(...args) => this.enableSnap(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:disable`,
async (...args) => this.disableSnap(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:remove`,
async (...args) => this.removeSnap(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:getPermitted`,
(...args) => this.getPermittedSnaps(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:install`,
async (...args) => this.installSnaps(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:removeSnapError`,
(...args) => this.removeSnapError(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:getAll`,
(...args) => this.getAllSnaps(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:incrementActiveReferences`,
(...args) => this.incrementActiveReferences(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:decrementActiveReferences`,
(...args) => this.decrementActiveReferences(...args),
);
}
#pollForLastRequestStatus() {
this.#timeoutForLastRequestStatus = setTimeout(() => {
this.#stopSnapsLastRequestPastMax().catch((error) => {
// TODO: Decide how to handle errors.
console.error(error);
});
this.#pollForLastRequestStatus();
}, this.#idleTimeCheckInterval) as unknown as number;
}
/**
* Checks all installed snaps against the block list and
* blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
* for more information.
*/
async updateBlockedSnaps(): Promise<void> {
const blockedSnaps = await this.#checkSnapBlockList(
Object.values(this.state.snaps).reduce<CheckSnapBlockListArg>(
(blockListArg, snap) => {
blockListArg[snap.id] = {
version: snap.version,
shasum: snap.manifest.source.shasum,
};
return blockListArg;
},
{},
),
);
await Promise.all(
Object.entries(blockedSnaps).map(
async ([snapId, { blocked, ...blockData }]) => {
if (blocked) {
return this.#blockSnap(snapId, blockData);
}
return this.#unblockSnap(snapId);
},
),
);
}
/**
* Blocks an installed snap and prevents it from being started again. Emits
* {@link SnapBlocked}. Does nothing if the snap is not installed.
*
* @param snapId - The snap to block.
* @param blockedSnapInfo - Information detailing why the snap is blocked.
*/
async #blockSnap(
snapId: SnapId,
blockedSnapInfo: BlockedSnapInfo,
): Promise<void> {
if (!this.has(snapId)) {
return;
}
try {
this.update((state: any) => {
state.snaps[snapId].blocked = true;
state.snaps[snapId].blockInformation = blockedSnapInfo;
});
await this.disableSnap(snapId);
} catch (error) {
console.error(
`Encountered error when stopping blocked snap "${snapId}".`,
error,
);
}
this.messagingSystem.publish(
`${controllerName}:snapBlocked`,
snapId,
blockedSnapInfo,
);
}
/**
* Unblocks a snap so that it can be enabled and started again. Emits
* {@link SnapUnblocked}. Does nothing if the snap is not installed or already
* unblocked.
*
* @param snapId - The id of the snap to unblock.
*/
#unblockSnap(snapId: SnapId) {
if (!this.has(snapId) || !this.state.snaps[snapId].blocked) {
return;
}
this.update((state: any) => {
state.snaps[snapId].blocked = false;
delete state.snaps[snapId].blockInformation;
});