microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.9.2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/networkInspector/networkInspectorServer.ts

404lines · modeblame

4bb0956eRedMickey5 years ago1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
09f6024fHeniker4 years ago4/* eslint-disable */
5/* eslint-enable prettier/prettier*/
6
4bb0956eRedMickey5 years ago7import { RSocketServer } from "rsocket-core";
8import RSocketTCPServer from "rsocket-tcp-server";
9import { AdbHelper } from "../android/adb";
10import { Single } from "rsocket-flowable";
11import { appNameWithUpdateHint, buildClientId } from "./clientUtils";
12import { SecureClientQuery, ClientCsrQuery, ClientDevice, ClientQuery } from "./clientDevice";
13import { OutputChannelLogger } from "../log/OutputChannelLogger";
14import { Responder, Payload, ReactiveSocket } from "rsocket-types";
15import {
16CertificateProvider,
17SecureServerConfig,
18CertificateExchangeMedium,
19} from "./certificateProvider";
20import { ClientOS } from "./clientUtils";
21import * as net from "net";
22import * as tls from "tls";
23import * as nls from "vscode-nls";
24import { InspectorViewType } from "./views/inspectorView";
ab0238b7RedMickey4 years ago25import { TipNotificationService } from "../services/tipsNotificationsService/tipsNotificationService";
4bb0956eRedMickey5 years ago26nls.config({
27messageFormat: nls.MessageFormat.bundle,
28bundleFormat: nls.BundleFormat.standalone,
29})();
30const localize = nls.loadMessageBundle();
31
32/**
33* @preserve
34* Start region: the code is borrowed from https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
35*
36* Copyright (c) Facebook, Inc. and its affiliates.
37*
38* This source code is licensed under the MIT license found in the
39* LICENSE file in the root directory of this source tree.
40*
41* @format
42*/
43
44function transformCertificateExchangeMediumToType(
45medium: number | undefined,
46): CertificateExchangeMedium {
47if (medium == 1) {
48return "FS_ACCESS";
49} else if (medium == 2) {
50return "WWW";
51} else {
52return "FS_ACCESS";
53}
54}
55
56export const NETWORK_INSPECTOR_LOG_CHANNEL_NAME = "Network Inspector";
57
58export class NetworkInspectorServer {
59public static readonly SecureServerPort = 8088;
60public static readonly InsecureServerPort = 8089;
61
62private connections: Map<string, ClientDevice>;
63private secureServer: RSocketServer<any, any> | null;
64private insecureServer: RSocketServer<any, any> | null;
65private certificateProvider: CertificateProvider;
66private initialisePromise: Promise<void> | null;
67private logger: OutputChannelLogger;
68
69constructor() {
70this.connections = new Map<string, ClientDevice>();
71this.logger = OutputChannelLogger.getChannel(NETWORK_INSPECTOR_LOG_CHANNEL_NAME);
72}
73
74public async start(adbHelper: AdbHelper): Promise<void> {
75this.logger.info(localize("StartNetworkinspector", "Starting Network inspector"));
f338085detatanova4 years ago76TipNotificationService.getInstance().setKnownDateForFeatureById("networkInspector");
77TipNotificationService.getInstance().showTipNotification(
78false,
79"networkInspectorLogsColorTheme",
80);
4bb0956eRedMickey5 years ago81this.initialisePromise = new Promise(async (resolve, reject) => {
82this.certificateProvider = new CertificateProvider(adbHelper);
83
84try {
85let options = await this.certificateProvider.loadSecureServerConfig();
86this.secureServer = await this.startServer(
87NetworkInspectorServer.SecureServerPort,
88options,
89);
90this.insecureServer = await this.startServer(
91NetworkInspectorServer.InsecureServerPort,
92);
93} catch (err) {
94return reject(err);
95}
96
97this.logger.info(localize("NetworkInspectorWorking", "Network inspector is working"));
98resolve();
99});
100return this.initialisePromise;
101}
102
103public async stop(): Promise<void> {
104if (this.initialisePromise) {
105try {
106await this.initialisePromise;
107} catch (err) {
108this.logger.error(err.toString());
109}
110if (this.secureServer) {
111this.secureServer.stop();
112}
113if (this.insecureServer) {
114this.insecureServer.stop();
115}
116}
117this.logger.info(localize("NetworkInspectorStopped", "Network inspector has been stopped"));
118}
119
120private async startServer(
121port: number,
122sslConfig?: SecureServerConfig,
123): Promise<RSocketServer<any, any>> {
124return new Promise((resolve, reject) => {
125let rsServer: RSocketServer<any, any> | undefined; // eslint-disable-line prefer-const
126const serverFactory = (onConnect: (socket: net.Socket) => void) => {
127const transportServer = sslConfig
128? tls.createServer(sslConfig, socket => {
129onConnect(socket);
130})
131: net.createServer(onConnect);
132transportServer
133.on("error", err => {
134this.logger.error(
135localize(
136"ErrorOpeningNetworkInspectorServerOnPort",
137"Error while opening Network inspector server on port {0}",
138port,
139),
140);
141reject(err);
142})
143.on("listening", () => {
144this.logger.debug(
145`${
146sslConfig ? "Secure" : "Certificate"
147} server started on port ${port}`,
148);
149resolve(rsServer!);
150});
151return transportServer;
152};
153rsServer = new RSocketServer({
154getRequestHandler: sslConfig
155? this.trustedRequestHandler
156: this.untrustedRequestHandler,
157transport: new RSocketTCPServer({
158port: port,
159serverFactory: serverFactory,
160}),
161});
162rsServer && rsServer.start();
163});
164}
165
166private trustedRequestHandler = (
167socket: ReactiveSocket<string, any>,
168payload: Payload<string, any>,
169): Partial<Responder<string, any>> => {
170// eslint-disable-next-line @typescript-eslint/no-this-alias
171const server = this;
172if (!payload.data) {
173return {};
174}
175
176const clientData: SecureClientQuery = JSON.parse(payload.data);
177
178const { app, os, device, device_id, sdk_version, csr, csr_path, medium } = clientData;
179const transformedMedium = transformCertificateExchangeMediumToType(medium);
180
181const client: Promise<ClientDevice> = this.addConnection(
182socket,
183{
184app,
185os,
186device,
187device_id,
188sdk_version,
189medium: transformedMedium,
190},
191{ csr, csr_path },
192).then(client => {
193return (resolvedClient = client);
194});
195let resolvedClient: ClientDevice | undefined;
196
197socket.connectionStatus().subscribe({
198onNext(payload) {
199if (payload.kind == "ERROR" || payload.kind == "CLOSED") {
200client.then(client => {
201server.logger.info(
202localize(
203"NIDeviceDisconnected",
204"Device disconnected {0} from the Network inspector",
205client.id,
206),
207);
208server.removeConnection(client.id);
209});
210}
211},
212onSubscribe(subscription) {
213subscription.request(Number.MAX_SAFE_INTEGER);
214},
215onError(error) {
216server.logger.error("Network inspector server connection status error ", error);
217},
218});
219
220return {
221fireAndForget: (payload: { data: string }) => {
222if (resolvedClient) {
223resolvedClient.onMessage(payload.data);
224} else {
225client.then(client => {
226client.onMessage(payload.data);
227});
228}
229},
230};
231};
232
233private untrustedRequestHandler = (
234_socket: ReactiveSocket<string, any>,
235payload: Payload<string, any>,
236): Partial<Responder<string, any>> => {
237if (!payload.data) {
238return {};
239}
240const clientData: ClientQuery = JSON.parse(payload.data);
241
242return {
243requestResponse: (payload: Payload<string, any>): Single<Payload<string, any>> => {
244if (typeof payload.data !== "string") {
245return new Single(() => {});
246}
247
248let rawData;
249try {
250rawData = JSON.parse(payload.data);
251} catch (err) {
252this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
253return new Single(() => {});
254}
255
256const json: {
257method: "signCertificate";
258csr: string;
259destination: string;
260medium: number | undefined; // OSS's older Client SDK might not send medium information. This is not an issue for internal FB users, as Flipper release is insync with client SDK through launcher.
261} = rawData;
262
263if (json.method === "signCertificate") {
264this.logger.debug("CSR received from device");
265
266const { csr, destination, medium } = json;
267return new Single(subscriber => {
268subscriber.onSubscribe(undefined);
269this.certificateProvider
270.processCertificateSigningRequest(
271csr,
272clientData.os,
273destination,
274transformCertificateExchangeMediumToType(medium),
275)
276.then(result => {
277subscriber.onComplete({
278data: JSON.stringify({
279deviceId: result.deviceId,
280}),
281metadata: "",
282});
283})
284.catch(e => {
285this.logger.error(e.toString());
286subscriber.onError(e);
287});
288});
289}
290return new Single(() => {});
291},
292
293// Leaving this here for a while for backwards compatibility,
294// but for up to date SDKs it will no longer used.
295// We can delete it after the SDK change has been using requestResponse for a few weeks.
296fireAndForget: (payload: Payload<string, any>) => {
297if (typeof payload.data !== "string") {
298return;
299}
300
301let json:
302| {
303method: "signCertificate";
304csr: string;
305destination: string;
306medium: number | undefined;
307}
308| undefined;
309try {
310json = JSON.parse(payload.data);
311} catch (err) {
312this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
313return;
314}
315
316if (json && json.method === "signCertificate") {
317this.logger.debug("CSR received from device");
318const { csr, destination, medium } = json;
319this.certificateProvider
320.processCertificateSigningRequest(
321csr,
322clientData.os,
323destination,
324transformCertificateExchangeMediumToType(medium),
325)
326.catch(e => {
327this.logger.error(e.toString());
328});
329}
330},
331};
332};
333
334private async addConnection(
335conn: ReactiveSocket<any, any>,
336query: ClientQuery & { medium: CertificateExchangeMedium },
337csrQuery: ClientCsrQuery,
338): Promise<ClientDevice> {
339// try to get id by comparing giving `csr` to file from `csr_path`
340// otherwise, use given device_id
341const { csr_path, csr } = csrQuery;
342// For iOS we do not need to confirm the device id, as it never changes unlike android.
09f6024fHeniker4 years ago343return (
344csr_path && csr && query.os !== ClientOS.iOS
345? this.certificateProvider.extractAppNameFromCSR(csr).then(appName => {
346return this.certificateProvider.getTargetDeviceId(
347query.os,
348appName,
349csr_path,
350csr,
351);
352})
353: Promise.resolve(query.device_id)
4bb0956eRedMickey5 years ago354).then(async csrId => {
355query.device_id = csrId;
356query.app = appNameWithUpdateHint(query);
357
358const id = buildClientId(
359{
360app: query.app,
361os: query.os,
362device: query.device,
363device_id: csrId,
364},
365this.logger,
366);
367this.logger.info(localize("NIDeviceConnected", "Device connected: {0}", id));
368
369const client = new ClientDevice(
370id,
371query,
372conn,
373InspectorViewType.console,
374this.logger,
375);
376
377client.init().then(() => {
378this.logger.debug(`Device client initialised: ${id}`);
379/* If a device gets disconnected without being cleaned up properly,
380* Flipper won't be aware until it attempts to reconnect.
381* When it does we need to terminate the zombie connection.
382*/
383this.removeConnection(id);
384
385this.connections.set(id, client);
386});
387
388return client;
389});
390}
391
392/**
393* @preserve
394* End region: https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
395*/
396
397private removeConnection(id: string) {
398const clientDevice = this.connections.get(id);
399if (clientDevice) {
400clientDevice.connection && clientDevice.connection.close();
401this.connections.delete(id);
402}
403}
404}