-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.js
386 lines (376 loc) · 10.5 KB
/
application.js
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
export class Applcation {
constructor(api, apiKey) {
this.enckeys = [
{
"name": "malfunctioning-unapproachability",
"key": "Em9k8X2SsEDHbC6mF9jwBug8BGfLYC2TR97hzKzCaAY="
},
{
"name": "tegular-peripatopsidae",
"key": "eOSPDQfRMp+RwOKE4v7TQc5yGgeg2ABQ23pjWg8kWAg="
},
{
"name": "elective-experience",
"key": "Wh7toVpICwu53zFH7+1PagoveuCK6uquyVfr8TSIwQw="
},
{
"name": "heraldic-epacris",
"key": "QnyTODU7KLY9taRt7V2sNyRflu97U3LYmnx4uhCsLDM="
}
];
this.socket = {};
this.connected = false;
this.viewingSelf = true;
this.api = api;
this.tk = {};
this.key = apiKey;
this.messages = {
"sent": 0
};
this.errors = [];
this.room = {};
this.roomid = 'welcome';
this.user = {};
this.profileUser = {};
this.init();
}
getRandomEncodingKey() {
return this.enckeys[Math.floor(Math.random() * this.enckeys.length)];
}
async login(email, password) {
try {
const out = {
email: email,
password: password
}
const res = await fetch(`${this.api}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
if (data.error) {
let msg = `login failed: ${data.message}`;
this.errors.push(msg);
}
this.user = data;
} else {
this.errors.push('login failed...');
}
} catch (error) {
this.errors.push("login failed", error.message);
}
}
async addPost(out) {
try {
const res = await fetch(`${this.api}/addpost`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
this.user = data;
} else {
this.errors.push('post not added...');
}
} catch (error) {
this.errors.push("error adding post...", error.message);
}
}
async updateProfile(out) {
try {
const res = await fetch(`${this.api}/profile`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
console.log("profile updated", data);
this.user = data;
} else {
this.errors.push('profile not updated...');
}
} catch (error) {
this.errors.push("error updating profile...", error.message);
}
}
async sendClearCommand() {
const out = {
"email": this.user.email,
"command": "/clear",
"room_id": this.roomid
}
try {
const res = await fetch(`${this.api}/clear`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
console.log("clear command", status, data);
if (status === 200) {
console.log("clear command sent", data);
} else {
this.errors.push('clear command not sent...');
}
} catch (error) {
this.errors.push("error sending clear command...", error.message);
}
}
async getTempKey() {
try {
const res = await fetch(`${this.api}/hotsauce`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
}
});
const status = res.status;
const data = await res.json();
if (status === 200) {
this.tk = data;
// console.log("temp key", this.tk);
} else {
this.errors.push('key not set...');
}
}
catch (error) {
this.errors.push("error getting temp key...", error.message);
}
}
async testConnection() {
try {
const resp = await fetch(`${this.api}/test`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
}
});
const status = resp.status;
// data = await resp.json();
if (status === 200) {
this.connected = true;
}
// console.log(status, "easy", this.connected);
} catch (error) {
this.errors.push("error testing connection...", error.message);
}
}
async establishWSConnection(roomID, key) {
this.socket = new WebSocket(`${this.api}/ws/${roomID}/${key}`);
}
closeWSConnection() {
this.socket.close();
this.connected = false;
}
async updateHistory() {
try {
let out = {
"user_id": this.user.email
};
const res = await fetch(`${this.api}/history`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
// console.log("updateHistory", data, this.user);
this.user.history = data.history;
} else {
this.errors.push('history not set (server error)');
}
}
catch (error) {
this.errors.push("error updating history...", error.message);
}
}
async addRoom(room) {
try {
const out = {
email: this.user.email,
name: room,
regular: true
}
const res = await fetch(`${this.api}/addroom`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
this.user.rooms.push(room)
console.log("addRoom", data);
} else {
this.errors.push('room not set (server error)');
}
} catch (error) {
this.errors.push("error adding room...", error.message);
}
}
async getUser(id) {
try {
const res = await fetch(`${this.api}/getuser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify({ user_id: id })
});
const status = res.status;
const data = await res.json();
if (status === 200) {
this.profileUser = data;
console.log("getUser", data);
} else {
this.errors.push('user not found...');
}
} catch (error) {
this.errors.push("error getting user...", error.message);
}
}
async setRoom(room) {
console.log("setRoom called", room);
try {
const out = {
email: this.user.email,
name: room,
regular: true
}
// console.log("setRoom called", out);
const res = await fetch(`${this.api}/room/${room}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.key}`
},
body: JSON.stringify(out)
});
const status = res.status;
const data = await res.json();
if (status === 200) {
// box.innerHTML = '';
this.room = data;
this.roomid = data.id;
this.updateHistory();
} else {
this.errors.push('room not set (server error)');
}
if (this.socket) {
this.socket.onmesage = null;
this.socket.close();
}
// this.establishWSConnection(this.roomid);
} catch (error) {
this.errors.push("error setting room...", error.message);
}
// console.log("setRoom done", this.room);
}
async encodeString(str, k) {
const hotsauce = window.crypto.getRandomValues(new Uint8Array(16));
const encoder = new TextEncoder();
const data = encoder.encode(str);
const cipher = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: hotsauce
},
k,
data
);
const encrypted = new Uint8Array(cipher);
const base64 = btoa(String.fromCharCode(...encrypted));
return { iv: btoa(String.fromCharCode(...hotsauce)), data: base64 };
}
async encrypt(val) {
const keyPair = this.getRandomEncodingKey();
const b64NoPadding = keyPair.key.replace(/=/g, "");
// const keyBytes = new Uint8Array(keyPair.key.match(/[\s\S]/g).map(ch => ch.charCodeAt(0)));
const keyBytes = Uint8Array.from(atob(b64NoPadding), c => c.charCodeAt(0));
if (keyBytes.length !== 32) {
console.log(`Invalid key length for ${keyPair.key}: ${keyBytes.length} bytes`);
return;
}
const secretKey = await window.crypto.subtle.importKey(
"raw",
keyBytes,
{ name: "AES-GCM" },
false,
["encrypt", "decrypt"]
);
const out = await this.encodeString(val, secretKey);
return { key: keyPair.name, data: out };
}
async decodeString(str, k, iv) {
const decoder = new TextDecoder();
const encrypted = new Uint8Array(atob(str).split("").map(c => c.charCodeAt(0)));
// Decode the Base64 encoded IV
const ivNoPadding = iv.replace(/=/g, "");
const ivBytes = new Uint8Array(atob(ivNoPadding).split("").map(c => c.charCodeAt(0)));
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: ivBytes // Use the correct IV
},
k,
encrypted
);
return decoder.decode(decrypted);
}
async decrypt(val, key) {
const keyPair = this.enckeys.find(k => k.name === key.hotsauce);
if (!keyPair) {
console.log(`No key found for ${key}`);
return;
}
const b64NoPadding = keyPair.key.replace(/=/g, "");
const keyBytes = Uint8Array.from(atob(b64NoPadding), c => c.charCodeAt(0));
if (keyBytes.length !== 32) {
console.log(`Invalid key length for ${keyPair.key}: ${keyBytes.length} bytes`);
return;
}
const secretKey = await window.crypto.subtle.importKey(
"raw",
keyBytes,
{ name: "AES-GCM" },
false,
["encrypt", "decrypt"]
);
const out = await this.decodeString(val, secretKey, key.iv);
return out;
}
init() {
this.testConnection();
this.getTempKey();
}
}