mockrtc 0.1.0

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.
Files changed (136) hide show
  1. package/.github/workflows/ci.yml +29 -0
  2. package/LICENSE +201 -0
  3. package/README.md +290 -0
  4. package/dist/admin-bin.d.ts +2 -0
  5. package/dist/admin-bin.js +67 -0
  6. package/dist/admin-bin.js.map +1 -0
  7. package/dist/client/mockrtc-client.d.ts +12 -0
  8. package/dist/client/mockrtc-client.js +67 -0
  9. package/dist/client/mockrtc-client.js.map +1 -0
  10. package/dist/client/mockrtc-remote-peer.d.ts +15 -0
  11. package/dist/client/mockrtc-remote-peer.js +246 -0
  12. package/dist/client/mockrtc-remote-peer.js.map +1 -0
  13. package/dist/control-channel.d.ts +8 -0
  14. package/dist/control-channel.js +11 -0
  15. package/dist/control-channel.js.map +1 -0
  16. package/dist/handling/handler-builder.d.ts +138 -0
  17. package/dist/handling/handler-builder.js +164 -0
  18. package/dist/handling/handler-builder.js.map +1 -0
  19. package/dist/handling/handler-step-definitions.d.ts +63 -0
  20. package/dist/handling/handler-step-definitions.js +123 -0
  21. package/dist/handling/handler-step-definitions.js.map +1 -0
  22. package/dist/handling/handler-steps.d.ts +48 -0
  23. package/dist/handling/handler-steps.js +218 -0
  24. package/dist/handling/handler-steps.js.map +1 -0
  25. package/dist/main-browser.d.ts +9 -0
  26. package/dist/main-browser.js +26 -0
  27. package/dist/main-browser.js.map +1 -0
  28. package/dist/main.d.ts +58 -0
  29. package/dist/main.js +67 -0
  30. package/dist/main.js.map +1 -0
  31. package/dist/mockrtc-admin-plugin.d.ts +56 -0
  32. package/dist/mockrtc-admin-plugin.js +151 -0
  33. package/dist/mockrtc-admin-plugin.js.map +1 -0
  34. package/dist/mockrtc-admin-server.d.ts +7 -0
  35. package/dist/mockrtc-admin-server.js +18 -0
  36. package/dist/mockrtc-admin-server.js.map +1 -0
  37. package/dist/mockrtc-client.d.ts +12 -0
  38. package/dist/mockrtc-client.js +64 -0
  39. package/dist/mockrtc-client.js.map +1 -0
  40. package/dist/mockrtc-handler-builder.d.ts +15 -0
  41. package/dist/mockrtc-handler-builder.js +24 -0
  42. package/dist/mockrtc-handler-builder.js.map +1 -0
  43. package/dist/mockrtc-peer.d.ts +147 -0
  44. package/dist/mockrtc-peer.js +7 -0
  45. package/dist/mockrtc-peer.js.map +1 -0
  46. package/dist/mockrtc-remote-peer.d.ts +15 -0
  47. package/dist/mockrtc-remote-peer.js +234 -0
  48. package/dist/mockrtc-remote-peer.js.map +1 -0
  49. package/dist/mockrtc-server-peer.d.ts +29 -0
  50. package/dist/mockrtc-server-peer.js +145 -0
  51. package/dist/mockrtc-server-peer.js.map +1 -0
  52. package/dist/mockrtc-server.d.ts +14 -0
  53. package/dist/mockrtc-server.js +53 -0
  54. package/dist/mockrtc-server.js.map +1 -0
  55. package/dist/mockrtc.d.ts +25 -0
  56. package/dist/mockrtc.js +7 -0
  57. package/dist/mockrtc.js.map +1 -0
  58. package/dist/package.json +52 -0
  59. package/dist/server/mockrtc-admin-plugin.d.ts +17 -0
  60. package/dist/server/mockrtc-admin-plugin.js +163 -0
  61. package/dist/server/mockrtc-admin-plugin.js.map +1 -0
  62. package/dist/server/mockrtc-admin-server.d.ts +7 -0
  63. package/dist/server/mockrtc-admin-server.js +18 -0
  64. package/dist/server/mockrtc-admin-server.js.map +1 -0
  65. package/dist/server/mockrtc-server-peer.d.ts +24 -0
  66. package/dist/server/mockrtc-server-peer.js +141 -0
  67. package/dist/server/mockrtc-server-peer.js.map +1 -0
  68. package/dist/server/mockrtc-server.d.ts +14 -0
  69. package/dist/server/mockrtc-server.js +53 -0
  70. package/dist/server/mockrtc-server.js.map +1 -0
  71. package/dist/src/main.d.ts +1 -0
  72. package/dist/src/main.js +24 -0
  73. package/dist/src/main.js.map +1 -0
  74. package/dist/src/mockrtc-peer.d.ts +0 -0
  75. package/dist/src/mockrtc-peer.js +2 -0
  76. package/dist/src/mockrtc-peer.js.map +1 -0
  77. package/dist/src/mockrtc.d.ts +0 -0
  78. package/dist/src/mockrtc.js +65 -0
  79. package/dist/src/mockrtc.js.map +1 -0
  80. package/dist/webrtc/control-channel.d.ts +8 -0
  81. package/dist/webrtc/control-channel.js +11 -0
  82. package/dist/webrtc/control-channel.js.map +1 -0
  83. package/dist/webrtc/datachannel-stream.d.ts +25 -0
  84. package/dist/webrtc/datachannel-stream.js +86 -0
  85. package/dist/webrtc/datachannel-stream.js.map +1 -0
  86. package/dist/webrtc/mediatrack-stream.d.ts +29 -0
  87. package/dist/webrtc/mediatrack-stream.js +109 -0
  88. package/dist/webrtc/mediatrack-stream.js.map +1 -0
  89. package/dist/webrtc/mockrtc-connection.d.ts +14 -0
  90. package/dist/webrtc/mockrtc-connection.js +147 -0
  91. package/dist/webrtc/mockrtc-connection.js.map +1 -0
  92. package/dist/webrtc/peer-connection.d.ts +16 -0
  93. package/dist/webrtc/peer-connection.js +81 -0
  94. package/dist/webrtc/peer-connection.js.map +1 -0
  95. package/dist/webrtc/rtc-connection.d.ts +47 -0
  96. package/dist/webrtc/rtc-connection.js +370 -0
  97. package/dist/webrtc/rtc-connection.js.map +1 -0
  98. package/dist/webrtc-hooks.d.ts +30 -0
  99. package/dist/webrtc-hooks.js +224 -0
  100. package/dist/webrtc-hooks.js.map +1 -0
  101. package/karma.conf.ts +89 -0
  102. package/ngi-eu-footer.png +0 -0
  103. package/package.json +86 -0
  104. package/src/admin-bin.ts +57 -0
  105. package/src/client/mockrtc-client.ts +79 -0
  106. package/src/client/mockrtc-remote-peer.ts +286 -0
  107. package/src/handling/handler-builder.ts +215 -0
  108. package/src/handling/handler-step-definitions.ts +142 -0
  109. package/src/handling/handler-steps.ts +254 -0
  110. package/src/main-browser.ts +44 -0
  111. package/src/main.ts +109 -0
  112. package/src/mockrtc-peer.ts +176 -0
  113. package/src/mockrtc.ts +36 -0
  114. package/src/server/mockrtc-admin-plugin.ts +196 -0
  115. package/src/server/mockrtc-admin-server.ts +17 -0
  116. package/src/server/mockrtc-server-peer.ts +159 -0
  117. package/src/server/mockrtc-server.ts +53 -0
  118. package/src/webrtc/control-channel.ts +13 -0
  119. package/src/webrtc/datachannel-stream.ts +102 -0
  120. package/src/webrtc/mediatrack-stream.ts +135 -0
  121. package/src/webrtc/mockrtc-connection.ts +164 -0
  122. package/src/webrtc/rtc-connection.ts +420 -0
  123. package/src/webrtc-hooks.ts +245 -0
  124. package/test/integration/close-steps.spec.ts +39 -0
  125. package/test/integration/connection-setup.spec.ts +230 -0
  126. package/test/integration/echo-steps.spec.ts +88 -0
  127. package/test/integration/proxy.spec.ts +526 -0
  128. package/test/integration/send-steps.spec.ts +76 -0
  129. package/test/integration/smoke-test.spec.ts +100 -0
  130. package/test/integration/wait-steps.spec.ts +225 -0
  131. package/test/start-test-admin-server.ts +12 -0
  132. package/test/test-setup.ts +136 -0
  133. package/test/tsconfig.json +11 -0
  134. package/tsconfig.json +14 -0
  135. package/typedoc.json +19 -0
  136. package/wallaby.js +41 -0
@@ -0,0 +1,29 @@
1
+ name: CI
2
+ on: [push, pull_request]
3
+ jobs:
4
+ build:
5
+ name: Build & test
6
+ runs-on: ubuntu-latest
7
+
8
+ strategy:
9
+ matrix:
10
+ node-version: [14.x, v14.18.3, 16.x, '*']
11
+
12
+ steps:
13
+ - uses: actions/checkout@v2
14
+
15
+ - uses: actions/setup-node@v2
16
+ with:
17
+ node-version: ${{ matrix.node-version }}
18
+
19
+ - run: npm install --no-package-lock
20
+ - run: npm run build
21
+ - run: npm test
22
+
23
+ - name: Deploy docs
24
+ if: github.ref == 'refs/heads/main' && matrix.node-version == 'v14.18.3'
25
+ uses: JamesIves/github-pages-deploy-action@v4.2.2
26
+ with:
27
+ single-commit: true
28
+ branch: gh-pages
29
+ folder: typedoc
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,290 @@
1
+ # MockRTC [![Build Status](https://github.com/httptoolkit/mockrtc/workflows/CI/badge.svg)](https://github.com/httptoolkit/mockrtc/actions) [![Available on NPM](https://img.shields.io/npm/v/mockrtc.svg)](https://npmjs.com/package/mockrtc)
2
+
3
+ > _Part of [HTTP Toolkit](https://httptoolkit.tech): powerful tools for building, testing & debugging HTTP(S), WebSockets and WebRTC_
4
+
5
+ MockRTC lets you intercept, assert on and mock WebRTC peers. This makes it possible to:
6
+
7
+ * Build automated tests for WebRTC traffic.
8
+ * Simulate WebRTC errors in a reliable reproducible way.
9
+ * Capture and inspect traffic between real WebRTC peers for debugging.
10
+ * Create WebRTC proxy peers to automate message transformation, monitoring or logging.
11
+
12
+ ---
13
+
14
+ :warning: _MockRTC is still new & rapidly developing!_ :warning:
15
+
16
+ _Everything described here works today, but there's lots more to come, and some advanced WebRTC use cases may run into rough edges. If you hit any problems or missing features, please [open an issue](https://github.com/httptoolkit/mockrtc/issues/new)._
17
+
18
+ ---
19
+
20
+ ## Example
21
+
22
+ Let's write an automated test with MockRTC. To test WebRTC-based code, you will typically need to:
23
+
24
+ * Start a MockRTC mock session
25
+ * Define rules that match and mock the traffic you're interested in
26
+ * Create a WebRTC connection to a mock peer, by either:
27
+ * Using MockRTC's offer or answer directly.
28
+ * Applying the provided `MockRTC.hookWebRTCConnection` hook function to your RTC connection, and then connecting to any other real peer as normal.
29
+ * Call the provided `MockRTC.hookAllWebRTC` global hook function before creating your connection(s), to hook all WebRTC connections automatically.
30
+
31
+ A simple example of that, running as a test in a browser with the built-in WebRTC APIs, and using a mock answer explicitly, looks like this:
32
+
33
+ ```typescript
34
+ import * as MockRTC from 'mockrtc'
35
+ const mockRTC = MockRTC.getRemote({ recordMessages: true });
36
+
37
+ describe("MockRTC", () => {
38
+
39
+ // Start & stop MockRTC between tests
40
+ beforeEach(() => mockRTC.start());
41
+ afterEach(() => mockRTC.stop());
42
+
43
+ it("lets you mock behaviour and assert on RTC interactions", async () => {
44
+ // Create a mock peer who sends 'Goodbye' after receiving its first message.
45
+ const mockPeer = await mockRTC
46
+ .buildPeer()
47
+ .waitForNextMessage()
48
+ .thenSend('Goodbye');
49
+
50
+ // Create a real WebRTC connection and data channel:
51
+ const localConnection = new RTCPeerConnection();
52
+ const dataChannel = localConnection.createDataChannel("dataChannel");
53
+
54
+ const localOffer = await localConnection.createOffer();
55
+ await localConnection.setLocalDescription(localOffer);
56
+
57
+ // Get a mock answer to connect to our mock peer:
58
+ const { answer } = await mockPeer.answerOffer(localOffer);
59
+ await localConnection.setRemoteDescription(answer);
60
+
61
+ // Once the connection is open, message the peer
62
+ dataChannel.onopen = () => {
63
+ dataChannel.send('Hello');
64
+ };
65
+
66
+ // Wait for a response:
67
+ const message = await new Promise((resolve) => {
68
+ dataChannel.addEventListener('message', (event) => resolve(event.data));
69
+ });
70
+ expect(message).to.equal('Goodbye'); // <-- We get our mock response!
71
+
72
+ // Assert on the messages the mock peer received:
73
+ expect(await mockPeer.getAllMessages()).to.deep.equal(['Hello']);
74
+ });
75
+ });
76
+ ```
77
+
78
+ ## Documentation
79
+
80
+ ### Set up guide
81
+
82
+ First, install MockRTC:
83
+
84
+ ```bash
85
+ npm install --save-dev mockrtc
86
+ ```
87
+
88
+ MockRTC can be controlled both from Node.js and from inside a browser, with the same mocking API available in both environments.
89
+
90
+ For automated testing, you'll generally want to run it inside a browser. To do this, you need two things:
91
+
92
+ * A MockRTC admin server, running in Node.js (v14.17.0+).
93
+ * A MockRTC client, running in the browser, which you can use to define your mock behaviour and query the mock peer's data.
94
+
95
+ For non-browser usage, you can just use `MockRTC.getLocal()` by itself to get a MockRTC instance, and ignore the admin server completely.
96
+
97
+ #### MockRTC Admin Server
98
+
99
+ The easiest way to launch an admin server for browser or remote-control usage is using the included command-line helper, like so:
100
+
101
+ ```
102
+ mockrtc -c <test command>
103
+ ```
104
+
105
+ This will start an admin server, run your test command, and then stop the admin server when it finishes.
106
+
107
+ You can also do this programmatically like so:
108
+
109
+ ```javascript
110
+ import * as MockRTC from 'mockrtc';
111
+
112
+ const adminServer = MockRTC.getAdminServer();
113
+ adminServer.start().then(() =>
114
+ console.log('Admin server started')
115
+ );
116
+ ```
117
+
118
+ #### MockRTC Browser Setup
119
+
120
+ Then from inside the browser you just need to call `MockRTC.getRemote()` to get a MockRTC instance:
121
+
122
+ ```javascript
123
+ import * as MockRTC from 'mockrtc';
124
+
125
+ const mockRTC = MockRTC.getRemote();
126
+
127
+ // Call .start() & .stop() between tests
128
+ // call .buildPeer()... to configure a peer for each test.
129
+ ```
130
+
131
+ Note that as this is a universal library (it works in Node.js & browsers) this code does reference some Node.js modules & globals in a couple of places. In many bundlers this will be handled automatically, but if it's not you may need to enable node polyfills for this. In Webpack that usually means enabling [node-polyfill-webpack-plugin](https://www.npmjs.com/package/node-polyfill-webpack-plugin), or in ESBuild you'll want the [`@esbuild-plugins/node-modules-polyfill`](https://www.npmjs.com/package/@esbuild-plugins/node-modules-polyfill) and [`@esbuild-plugins/node-globals-polyfill`](https://www.npmjs.com/package/@esbuild-plugins/node-globals-polyfill) plugins.
132
+
133
+ #### MockRTC Non-Browser Setup
134
+
135
+ You can also use MockRTC outside the browser: either to configure and manage test peers from a Node.js process and connect using a signalling channel, or to build non-test MockRTC debugging or proxy tools.
136
+
137
+ When doing so, you can skip the admin server entirely, and use MockRTC like so:
138
+
139
+ ```javascript
140
+ import * as MockRTC from 'mockrtc';
141
+
142
+ const mockRTC = MockRTC.getLocal();
143
+
144
+ // Use exactly the same API to configure behaviour and get signalling info
145
+ // as in the browser getRemote() case.
146
+ ```
147
+
148
+ ### Mocking WebRTC Traffic
149
+
150
+ MockRTC provides APIs to define mock peers. Each peer has associated behaviour, defined as a series of steps, and runs each step in turn for each connection it receives.
151
+
152
+ To create a peer, use the `.buildPeer()` method on a MockRTC instance, call methods to define steps, and then call a `.thenX()` method to define the final step and create the peer itself. Here's an example:
153
+
154
+ ```javascript
155
+ import * as MockRTC from 'mockrtc';
156
+
157
+ const mockRTC = MockRTC.getRemote();
158
+ mockRTC.start().then(() => {
159
+
160
+ const mockPeer = mockRTC.buildPeer()
161
+ .waitForChannel('chat-datachannel')
162
+ .sleep(100)
163
+ .send("hi there")
164
+ .thenEcho();
165
+
166
+ });
167
+ ```
168
+
169
+ For a full list of the behaviours available, see the [reference documentation](https://httptoolkit.github.io/mockrtc/interfaces/MockRTCPeerBuilder.html).
170
+
171
+ Once you have a peer configured, you can make explicit connections to it by generating an WebRTC offer, or providing a WebRTC offer yourself to get an answer. The offers & answers should be in the format of [RTCSessionDescriptions](https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescription), as normally returned by `peerConn.createOffer()` in the browser WebRTC APIs.
172
+
173
+ For example:
174
+
175
+ ```javascript
176
+ // Given a real non-mocked WebRTC browser connection:
177
+ const myConnection = new RTCPeerConnection();
178
+
179
+ // Call create offer to get an offer description for a mocked connection:
180
+ const { offer: mockOffer, setAnswer } = await mockPeer.createOffer();
181
+
182
+ myConnection.setRemoteDescription(mockOffer);
183
+ const realAnswer = await myConnection.createAnswer();
184
+ myConnection.setLocalDescription(realAnswer);
185
+
186
+ // Pass the real answer back to the callback provided by createOffer:
187
+ setAnswer(realAnswer);
188
+
189
+ // -- Alternatively, MockRTC can answer an offer: --
190
+
191
+ const realOffer = await myConnection.createOffer();
192
+ myConnection.setLocalDescription(realOffer);
193
+ const { answer } = await mockPeer.answerOffer(realOffer);
194
+ myConnection.setRemoteDescription(answer);
195
+ ```
196
+
197
+ It's also possible to renegotiate existing connections: both methods also return a `session`, which exposes a very similar API to create and answer offers on the existing connection, but applied to the existing connection so that it's renegotiated in place, continuing the existing mock step processing.
198
+
199
+ ### Proxying WebRTC Traffic
200
+
201
+ MockRTC can also act as a [MitM proxy](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) for WebRTC connections, sitting between two peers to record or modify traffic in flight.
202
+
203
+ This works by creating two connections within MockRTC: a connection from your local client to a mock peer (the same as above) and an 'external' connection to the remote peer. External connections do nothing by default, but mock connections can be connected to them to begin proxying.
204
+
205
+ That means the connection structure for a proxied connection looks like this:
206
+
207
+ ```mermaid
208
+ graph TD
209
+ i["Our own local connection (internal)"] ---
210
+ m[/"MockRTC mock peer connection (mock)"/] ---
211
+ e[/"MockRTC external connection (external)"/] ---
212
+ r["The target peer's connection (remote)"]
213
+ ```
214
+
215
+ To set this up, you need to:
216
+
217
+ * Configure your mock peer to transparently proxy traffic, by using `.thenPassThrough()` when defining the peer.
218
+ * Create a connection from your own peer (internal) to the mock peer.
219
+ * Create a connection from the external peer to the remote peer.
220
+ * Tell your mock peer which external connection to proxy you to, to create the mock + external connection.
221
+
222
+ This is a bit fiddly, so MockRTC includes functionality to take a connection and automatically hook all its methods so that this process happens automatically: `MockRTC.hookWebRTCConnection(realConnection, mockPeer)`.
223
+
224
+ That looks like this:
225
+
226
+ ```javascript
227
+ const mockPeer = await mockRTC.buildPeer()
228
+ .waitForNextMessage() // Wait for and drop the first datachannel message
229
+ .send('Injected message') // Send a message on every data channel
230
+ .thenPassThrough(); // Then proxy everything else
231
+
232
+ const localConn = new RTCPeerConnection();
233
+
234
+ // The magic:
235
+ MockRTC.hookWebRTCConnection(localConn, mockPeer);
236
+ // ^ This redirects all connA's traffic via the mock peer, no matter who it connects to.
237
+
238
+ // Normal WebRTC setup using real browser connections:
239
+ const localOffer = await localConn.createOffer();
240
+ const localDataChannel = localConn.createDataChannel("dataChannel");
241
+ localConn.setLocalDescription(localOffer);
242
+
243
+ const remoteConn = new RTCPeerConnection();
244
+ remoteConn.setRemoteDescription(localOffer);
245
+ const remoteAnswer = await remoteConn.createAnswer();
246
+ remoteConn.setLocalDescription(remoteAnswer);
247
+ localConn.setRemoteDescription(remoteAnswer);
248
+
249
+ // Once set up, send a few messages and log all received messages:
250
+ localDataChannel.onopen = () => {
251
+ channel.addEventListener('message', ({ data }) => console.log('LOCAL:', data));
252
+ localDataChannel.send('local message 1');
253
+ localDataChannel.send('local message 2');
254
+ };
255
+
256
+ remoteConn.addEventListener('datachannel', ({ channel }) => {
257
+ channel.addEventListener('message', ({ data }) => console.log('REMOTE:', data));
258
+ channel.send("remote message 1");
259
+ channel.send("remote message 2");
260
+ });
261
+ ```
262
+
263
+ The above prints:
264
+
265
+ ```
266
+ LOCAL: MockRTC injected message
267
+ REMOTE: local message 2
268
+ LOCAL: remote message 1
269
+ LOCAL: remote message 2
270
+ ```
271
+
272
+ Here you can see the local connection receives the injected message, then the mock peer drops the first message from the local connection (so "local message 1" never arrives) and then everything else is proxied like any real connection.
273
+
274
+ If you wan to do this automatically for all WebRTC connections, you can also use the `WebRTC.hookAllWebRTC(mockPeer)` function, which will wrap the global `RTCPeerConnection` constructor to automatically apply this hook to every WebRTC connection when it's created, to redirect _all_ traffic through the given mock peer. Note that this only applies to new WebRTC connections, so this should be called before your first WebRTC connection is created.
275
+
276
+ ### API Reference Docs
277
+
278
+ For more details, see the [MockRTC reference docs](https://httptoolkit.github.io/mockrtc/).
279
+
280
+ ---
281
+
282
+ Have more questions, issues or feature requests? [File an issue](https://github.com/httptoolkit/mockrtc/issues/new).
283
+
284
+ You might also be interested in scrolling through MockRTC's [test suite](https://github.com/httptoolkit/mockrtc/tree/main/test/integration), which provides a wide set of examples for all functionality.
285
+
286
+ ---
287
+
288
+ _This‌ ‌project‌ ‌has‌ ‌received‌ ‌funding‌ ‌from‌ ‌the‌ ‌European‌ ‌Union’s‌ ‌Horizon‌ ‌2020‌‌ research‌ ‌and‌ ‌innovation‌ ‌programme‌ ‌within‌ ‌the‌ ‌framework‌ ‌of‌ ‌the‌ ‌NGI-POINTER‌‌ Project‌ ‌funded‌ ‌under‌ ‌grant‌ ‌agreement‌ ‌No‌ 871528._
289
+
290
+ ![The NGI logo and EU flag](./ngi-eu-footer.png)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * SPDX-FileCopyrightText: 2022 Tim Perry <tim@httptoolkit.tech>
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9
+ return new (P || (P = Promise))(function (resolve, reject) {
10
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
14
+ });
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const childProcess = require("child_process");
18
+ const MockRTC = require("./main");
19
+ handleArgs(process.argv).catch((e) => {
20
+ console.error(e);
21
+ process.exit(1);
22
+ });
23
+ function handleArgs(args) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ const remainingArgs = args.slice(2);
26
+ let nextArg = remainingArgs.shift();
27
+ while (nextArg) {
28
+ if (nextArg === '-c') {
29
+ yield runCommandWithServer(remainingArgs.join(' '));
30
+ return;
31
+ }
32
+ else {
33
+ break;
34
+ }
35
+ }
36
+ console.log("Usage: mockrtc -c <test command>");
37
+ process.exit(1);
38
+ });
39
+ }
40
+ function runCommandWithServer(command) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ const server = MockRTC.getAdminServer();
43
+ yield server.start();
44
+ let realProcess = childProcess.spawn(command, [], {
45
+ shell: true,
46
+ stdio: 'inherit'
47
+ });
48
+ realProcess.on('error', (error) => {
49
+ server.stop().then(function () {
50
+ console.error(error);
51
+ process.exit(1);
52
+ });
53
+ });
54
+ realProcess.on('exit', (code, signal) => {
55
+ server.stop().then(function () {
56
+ if (code == null) {
57
+ console.error('Executed process exited due to signal: ' + signal);
58
+ process.exit(1);
59
+ }
60
+ else {
61
+ process.exit(code);
62
+ }
63
+ });
64
+ });
65
+ });
66
+ }
67
+ //# sourceMappingURL=admin-bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-bin.js","sourceRoot":"","sources":["../src/admin-bin.ts"],"names":[],"mappings":";;AACA;;;GAGG;;;;;;;;;;;AAEH,8CAA+C;AAC/C,kCAAmC;AAEnC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;IACjC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,SAAe,UAAU,CAAC,IAAc;;QACpC,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACpC,IAAI,OAAO,GAAG,aAAa,CAAC,KAAK,EAAE,CAAC;QACpC,OAAO,OAAO,EAAE;YACZ,IAAI,OAAO,KAAK,IAAI,EAAE;gBAClB,MAAM,oBAAoB,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;gBACpD,OAAO;aACV;iBAAM;gBACH,MAAM;aACT;SACJ;QAED,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;CAAA;AAED,SAAe,oBAAoB,CAAC,OAAe;;QAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QACxC,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAErB,IAAI,WAAW,GAAG,YAAY,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,EAAE;YAC9C,KAAK,EAAE,IAAI;YACX,KAAK,EAAE,SAAS;SACnB,CAAC,CAAC;QAEH,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9B,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACpB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE;YACpC,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC;gBACf,IAAI,IAAI,IAAI,IAAI,EAAE;oBACd,OAAO,CAAC,KAAK,CAAC,yCAAyC,GAAG,MAAM,CAAC,CAAC;oBAClE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;iBACnB;qBAAM;oBACH,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBACtB;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;CAAA"}
@@ -0,0 +1,12 @@
1
+ import type { PluggableAdmin } from 'mockttp';
2
+ import { MockRTC, MockRTCOptions, MockRTCPeerBuilder } from "../mockrtc";
3
+ export declare type MockRTCClientOptions = PluggableAdmin.AdminClientOptions & MockRTCOptions;
4
+ export declare class MockRTCClient implements MockRTC {
5
+ private options;
6
+ private adminClient;
7
+ constructor(options?: MockRTCClientOptions);
8
+ buildPeer(): MockRTCPeerBuilder;
9
+ private buildPeerFromData;
10
+ start(): Promise<void>;
11
+ stop(): Promise<void>;
12
+ }