@onekeyfe/extension-bridge-hosted 0.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # @onekeyfe/extension-bridge-hosted
@@ -0,0 +1,14 @@
1
+ /// <reference types="chrome" />
2
+ import { IInjectedProviderNamesStrings, IJsBridgeConfig, IJsBridgeMessagePayload } from '@onekeyfe/cross-inpage-provider-types';
3
+ import { JsBridgeBase } from '@onekeyfe/cross-inpage-provider-core';
4
+ declare class JsBridgeExtBackground extends JsBridgeBase {
5
+ constructor(config: IJsBridgeConfig);
6
+ sendAsString: boolean;
7
+ ports: Record<number | string, chrome.runtime.Port>;
8
+ private portIdIndex;
9
+ sendPayload(payload0: IJsBridgeMessagePayload | string): void;
10
+ setupMessagePortOnConnect(): void;
11
+ requestToAllCS(scope: IInjectedProviderNamesStrings, data: unknown): void;
12
+ requestToAllUi(data: unknown): void;
13
+ }
14
+ export { JsBridgeExtBackground };
@@ -0,0 +1,120 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import isFunction from 'lodash/isFunction';
11
+ import entries from 'lodash/entries';
12
+ import { JsBridgeBase, consts } from '@onekeyfe/cross-inpage-provider-core';
13
+ const { EXT_PORT_CS_TO_BG, EXT_PORT_UI_TO_BG } = consts;
14
+ class JsBridgeExtBackground extends JsBridgeBase {
15
+ constructor(config) {
16
+ super(config);
17
+ this.sendAsString = false;
18
+ this.ports = {};
19
+ this.portIdIndex = 1;
20
+ this.setupMessagePortOnConnect();
21
+ }
22
+ sendPayload(payload0) {
23
+ const payload = payload0;
24
+ if (!payload.remoteId) {
25
+ return;
26
+ }
27
+ const port = this.ports[payload.remoteId];
28
+ // TODO onDisconnect remove ports cache
29
+ // try catch error test
30
+ try {
31
+ port.postMessage(payload);
32
+ }
33
+ catch (err) {
34
+ const error = err;
35
+ // TODO message maybe different in browser
36
+ if (error && (error === null || error === void 0 ? void 0 : error.message) === 'Attempting to use a disconnected port object') {
37
+ console.error('onDisconnect handler');
38
+ }
39
+ throw error;
40
+ }
41
+ }
42
+ setupMessagePortOnConnect() {
43
+ // TODO removeListener
44
+ chrome.runtime.onConnect.addListener((port) => {
45
+ /* port.sender
46
+ frameId: 0
47
+ id: "nhccmkonbhjkihmkjcodcepopkjpldoa"
48
+ origin: "https://app.uniswap.org"
49
+ tab: {active: true, audible: false, autoDiscardable: true, discarded: false, favIconUrl: 'https://app.uniswap.org/favicon.png', …}
50
+ url: "https://app.uniswap.org/#/swap"
51
+ */
52
+ // content-script may be multiple
53
+ if (port.name === EXT_PORT_CS_TO_BG || port.name === EXT_PORT_UI_TO_BG) {
54
+ this.portIdIndex += 1;
55
+ const portId = this.portIdIndex;
56
+ this.ports[portId] = port;
57
+ const onMessage = (payload, port0) => {
58
+ var _a;
59
+ const origin = ((_a = port0.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
60
+ payload.remoteId = portId;
61
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
62
+ const jsBridge = this;
63
+ // TODO if EXT_PORT_CS_TO_BG ignore "internal_" prefix methods
64
+ // ignore scope=walletPrivate
65
+ // - receive
66
+ jsBridge.receive(payload, {
67
+ origin,
68
+ // only trust message from UI, but NOT from content-script(dapp)
69
+ internal: port.name === EXT_PORT_UI_TO_BG,
70
+ });
71
+ };
72
+ // #### content-script -> background
73
+ port.onMessage.addListener(onMessage);
74
+ // TODO onDisconnect remove ports cache
75
+ const onDisconnect = () => {
76
+ delete this.ports[portId];
77
+ port.onMessage.removeListener(onMessage);
78
+ port.onDisconnect.removeListener(onDisconnect);
79
+ };
80
+ port.onDisconnect.addListener(onDisconnect);
81
+ }
82
+ });
83
+ }
84
+ requestToAllCS(scope, data) {
85
+ // TODO optimize rename: broadcastRequest
86
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
87
+ entries(this.ports).forEach(([portId, port]) => __awaiter(this, void 0, void 0, function* () {
88
+ var _a;
89
+ if (port.name === EXT_PORT_CS_TO_BG) {
90
+ const origin = ((_a = port === null || port === void 0 ? void 0 : port.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
91
+ if (isFunction(data)) {
92
+ // eslint-disable-next-line no-param-reassign
93
+ data = yield data({ origin });
94
+ }
95
+ console.log(`notify to content-script port: ${portId}`, data);
96
+ // TODO check ports disconnected
97
+ this.requestSync({
98
+ data,
99
+ scope,
100
+ remoteId: portId,
101
+ });
102
+ }
103
+ void 0;
104
+ }));
105
+ }
106
+ requestToAllUi(data) {
107
+ // TODO optimize
108
+ entries(this.ports).forEach(([portId, port]) => {
109
+ if (port.name === EXT_PORT_UI_TO_BG) {
110
+ console.log(`notify to ui port: ${portId}`);
111
+ // TODO check ports disconnected
112
+ this.requestSync({
113
+ data,
114
+ remoteId: portId,
115
+ });
116
+ }
117
+ });
118
+ }
119
+ }
120
+ export { JsBridgeExtBackground };
@@ -0,0 +1,15 @@
1
+ /// <reference types="chrome" />
2
+ import { IJsBridgeConfig, IJsBridgeMessagePayload } from '@onekeyfe/cross-inpage-provider-types';
3
+ import { JsBridgeBase } from '@onekeyfe/cross-inpage-provider-core';
4
+ export declare type IJsBridgeExtUiConfig = IJsBridgeConfig & {
5
+ onPortConnect: (port0: chrome.runtime.Port) => void;
6
+ };
7
+ declare class JsBridgeExtUi extends JsBridgeBase {
8
+ constructor(config: IJsBridgeExtUiConfig);
9
+ isExtUi: boolean;
10
+ sendAsString: boolean;
11
+ private portToBg;
12
+ sendPayload(payload: IJsBridgeMessagePayload | string): void;
13
+ setupMessagePortConnect(config: IJsBridgeExtUiConfig): void;
14
+ }
15
+ export { JsBridgeExtUi };
@@ -0,0 +1,47 @@
1
+ import messagePort from './extensionMessagePort';
2
+ import { JsBridgeBase, consts } from '@onekeyfe/cross-inpage-provider-core';
3
+ const { EXT_PORT_UI_TO_BG } = consts;
4
+ class JsBridgeExtUi extends JsBridgeBase {
5
+ constructor(config) {
6
+ super(config);
7
+ this.isExtUi = true;
8
+ this.sendAsString = false;
9
+ this.portToBg = null;
10
+ this.setupMessagePortConnect(config);
11
+ }
12
+ sendPayload(payload) {
13
+ if (this.portToBg) {
14
+ this.portToBg.postMessage(payload);
15
+ }
16
+ }
17
+ setupMessagePortConnect(config) {
18
+ messagePort.connect({
19
+ name: EXT_PORT_UI_TO_BG,
20
+ // #### background -> ui
21
+ onMessage: (payload, port0) => {
22
+ var _a;
23
+ let origin = ((_a = port0.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
24
+ // in ext ui, port.sender?.origin is always empty,
25
+ // so we trust remote (background) origin
26
+ origin = origin || payload.origin || '';
27
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
28
+ const jsBridge = this;
29
+ jsBridge.receive(payload, {
30
+ origin,
31
+ // trust message from background
32
+ internal: port0.name === EXT_PORT_UI_TO_BG,
33
+ });
34
+ },
35
+ onConnect: (port) => {
36
+ this.portToBg = port;
37
+ setTimeout(() => {
38
+ config.onPortConnect(port);
39
+ }, 0);
40
+ return () => {
41
+ this.portToBg = null;
42
+ };
43
+ },
44
+ });
45
+ }
46
+ }
47
+ export { JsBridgeExtUi };
@@ -0,0 +1,10 @@
1
+ import { IJsBridgeMessagePayload } from '@onekeyfe/cross-inpage-provider-types';
2
+ import { JsBridgeBase } from '@onekeyfe/cross-inpage-provider-core';
3
+ declare class JsBridgeSimple extends JsBridgeBase {
4
+ sendAsString: boolean;
5
+ isInjected: boolean;
6
+ private remote;
7
+ sendPayload(payload: IJsBridgeMessagePayload | string): void;
8
+ setRemote(remote: JsBridgeBase): void;
9
+ }
10
+ export { JsBridgeSimple };
@@ -0,0 +1,19 @@
1
+ import { JsBridgeBase } from '@onekeyfe/cross-inpage-provider-core';
2
+ class JsBridgeSimple extends JsBridgeBase {
3
+ constructor() {
4
+ super(...arguments);
5
+ this.sendAsString = true;
6
+ this.isInjected = true;
7
+ this.remote = null;
8
+ }
9
+ sendPayload(payload) {
10
+ if (!this.remote) {
11
+ throw new Error('JsBridgeSimple ERROR: remote not set.');
12
+ }
13
+ this.remote.receive(payload);
14
+ }
15
+ setRemote(remote) {
16
+ this.remote = remote;
17
+ }
18
+ }
19
+ export { JsBridgeSimple };
@@ -0,0 +1,9 @@
1
+ import { JsBridgeExtBackground } from '../JsBridgeExtBackground';
2
+ import { IJsBridgeReceiveHandler } from '@onekeyfe/cross-inpage-provider-types';
3
+ declare function createHostBridge({ receiveHandler }: {
4
+ receiveHandler: IJsBridgeReceiveHandler;
5
+ }): JsBridgeExtBackground;
6
+ declare const _default: {
7
+ createHostBridge: typeof createHostBridge;
8
+ };
9
+ export default _default;
@@ -0,0 +1,10 @@
1
+ import { JsBridgeExtBackground } from '../JsBridgeExtBackground';
2
+ function createHostBridge({ receiveHandler }) {
3
+ const bridge = new JsBridgeExtBackground({
4
+ receiveHandler,
5
+ });
6
+ return bridge;
7
+ }
8
+ export default {
9
+ createHostBridge,
10
+ };
@@ -0,0 +1,7 @@
1
+ declare function inject(filename: string): void;
2
+ declare function setupMessagePort(): void;
3
+ declare const _default: {
4
+ inject: typeof inject;
5
+ setupMessagePort: typeof setupMessagePort;
6
+ };
7
+ export default _default;
@@ -0,0 +1,68 @@
1
+ import { consts, isLegacyExtMessage, debugLogger, injectedFactory } from '@onekeyfe/cross-inpage-provider-core';
2
+ import messagePort from '../extensionMessagePort';
3
+ const { EXT_PORT_CS_TO_BG, JS_BRIDGE_MESSAGE_DIRECTION, JS_BRIDGE_MESSAGE_EXT_CHANNEL } = consts;
4
+ // TODO one-time only
5
+ function inject(filename) {
6
+ // Manifest V2 Only
7
+ /*
8
+ injectedFactory.injectCodeWithScriptTag({
9
+ code: injectedExtension as string,
10
+ });
11
+ */
12
+ // Manifest V3 & V2
13
+ injectedFactory.injectCodeWithScriptTag({
14
+ file: chrome.runtime.getURL(filename),
15
+ remove: true,
16
+ });
17
+ }
18
+ // TODO one-time only
19
+ function setupMessagePort() {
20
+ messagePort.connect({
21
+ name: EXT_PORT_CS_TO_BG,
22
+ // #### background -> content-script
23
+ onMessage(payload) {
24
+ // ignore legacy Ext publicConfig message
25
+ if (isLegacyExtMessage(payload)) {
26
+ return;
27
+ }
28
+ // #### content-script -> injected
29
+ window.postMessage({
30
+ channel: JS_BRIDGE_MESSAGE_EXT_CHANNEL,
31
+ direction: JS_BRIDGE_MESSAGE_DIRECTION.HOST_TO_INPAGE,
32
+ payload,
33
+ });
34
+ },
35
+ onConnect(port) {
36
+ // #### injected -> content-script
37
+ const onWindowPostMessage = (event) => {
38
+ // We only accept messages from ourselves
39
+ if (event.source !== window) {
40
+ return;
41
+ }
42
+ const eventData = event.data;
43
+ // only accept extension messages
44
+ if (eventData.channel === JS_BRIDGE_MESSAGE_EXT_CHANNEL &&
45
+ eventData.direction === JS_BRIDGE_MESSAGE_DIRECTION.INPAGE_TO_HOST) {
46
+ debugLogger.extContentScripts('onWindowPostMessage', event.data);
47
+ // #### content-script -> background
48
+ port.postMessage(eventData.payload);
49
+ }
50
+ };
51
+ window.addEventListener('message', onWindowPostMessage, false);
52
+ return () => {
53
+ window.removeEventListener('message', onWindowPostMessage, false);
54
+ };
55
+ },
56
+ });
57
+ }
58
+ // -> inpage -> dapp injected jsBridge -> bridge.request()
59
+ // -> window.postMessage
60
+ // -> contentScript -> on message -> chrome.runtime.connect port
61
+ // -> port.postMessage
62
+ // -> background -> createJsBridgeHost -> chrome.runtime.onConnect.addListener -> bridge.receive()
63
+ // -> port.postMessage
64
+ // -> ui -> createJsBridgeInpage -> chrome.runtime.connect port -> bridge.receive()
65
+ export default {
66
+ inject,
67
+ setupMessagePort,
68
+ };
@@ -0,0 +1,14 @@
1
+ export declare const bridgeSetup: {
2
+ contentScript: {
3
+ inject: (filename: string) => void;
4
+ setupMessagePort: () => void;
5
+ };
6
+ ui: {
7
+ createUiJsBridge: (config: import("..").IJsBridgeExtUiConfig) => import("../JsBridgeExtUi").JsBridgeExtUi;
8
+ };
9
+ background: {
10
+ createHostBridge: ({ receiveHandler }: {
11
+ receiveHandler: import("@onekeyfe/cross-inpage-provider-types").IJsBridgeReceiveHandler;
12
+ }) => import("../JsBridgeExtBackground").JsBridgeExtBackground;
13
+ };
14
+ };
@@ -0,0 +1,8 @@
1
+ import background from './background';
2
+ import ui from './ui';
3
+ import contentScript from './contentScript';
4
+ export const bridgeSetup = {
5
+ contentScript,
6
+ ui,
7
+ background,
8
+ };
@@ -0,0 +1,6 @@
1
+ import { JsBridgeExtUi, IJsBridgeExtUiConfig } from '../JsBridgeExtUi';
2
+ declare function createUiJsBridge(config: IJsBridgeExtUiConfig): JsBridgeExtUi;
3
+ declare const _default: {
4
+ createUiJsBridge: typeof createUiJsBridge;
5
+ };
6
+ export default _default;
@@ -0,0 +1,9 @@
1
+ // like injected + contentScript
2
+ import { JsBridgeExtUi } from '../JsBridgeExtUi';
3
+ function createUiJsBridge(config) {
4
+ const bridge = new JsBridgeExtUi(config);
5
+ return bridge;
6
+ }
7
+ export default {
8
+ createUiJsBridge,
9
+ };
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.JsBridgeExtBackground = void 0;
16
+ const isFunction_1 = __importDefault(require("lodash/isFunction"));
17
+ const entries_1 = __importDefault(require("lodash/entries"));
18
+ const cross_inpage_provider_core_1 = require("@onekeyfe/cross-inpage-provider-core");
19
+ const { EXT_PORT_CS_TO_BG, EXT_PORT_UI_TO_BG } = cross_inpage_provider_core_1.consts;
20
+ class JsBridgeExtBackground extends cross_inpage_provider_core_1.JsBridgeBase {
21
+ constructor(config) {
22
+ super(config);
23
+ this.sendAsString = false;
24
+ this.ports = {};
25
+ this.portIdIndex = 1;
26
+ this.setupMessagePortOnConnect();
27
+ }
28
+ sendPayload(payload0) {
29
+ const payload = payload0;
30
+ if (!payload.remoteId) {
31
+ return;
32
+ }
33
+ const port = this.ports[payload.remoteId];
34
+ // TODO onDisconnect remove ports cache
35
+ // try catch error test
36
+ try {
37
+ port.postMessage(payload);
38
+ }
39
+ catch (err) {
40
+ const error = err;
41
+ // TODO message maybe different in browser
42
+ if (error && (error === null || error === void 0 ? void 0 : error.message) === 'Attempting to use a disconnected port object') {
43
+ console.error('onDisconnect handler');
44
+ }
45
+ throw error;
46
+ }
47
+ }
48
+ setupMessagePortOnConnect() {
49
+ // TODO removeListener
50
+ chrome.runtime.onConnect.addListener((port) => {
51
+ /* port.sender
52
+ frameId: 0
53
+ id: "nhccmkonbhjkihmkjcodcepopkjpldoa"
54
+ origin: "https://app.uniswap.org"
55
+ tab: {active: true, audible: false, autoDiscardable: true, discarded: false, favIconUrl: 'https://app.uniswap.org/favicon.png', …}
56
+ url: "https://app.uniswap.org/#/swap"
57
+ */
58
+ // content-script may be multiple
59
+ if (port.name === EXT_PORT_CS_TO_BG || port.name === EXT_PORT_UI_TO_BG) {
60
+ this.portIdIndex += 1;
61
+ const portId = this.portIdIndex;
62
+ this.ports[portId] = port;
63
+ const onMessage = (payload, port0) => {
64
+ var _a;
65
+ const origin = ((_a = port0.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
66
+ payload.remoteId = portId;
67
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
68
+ const jsBridge = this;
69
+ // TODO if EXT_PORT_CS_TO_BG ignore "internal_" prefix methods
70
+ // ignore scope=walletPrivate
71
+ // - receive
72
+ jsBridge.receive(payload, {
73
+ origin,
74
+ // only trust message from UI, but NOT from content-script(dapp)
75
+ internal: port.name === EXT_PORT_UI_TO_BG,
76
+ });
77
+ };
78
+ // #### content-script -> background
79
+ port.onMessage.addListener(onMessage);
80
+ // TODO onDisconnect remove ports cache
81
+ const onDisconnect = () => {
82
+ delete this.ports[portId];
83
+ port.onMessage.removeListener(onMessage);
84
+ port.onDisconnect.removeListener(onDisconnect);
85
+ };
86
+ port.onDisconnect.addListener(onDisconnect);
87
+ }
88
+ });
89
+ }
90
+ requestToAllCS(scope, data) {
91
+ // TODO optimize rename: broadcastRequest
92
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
93
+ (0, entries_1.default)(this.ports).forEach(([portId, port]) => __awaiter(this, void 0, void 0, function* () {
94
+ var _a;
95
+ if (port.name === EXT_PORT_CS_TO_BG) {
96
+ const origin = ((_a = port === null || port === void 0 ? void 0 : port.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
97
+ if ((0, isFunction_1.default)(data)) {
98
+ // eslint-disable-next-line no-param-reassign
99
+ data = yield data({ origin });
100
+ }
101
+ console.log(`notify to content-script port: ${portId}`, data);
102
+ // TODO check ports disconnected
103
+ this.requestSync({
104
+ data,
105
+ scope,
106
+ remoteId: portId,
107
+ });
108
+ }
109
+ void 0;
110
+ }));
111
+ }
112
+ requestToAllUi(data) {
113
+ // TODO optimize
114
+ (0, entries_1.default)(this.ports).forEach(([portId, port]) => {
115
+ if (port.name === EXT_PORT_UI_TO_BG) {
116
+ console.log(`notify to ui port: ${portId}`);
117
+ // TODO check ports disconnected
118
+ this.requestSync({
119
+ data,
120
+ remoteId: portId,
121
+ });
122
+ }
123
+ });
124
+ }
125
+ }
126
+ exports.JsBridgeExtBackground = JsBridgeExtBackground;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.JsBridgeExtUi = void 0;
7
+ const extensionMessagePort_1 = __importDefault(require("./extensionMessagePort"));
8
+ const cross_inpage_provider_core_1 = require("@onekeyfe/cross-inpage-provider-core");
9
+ const { EXT_PORT_UI_TO_BG } = cross_inpage_provider_core_1.consts;
10
+ class JsBridgeExtUi extends cross_inpage_provider_core_1.JsBridgeBase {
11
+ constructor(config) {
12
+ super(config);
13
+ this.isExtUi = true;
14
+ this.sendAsString = false;
15
+ this.portToBg = null;
16
+ this.setupMessagePortConnect(config);
17
+ }
18
+ sendPayload(payload) {
19
+ if (this.portToBg) {
20
+ this.portToBg.postMessage(payload);
21
+ }
22
+ }
23
+ setupMessagePortConnect(config) {
24
+ extensionMessagePort_1.default.connect({
25
+ name: EXT_PORT_UI_TO_BG,
26
+ // #### background -> ui
27
+ onMessage: (payload, port0) => {
28
+ var _a;
29
+ let origin = ((_a = port0.sender) === null || _a === void 0 ? void 0 : _a.origin) || '';
30
+ // in ext ui, port.sender?.origin is always empty,
31
+ // so we trust remote (background) origin
32
+ origin = origin || payload.origin || '';
33
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
34
+ const jsBridge = this;
35
+ jsBridge.receive(payload, {
36
+ origin,
37
+ // trust message from background
38
+ internal: port0.name === EXT_PORT_UI_TO_BG,
39
+ });
40
+ },
41
+ onConnect: (port) => {
42
+ this.portToBg = port;
43
+ setTimeout(() => {
44
+ config.onPortConnect(port);
45
+ }, 0);
46
+ return () => {
47
+ this.portToBg = null;
48
+ };
49
+ },
50
+ });
51
+ }
52
+ }
53
+ exports.JsBridgeExtUi = JsBridgeExtUi;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JsBridgeSimple = void 0;
4
+ const cross_inpage_provider_core_1 = require("@onekeyfe/cross-inpage-provider-core");
5
+ class JsBridgeSimple extends cross_inpage_provider_core_1.JsBridgeBase {
6
+ constructor() {
7
+ super(...arguments);
8
+ this.sendAsString = true;
9
+ this.isInjected = true;
10
+ this.remote = null;
11
+ }
12
+ sendPayload(payload) {
13
+ if (!this.remote) {
14
+ throw new Error('JsBridgeSimple ERROR: remote not set.');
15
+ }
16
+ this.remote.receive(payload);
17
+ }
18
+ setRemote(remote) {
19
+ this.remote = remote;
20
+ }
21
+ }
22
+ exports.JsBridgeSimple = JsBridgeSimple;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const JsBridgeExtBackground_1 = require("../JsBridgeExtBackground");
4
+ function createHostBridge({ receiveHandler }) {
5
+ const bridge = new JsBridgeExtBackground_1.JsBridgeExtBackground({
6
+ receiveHandler,
7
+ });
8
+ return bridge;
9
+ }
10
+ exports.default = {
11
+ createHostBridge,
12
+ };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cross_inpage_provider_core_1 = require("@onekeyfe/cross-inpage-provider-core");
7
+ const extensionMessagePort_1 = __importDefault(require("../extensionMessagePort"));
8
+ const { EXT_PORT_CS_TO_BG, JS_BRIDGE_MESSAGE_DIRECTION, JS_BRIDGE_MESSAGE_EXT_CHANNEL } = cross_inpage_provider_core_1.consts;
9
+ // TODO one-time only
10
+ function inject(filename) {
11
+ // Manifest V2 Only
12
+ /*
13
+ injectedFactory.injectCodeWithScriptTag({
14
+ code: injectedExtension as string,
15
+ });
16
+ */
17
+ // Manifest V3 & V2
18
+ cross_inpage_provider_core_1.injectedFactory.injectCodeWithScriptTag({
19
+ file: chrome.runtime.getURL(filename),
20
+ remove: true,
21
+ });
22
+ }
23
+ // TODO one-time only
24
+ function setupMessagePort() {
25
+ extensionMessagePort_1.default.connect({
26
+ name: EXT_PORT_CS_TO_BG,
27
+ // #### background -> content-script
28
+ onMessage(payload) {
29
+ // ignore legacy Ext publicConfig message
30
+ if ((0, cross_inpage_provider_core_1.isLegacyExtMessage)(payload)) {
31
+ return;
32
+ }
33
+ // #### content-script -> injected
34
+ window.postMessage({
35
+ channel: JS_BRIDGE_MESSAGE_EXT_CHANNEL,
36
+ direction: JS_BRIDGE_MESSAGE_DIRECTION.HOST_TO_INPAGE,
37
+ payload,
38
+ });
39
+ },
40
+ onConnect(port) {
41
+ // #### injected -> content-script
42
+ const onWindowPostMessage = (event) => {
43
+ // We only accept messages from ourselves
44
+ if (event.source !== window) {
45
+ return;
46
+ }
47
+ const eventData = event.data;
48
+ // only accept extension messages
49
+ if (eventData.channel === JS_BRIDGE_MESSAGE_EXT_CHANNEL &&
50
+ eventData.direction === JS_BRIDGE_MESSAGE_DIRECTION.INPAGE_TO_HOST) {
51
+ cross_inpage_provider_core_1.debugLogger.extContentScripts('onWindowPostMessage', event.data);
52
+ // #### content-script -> background
53
+ port.postMessage(eventData.payload);
54
+ }
55
+ };
56
+ window.addEventListener('message', onWindowPostMessage, false);
57
+ return () => {
58
+ window.removeEventListener('message', onWindowPostMessage, false);
59
+ };
60
+ },
61
+ });
62
+ }
63
+ // -> inpage -> dapp injected jsBridge -> bridge.request()
64
+ // -> window.postMessage
65
+ // -> contentScript -> on message -> chrome.runtime.connect port
66
+ // -> port.postMessage
67
+ // -> background -> createJsBridgeHost -> chrome.runtime.onConnect.addListener -> bridge.receive()
68
+ // -> port.postMessage
69
+ // -> ui -> createJsBridgeInpage -> chrome.runtime.connect port -> bridge.receive()
70
+ exports.default = {
71
+ inject,
72
+ setupMessagePort,
73
+ };
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.bridgeSetup = void 0;
7
+ const background_1 = __importDefault(require("./background"));
8
+ const ui_1 = __importDefault(require("./ui"));
9
+ const contentScript_1 = __importDefault(require("./contentScript"));
10
+ exports.bridgeSetup = {
11
+ contentScript: contentScript_1.default,
12
+ ui: ui_1.default,
13
+ background: background_1.default,
14
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ // like injected + contentScript
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const JsBridgeExtUi_1 = require("../JsBridgeExtUi");
5
+ function createUiJsBridge(config) {
6
+ const bridge = new JsBridgeExtUi_1.JsBridgeExtUi(config);
7
+ return bridge;
8
+ }
9
+ exports.default = {
10
+ createUiJsBridge,
11
+ };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function connect({ reconnect = false, name, onMessage, onConnect, }) {
4
+ // eslint-disable-next-line no-useless-catch
5
+ try {
6
+ if (reconnect) {
7
+ // noop
8
+ }
9
+ const port = chrome.runtime.connect({
10
+ includeTlsChannelId: true,
11
+ name,
12
+ });
13
+ if (chrome.runtime.lastError) {
14
+ // NOT Working for port connect error
15
+ }
16
+ port.onMessage.addListener(onMessage);
17
+ let cleanup;
18
+ const onDisconnect = () => {
19
+ // TODO re-connect to background
20
+ port.onMessage.removeListener(onMessage);
21
+ port.onDisconnect.removeListener(onDisconnect);
22
+ if (cleanup) {
23
+ cleanup();
24
+ }
25
+ };
26
+ port.onDisconnect.addListener(onDisconnect);
27
+ if (onConnect) {
28
+ cleanup = onConnect(port);
29
+ }
30
+ return port;
31
+ }
32
+ catch (error) {
33
+ // NOT Working for port connect error
34
+ throw error;
35
+ }
36
+ }
37
+ exports.default = {
38
+ connect,
39
+ };
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.extensionMessagePort = void 0;
17
+ __exportStar(require("./bridgeSetup"), exports);
18
+ __exportStar(require("./JsBridgeExtBackground"), exports);
19
+ __exportStar(require("./JsBridgeExtUi"), exports);
20
+ __exportStar(require("./JsBridgeSimple"), exports);
21
+ const extensionMessagePort_1 = __importDefault(require("./extensionMessagePort"));
22
+ exports.extensionMessagePort = extensionMessagePort_1.default;
@@ -0,0 +1,11 @@
1
+ /// <reference types="chrome" />
2
+ declare function connect({ reconnect, name, onMessage, onConnect, }: {
3
+ reconnect?: boolean;
4
+ name: string;
5
+ onMessage: (payload: any, port: chrome.runtime.Port) => void;
6
+ onConnect: (port: chrome.runtime.Port) => () => void;
7
+ }): chrome.runtime.Port;
8
+ declare const _default: {
9
+ connect: typeof connect;
10
+ };
11
+ export default _default;
@@ -0,0 +1,37 @@
1
+ function connect({ reconnect = false, name, onMessage, onConnect, }) {
2
+ // eslint-disable-next-line no-useless-catch
3
+ try {
4
+ if (reconnect) {
5
+ // noop
6
+ }
7
+ const port = chrome.runtime.connect({
8
+ includeTlsChannelId: true,
9
+ name,
10
+ });
11
+ if (chrome.runtime.lastError) {
12
+ // NOT Working for port connect error
13
+ }
14
+ port.onMessage.addListener(onMessage);
15
+ let cleanup;
16
+ const onDisconnect = () => {
17
+ // TODO re-connect to background
18
+ port.onMessage.removeListener(onMessage);
19
+ port.onDisconnect.removeListener(onDisconnect);
20
+ if (cleanup) {
21
+ cleanup();
22
+ }
23
+ };
24
+ port.onDisconnect.addListener(onDisconnect);
25
+ if (onConnect) {
26
+ cleanup = onConnect(port);
27
+ }
28
+ return port;
29
+ }
30
+ catch (error) {
31
+ // NOT Working for port connect error
32
+ throw error;
33
+ }
34
+ }
35
+ export default {
36
+ connect,
37
+ };
@@ -0,0 +1,6 @@
1
+ export * from './bridgeSetup';
2
+ export * from './JsBridgeExtBackground';
3
+ export * from './JsBridgeExtUi';
4
+ export * from './JsBridgeSimple';
5
+ import extensionMessagePort from './extensionMessagePort';
6
+ export { extensionMessagePort };
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './bridgeSetup';
2
+ export * from './JsBridgeExtBackground';
3
+ export * from './JsBridgeExtUi';
4
+ export * from './JsBridgeSimple';
5
+ import extensionMessagePort from './extensionMessagePort';
6
+ export { extensionMessagePort };
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@onekeyfe/extension-bridge-hosted",
3
+ "version": "0.0.1",
4
+ "keywords": [
5
+ "cross-inpage-provider"
6
+ ],
7
+ "author": "dev-fe@onekey.so",
8
+ "repository": "https://github.com/OneKeyHQ/cross-inpage-provider",
9
+ "license": "Apache-2.0",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "type": "module",
14
+ "files": [
15
+ "dist/*"
16
+ ],
17
+ "exports": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/cjs/index.js"
21
+ },
22
+ "types": "./dist/index.d.ts",
23
+ "module": "dist/index.js",
24
+ "main": "dist/cjs/index.js",
25
+ "scripts": {
26
+ "prebuild": "rm -rf dist",
27
+ "build": "tsc && tsc --project tsconfig.cjs.json",
28
+ "start": "tsc --watch"
29
+ },
30
+ "dependencies": {
31
+ "@onekeyfe/cross-inpage-provider-core": "^0.0.1",
32
+ "@onekeyfe/cross-inpage-provider-types": "^0.0.1"
33
+ },
34
+ "gitHead": "443a40bcb8cc29616dbbaebd6f6f025c20b7e2b5"
35
+ }