Skip to content

feat(websockets): add ssl pinning #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/nativescript-websockets/bridge.android.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HeaderType } from './common';
import { NativeBridgeDefinition } from './websocket.definition';
import { NativeBridgeDefinition, WebSocketBridgeConnectOptions } from './websocket.definition';

interface ExtendedArrayBuffer extends ArrayBuffer {
from?(nativeBuffer: java.nio.ByteBuffer): ArrayBuffer;
Expand Down Expand Up @@ -72,7 +72,7 @@ export class NativeBridge extends NativeBridgeDefinition {
nativeWs!: okhttp3.WebSocket;
startLooper?: android.os.Looper;
handler?: android.os.Handler;
connect(url: string, protocols: string[], headers: HeaderType): void {
connect({ url, protocols, headers }: WebSocketBridgeConnectOptions): void {
this.startLooper = android.os.Looper.myLooper();
this.handler = new android.os.Handler(this.startLooper);
protocols = protocols || [];
Expand Down
22 changes: 20 additions & 2 deletions packages/nativescript-websockets/bridge.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/

import { HeaderType } from './common';
import { NativeBridgeDefinition } from './websocket.definition';
import { NativeBridgeDefinition, WebSocketBridgeConnectOptions } from './websocket.definition';

@NativeClass
class RCTSRWebSocketDelegateImpl extends NSObject implements RCTSRWebSocketDelegate {
Expand Down Expand Up @@ -41,7 +41,7 @@ export class NativeBridge extends NativeBridgeDefinition {
// store the delegate so it isn't garbage collected
// TODO: fix the iOS runtime so we don't need this
delegate!: RCTSRWebSocketDelegateImpl;
connect(url: string, protocols: string[], headers: HeaderType) {
connect({ url, protocols, headers, pinnedCertificates }: WebSocketBridgeConnectOptions): void {
const nativeUrl = NSURL.URLWithString(url);
const request = NSMutableURLRequest.requestWithURL(nativeUrl);
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
Expand All @@ -63,6 +63,24 @@ export class NativeBridge extends NativeBridgeDefinition {
for (const k of Object.keys(headers.headers)) {
request.addValueForHTTPHeaderField(`${headers.headers[k]}`, k);
}
if (pinnedCertificates) {
const sslArray = NSMutableArray.new();

for (const c of pinnedCertificates) {
// convert from pem to der (base64)
const der = c
.replace(/-----BEGIN CERTIFICATE-----/g, '')
.replace(/-----END CERTIFICATE-----/g, '')
.replace(/\r?\n/g, '');
const cert = SecCertificateCreateWithData(null, NSData.alloc().initWithBase64EncodedStringOptions(der, NSDataBase64DecodingOptions.IgnoreUnknownCharacters));
if (cert) {
sslArray.addObject(cert);
} else {
console.warn('Unable to create certificate from pem');
}
}
request.RCTSR_SSLPinnedCertificates = sslArray;
}

const webSocket = RCTSRWebSocket.alloc().initWithURLRequestProtocols(request, protocols);
this.nativeSocket = webSocket;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ declare const enum RCTSRStatusCode {
CodeMessageTooBig = 1009
}

interface NSMutableURLRequest {
RCTSR_SSLPinnedCertificates: NSArray<any>;
}

declare class RCTSRWebSocket extends NSObject implements NSStreamDelegate {

static alloc(): RCTSRWebSocket; // inherited from NSObject
Expand Down
9 changes: 8 additions & 1 deletion packages/nativescript-websockets/websocket.definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@ export interface WebSocketPolyfill {
_websocketFailed(message: string): void;
}

export interface WebSocketBridgeConnectOptions {
url: string;
protocols: string[];
headers: HeaderType;
pinnedCertificates?: string[];
}

export abstract class NativeBridgeDefinition {
public handleThreading = true;
constructor(protected ws: WebSocketPolyfill) {}
abstract connect(url: string, protocols: string | string[], headers: HeaderType): void;
abstract connect(options: WebSocketBridgeConnectOptions): void;
abstract send(data: string | ArrayBuffer | ArrayBufferView | Blob): void;
abstract closeWithCodeReason(statusCode: number, closeReason: string): void;
abstract sendPing(): void;
Expand Down
13 changes: 10 additions & 3 deletions packages/nativescript-websockets/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ const openWebsockets = new Set<WebSocketPolyfill>();
// websocketFailed: [{ id: number; message: string }];
// };

interface ExtraWebsocketOptions {
headers: { origin?: string; [key: string]: unknown };
nativescript: { handleThreading: boolean };
pinnedCertificates?: string[];
[key: string]: unknown;
}

/**
* Browser-compatible WebSockets implementation.
*
Expand Down Expand Up @@ -81,7 +88,7 @@ export class WebSocket implements WebSocketPolyfill {
message: new Map(),
};

constructor(url: string, protocols?: string | Array<string>, options?: { headers: { origin?: string; [key: string]: unknown }; nativescript: { handleThreading: boolean }; [key: string]: unknown }) {
constructor(url: string, protocols?: string | Array<string>, options?: ExtraWebsocketOptions) {
this.nativeBridge = new NativeBridge(this);
this.url = url;
if (typeof protocols === 'string') {
Expand All @@ -91,7 +98,7 @@ export class WebSocket implements WebSocketPolyfill {
protocols = [];
}

const { headers = {}, nativescript = { handleThreading: true }, ...unrecognized } = options || ({} as { headers: { origin?: string; [key: string]: unknown }; nativescript: { handleThreading: boolean }; [key: string]: unknown });
const { headers = {}, nativescript = { handleThreading: true }, pinnedCertificates, ...unrecognized } = options || ({} as ExtraWebsocketOptions);
this.nativeBridge.handleThreading = nativescript?.handleThreading ?? WebSocket.HANDLE_THREADING;
this._binaryType = 'arraybuffer';

Expand Down Expand Up @@ -119,7 +126,7 @@ export class WebSocket implements WebSocketPolyfill {
// Platform.OS !== 'ios' ? null : NativeWebSocketModule,
// );
this._registerEvents();
this.nativeBridge.connect(url, protocols, { headers });
this.nativeBridge.connect({ url, protocols, headers: { headers }, pinnedCertificates });
openWebsockets.add(this);
// NativeWebSocketModule.connect(url, protocols, {headers}, this._socketId);
}
Expand Down
1 change: 1 addition & 0 deletions references.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/// <reference path="./node_modules/@nativescript/types-ios/index.d.ts" />
/// <reference path="./node_modules/@nativescript/types-ios/lib/ios/objc-x86_64/objc!Security.d.ts" />
/// <reference path="./node_modules/@nativescript/types-android/lib/android-29.d.ts" />