@metamask/eth-ledger-bridge-keyring 11.0.0 → 11.0.1
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.
- package/CHANGELOG.md +9 -1
- package/dist/ledger-iframe-bridge.cjs +57 -58
- package/dist/ledger-iframe-bridge.cjs.map +1 -1
- package/dist/ledger-iframe-bridge.d.cts +1 -1
- package/dist/ledger-iframe-bridge.d.cts.map +1 -1
- package/dist/ledger-iframe-bridge.d.mts +1 -1
- package/dist/ledger-iframe-bridge.d.mts.map +1 -1
- package/dist/ledger-iframe-bridge.mjs +57 -58
- package/dist/ledger-iframe-bridge.mjs.map +1 -1
- package/dist/ledger-keyring.cjs +4 -10
- package/dist/ledger-keyring.cjs.map +1 -1
- package/dist/ledger-keyring.d.cts.map +1 -1
- package/dist/ledger-keyring.d.mts.map +1 -1
- package/dist/ledger-keyring.mjs +4 -10
- package/dist/ledger-keyring.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [11.0.1]
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Fix use of `salt` value as a `string` for `signTypedData<V4>` ([#249](https://github.com/MetaMask/accounts/pull/249))
|
|
15
|
+
- Use timeouts for Ledger iframe messages ([#271](https://github.com/MetaMask/accounts/pull/271))
|
|
16
|
+
|
|
10
17
|
## [11.0.0]
|
|
11
18
|
|
|
12
19
|
### Changed
|
|
@@ -305,7 +312,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
305
312
|
|
|
306
313
|
- Support new versions of ethereumjs/tx ([#68](https://github.com/MetaMask/eth-ledger-bridge-keyring/pull/68))
|
|
307
314
|
|
|
308
|
-
[Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@11.0.
|
|
315
|
+
[Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@11.0.1...HEAD
|
|
316
|
+
[11.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@11.0.0...@metamask/eth-ledger-bridge-keyring@11.0.1
|
|
309
317
|
[11.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@10.0.0...@metamask/eth-ledger-bridge-keyring@11.0.0
|
|
310
318
|
[10.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@9.0.0...@metamask/eth-ledger-bridge-keyring@10.0.0
|
|
311
319
|
[9.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-ledger-bridge-keyring@8.0.5...@metamask/eth-ledger-bridge-keyring@9.0.0
|
|
@@ -10,12 +10,15 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
11
11
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
12
12
|
};
|
|
13
|
-
var _LedgerIframeBridge_instances, _LedgerIframeBridge_opts, _LedgerIframeBridge_deviceActionMessage, _LedgerIframeBridge_setupIframe, _LedgerIframeBridge_getOrigin, _LedgerIframeBridge_eventListener, _LedgerIframeBridge_sendMessage, _LedgerIframeBridge_validateConfiguration;
|
|
13
|
+
var _LedgerIframeBridge_instances, _LedgerIframeBridge_opts, _LedgerIframeBridge_messageResponseHandles, _LedgerIframeBridge_deviceActionMessage, _LedgerIframeBridge_setupIframe, _LedgerIframeBridge_getOrigin, _LedgerIframeBridge_eventListener, _LedgerIframeBridge_sendMessage, _LedgerIframeBridge_validateConfiguration;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.LedgerIframeBridge = exports.IFrameMessageAction = void 0;
|
|
16
|
+
const utils_1 = require("@metamask/utils");
|
|
16
17
|
const LEDGER_IFRAME_ID = 'LEDGER-IFRAME';
|
|
18
|
+
const IFRAME_MESSAGE_TIMEOUT = 4000;
|
|
17
19
|
var IFrameMessageAction;
|
|
18
20
|
(function (IFrameMessageAction) {
|
|
21
|
+
IFrameMessageAction["LedgerIsIframeReady"] = "ledger-is-iframe-ready";
|
|
19
22
|
IFrameMessageAction["LedgerConnectionChange"] = "ledger-connection-change";
|
|
20
23
|
IFrameMessageAction["LedgerUnlock"] = "ledger-unlock";
|
|
21
24
|
IFrameMessageAction["LedgerMakeApp"] = "ledger-make-app";
|
|
@@ -33,7 +36,7 @@ class LedgerIframeBridge {
|
|
|
33
36
|
_LedgerIframeBridge_opts.set(this, void 0);
|
|
34
37
|
this.isDeviceConnected = false;
|
|
35
38
|
this.currentMessageId = 0;
|
|
36
|
-
this
|
|
39
|
+
_LedgerIframeBridge_messageResponseHandles.set(this, new Map());
|
|
37
40
|
__classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_validateConfiguration).call(this, opts);
|
|
38
41
|
__classPrivateFieldSet(this, _LedgerIframeBridge_opts, {
|
|
39
42
|
bridgeUrl: opts?.bridgeUrl,
|
|
@@ -61,40 +64,32 @@ class LedgerIframeBridge {
|
|
|
61
64
|
}
|
|
62
65
|
}
|
|
63
66
|
async attemptMakeApp() {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
action: IFrameMessageAction.LedgerMakeApp,
|
|
67
|
-
}, (response) => {
|
|
68
|
-
if ('success' in response && response.success) {
|
|
69
|
-
resolve(true);
|
|
70
|
-
}
|
|
71
|
-
else if ('error' in response) {
|
|
72
|
-
// Assuming this is using an `Error` type:
|
|
73
|
-
reject(response.error);
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
reject(new Error('Unknown error occurred'));
|
|
77
|
-
}
|
|
78
|
-
});
|
|
67
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
68
|
+
action: IFrameMessageAction.LedgerMakeApp,
|
|
79
69
|
});
|
|
70
|
+
if ('success' in response && response.success) {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
else if ('error' in response) {
|
|
74
|
+
// Assuming this is using an `Error` type:
|
|
75
|
+
throw response.error;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
throw new Error('Unknown error occurred');
|
|
79
|
+
}
|
|
80
80
|
}
|
|
81
81
|
async updateTransportMethod(transportType) {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
__classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
89
|
-
action: IFrameMessageAction.LedgerUpdateTransport,
|
|
90
|
-
params: { transportType },
|
|
91
|
-
}, (response) => {
|
|
92
|
-
if ('success' in response && response.success) {
|
|
93
|
-
return resolve(true);
|
|
94
|
-
}
|
|
95
|
-
return reject(new Error('Ledger transport could not be updated'));
|
|
96
|
-
});
|
|
82
|
+
if (!this.iframeLoaded) {
|
|
83
|
+
throw new Error('The iframe is not loaded yet');
|
|
84
|
+
}
|
|
85
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
86
|
+
action: IFrameMessageAction.LedgerUpdateTransport,
|
|
87
|
+
params: { transportType },
|
|
97
88
|
});
|
|
89
|
+
if ('success' in response && response.success) {
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
throw new Error('Ledger transport could not be updated');
|
|
98
93
|
}
|
|
99
94
|
async getPublicKey(params) {
|
|
100
95
|
return __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_deviceActionMessage).call(this, IFrameMessageAction.LedgerUnlock, params);
|
|
@@ -110,23 +105,17 @@ class LedgerIframeBridge {
|
|
|
110
105
|
}
|
|
111
106
|
}
|
|
112
107
|
exports.LedgerIframeBridge = LedgerIframeBridge;
|
|
113
|
-
_LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_instances = new WeakSet(), _LedgerIframeBridge_deviceActionMessage = async function _LedgerIframeBridge_deviceActionMessage(...[action, params]) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return reject(response.payload.error);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
return reject(new Error('Unknown error occurred'));
|
|
128
|
-
});
|
|
129
|
-
});
|
|
108
|
+
_LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_messageResponseHandles = new WeakMap(), _LedgerIframeBridge_instances = new WeakSet(), _LedgerIframeBridge_deviceActionMessage = async function _LedgerIframeBridge_deviceActionMessage(...[action, params]) {
|
|
109
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, { action, params });
|
|
110
|
+
if ('payload' in response && response.payload) {
|
|
111
|
+
if ('success' in response && response.success) {
|
|
112
|
+
return response.payload;
|
|
113
|
+
}
|
|
114
|
+
if ('error' in response.payload) {
|
|
115
|
+
throw response.payload.error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
throw new Error('Unknown error occurred');
|
|
130
119
|
}, _LedgerIframeBridge_setupIframe = async function _LedgerIframeBridge_setupIframe(bridgeUrl) {
|
|
131
120
|
return new Promise((resolve) => {
|
|
132
121
|
this.iframe = document.createElement('iframe');
|
|
@@ -143,30 +132,40 @@ _LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_instances = new We
|
|
|
143
132
|
tmp.splice(-1, 1);
|
|
144
133
|
return tmp.join('/');
|
|
145
134
|
}, _LedgerIframeBridge_eventListener = function _LedgerIframeBridge_eventListener(bridgeUrl, eventMessage) {
|
|
146
|
-
|
|
135
|
+
const { origin, data } = eventMessage;
|
|
136
|
+
if (origin !== __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_getOrigin).call(this, bridgeUrl)) {
|
|
147
137
|
return;
|
|
148
138
|
}
|
|
149
|
-
if (
|
|
150
|
-
const
|
|
151
|
-
if (
|
|
152
|
-
|
|
139
|
+
if (data) {
|
|
140
|
+
const messageResponseHandle = __classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").get(data.messageId);
|
|
141
|
+
if (messageResponseHandle) {
|
|
142
|
+
messageResponseHandle.resolve(data);
|
|
143
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").delete(data.messageId);
|
|
153
144
|
}
|
|
154
|
-
else if (
|
|
155
|
-
this.isDeviceConnected =
|
|
145
|
+
else if (data.action === IFrameMessageAction.LedgerConnectionChange) {
|
|
146
|
+
this.isDeviceConnected = data.payload.connected;
|
|
156
147
|
}
|
|
157
148
|
}
|
|
158
|
-
}, _LedgerIframeBridge_sendMessage = function _LedgerIframeBridge_sendMessage(message
|
|
149
|
+
}, _LedgerIframeBridge_sendMessage = async function _LedgerIframeBridge_sendMessage(message) {
|
|
159
150
|
this.currentMessageId += 1;
|
|
160
151
|
const postMsg = {
|
|
161
152
|
...message,
|
|
162
153
|
messageId: this.currentMessageId,
|
|
163
154
|
target: LEDGER_IFRAME_ID,
|
|
164
155
|
};
|
|
165
|
-
|
|
156
|
+
const messageResponseHandle = (0, utils_1.createDeferredPromise)();
|
|
157
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").set(this.currentMessageId, messageResponseHandle);
|
|
166
158
|
if (!this.iframeLoaded || !this.iframe?.contentWindow) {
|
|
167
159
|
throw new Error('The iframe is not loaded yet');
|
|
168
160
|
}
|
|
161
|
+
setTimeout(() => {
|
|
162
|
+
if (__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").has(postMsg.messageId)) {
|
|
163
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").delete(postMsg.messageId);
|
|
164
|
+
messageResponseHandle.reject(new Error('Ledger iframe message timeout'));
|
|
165
|
+
}
|
|
166
|
+
}, IFRAME_MESSAGE_TIMEOUT);
|
|
169
167
|
this.iframe.contentWindow.postMessage(postMsg, '*');
|
|
168
|
+
return messageResponseHandle.promise;
|
|
170
169
|
}, _LedgerIframeBridge_validateConfiguration = function _LedgerIframeBridge_validateConfiguration(opts) {
|
|
171
170
|
if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {
|
|
172
171
|
throw new Error('bridgeURL is not a valid URL');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-iframe-bridge.cjs","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,IAAY,mBAQX;AARD,WAAY,mBAAmB;IAC7B,0EAAmD,CAAA;IACnD,qDAA8B,CAAA;IAC9B,wDAAiC,CAAA;IACjC,wEAAiD,CAAA;IACjD,wEAAiD,CAAA;IACjD,iFAA0D,CAAA;IAC1D,qEAA8C,CAAA;AAChD,CAAC,EARW,mBAAmB,mCAAnB,mBAAmB,QAQ9B;AAqED,MAAa,kBAAkB;IAqB7B,YACE,OAAkC;QAChC,SAAS,EAAE,sDAAsD;KAClE;;QAnBH,iBAAY,GAAG,KAAK,CAAC;QAEZ,2CAAiC;QAO1C,sBAAiB,GAAG,KAAK,CAAC;QAE1B,qBAAgB,GAAG,CAAC,CAAC;QAErB,qBAAgB,GACd,EAAE,CAAC;QAOH,uBAAA,IAAI,gFAAuB,MAA3B,IAAI,EAAwB,IAAI,CAAC,CAAC;QAClC,uBAAA,IAAI,4BAAS;YACX,SAAS,EAAE,IAAI,EAAE,SAAS;SAC3B,MA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M,OAAO,GAA+B;QAC1C,GAAG,OAAO;QACV,SAAS,EAAE,IAAI,CAAC,gBAAgB;QAChC,MAAM,EAAE,gBAAgB;KACzB,CAAC;IAEF,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,QAAQ,CAAC;IAExD,IAAI,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACtD,CAAC,iGAEsB,IAA+B;IACpD,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["import {\n GetPublicKeyParams,\n GetPublicKeyResponse,\n LedgerBridge,\n LedgerSignMessageParams,\n LedgerSignMessageResponse,\n LedgerSignTransactionParams,\n LedgerSignTransactionResponse,\n LedgerSignTypedDataParams,\n LedgerSignTypedDataResponse,\n} from './ledger-bridge';\n\nconst LEDGER_IFRAME_ID = 'LEDGER-IFRAME';\n\nexport enum IFrameMessageAction {\n LedgerConnectionChange = 'ledger-connection-change',\n LedgerUnlock = 'ledger-unlock',\n LedgerMakeApp = 'ledger-make-app',\n LedgerUpdateTransport = 'ledger-update-transport',\n LedgerSignTransaction = 'ledger-sign-transaction',\n LedgerSignPersonalMessage = 'ledger-sign-personal-message',\n LedgerSignTypedData = 'ledger-sign-typed-data',\n}\n\ntype IFrameMessageResponseStub<\n SuccessResult extends Record<string, unknown>,\n FailureResult = Error,\n> = {\n messageId: number;\n} & (\n | { success: true; payload: SuccessResult }\n | { success: false; payload: { error: FailureResult } }\n);\n\ntype LedgerConnectionChangeActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerConnectionChange;\n payload: { connected: boolean };\n};\n\ntype LedgerMakeAppActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerMakeApp;\n} & ({ success: true } | { success: false; error?: unknown });\n\ntype LedgerUpdateTransportActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerUpdateTransport;\n success: boolean;\n};\n\ntype LedgerUnlockActionResponse = {\n action: IFrameMessageAction.LedgerUnlock;\n} & IFrameMessageResponseStub<GetPublicKeyResponse>;\n\ntype LedgerSignTransactionActionResponse = {\n action: IFrameMessageAction.LedgerSignTransaction;\n} & IFrameMessageResponseStub<LedgerSignTransactionResponse>;\n\ntype LedgerSignPersonalMessageActionResponse = {\n action: IFrameMessageAction.LedgerSignPersonalMessage;\n} & IFrameMessageResponseStub<LedgerSignMessageResponse>;\n\ntype LedgerSignTypedDataActionResponse = {\n action: IFrameMessageAction.LedgerSignTypedData;\n} & IFrameMessageResponseStub<LedgerSignTypedDataResponse>;\n\nexport type IFrameMessageResponse =\n | LedgerConnectionChangeActionResponse\n | LedgerMakeAppActionResponse\n | LedgerUpdateTransportActionResponse\n | LedgerUnlockActionResponse\n | LedgerSignTransactionActionResponse\n | LedgerSignPersonalMessageActionResponse\n | LedgerSignTypedDataActionResponse;\n\ntype IFrameMessage<TAction extends IFrameMessageAction> = {\n action: TAction;\n params?: Readonly<Record<string, unknown>>;\n};\n\ntype IFramePostMessage<TAction extends IFrameMessageAction> =\n IFrameMessage<TAction> & {\n messageId: number;\n target: typeof LEDGER_IFRAME_ID;\n };\n\nexport type LedgerIframeBridgeOptions = {\n bridgeUrl: string;\n};\n\nexport class LedgerIframeBridge\n implements LedgerBridge<LedgerIframeBridgeOptions>\n{\n iframe?: HTMLIFrameElement;\n\n iframeLoaded = false;\n\n readonly #opts: LedgerIframeBridgeOptions;\n\n eventListener?: (eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n }) => void;\n\n isDeviceConnected = false;\n\n currentMessageId = 0;\n\n messageCallbacks: Record<number, (response: IFrameMessageResponse) => void> =\n {};\n\n constructor(\n opts: LedgerIframeBridgeOptions = {\n bridgeUrl: 'https://metamask.github.io/eth-ledger-bridge-keyring',\n },\n ) {\n this.#validateConfiguration(opts);\n this.#opts = {\n bridgeUrl: opts?.bridgeUrl,\n };\n }\n\n async init(): Promise<void> {\n await this.#setupIframe(this.#opts.bridgeUrl);\n\n this.eventListener = this.#eventListener.bind(this, this.#opts.bridgeUrl);\n\n window.addEventListener('message', this.eventListener);\n }\n\n async destroy(): Promise<void> {\n if (this.eventListener) {\n window.removeEventListener('message', this.eventListener);\n }\n }\n\n async getOptions(): Promise<LedgerIframeBridgeOptions> {\n return this.#opts;\n }\n\n async setOptions(opts: LedgerIframeBridgeOptions): Promise<void> {\n this.#validateConfiguration(opts);\n if (this.#opts?.bridgeUrl !== opts.bridgeUrl) {\n this.#opts.bridgeUrl = opts.bridgeUrl;\n await this.destroy();\n await this.init();\n }\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n this.#sendMessage(\n {\n action: IFrameMessageAction.LedgerMakeApp,\n },\n (response) => {\n if ('success' in response && response.success) {\n resolve(true);\n } else if ('error' in response) {\n // Assuming this is using an `Error` type:\n reject(response.error as Error);\n } else {\n reject(new Error('Unknown error occurred'));\n }\n },\n );\n });\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n // If the iframe isn't loaded yet, let's store the desired transportType value and\n // optimistically return a successful promise\n if (!this.iframeLoaded) {\n throw new Error('The iframe is not loaded yet');\n }\n\n this.#sendMessage(\n {\n action: IFrameMessageAction.LedgerUpdateTransport,\n params: { transportType },\n },\n (response) => {\n if ('success' in response && response.success) {\n return resolve(true);\n }\n return reject(new Error('Ledger transport could not be updated'));\n },\n );\n });\n }\n\n async getPublicKey(\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse> {\n return this.#deviceActionMessage(IFrameMessageAction.LedgerUnlock, params);\n }\n\n async deviceSignTransaction(\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTransaction,\n params,\n );\n }\n\n async deviceSignMessage(\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignPersonalMessage,\n params,\n );\n }\n\n async deviceSignTypedData(\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTypedData,\n params,\n );\n }\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerUnlock,\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTransaction,\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignPersonalMessage,\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTypedData,\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse>;\n\n async #deviceActionMessage(\n ...[action, params]:\n | [IFrameMessageAction.LedgerUnlock, GetPublicKeyParams]\n | [IFrameMessageAction.LedgerSignTransaction, LedgerSignTransactionParams]\n | [IFrameMessageAction.LedgerSignPersonalMessage, LedgerSignMessageParams]\n | [IFrameMessageAction.LedgerSignTypedData, LedgerSignTypedDataParams]\n ): Promise<\n | GetPublicKeyResponse\n | LedgerSignTransactionResponse\n | LedgerSignMessageResponse\n | LedgerSignTypedDataResponse\n > {\n return new Promise((resolve, reject) => {\n this.#sendMessage(\n {\n action,\n params,\n },\n (response) => {\n if ('payload' in response && response.payload) {\n if ('success' in response && response.success) {\n return resolve(response.payload);\n }\n if ('error' in response.payload) {\n return reject(response.payload.error);\n }\n }\n return reject(new Error('Unknown error occurred'));\n },\n );\n });\n }\n\n async #setupIframe(bridgeUrl: string): Promise<void> {\n return new Promise((resolve) => {\n this.iframe = document.createElement('iframe');\n this.iframe.src = bridgeUrl;\n this.iframe.allow = `hid 'src'`;\n this.iframe.onload = async (): Promise<void> => {\n this.iframeLoaded = true;\n resolve();\n };\n document.head.appendChild(this.iframe);\n });\n }\n\n #getOrigin(bridgeUrl: string): string {\n const tmp = bridgeUrl.split('/');\n tmp.splice(-1, 1);\n return tmp.join('/');\n }\n\n #eventListener(\n bridgeUrl: string,\n eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n },\n ): void {\n if (eventMessage.origin !== this.#getOrigin(bridgeUrl)) {\n return;\n }\n\n if (eventMessage.data) {\n const messageCallback =\n this.messageCallbacks[eventMessage.data.messageId];\n if (messageCallback) {\n messageCallback(eventMessage.data);\n } else if (\n eventMessage.data.action === IFrameMessageAction.LedgerConnectionChange\n ) {\n this.isDeviceConnected = eventMessage.data.payload.connected;\n }\n }\n }\n\n #sendMessage<TAction extends IFrameMessageAction>(\n message: IFrameMessage<TAction>,\n callback: (response: IFrameMessageResponse) => void,\n ): void {\n this.currentMessageId += 1;\n\n const postMsg: IFramePostMessage<TAction> = {\n ...message,\n messageId: this.currentMessageId,\n target: LEDGER_IFRAME_ID,\n };\n\n this.messageCallbacks[this.currentMessageId] = callback;\n\n if (!this.iframeLoaded || !this.iframe?.contentWindow) {\n throw new Error('The iframe is not loaded yet');\n }\n\n this.iframe.contentWindow.postMessage(postMsg, '*');\n }\n\n #validateConfiguration(opts: LedgerIframeBridgeOptions): void {\n if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {\n throw new Error('bridgeURL is not a valid URL');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ledger-iframe-bridge.cjs","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAyE;AA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KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["import { createDeferredPromise, DeferredPromise } from '@metamask/utils';\n\nimport {\n GetPublicKeyParams,\n GetPublicKeyResponse,\n LedgerBridge,\n LedgerSignMessageParams,\n LedgerSignMessageResponse,\n LedgerSignTransactionParams,\n LedgerSignTransactionResponse,\n LedgerSignTypedDataParams,\n LedgerSignTypedDataResponse,\n} from './ledger-bridge';\n\nconst LEDGER_IFRAME_ID = 'LEDGER-IFRAME';\n\nconst IFRAME_MESSAGE_TIMEOUT = 4000;\n\nexport enum IFrameMessageAction {\n LedgerIsIframeReady = 'ledger-is-iframe-ready',\n LedgerConnectionChange = 'ledger-connection-change',\n LedgerUnlock = 'ledger-unlock',\n LedgerMakeApp = 'ledger-make-app',\n LedgerUpdateTransport = 'ledger-update-transport',\n LedgerSignTransaction = 'ledger-sign-transaction',\n LedgerSignPersonalMessage = 'ledger-sign-personal-message',\n LedgerSignTypedData = 'ledger-sign-typed-data',\n}\n\ntype IFrameMessageResponseStub<\n SuccessResult extends Record<string, unknown>,\n FailureResult = Error,\n> = {\n messageId: number;\n} & (\n | { success: true; payload: SuccessResult }\n | { success: false; payload: { error: FailureResult } }\n);\n\ntype LedgerConnectionChangeActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerConnectionChange;\n payload: { connected: boolean };\n};\n\ntype LedgerMakeAppActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerMakeApp;\n} & ({ success: true } | { success: false; error?: unknown });\n\ntype LedgerUpdateTransportActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerUpdateTransport;\n success: boolean;\n};\n\ntype LedgerUnlockActionResponse = {\n action: IFrameMessageAction.LedgerUnlock;\n} & IFrameMessageResponseStub<GetPublicKeyResponse>;\n\ntype LedgerSignTransactionActionResponse = {\n action: IFrameMessageAction.LedgerSignTransaction;\n} & IFrameMessageResponseStub<LedgerSignTransactionResponse>;\n\ntype LedgerSignPersonalMessageActionResponse = {\n action: IFrameMessageAction.LedgerSignPersonalMessage;\n} & IFrameMessageResponseStub<LedgerSignMessageResponse>;\n\ntype LedgerSignTypedDataActionResponse = {\n action: IFrameMessageAction.LedgerSignTypedData;\n} & IFrameMessageResponseStub<LedgerSignTypedDataResponse>;\n\nexport type IFrameMessageResponse =\n | LedgerConnectionChangeActionResponse\n | LedgerMakeAppActionResponse\n | LedgerUpdateTransportActionResponse\n | LedgerUnlockActionResponse\n | LedgerSignTransactionActionResponse\n | LedgerSignPersonalMessageActionResponse\n | LedgerSignTypedDataActionResponse;\n\ntype IFrameMessage<TAction extends IFrameMessageAction> = {\n action: TAction;\n params?: Readonly<Record<string, unknown>>;\n};\n\ntype IFramePostMessage<TAction extends IFrameMessageAction> =\n IFrameMessage<TAction> & {\n messageId: number;\n target: typeof LEDGER_IFRAME_ID;\n };\n\nexport type LedgerIframeBridgeOptions = {\n bridgeUrl: string;\n};\n\nexport class LedgerIframeBridge\n implements LedgerBridge<LedgerIframeBridgeOptions>\n{\n iframe?: HTMLIFrameElement;\n\n iframeLoaded = false;\n\n readonly #opts: LedgerIframeBridgeOptions;\n\n eventListener?: (eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n }) => void;\n\n isDeviceConnected = false;\n\n currentMessageId = 0;\n\n readonly #messageResponseHandles: Map<\n number,\n DeferredPromise<IFrameMessageResponse>\n > = new Map();\n\n constructor(\n opts: LedgerIframeBridgeOptions = {\n bridgeUrl: 'https://metamask.github.io/eth-ledger-bridge-keyring',\n },\n ) {\n this.#validateConfiguration(opts);\n this.#opts = {\n bridgeUrl: opts?.bridgeUrl,\n };\n }\n\n async init(): Promise<void> {\n await this.#setupIframe(this.#opts.bridgeUrl);\n\n this.eventListener = this.#eventListener.bind(this, this.#opts.bridgeUrl);\n\n window.addEventListener('message', this.eventListener);\n }\n\n async destroy(): Promise<void> {\n if (this.eventListener) {\n window.removeEventListener('message', this.eventListener);\n }\n }\n\n async getOptions(): Promise<LedgerIframeBridgeOptions> {\n return this.#opts;\n }\n\n async setOptions(opts: LedgerIframeBridgeOptions): Promise<void> {\n this.#validateConfiguration(opts);\n if (this.#opts?.bridgeUrl !== opts.bridgeUrl) {\n this.#opts.bridgeUrl = opts.bridgeUrl;\n await this.destroy();\n await this.init();\n }\n }\n\n async attemptMakeApp(): Promise<boolean> {\n const response = await this.#sendMessage({\n action: IFrameMessageAction.LedgerMakeApp,\n });\n\n if ('success' in response && response.success) {\n return true;\n } else if ('error' in response) {\n // Assuming this is using an `Error` type:\n throw response.error;\n } else {\n throw new Error('Unknown error occurred');\n }\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n if (!this.iframeLoaded) {\n throw new Error('The iframe is not loaded yet');\n }\n\n const response = await this.#sendMessage({\n action: IFrameMessageAction.LedgerUpdateTransport,\n params: { transportType },\n });\n\n if ('success' in response && response.success) {\n return true;\n }\n\n throw new Error('Ledger transport could not be updated');\n }\n\n async getPublicKey(\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse> {\n return this.#deviceActionMessage(IFrameMessageAction.LedgerUnlock, params);\n }\n\n async deviceSignTransaction(\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTransaction,\n params,\n );\n }\n\n async deviceSignMessage(\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignPersonalMessage,\n params,\n );\n }\n\n async deviceSignTypedData(\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTypedData,\n params,\n );\n }\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerUnlock,\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTransaction,\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignPersonalMessage,\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTypedData,\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse>;\n\n async #deviceActionMessage(\n ...[action, params]:\n | [IFrameMessageAction.LedgerUnlock, GetPublicKeyParams]\n | [IFrameMessageAction.LedgerSignTransaction, LedgerSignTransactionParams]\n | [IFrameMessageAction.LedgerSignPersonalMessage, LedgerSignMessageParams]\n | [IFrameMessageAction.LedgerSignTypedData, LedgerSignTypedDataParams]\n ): Promise<\n | GetPublicKeyResponse\n | LedgerSignTransactionResponse\n | LedgerSignMessageResponse\n | LedgerSignTypedDataResponse\n > {\n const response = await this.#sendMessage({ action, params });\n\n if ('payload' in response && response.payload) {\n if ('success' in response && response.success) {\n return response.payload;\n }\n if ('error' in response.payload) {\n throw response.payload.error;\n }\n }\n\n throw new Error('Unknown error occurred');\n }\n\n async #setupIframe(bridgeUrl: string): Promise<void> {\n return new Promise((resolve) => {\n this.iframe = document.createElement('iframe');\n this.iframe.src = bridgeUrl;\n this.iframe.allow = `hid 'src'`;\n this.iframe.onload = async (): Promise<void> => {\n this.iframeLoaded = true;\n resolve();\n };\n document.head.appendChild(this.iframe);\n });\n }\n\n #getOrigin(bridgeUrl: string): string {\n const tmp = bridgeUrl.split('/');\n tmp.splice(-1, 1);\n return tmp.join('/');\n }\n\n #eventListener(\n bridgeUrl: string,\n eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n },\n ): void {\n const { origin, data } = eventMessage;\n\n if (origin !== this.#getOrigin(bridgeUrl)) {\n return;\n }\n\n if (data) {\n const messageResponseHandle = this.#messageResponseHandles.get(\n data.messageId,\n );\n if (messageResponseHandle) {\n messageResponseHandle.resolve(data);\n this.#messageResponseHandles.delete(data.messageId);\n } else if (data.action === IFrameMessageAction.LedgerConnectionChange) {\n this.isDeviceConnected = data.payload.connected;\n }\n }\n }\n\n async #sendMessage<TAction extends IFrameMessageAction>(\n message: IFrameMessage<TAction>,\n ): Promise<IFrameMessageResponse> {\n this.currentMessageId += 1;\n\n const postMsg: IFramePostMessage<TAction> = {\n ...message,\n messageId: this.currentMessageId,\n target: LEDGER_IFRAME_ID,\n };\n\n const messageResponseHandle =\n createDeferredPromise<IFrameMessageResponse>();\n\n this.#messageResponseHandles.set(\n this.currentMessageId,\n messageResponseHandle,\n );\n\n if (!this.iframeLoaded || !this.iframe?.contentWindow) {\n throw new Error('The iframe is not loaded yet');\n }\n\n setTimeout(() => {\n if (this.#messageResponseHandles.has(postMsg.messageId)) {\n this.#messageResponseHandles.delete(postMsg.messageId);\n messageResponseHandle.reject(\n new Error('Ledger iframe message timeout'),\n );\n }\n }, IFRAME_MESSAGE_TIMEOUT);\n\n this.iframe.contentWindow.postMessage(postMsg, '*');\n\n return messageResponseHandle.promise;\n }\n\n #validateConfiguration(opts: LedgerIframeBridgeOptions): void {\n if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {\n throw new Error('bridgeURL is not a valid URL');\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { GetPublicKeyParams, GetPublicKeyResponse, LedgerBridge, LedgerSignMessageParams, LedgerSignMessageResponse, LedgerSignTransactionParams, LedgerSignTransactionResponse, LedgerSignTypedDataParams, LedgerSignTypedDataResponse } from "./ledger-bridge.cjs";
|
|
2
2
|
export declare enum IFrameMessageAction {
|
|
3
|
+
LedgerIsIframeReady = "ledger-is-iframe-ready",
|
|
3
4
|
LedgerConnectionChange = "ledger-connection-change",
|
|
4
5
|
LedgerUnlock = "ledger-unlock",
|
|
5
6
|
LedgerMakeApp = "ledger-make-app",
|
|
@@ -66,7 +67,6 @@ export declare class LedgerIframeBridge implements LedgerBridge<LedgerIframeBrid
|
|
|
66
67
|
}) => void;
|
|
67
68
|
isDeviceConnected: boolean;
|
|
68
69
|
currentMessageId: number;
|
|
69
|
-
messageCallbacks: Record<number, (response: IFrameMessageResponse) => void>;
|
|
70
70
|
constructor(opts?: LedgerIframeBridgeOptions);
|
|
71
71
|
init(): Promise<void>;
|
|
72
72
|
destroy(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-iframe-bridge.d.cts","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ledger-iframe-bridge.d.cts","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,EACZ,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,6BAA6B,EAC7B,yBAAyB,EACzB,2BAA2B,EAC5B,4BAAwB;AAMzB,oBAAY,mBAAmB;IAC7B,mBAAmB,2BAA2B;IAC9C,sBAAsB,6BAA6B;IACnD,YAAY,kBAAkB;IAC9B,aAAa,oBAAoB;IACjC,qBAAqB,4BAA4B;IACjD,qBAAqB,4BAA4B;IACjD,yBAAyB,iCAAiC;IAC1D,mBAAmB,2BAA2B;CAC/C;AAED,KAAK,yBAAyB,CAC5B,aAAa,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7C,aAAa,GAAG,KAAK,IACnB;IACF,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,CACA;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,aAAa,CAAA;CAAE,GACzC;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE;QAAE,KAAK,EAAE,aAAa,CAAA;KAAE,CAAA;CAAE,CACxD,CAAC;AAEF,KAAK,oCAAoC,GAAG;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM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AAC,yBAAyB,CAAC;;IAElD,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAE3B,YAAY,UAAS;IAIrB,aAAa,CAAC,EAAE,CAAC,YAAY,EAAE;QAC7B,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,qBAAqB,CAAC;KAC7B,KAAK,IAAI,CAAC;IAEX,iBAAiB,UAAS;IAE1B,gBAAgB,SAAK;gBAQnB,IAAI,GAAE,yBAEL;IAQG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQrB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxB,UAAU,IAAI,OAAO,CAAC,yBAAyB,CAAC;IAIhD,UAAU,CAAC,IAAI,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAS1D,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IAelC,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAiB9D,YAAY,CAChB,MAAM,EAAE,kBAAkB,GACzB,OAAO,CAAC,oBAAoB,CAAC;IAI1B,qBAAqB,CACzB,MAAM,EAAE,2BAA2B,GAClC,OAAO,CAAC,6BAA6B,CAAC;IAOnC,iBAAiB,CACrB,MAAM,EAAE,uBAAuB,GAC9B,OAAO,CAAC,yBAAyB,CAAC;IAO/B,mBAAmB,CACvB,MAAM,EAAE,yBAAyB,GAChC,OAAO,CAAC,2BAA2B,CAAC;CA4IxC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { GetPublicKeyParams, GetPublicKeyResponse, LedgerBridge, LedgerSignMessageParams, LedgerSignMessageResponse, LedgerSignTransactionParams, LedgerSignTransactionResponse, LedgerSignTypedDataParams, LedgerSignTypedDataResponse } from "./ledger-bridge.mjs";
|
|
2
2
|
export declare enum IFrameMessageAction {
|
|
3
|
+
LedgerIsIframeReady = "ledger-is-iframe-ready",
|
|
3
4
|
LedgerConnectionChange = "ledger-connection-change",
|
|
4
5
|
LedgerUnlock = "ledger-unlock",
|
|
5
6
|
LedgerMakeApp = "ledger-make-app",
|
|
@@ -66,7 +67,6 @@ export declare class LedgerIframeBridge implements LedgerBridge<LedgerIframeBrid
|
|
|
66
67
|
}) => void;
|
|
67
68
|
isDeviceConnected: boolean;
|
|
68
69
|
currentMessageId: number;
|
|
69
|
-
messageCallbacks: Record<number, (response: IFrameMessageResponse) => void>;
|
|
70
70
|
constructor(opts?: LedgerIframeBridgeOptions);
|
|
71
71
|
init(): Promise<void>;
|
|
72
72
|
destroy(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-iframe-bridge.d.mts","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ledger-iframe-bridge.d.mts","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,EACZ,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,6BAA6B,EAC7B,yBAAyB,EACzB,2BAA2B,EAC5B,4BAAwB;AAMzB,oBAAY,mBAAmB;IAC7B,mBAAmB,2BAA2B;IAC9C,sBAAsB,6BAA6B;IACnD,YAAY,kBAAkB;IAC9B,aAAa,oBAAoB;IACjC,qBAAqB,4BAA4B;IACjD,qBAAqB,4BAA4B;IACjD,yBAAyB,iCAAiC;IAC1D,mBAAmB,2BAA2B;CAC/C;AAED,KAAK,yBAAyB,CAC5B,aAAa,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7C,aAAa,GAAG,KAAK,IACnB;IACF,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,CACA;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,aAAa,CAAA;CAAE,GACzC;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE;QAAE,KAAK,EAAE,aAAa,CAAA;KAAE,CAAA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BAAyB,GAAG;IACtC,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,qBAAa,kBACX,YAAW,YAAY,CAAC,yBAAyB,CAAC;;IAElD,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAE3B,YAAY,UAAS;IAIrB,aAAa,CAAC,EAAE,CAAC,YAAY,EAAE;QAC7B,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,qBAAqB,CAAC;KAC7B,KAAK,IAAI,CAAC;IAEX,iBAAiB,UAAS;IAE1B,gBAAgB,SAAK;gBAQnB,IAAI,GAAE,yBAEL;IAQG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQrB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxB,UAAU,IAAI,OAAO,CAAC,yBAAyB,CAAC;IAIhD,UAAU,CAAC,IAAI,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAS1D,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IAelC,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAiB9D,YAAY,CAChB,MAAM,EAAE,kBAAkB,GACzB,OAAO,CAAC,oBAAoB,CAAC;IAI1B,qBAAqB,CACzB,MAAM,EAAE,2BAA2B,GAClC,OAAO,CAAC,6BAA6B,CAAC;IAOnC,iBAAiB,CACrB,MAAM,EAAE,uBAAuB,GAC9B,OAAO,CAAC,yBAAyB,CAAC;IAO/B,mBAAmB,CACvB,MAAM,EAAE,yBAAyB,GAChC,OAAO,CAAC,2BAA2B,CAAC;CA4IxC"}
|
|
@@ -9,10 +9,13 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
10
10
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
11
11
|
};
|
|
12
|
-
var _LedgerIframeBridge_instances, _LedgerIframeBridge_opts, _LedgerIframeBridge_deviceActionMessage, _LedgerIframeBridge_setupIframe, _LedgerIframeBridge_getOrigin, _LedgerIframeBridge_eventListener, _LedgerIframeBridge_sendMessage, _LedgerIframeBridge_validateConfiguration;
|
|
12
|
+
var _LedgerIframeBridge_instances, _LedgerIframeBridge_opts, _LedgerIframeBridge_messageResponseHandles, _LedgerIframeBridge_deviceActionMessage, _LedgerIframeBridge_setupIframe, _LedgerIframeBridge_getOrigin, _LedgerIframeBridge_eventListener, _LedgerIframeBridge_sendMessage, _LedgerIframeBridge_validateConfiguration;
|
|
13
|
+
import { createDeferredPromise } from "@metamask/utils";
|
|
13
14
|
const LEDGER_IFRAME_ID = 'LEDGER-IFRAME';
|
|
15
|
+
const IFRAME_MESSAGE_TIMEOUT = 4000;
|
|
14
16
|
export var IFrameMessageAction;
|
|
15
17
|
(function (IFrameMessageAction) {
|
|
18
|
+
IFrameMessageAction["LedgerIsIframeReady"] = "ledger-is-iframe-ready";
|
|
16
19
|
IFrameMessageAction["LedgerConnectionChange"] = "ledger-connection-change";
|
|
17
20
|
IFrameMessageAction["LedgerUnlock"] = "ledger-unlock";
|
|
18
21
|
IFrameMessageAction["LedgerMakeApp"] = "ledger-make-app";
|
|
@@ -30,7 +33,7 @@ export class LedgerIframeBridge {
|
|
|
30
33
|
_LedgerIframeBridge_opts.set(this, void 0);
|
|
31
34
|
this.isDeviceConnected = false;
|
|
32
35
|
this.currentMessageId = 0;
|
|
33
|
-
this
|
|
36
|
+
_LedgerIframeBridge_messageResponseHandles.set(this, new Map());
|
|
34
37
|
__classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_validateConfiguration).call(this, opts);
|
|
35
38
|
__classPrivateFieldSet(this, _LedgerIframeBridge_opts, {
|
|
36
39
|
bridgeUrl: opts?.bridgeUrl,
|
|
@@ -58,40 +61,32 @@ export class LedgerIframeBridge {
|
|
|
58
61
|
}
|
|
59
62
|
}
|
|
60
63
|
async attemptMakeApp() {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
action: IFrameMessageAction.LedgerMakeApp,
|
|
64
|
-
}, (response) => {
|
|
65
|
-
if ('success' in response && response.success) {
|
|
66
|
-
resolve(true);
|
|
67
|
-
}
|
|
68
|
-
else if ('error' in response) {
|
|
69
|
-
// Assuming this is using an `Error` type:
|
|
70
|
-
reject(response.error);
|
|
71
|
-
}
|
|
72
|
-
else {
|
|
73
|
-
reject(new Error('Unknown error occurred'));
|
|
74
|
-
}
|
|
75
|
-
});
|
|
64
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
65
|
+
action: IFrameMessageAction.LedgerMakeApp,
|
|
76
66
|
});
|
|
67
|
+
if ('success' in response && response.success) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
else if ('error' in response) {
|
|
71
|
+
// Assuming this is using an `Error` type:
|
|
72
|
+
throw response.error;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
throw new Error('Unknown error occurred');
|
|
76
|
+
}
|
|
77
77
|
}
|
|
78
78
|
async updateTransportMethod(transportType) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
__classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
86
|
-
action: IFrameMessageAction.LedgerUpdateTransport,
|
|
87
|
-
params: { transportType },
|
|
88
|
-
}, (response) => {
|
|
89
|
-
if ('success' in response && response.success) {
|
|
90
|
-
return resolve(true);
|
|
91
|
-
}
|
|
92
|
-
return reject(new Error('Ledger transport could not be updated'));
|
|
93
|
-
});
|
|
79
|
+
if (!this.iframeLoaded) {
|
|
80
|
+
throw new Error('The iframe is not loaded yet');
|
|
81
|
+
}
|
|
82
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, {
|
|
83
|
+
action: IFrameMessageAction.LedgerUpdateTransport,
|
|
84
|
+
params: { transportType },
|
|
94
85
|
});
|
|
86
|
+
if ('success' in response && response.success) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
throw new Error('Ledger transport could not be updated');
|
|
95
90
|
}
|
|
96
91
|
async getPublicKey(params) {
|
|
97
92
|
return __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_deviceActionMessage).call(this, IFrameMessageAction.LedgerUnlock, params);
|
|
@@ -106,23 +101,17 @@ export class LedgerIframeBridge {
|
|
|
106
101
|
return __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_deviceActionMessage).call(this, IFrameMessageAction.LedgerSignTypedData, params);
|
|
107
102
|
}
|
|
108
103
|
}
|
|
109
|
-
_LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_instances = new WeakSet(), _LedgerIframeBridge_deviceActionMessage = async function _LedgerIframeBridge_deviceActionMessage(...[action, params]) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
return reject(response.payload.error);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return reject(new Error('Unknown error occurred'));
|
|
124
|
-
});
|
|
125
|
-
});
|
|
104
|
+
_LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_messageResponseHandles = new WeakMap(), _LedgerIframeBridge_instances = new WeakSet(), _LedgerIframeBridge_deviceActionMessage = async function _LedgerIframeBridge_deviceActionMessage(...[action, params]) {
|
|
105
|
+
const response = await __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_sendMessage).call(this, { action, params });
|
|
106
|
+
if ('payload' in response && response.payload) {
|
|
107
|
+
if ('success' in response && response.success) {
|
|
108
|
+
return response.payload;
|
|
109
|
+
}
|
|
110
|
+
if ('error' in response.payload) {
|
|
111
|
+
throw response.payload.error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
throw new Error('Unknown error occurred');
|
|
126
115
|
}, _LedgerIframeBridge_setupIframe = async function _LedgerIframeBridge_setupIframe(bridgeUrl) {
|
|
127
116
|
return new Promise((resolve) => {
|
|
128
117
|
this.iframe = document.createElement('iframe');
|
|
@@ -139,30 +128,40 @@ _LedgerIframeBridge_opts = new WeakMap(), _LedgerIframeBridge_instances = new We
|
|
|
139
128
|
tmp.splice(-1, 1);
|
|
140
129
|
return tmp.join('/');
|
|
141
130
|
}, _LedgerIframeBridge_eventListener = function _LedgerIframeBridge_eventListener(bridgeUrl, eventMessage) {
|
|
142
|
-
|
|
131
|
+
const { origin, data } = eventMessage;
|
|
132
|
+
if (origin !== __classPrivateFieldGet(this, _LedgerIframeBridge_instances, "m", _LedgerIframeBridge_getOrigin).call(this, bridgeUrl)) {
|
|
143
133
|
return;
|
|
144
134
|
}
|
|
145
|
-
if (
|
|
146
|
-
const
|
|
147
|
-
if (
|
|
148
|
-
|
|
135
|
+
if (data) {
|
|
136
|
+
const messageResponseHandle = __classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").get(data.messageId);
|
|
137
|
+
if (messageResponseHandle) {
|
|
138
|
+
messageResponseHandle.resolve(data);
|
|
139
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").delete(data.messageId);
|
|
149
140
|
}
|
|
150
|
-
else if (
|
|
151
|
-
this.isDeviceConnected =
|
|
141
|
+
else if (data.action === IFrameMessageAction.LedgerConnectionChange) {
|
|
142
|
+
this.isDeviceConnected = data.payload.connected;
|
|
152
143
|
}
|
|
153
144
|
}
|
|
154
|
-
}, _LedgerIframeBridge_sendMessage = function _LedgerIframeBridge_sendMessage(message
|
|
145
|
+
}, _LedgerIframeBridge_sendMessage = async function _LedgerIframeBridge_sendMessage(message) {
|
|
155
146
|
this.currentMessageId += 1;
|
|
156
147
|
const postMsg = {
|
|
157
148
|
...message,
|
|
158
149
|
messageId: this.currentMessageId,
|
|
159
150
|
target: LEDGER_IFRAME_ID,
|
|
160
151
|
};
|
|
161
|
-
|
|
152
|
+
const messageResponseHandle = createDeferredPromise();
|
|
153
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").set(this.currentMessageId, messageResponseHandle);
|
|
162
154
|
if (!this.iframeLoaded || !this.iframe?.contentWindow) {
|
|
163
155
|
throw new Error('The iframe is not loaded yet');
|
|
164
156
|
}
|
|
157
|
+
setTimeout(() => {
|
|
158
|
+
if (__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").has(postMsg.messageId)) {
|
|
159
|
+
__classPrivateFieldGet(this, _LedgerIframeBridge_messageResponseHandles, "f").delete(postMsg.messageId);
|
|
160
|
+
messageResponseHandle.reject(new Error('Ledger iframe message timeout'));
|
|
161
|
+
}
|
|
162
|
+
}, IFRAME_MESSAGE_TIMEOUT);
|
|
165
163
|
this.iframe.contentWindow.postMessage(postMsg, '*');
|
|
164
|
+
return messageResponseHandle.promise;
|
|
166
165
|
}, _LedgerIframeBridge_validateConfiguration = function _LedgerIframeBridge_validateConfiguration(opts) {
|
|
167
166
|
if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {
|
|
168
167
|
throw new Error('bridgeURL is not a valid URL');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-iframe-bridge.mjs","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,MAAM,CAAN,IAAY,mBAQX;AARD,WAAY,mBAAmB;IAC7B,0EAAmD,CAAA;IACnD,qDAA8B,CAAA;IAC9B,wDAAiC,CAAA;IACjC,wEAAiD,CAAA;IACjD,wEAAiD,CAAA;IACjD,iFAA0D,CAAA;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CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,IAAI,eAAe,EAAE,CAAC;YACpB,eAAe,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QACrC,CAAC;aAAM,IACL,YAAY,CAAC,IAAI,CAAC,MAAM,KAAK,mBAAmB,CAAC,sBAAsB,EACvE,CAAC;YACD,IAAI,CAAC,iBAAiB,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;QAC/D,CAAC;IACH,CAAC;AACH,CAAC,6EAGC,OAA+B,EAC/B,QAAmD;IAEnD,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;IAE3B,MAAM,OAAO,GAA+B;QAC1C,GAAG,OAAO;QACV,SAAS,EAAE,IAAI,CAAC,gBAAgB;QAChC,MAAM,EAAE,gBAAgB;KACzB,CAAC;IAEF,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,QAAQ,CAAC;IAExD,IAAI,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACtD,CAAC,iGAEsB,IAA+B;IACpD,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["import {\n GetPublicKeyParams,\n GetPublicKeyResponse,\n LedgerBridge,\n LedgerSignMessageParams,\n LedgerSignMessageResponse,\n LedgerSignTransactionParams,\n LedgerSignTransactionResponse,\n LedgerSignTypedDataParams,\n LedgerSignTypedDataResponse,\n} from './ledger-bridge';\n\nconst LEDGER_IFRAME_ID = 'LEDGER-IFRAME';\n\nexport enum IFrameMessageAction {\n LedgerConnectionChange = 'ledger-connection-change',\n LedgerUnlock = 'ledger-unlock',\n LedgerMakeApp = 'ledger-make-app',\n LedgerUpdateTransport = 'ledger-update-transport',\n LedgerSignTransaction = 'ledger-sign-transaction',\n LedgerSignPersonalMessage = 'ledger-sign-personal-message',\n LedgerSignTypedData = 'ledger-sign-typed-data',\n}\n\ntype IFrameMessageResponseStub<\n SuccessResult extends Record<string, unknown>,\n FailureResult = Error,\n> = {\n messageId: number;\n} & (\n | { success: true; payload: SuccessResult }\n | { success: false; payload: { error: FailureResult } }\n);\n\ntype LedgerConnectionChangeActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerConnectionChange;\n payload: { connected: boolean };\n};\n\ntype LedgerMakeAppActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerMakeApp;\n} & ({ success: true } | { success: false; error?: unknown });\n\ntype LedgerUpdateTransportActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerUpdateTransport;\n success: boolean;\n};\n\ntype LedgerUnlockActionResponse = {\n action: IFrameMessageAction.LedgerUnlock;\n} & IFrameMessageResponseStub<GetPublicKeyResponse>;\n\ntype LedgerSignTransactionActionResponse = {\n action: IFrameMessageAction.LedgerSignTransaction;\n} & IFrameMessageResponseStub<LedgerSignTransactionResponse>;\n\ntype LedgerSignPersonalMessageActionResponse = {\n action: IFrameMessageAction.LedgerSignPersonalMessage;\n} & IFrameMessageResponseStub<LedgerSignMessageResponse>;\n\ntype LedgerSignTypedDataActionResponse = {\n action: IFrameMessageAction.LedgerSignTypedData;\n} & IFrameMessageResponseStub<LedgerSignTypedDataResponse>;\n\nexport type IFrameMessageResponse =\n | LedgerConnectionChangeActionResponse\n | LedgerMakeAppActionResponse\n | LedgerUpdateTransportActionResponse\n | LedgerUnlockActionResponse\n | LedgerSignTransactionActionResponse\n | LedgerSignPersonalMessageActionResponse\n | LedgerSignTypedDataActionResponse;\n\ntype IFrameMessage<TAction extends IFrameMessageAction> = {\n action: TAction;\n params?: Readonly<Record<string, unknown>>;\n};\n\ntype IFramePostMessage<TAction extends IFrameMessageAction> =\n IFrameMessage<TAction> & {\n messageId: number;\n target: typeof LEDGER_IFRAME_ID;\n };\n\nexport type LedgerIframeBridgeOptions = {\n bridgeUrl: string;\n};\n\nexport class LedgerIframeBridge\n implements LedgerBridge<LedgerIframeBridgeOptions>\n{\n iframe?: HTMLIFrameElement;\n\n iframeLoaded = false;\n\n readonly #opts: LedgerIframeBridgeOptions;\n\n eventListener?: (eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n }) => void;\n\n isDeviceConnected = false;\n\n currentMessageId = 0;\n\n messageCallbacks: Record<number, (response: IFrameMessageResponse) => void> =\n {};\n\n constructor(\n opts: LedgerIframeBridgeOptions = {\n bridgeUrl: 'https://metamask.github.io/eth-ledger-bridge-keyring',\n },\n ) {\n this.#validateConfiguration(opts);\n this.#opts = {\n bridgeUrl: opts?.bridgeUrl,\n };\n }\n\n async init(): Promise<void> {\n await this.#setupIframe(this.#opts.bridgeUrl);\n\n this.eventListener = this.#eventListener.bind(this, this.#opts.bridgeUrl);\n\n window.addEventListener('message', this.eventListener);\n }\n\n async destroy(): Promise<void> {\n if (this.eventListener) {\n window.removeEventListener('message', this.eventListener);\n }\n }\n\n async getOptions(): Promise<LedgerIframeBridgeOptions> {\n return this.#opts;\n }\n\n async setOptions(opts: LedgerIframeBridgeOptions): Promise<void> {\n this.#validateConfiguration(opts);\n if (this.#opts?.bridgeUrl !== opts.bridgeUrl) {\n this.#opts.bridgeUrl = opts.bridgeUrl;\n await this.destroy();\n await this.init();\n }\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n this.#sendMessage(\n {\n action: IFrameMessageAction.LedgerMakeApp,\n },\n (response) => {\n if ('success' in response && response.success) {\n resolve(true);\n } else if ('error' in response) {\n // Assuming this is using an `Error` type:\n reject(response.error as Error);\n } else {\n reject(new Error('Unknown error occurred'));\n }\n },\n );\n });\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n // If the iframe isn't loaded yet, let's store the desired transportType value and\n // optimistically return a successful promise\n if (!this.iframeLoaded) {\n throw new Error('The iframe is not loaded yet');\n }\n\n this.#sendMessage(\n {\n action: IFrameMessageAction.LedgerUpdateTransport,\n params: { transportType },\n },\n (response) => {\n if ('success' in response && response.success) {\n return resolve(true);\n }\n return reject(new Error('Ledger transport could not be updated'));\n },\n );\n });\n }\n\n async getPublicKey(\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse> {\n return this.#deviceActionMessage(IFrameMessageAction.LedgerUnlock, params);\n }\n\n async deviceSignTransaction(\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTransaction,\n params,\n );\n }\n\n async deviceSignMessage(\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignPersonalMessage,\n params,\n );\n }\n\n async deviceSignTypedData(\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTypedData,\n params,\n );\n }\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerUnlock,\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTransaction,\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignPersonalMessage,\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTypedData,\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse>;\n\n async #deviceActionMessage(\n ...[action, params]:\n | [IFrameMessageAction.LedgerUnlock, GetPublicKeyParams]\n | [IFrameMessageAction.LedgerSignTransaction, LedgerSignTransactionParams]\n | [IFrameMessageAction.LedgerSignPersonalMessage, LedgerSignMessageParams]\n | [IFrameMessageAction.LedgerSignTypedData, LedgerSignTypedDataParams]\n ): Promise<\n | GetPublicKeyResponse\n | LedgerSignTransactionResponse\n | LedgerSignMessageResponse\n | LedgerSignTypedDataResponse\n > {\n return new Promise((resolve, reject) => {\n this.#sendMessage(\n {\n action,\n params,\n },\n (response) => {\n if ('payload' in response && response.payload) {\n if ('success' in response && response.success) {\n return resolve(response.payload);\n }\n if ('error' in response.payload) {\n return reject(response.payload.error);\n }\n }\n return reject(new Error('Unknown error occurred'));\n },\n );\n });\n }\n\n async #setupIframe(bridgeUrl: string): Promise<void> {\n return new Promise((resolve) => {\n this.iframe = document.createElement('iframe');\n this.iframe.src = bridgeUrl;\n this.iframe.allow = `hid 'src'`;\n this.iframe.onload = async (): Promise<void> => {\n this.iframeLoaded = true;\n resolve();\n };\n document.head.appendChild(this.iframe);\n });\n }\n\n #getOrigin(bridgeUrl: string): string {\n const tmp = bridgeUrl.split('/');\n tmp.splice(-1, 1);\n return tmp.join('/');\n }\n\n #eventListener(\n bridgeUrl: string,\n eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n },\n ): void {\n if (eventMessage.origin !== this.#getOrigin(bridgeUrl)) {\n return;\n }\n\n if (eventMessage.data) {\n const messageCallback =\n this.messageCallbacks[eventMessage.data.messageId];\n if (messageCallback) {\n messageCallback(eventMessage.data);\n } else if (\n eventMessage.data.action === IFrameMessageAction.LedgerConnectionChange\n ) {\n this.isDeviceConnected = eventMessage.data.payload.connected;\n }\n }\n }\n\n #sendMessage<TAction extends IFrameMessageAction>(\n message: IFrameMessage<TAction>,\n callback: (response: IFrameMessageResponse) => void,\n ): void {\n this.currentMessageId += 1;\n\n const postMsg: IFramePostMessage<TAction> = {\n ...message,\n messageId: this.currentMessageId,\n target: LEDGER_IFRAME_ID,\n };\n\n this.messageCallbacks[this.currentMessageId] = callback;\n\n if (!this.iframeLoaded || !this.iframe?.contentWindow) {\n throw new Error('The iframe is not loaded yet');\n }\n\n this.iframe.contentWindow.postMessage(postMsg, '*');\n }\n\n #validateConfiguration(opts: LedgerIframeBridgeOptions): void {\n if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {\n throw new Error('bridgeURL is not a valid URL');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ledger-iframe-bridge.mjs","sourceRoot":"","sources":["../src/ledger-iframe-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,qBAAqB,EAAmB,wBAAwB;AAczE,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,MAAM,CAAN,IAAY,mBASX;AATD,WAAY,mBAAmB;IAC7B,qEAA8C,CAAA;IAC9C,0EAAmD,CAAA;IACnD,qDAA8B,CAAA;IAC9B,wDAAiC,CAAA;IACjC,wEAAiD,CAAA;IACjD,wEAAiD,CAAA;IACjD,iFAA0D,CAAA;IAC1D,qEAA8C,CAAA;AAChD,CAAC,EATW,mBAAmB,KAAnB,mBAAmB,QAS9B;AAqED,MAAM,OAAO,kBAAkB;IAuB7B,YACE,OAAkC;QAChC,SAAS,EAAE,sDAAsD;KAClE;;QArBH,iBAAY,GAAG,KAAK,CAAC;QAEZ,2CAAiC;QAO1C,sBAAiB,GAAG,KAAK,CAAC;QAE1B,qBAAgB,GAAG,CAAC,CAAC;QAEZ,qDAGL,IAAI,GAAG,EAAE,EAAC;QAOZ,uBAAA,IAAI,gFAAuB,MAA3B,IAAI,EAAwB,IAAI,CAAC,CAAC;QAClC,uBAAA,IAAI,4BAAS;YACX,SAAS,EAAE,IAAI,EAAE,SAAS;SAC3B,MAAA,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,uBAAA,IAAI,sEAA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AG,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;YACxD,uBAAA,IAAI,kDAAwB,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACvD,qBAAqB,CAAC,MAAM,CAC1B,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAC3C,CAAC;QACJ,CAAC;IACH,CAAC,EAAE,sBAAsB,CAAC,CAAC;IAE3B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAEpD,OAAO,qBAAqB,CAAC,OAAO,CAAC;AACvC,CAAC,iGAEsB,IAA+B;IACpD,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["import { createDeferredPromise, DeferredPromise } from '@metamask/utils';\n\nimport {\n GetPublicKeyParams,\n GetPublicKeyResponse,\n LedgerBridge,\n LedgerSignMessageParams,\n LedgerSignMessageResponse,\n LedgerSignTransactionParams,\n LedgerSignTransactionResponse,\n LedgerSignTypedDataParams,\n LedgerSignTypedDataResponse,\n} from './ledger-bridge';\n\nconst LEDGER_IFRAME_ID = 'LEDGER-IFRAME';\n\nconst IFRAME_MESSAGE_TIMEOUT = 4000;\n\nexport enum IFrameMessageAction {\n LedgerIsIframeReady = 'ledger-is-iframe-ready',\n LedgerConnectionChange = 'ledger-connection-change',\n LedgerUnlock = 'ledger-unlock',\n LedgerMakeApp = 'ledger-make-app',\n LedgerUpdateTransport = 'ledger-update-transport',\n LedgerSignTransaction = 'ledger-sign-transaction',\n LedgerSignPersonalMessage = 'ledger-sign-personal-message',\n LedgerSignTypedData = 'ledger-sign-typed-data',\n}\n\ntype IFrameMessageResponseStub<\n SuccessResult extends Record<string, unknown>,\n FailureResult = Error,\n> = {\n messageId: number;\n} & (\n | { success: true; payload: SuccessResult }\n | { success: false; payload: { error: FailureResult } }\n);\n\ntype LedgerConnectionChangeActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerConnectionChange;\n payload: { connected: boolean };\n};\n\ntype LedgerMakeAppActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerMakeApp;\n} & ({ success: true } | { success: false; error?: unknown });\n\ntype LedgerUpdateTransportActionResponse = {\n messageId: number;\n action: IFrameMessageAction.LedgerUpdateTransport;\n success: boolean;\n};\n\ntype LedgerUnlockActionResponse = {\n action: IFrameMessageAction.LedgerUnlock;\n} & IFrameMessageResponseStub<GetPublicKeyResponse>;\n\ntype LedgerSignTransactionActionResponse = {\n action: IFrameMessageAction.LedgerSignTransaction;\n} & IFrameMessageResponseStub<LedgerSignTransactionResponse>;\n\ntype LedgerSignPersonalMessageActionResponse = {\n action: IFrameMessageAction.LedgerSignPersonalMessage;\n} & IFrameMessageResponseStub<LedgerSignMessageResponse>;\n\ntype LedgerSignTypedDataActionResponse = {\n action: IFrameMessageAction.LedgerSignTypedData;\n} & IFrameMessageResponseStub<LedgerSignTypedDataResponse>;\n\nexport type IFrameMessageResponse =\n | LedgerConnectionChangeActionResponse\n | LedgerMakeAppActionResponse\n | LedgerUpdateTransportActionResponse\n | LedgerUnlockActionResponse\n | LedgerSignTransactionActionResponse\n | LedgerSignPersonalMessageActionResponse\n | LedgerSignTypedDataActionResponse;\n\ntype IFrameMessage<TAction extends IFrameMessageAction> = {\n action: TAction;\n params?: Readonly<Record<string, unknown>>;\n};\n\ntype IFramePostMessage<TAction extends IFrameMessageAction> =\n IFrameMessage<TAction> & {\n messageId: number;\n target: typeof LEDGER_IFRAME_ID;\n };\n\nexport type LedgerIframeBridgeOptions = {\n bridgeUrl: string;\n};\n\nexport class LedgerIframeBridge\n implements LedgerBridge<LedgerIframeBridgeOptions>\n{\n iframe?: HTMLIFrameElement;\n\n iframeLoaded = false;\n\n readonly #opts: LedgerIframeBridgeOptions;\n\n eventListener?: (eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n }) => void;\n\n isDeviceConnected = false;\n\n currentMessageId = 0;\n\n readonly #messageResponseHandles: Map<\n number,\n DeferredPromise<IFrameMessageResponse>\n > = new Map();\n\n constructor(\n opts: LedgerIframeBridgeOptions = {\n bridgeUrl: 'https://metamask.github.io/eth-ledger-bridge-keyring',\n },\n ) {\n this.#validateConfiguration(opts);\n this.#opts = {\n bridgeUrl: opts?.bridgeUrl,\n };\n }\n\n async init(): Promise<void> {\n await this.#setupIframe(this.#opts.bridgeUrl);\n\n this.eventListener = this.#eventListener.bind(this, this.#opts.bridgeUrl);\n\n window.addEventListener('message', this.eventListener);\n }\n\n async destroy(): Promise<void> {\n if (this.eventListener) {\n window.removeEventListener('message', this.eventListener);\n }\n }\n\n async getOptions(): Promise<LedgerIframeBridgeOptions> {\n return this.#opts;\n }\n\n async setOptions(opts: LedgerIframeBridgeOptions): Promise<void> {\n this.#validateConfiguration(opts);\n if (this.#opts?.bridgeUrl !== opts.bridgeUrl) {\n this.#opts.bridgeUrl = opts.bridgeUrl;\n await this.destroy();\n await this.init();\n }\n }\n\n async attemptMakeApp(): Promise<boolean> {\n const response = await this.#sendMessage({\n action: IFrameMessageAction.LedgerMakeApp,\n });\n\n if ('success' in response && response.success) {\n return true;\n } else if ('error' in response) {\n // Assuming this is using an `Error` type:\n throw response.error;\n } else {\n throw new Error('Unknown error occurred');\n }\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n if (!this.iframeLoaded) {\n throw new Error('The iframe is not loaded yet');\n }\n\n const response = await this.#sendMessage({\n action: IFrameMessageAction.LedgerUpdateTransport,\n params: { transportType },\n });\n\n if ('success' in response && response.success) {\n return true;\n }\n\n throw new Error('Ledger transport could not be updated');\n }\n\n async getPublicKey(\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse> {\n return this.#deviceActionMessage(IFrameMessageAction.LedgerUnlock, params);\n }\n\n async deviceSignTransaction(\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTransaction,\n params,\n );\n }\n\n async deviceSignMessage(\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignPersonalMessage,\n params,\n );\n }\n\n async deviceSignTypedData(\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse> {\n return this.#deviceActionMessage(\n IFrameMessageAction.LedgerSignTypedData,\n params,\n );\n }\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerUnlock,\n params: GetPublicKeyParams,\n ): Promise<GetPublicKeyResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTransaction,\n params: LedgerSignTransactionParams,\n ): Promise<LedgerSignTransactionResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignPersonalMessage,\n params: LedgerSignMessageParams,\n ): Promise<LedgerSignMessageResponse>;\n\n async #deviceActionMessage(\n action: IFrameMessageAction.LedgerSignTypedData,\n params: LedgerSignTypedDataParams,\n ): Promise<LedgerSignTypedDataResponse>;\n\n async #deviceActionMessage(\n ...[action, params]:\n | [IFrameMessageAction.LedgerUnlock, GetPublicKeyParams]\n | [IFrameMessageAction.LedgerSignTransaction, LedgerSignTransactionParams]\n | [IFrameMessageAction.LedgerSignPersonalMessage, LedgerSignMessageParams]\n | [IFrameMessageAction.LedgerSignTypedData, LedgerSignTypedDataParams]\n ): Promise<\n | GetPublicKeyResponse\n | LedgerSignTransactionResponse\n | LedgerSignMessageResponse\n | LedgerSignTypedDataResponse\n > {\n const response = await this.#sendMessage({ action, params });\n\n if ('payload' in response && response.payload) {\n if ('success' in response && response.success) {\n return response.payload;\n }\n if ('error' in response.payload) {\n throw response.payload.error;\n }\n }\n\n throw new Error('Unknown error occurred');\n }\n\n async #setupIframe(bridgeUrl: string): Promise<void> {\n return new Promise((resolve) => {\n this.iframe = document.createElement('iframe');\n this.iframe.src = bridgeUrl;\n this.iframe.allow = `hid 'src'`;\n this.iframe.onload = async (): Promise<void> => {\n this.iframeLoaded = true;\n resolve();\n };\n document.head.appendChild(this.iframe);\n });\n }\n\n #getOrigin(bridgeUrl: string): string {\n const tmp = bridgeUrl.split('/');\n tmp.splice(-1, 1);\n return tmp.join('/');\n }\n\n #eventListener(\n bridgeUrl: string,\n eventMessage: {\n origin: string;\n data: IFrameMessageResponse;\n },\n ): void {\n const { origin, data } = eventMessage;\n\n if (origin !== this.#getOrigin(bridgeUrl)) {\n return;\n }\n\n if (data) {\n const messageResponseHandle = this.#messageResponseHandles.get(\n data.messageId,\n );\n if (messageResponseHandle) {\n messageResponseHandle.resolve(data);\n this.#messageResponseHandles.delete(data.messageId);\n } else if (data.action === IFrameMessageAction.LedgerConnectionChange) {\n this.isDeviceConnected = data.payload.connected;\n }\n }\n }\n\n async #sendMessage<TAction extends IFrameMessageAction>(\n message: IFrameMessage<TAction>,\n ): Promise<IFrameMessageResponse> {\n this.currentMessageId += 1;\n\n const postMsg: IFramePostMessage<TAction> = {\n ...message,\n messageId: this.currentMessageId,\n target: LEDGER_IFRAME_ID,\n };\n\n const messageResponseHandle =\n createDeferredPromise<IFrameMessageResponse>();\n\n this.#messageResponseHandles.set(\n this.currentMessageId,\n messageResponseHandle,\n );\n\n if (!this.iframeLoaded || !this.iframe?.contentWindow) {\n throw new Error('The iframe is not loaded yet');\n }\n\n setTimeout(() => {\n if (this.#messageResponseHandles.has(postMsg.messageId)) {\n this.#messageResponseHandles.delete(postMsg.messageId);\n messageResponseHandle.reject(\n new Error('Ledger iframe message timeout'),\n );\n }\n }, IFRAME_MESSAGE_TIMEOUT);\n\n this.iframe.contentWindow.postMessage(postMsg, '*');\n\n return messageResponseHandle.promise;\n }\n\n #validateConfiguration(opts: LedgerIframeBridgeOptions): void {\n if (typeof opts.bridgeUrl !== 'string' || opts.bridgeUrl.length === 0) {\n throw new Error('bridgeURL is not a valid URL');\n }\n }\n}\n"]}
|
package/dist/ledger-keyring.cjs
CHANGED
|
@@ -7,7 +7,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
7
7
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
8
8
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9
9
|
};
|
|
10
|
-
var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction,
|
|
10
|
+
var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress;
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.LedgerKeyring = void 0;
|
|
13
13
|
const rlp_1 = require("@ethereumjs/rlp");
|
|
@@ -332,7 +332,9 @@ class LedgerKeyring {
|
|
|
332
332
|
chainId: domain.chainId,
|
|
333
333
|
version: domain.version,
|
|
334
334
|
verifyingContract: domain.verifyingContract,
|
|
335
|
-
salt:
|
|
335
|
+
salt: domain.salt instanceof ArrayBuffer
|
|
336
|
+
? buffer_1.Buffer.from(domain.salt).toString('hex')
|
|
337
|
+
: domain.salt,
|
|
336
338
|
},
|
|
337
339
|
types,
|
|
338
340
|
primaryType: primaryType.toString(),
|
|
@@ -417,14 +419,6 @@ _LedgerKeyring_instances = new WeakSet(), _LedgerKeyring_migrateAccountDetails =
|
|
|
417
419
|
return newOrMutatedTx;
|
|
418
420
|
}
|
|
419
421
|
throw new Error('Ledger: The transaction signature is not valid');
|
|
420
|
-
}, _LedgerKeyring_convertSaltIfAny = function _LedgerKeyring_convertSaltIfAny(salt) {
|
|
421
|
-
if (!salt) {
|
|
422
|
-
return undefined;
|
|
423
|
-
}
|
|
424
|
-
// We convert this to a plain string to avoid encoding issue on the
|
|
425
|
-
// mobile side (to avoid using `TextDecoder`).
|
|
426
|
-
const saltBytes = new Uint8Array(salt);
|
|
427
|
-
return String.fromCharCode(...saltBytes);
|
|
428
422
|
}, _LedgerKeyring_getPage =
|
|
429
423
|
/* PRIVATE METHODS */
|
|
430
424
|
async function _LedgerKeyring_getPage(increment) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-keyring.cjs","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yCAAsC;AACtC,uCAIwB;AACxB,2CAAmD;AAEnD,yDAKgC;AAEhC,2CAMyB;AACzB,mCAAgC;AAEhC,kDAA0B;AAK1B,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,YAAY,GAAG,GAAG,QAAQ,aAAa,CAAC;AAC9C,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAEtC,+GAA+G;AAC/G,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,IAAK,cAKJ;AALD,WAAK,cAAc;IACjB,8DAA4C,CAAA;IAC5C,0DAAwC,CAAA;IACxC,8DAA4C,CAAA;IAC5C,sDAAoC,CAAA;AACtC,CAAC,EALI,cAAc,KAAd,cAAc,QAKlB;AA+BD;;;;;;;;;;;;GAYG;AACH,SAAS,sBAAsB,CAC7B,EAA0C;IAE1C,OAAO,YAAY,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,UAAU,KAAK,UAAU,CAAC;AACnE,CAAC;AAED,MAAa,aAAa;IA6BxB,YAAY,EAAE,MAAM,EAAiD;;QA1BrE,aAAQ,GAAG,EAAE,CAAC;QAEL,SAAI,GAAW,WAAW,CAAC;QAEpC,SAAI,GAAG,CAAC,CAAC;QAET,YAAO,GAAG,CAAC,CAAC;QAEZ,oBAAe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;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,IAAA,0BAAkB,EAAC,IAAA,aAAK,EAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC;AAjmBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger Ethereum app closed. Open it to unlock.');\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing transaction');\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let modifiedV = parseInt(String(payload.v), 10).toString(16);\n if (modifiedV.length < 2) {\n modifiedV = `0${modifiedV}`;\n }\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt: this.#convertSaltIfAny(domain.salt),\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let recoveryId = parseInt(String(payload.v), 10).toString(16);\n if (recoveryId.length < 2) {\n recoveryId = `0${recoveryId}`;\n }\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n #convertSaltIfAny(salt: ArrayBuffer | undefined): string | undefined {\n if (!salt) {\n return undefined;\n }\n\n // We convert this to a plain string to avoid encoding issue on the\n // mobile side (to avoid using `TextDecoder`).\n const saltBytes = new Uint8Array(salt);\n return String.fromCharCode(...saltBytes);\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ledger-keyring.cjs","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yCAAsC;AACtC,uCAIwB;AACxB,2CAAmD;AAEnD,yDAKgC;AAEhC,2CAMyB;AACzB,mCAAgC;AAEhC,kDAA0B;AAK1B,MAAM,QAAQ,GAAG,GAAG,CAAC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AO,IAAI,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC,2CAED,KAAK,iDAA0B,OAAe;IAC5C,MAAM,MAAM,GAAG,uBAAA,IAAI,0DAAW,MAAf,IAAI,CAAa,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,GAAG,MAAM,6CAA6C,OAAO,6BAA6B,CAC3F,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,cAAc,CAAC,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3E,CAAC;IAGC,OAAO,IAAI,CAAC,OAAO,CAAC;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,IAAA,0BAAkB,EAAC,IAAA,aAAK,EAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC;AAzlBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger Ethereum app closed. Open it to unlock.');\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing transaction');\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let modifiedV = parseInt(String(payload.v), 10).toString(16);\n if (modifiedV.length < 2) {\n modifiedV = `0${modifiedV}`;\n }\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt:\n domain.salt instanceof ArrayBuffer\n ? Buffer.from(domain.salt).toString('hex')\n : domain.salt,\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let recoveryId = parseInt(String(payload.v), 10).toString(16);\n if (recoveryId.length < 2) {\n recoveryId = `0${recoveryId}`;\n }\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-keyring.d.cts","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,gBAAgB,EACtB,uBAAuB;AAExB,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,+BAA+B;AACzE,OAAO,EAGL,oBAAoB,EAErB,+BAA+B;AAChC,OAAO,KAAK,EAAE,OAAO,EAAE,gCAAgC;AACvD,OAAO,EAIL,GAAG,EAEJ,wBAAwB;AAEzB,OAAO,KAAK,mBAAmB,sBAAsB;AACrD,OAAO,KAAK,cAAc;AAE1B,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,4BAAwB;AAUpE,aAAK,cAAc;IACjB,OAAO,qCAAqC;IAC5C,KAAK,mCAAmC;IACxC,OAAO,qCAAqC;IAC5C,OAAO,6BAA6B;CACrC;AAMD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG,gBAAgB,EAAE,CAAC;AAE7C,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,EAAE,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,C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AAM,GAAG,IAAI;IAa9B,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IAIlC,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAK9D,eAAe,CACnB,OAAO,EAAE,GAAG,EACZ,EAAE,EAAE,gBAAgB,GAAG,mBAAmB,GACzC,OAAO,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;IAgG5C,WAAW,CAAC,WAAW,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAK5D,mBAAmB,CACvB,WAAW,EAAE,GAAG,EAChB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,CAAC;IAsCZ,sBAAsB,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAqBjE,aAAa,CACjB,OAAO,SAAS,oBAAoB,CAAC,EAAE,EACvC,KAAK,SAAS,YAAY,EAC1B,OAAO,SAAS;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,EAErC,WAAW,EAAE,GAAG,EAChB,IAAI,EAAE,YAAY,CAAC,KAAK,CAAC,EACzB,OAAO,CAAC,EAAE,OAAO,GAChB,OAAO,CAAC,MAAM,CAAC;IAgElB,YAAY,IAAI,IAAI;CA8HrB"}
|
package/dist/ledger-keyring.mjs
CHANGED
|
@@ -3,7 +3,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
3
3
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
4
4
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
5
5
|
};
|
|
6
|
-
var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction,
|
|
6
|
+
var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress;
|
|
7
7
|
function $importDefault(module) {
|
|
8
8
|
if (module?.__esModule) {
|
|
9
9
|
return module.default;
|
|
@@ -333,7 +333,9 @@ export class LedgerKeyring {
|
|
|
333
333
|
chainId: domain.chainId,
|
|
334
334
|
version: domain.version,
|
|
335
335
|
verifyingContract: domain.verifyingContract,
|
|
336
|
-
salt:
|
|
336
|
+
salt: domain.salt instanceof ArrayBuffer
|
|
337
|
+
? Buffer.from(domain.salt).toString('hex')
|
|
338
|
+
: domain.salt,
|
|
337
339
|
},
|
|
338
340
|
types,
|
|
339
341
|
primaryType: primaryType.toString(),
|
|
@@ -417,14 +419,6 @@ _LedgerKeyring_instances = new WeakSet(), _LedgerKeyring_migrateAccountDetails =
|
|
|
417
419
|
return newOrMutatedTx;
|
|
418
420
|
}
|
|
419
421
|
throw new Error('Ledger: The transaction signature is not valid');
|
|
420
|
-
}, _LedgerKeyring_convertSaltIfAny = function _LedgerKeyring_convertSaltIfAny(salt) {
|
|
421
|
-
if (!salt) {
|
|
422
|
-
return undefined;
|
|
423
|
-
}
|
|
424
|
-
// We convert this to a plain string to avoid encoding issue on the
|
|
425
|
-
// mobile side (to avoid using `TextDecoder`).
|
|
426
|
-
const saltBytes = new Uint8Array(salt);
|
|
427
|
-
return String.fromCharCode(...saltBytes);
|
|
428
422
|
}, _LedgerKeyring_getPage =
|
|
429
423
|
/* PRIVATE METHODS */
|
|
430
424
|
async function _LedgerKeyring_getPage(increment) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-keyring.mjs","sourceRoot":"","sources":["../src/ledger-keyring.ts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AAK,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,uBAAA,IAAI,gEAAiB,MAArB,IAAI,EAAkB,KAAK,CAAC,CAAC;AACtC,CAAC,2EAEgB,KAAa;IAC5B,4CAA4C;IAC5C,OAAO,uBAAA,IAAI,mEAAoB,MAAxB,IAAI,CAAsB;QAC/B,CAAC,CAAC,aAAa,KAAK,OAAO;QAC3B,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AAChC,CAAC;IAGC,OAAO,IAAI,CAAC,MAAM,KAAK,kBAAkB,CAAC;AAC5C,CAAC,qEAEa,IAAY;IACxB,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC,2CAED,KAAK,iDAA0B,OAAe;IAC5C,MAAM,MAAM,GAAG,uBAAA,IAAI,0DAAW,MAAf,IAAI,CAAa,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,GAAG,MAAM,6CAA6C,OAAO,6BAA6B,CAC3F,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,cAAc,CAAC,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3E,CAAC;IAGC,OAAO,IAAI,CAAC,OAAO,CAAC;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,kBAAkB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC;AAjmBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger Ethereum app closed. Open it to unlock.');\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing transaction');\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let modifiedV = parseInt(String(payload.v), 10).toString(16);\n if (modifiedV.length < 2) {\n modifiedV = `0${modifiedV}`;\n }\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt: this.#convertSaltIfAny(domain.salt),\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let recoveryId = parseInt(String(payload.v), 10).toString(16);\n if (recoveryId.length < 2) {\n recoveryId = `0${recoveryId}`;\n }\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n #convertSaltIfAny(salt: ArrayBuffer | undefined): string | undefined {\n if (!salt) {\n return undefined;\n }\n\n // We convert this to a plain string to avoid encoding issue on the\n // mobile side (to avoid using `TextDecoder`).\n const saltBytes = new Uint8Array(salt);\n return String.fromCharCode(...saltBytes);\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ledger-keyring.mjs","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,GAAG,EAAE,wBAAwB;AACtC,OAAO,EACL,kBAAkB,EAGnB,uBAAuB;AACxB,OAAO,EAAE,eAAe,EAAE,yBAAyB;AAEnD,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACf,+BAA+B;AAEhC,OAAO,EACL,KAAK,EACL,UAAU,EACV,kBAAkB,EAElB,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,MAAK,cAAc;;AAK1B,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,YAAY,GAAG,GAAG,QAAQ,aAAa,CAAC;AAC9C,MAAM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W,MAAf,IAAI,CAAa,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,GAAG,MAAM,6CAA6C,OAAO,6BAA6B,CAC3F,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,cAAc,CAAC,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3E,CAAC;IAGC,OAAO,IAAI,CAAC,OAAO,CAAC;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,kBAAkB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC;AAzlBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger Ethereum app closed. Open it to unlock.');\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing transaction');\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let modifiedV = parseInt(String(payload.v), 10).toString(16);\n if (modifiedV.length < 2) {\n modifiedV = `0${modifiedV}`;\n }\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt:\n domain.salt instanceof ArrayBuffer\n ? Buffer.from(domain.salt).toString('hex')\n : domain.salt,\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error) {\n throw error instanceof Error\n ? error\n : new Error('Ledger: Unknown error while signing message');\n }\n\n let recoveryId = parseInt(String(payload.v), 10).toString(16);\n if (recoveryId.length < 2) {\n recoveryId = `0${recoveryId}`;\n }\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n}\n"]}
|