forked from LedgerHQ/ledger-live-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deviceAccess.ts
188 lines (170 loc) · 5.84 KB
/
deviceAccess.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
import { Observable, throwError, timer } from "rxjs";
import { retryWhen, mergeMap, catchError } from "rxjs/operators";
import Transport from "@ledgerhq/hw-transport";
import {
WrongDeviceForAccount,
WrongAppForCurrency,
CantOpenDevice,
UpdateYourApp,
BluetoothRequired,
TransportWebUSBGestureRequired,
TransportInterfaceNotAvailable,
FirmwareOrAppUpdateRequired,
TransportStatusError,
DeviceHalted,
} from "@ledgerhq/errors";
import { getEnv } from "../env";
import { open, close } from ".";
export type AccessHook = () => () => void;
const initialErrorRemapping = (error) =>
throwError(
error &&
error instanceof TransportStatusError &&
// @ts-expect-error typescript not checking agains the instanceof
error.statusCode === 0x6faa
? new DeviceHalted(error.message)
: error.statusCode === 0x6b00
? new FirmwareOrAppUpdateRequired(error.message)
: error
);
const accessHooks: AccessHook[] = [];
let errorRemapping = (e) => throwError(e);
export const addAccessHook = (accessHook: AccessHook): void => {
accessHooks.push(accessHook);
};
export const setErrorRemapping = (
f: (arg0: Error) => Observable<never>
): void => {
errorRemapping = f;
};
const never = new Promise(() => {});
const transportFinally =
(cleanup: () => Promise<void>) =>
<T>(observable: Observable<T>): Observable<T> =>
Observable.create((o) => {
let done = false;
const finalize = () => {
if (done) return never;
done = true;
return cleanup();
};
const sub = observable.subscribe({
next: (e) => o.next(e),
complete: () => {
finalize().then(() => o.complete());
},
error: (e) => {
finalize().then(() => o.error(e));
},
});
return () => {
sub.unsubscribe();
finalize();
};
});
const identifyTransport = (t) => (typeof t.id === "string" ? t.id : "");
const needsCleanup = {};
// when a series of APDUs are interrupted, this is called
// so we don't forget to cleanup on the next withDevice
export const cancelDeviceAction = (transport: Transport) => {
needsCleanup[identifyTransport(transport)] = true;
};
const deviceQueues = {};
export const withDevice =
(deviceId: string) =>
<T>(job: (t: Transport) => Observable<T>): Observable<T> =>
new Observable((o) => {
let unsubscribed;
let sub;
const deviceQueue = deviceQueues[deviceId] || Promise.resolve();
const finalize = (transport, cleanups) =>
close(transport, deviceId)
.catch(() => {})
.then(() => {
cleanups.forEach((c) => c());
});
// when we'll finish all the current job, we'll call finish
let finish;
// this new promise is the next exec queue
deviceQueues[deviceId] = new Promise((resolve) => {
finish = resolve;
});
// for any new job, we'll now wait the exec queue to be available
deviceQueue
.then(() => open(deviceId)) // open the transport
.then(async (transport) => {
if (unsubscribed) {
// it was unsubscribed prematurely
return finalize(transport, [finish]);
}
if (needsCleanup[identifyTransport(transport)]) {
delete needsCleanup[identifyTransport(transport)];
await transport.send(0, 0, 0, 0).catch(() => {});
}
if (
transport.requestConnectionPriority &&
typeof transport.requestConnectionPriority === "function"
) {
await transport.requestConnectionPriority("High");
}
return transport;
})
.catch((e) => {
finish();
if (e instanceof BluetoothRequired) throw e;
if (e instanceof TransportWebUSBGestureRequired) throw e;
if (e instanceof TransportInterfaceNotAvailable) throw e;
throw new CantOpenDevice(e.message);
})
.then((transport) => {
if (!transport) return;
if (unsubscribed) {
// it was unsubscribed prematurely
return finalize(transport, [finish]);
}
const cleanups = accessHooks.map((hook) => hook());
sub = job(transport) // $FlowFixMe
.pipe(
catchError(initialErrorRemapping),
catchError(errorRemapping), // close the transport and clean up everything
// $FlowFixMe
transportFinally(() => finalize(transport, [...cleanups, finish]))
)
.subscribe(o);
})
.catch((error) => o.error(error));
return () => {
unsubscribed = true;
if (sub) sub.unsubscribe();
};
});
export const genericCanRetryOnError = (err: Error | null | undefined) => {
if (err instanceof WrongAppForCurrency) return false;
if (err instanceof WrongDeviceForAccount) return false;
if (err instanceof CantOpenDevice) return false;
if (err instanceof BluetoothRequired) return false;
if (err instanceof UpdateYourApp) return false;
if (err instanceof FirmwareOrAppUpdateRequired) return false;
if (err instanceof DeviceHalted) return false;
if (err instanceof TransportWebUSBGestureRequired) return false;
if (err instanceof TransportInterfaceNotAvailable) return false;
return true;
};
export const retryWhileErrors =
(acceptError: (arg0: Error) => boolean) =>
(attempts: Observable<any>): Observable<any> =>
attempts.pipe(
mergeMap((error) => {
if (!acceptError(error)) {
return throwError(error);
}
return timer(getEnv("WITH_DEVICE_POLLING_DELAY"));
})
);
export const withDevicePolling =
(deviceId: string) =>
<T>(
job: (arg0: Transport) => Observable<T>,
acceptError: (arg0: Error) => boolean = genericCanRetryOnError
): Observable<T> =>
withDevice(deviceId)(job).pipe(retryWhen(retryWhileErrors(acceptError)));