/
client.ts
265 lines (242 loc) · 8.1 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import * as ratchet from "2key-ratchet";
import * as core from "@webcrypto-local/core";
import * as proto from "@webcrypto-local/proto";
import { EventEmitter } from "events";
import fetch from "node-fetch";
import { Convert } from "pvtsutils";
import WebSocket from "ws";
import { CryptoServerError } from "../errors";
import * as events from "./events";
import { RatchetStorage } from "./storages";
export interface PromiseStackItem {
resolve: (...args: any[]) => void;
reject: (...args: any[]) => void;
}
export enum SocketCryptoState {
connecting = 0,
open = 1,
closing = 2,
closed = 3,
}
/**
* Implementation of WebCrypto interface
* - `getRandomValues` native implementation
* - Symmetric cryptography uses native implementation
* - Asymmetric cryptography uses calls to Server
*/
export class Client extends EventEmitter {
public serviceInfo?: core.ServerInfo;
public stack: { [key: string]: PromiseStackItem } = {};
public get state(): SocketCryptoState {
if (this.socket) {
return this.socket.readyState;
} else {
return SocketCryptoState.closed;
}
}
/**
* double ratchet session
*/
protected cipher?: ratchet.AsymmetricRatchet;
protected socket?: WebSocket;
protected messageCounter = 0;
protected storage: RatchetStorage;
constructor(storage: RatchetStorage) {
super();
this.storage = storage;
}
/**
* Connects to Service
* Steps:
* 1. Requests info data from Server
* - if server not found emits `error`
* 2. Create 2key-ratchet session from PreKeyBundle
*/
public connect(address: string, options?: WebSocket.ClientOptions): this {
this.getServerInfo(address)
.then((info) => {
this.serviceInfo = info;
const url = `wss://${address}`;
this.socket = options
? new WebSocket(url, undefined, options)
: new WebSocket(url);
this.socket.binaryType = "arraybuffer";
this.socket.onerror = (e: any) => {
this.emit("error", new events.ClientErrorEvent(this, e.error));
};
this.socket.onopen = () => {
(async () => {
let identity = await this.storage.loadIdentity();
if (!identity) {
// if ((self as any).PV_WEBCRYPTO_SOCKET_LOG) {
// console.info("Generates new identity");
// }
identity = await ratchet.Identity.create(1);
await this.storage.saveIdentity(identity);
}
const remoteIdentityId = "0";
const bundle = await ratchet.PreKeyBundleProtocol.importProto(Convert.FromBase64(info.preKey));
this.cipher = await ratchet.AsymmetricRatchet.create(identity, bundle);
// save new remote identity
await this.storage.saveRemoteIdentity(remoteIdentityId, this.cipher.remoteIdentity);
this.emit("listening", new events.ClientListeningEvent(this, address));
})().catch((error) => this.emit("error", new events.ClientErrorEvent(this, error)));
};
this.socket.onclose = (e) => {
for (const actionId in this.stack) {
const message = this.stack[actionId];
message.reject(new Error("Cannot finish operation. Session was closed"));
}
this.emit("close", new events.ClientCloseEvent(this, address, e.code, e.reason));
};
this.socket.onmessage = (e) => {
if (e.data instanceof ArrayBuffer) {
// decrypt
ratchet.MessageSignedProtocol.importProto(e.data)
.then((proto2) => {
if (!this.cipher) {
throw new Error("Client cipher is not initialized");
}
return this.cipher.decrypt(proto2);
})
.then((msg) => {
this.onMessage(msg);
})
.catch((err) => {
this.emit("error", new events.ClientErrorEvent(this, err));
});
}
};
})
.catch((err) => {
this.emit("error", new events.ClientErrorEvent(this, err));
});
return this;
}
/**
* Close connection
*/
public close() {
if (this.socket) {
this.socket.close();
}
}
public on(event: "event", listener: (e: proto.ActionProto) => void): this;
public on(event: "listening", listener: (e: events.ClientListeningEvent) => void): this;
public on(event: "close", listener: (e: events.ClientCloseEvent) => void): this;
public on(event: "error", listener: (e: events.ClientErrorEvent) => void): this;
public on(event: string | symbol, listener: (...args: any[]) => void) {
return super.on(event, listener);
}
public once(event: "listening", listener: (e: events.ClientListeningEvent) => void): this;
public once(event: "close", listener: (e: events.ClientCloseEvent) => void): this;
public once(event: "error", listener: (e: events.ClientErrorEvent) => void): this;
public once(event: string | symbol, listener: (...args: any[]) => void): this;
public once(event: string | symbol, listener: (...args: any[]) => void) {
return super.once(event, listener);
}
/**
* Return PIN for current session
*
* @returns
*
* @memberOf Client
*/
public async challenge() {
if (!this.cipher) {
throw new Error("Client cipher is not initialized");
}
return core.challenge(this.cipher.remoteIdentity.signingKey, this.cipher.identity.signingKey.publicKey);
}
/**
* Returns true if session is authorized
*
*
* @memberOf Client
*/
public async isLoggedIn() {
const action = new proto.ServerIsLoggedInActionProto();
const data = await this.send(action);
return data ? !!(new Uint8Array(data)[0]) : false;
}
/**
* Request session authentication
*
*
* @memberOf Client
*/
public async login() {
const action = new proto.ServerLoginActionProto();
await this.send(action);
}
/**
* Sends and receives
*/
public send(data?: proto.ActionProto): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
this.checkSocketState();
if (!data) {
data = new proto.ActionProto();
}
data.action = data.action;
data.actionId = (this.messageCounter++).toString();
data.exportProto()
.then((raw) => {
// encrypt data
if (!this.cipher) {
throw new Error("Client cipher is not initialized");
}
return this.cipher.encrypt(raw)
.then((msg) => msg.exportProto());
})
.then((raw) => {
// console.log(Convert.ToBinary(raw));
if (!this.socket) {
throw new Error("Client socket is not initialized");
}
this.stack[data!.actionId] = { resolve, reject };
this.socket.send(raw);
})
.catch(reject);
});
}
/**
* Sends Request to server and gets info about server and PreKeyBundle data for DKeyRatchet connection
*/
protected async getServerInfo(address: string): Promise<core.ServerInfo> {
const url = `https://${address}${core.SERVER_WELL_KNOWN}`;
const response = await fetch(url);
if (response.status !== 200) {
throw new Error("Cannot get wellknown link");
} else {
const json = await response.json();
return json;
}
}
protected checkSocketState() {
if (this.state !== SocketCryptoState.open) {
throw new Error("Socket connection is not open");
}
}
protected async onMessage(message: ArrayBuffer) {
const p = await proto.ActionProto.importProto(message);
// if ((self as any).PV_WEBCRYPTO_SOCKET_LOG) {
// console.info("Action:", p.action);
// }
// find Promise
const promise = this.stack[p.actionId];
if (promise) {
delete this.stack[p.actionId];
const messageProto = await proto.ResultProto.importProto(await p.exportProto());
if (messageProto.error && messageProto.error.message) {
const errorProto = messageProto.error;
const error = new CryptoServerError(errorProto);
promise.reject(error);
} else {
promise.resolve(messageProto.data);
}
} else {
this.emit("event", p);
}
}
}