-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
849 lines (741 loc) · 32.5 KB
/
server.ts
File metadata and controls
849 lines (741 loc) · 32.5 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
import { DB } from "https://deno.land/x/sqlite/mod.ts";
import { Fido2Lib } from "https://deno.land/x/fido2/dist/main.js";
const f2l = new Fido2Lib({
timeout: 42,
rpId: "localhost",
rpName: "Fido Implementation Nathan",
rpIcon: "http://localhost:8000/favicon.ico",
challengeSize: 128,
attestation: "none", // The preferred attestation type to be used. See [AttestationConveyancePreference]
// {https://w3.org/TR/webauthn/#enumdef-attestationconveyancepreference} in the WebAuthn spec
cryptoParams: [-7, -257],
authenticatorAttachment: "cross-platform", //cross-platform is roaming, platform is OS
authenticatorRequireResidentKey: false,
authenticatorUserVerification: "required"
});
const challengeMap = new Map<string, string>();
export function setChallenge(username: string, challenge: string) {
challengeMap.set(username, challenge);
// Optional: setTimeout(() => challengeMap.delete(userId), 5 * 60 * 1000);
}
export function getChallenge(username: string): string | undefined {
return challengeMap.get(username);
}
export function deleteChallenge(username: string) {
challengeMap.delete(username);
}
function generateUserId() {
// 32 random bytes (safe within 1–64 bytes range)
return crypto.getRandomValues(new Uint8Array(32));
}
function toBase64Url(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let str = '';
for (let i = 0; i < bytes.byteLength; i++) {
str += String.fromCharCode(bytes[i]);
}
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function bufferSourceToBase64Url(buf: BufferSource): string {
const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
const bin = String.fromCharCode(...bytes);
return btoa(bin)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
function base64urlToUint8Array(base64url: string) {
// Replace - with + and _ with / and pad with =
let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4 !== 0) {
base64 += '=';
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function prepareRegistrationOptionsForClient(options: PublicKeyCredentialCreationOptions) {
return {
...options,
challenge: bufferSourceToBase64Url(options.challenge),
user: {
...options.user,
id: bufferSourceToBase64Url(options.user.id),
},
excludeCredentials: options.excludeCredentials?.map((cred) => ({
...cred,
id: bufferSourceToBase64Url(cred.id),
})),
};
}
function prepareAuthenticationOptionsForClient(options: PublicKeyCredentialRequestOptions) {
return {
...options,
challenge: bufferSourceToBase64Url(options.challenge),
};
}
// Function to read and serve the HTML file
const serveHtml = async (): Promise<string> => {
// Read the HTML file from the filesystem (ensure the correct path)
const htmlContent = await Deno.readTextFile("./basic.html");
return htmlContent;
};
const serveHtmlRegister = async (): Promise<string> => {
// Read the HTML file from the filesystem (ensure the correct path)
const htmlContent = await Deno.readTextFile("./register.html");
return htmlContent;
};
/*
const serveHTMLIndex = async (): Promise<string> => {
const htmlContent = await Deno.readTextFile("./Box/index.html");
return htmlContent;
}
*/
const servePNG = async (): Promise<Uint8Array> => {
const htmlContent = await Deno.readFile("./Box/Service.png");
return htmlContent;
}
const serveICO = async (): Promise<Uint8Array> => {
const Content = await Deno.readFile("./favicon.ico");
return Content;
}
async function hash(message: string | undefined) {
const data = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
return hashHex
}
function checkSessionExists(db : DB, cookie : string) {
try {
const query = db.prepareQuery("SELECT id FROM cookies WHERE cookie = ?");
const row = query.first([cookie]);
if (row === undefined) {
return false
} else {
return true
}
} catch (error) {
throw error
}
}
// Define the server using Deno.serve()
Deno.serve(async (req) => {
const db = new DB("./test.db");
const pathname = new URL(req.url).pathname;
const cookieHeader = req.headers.get("Cookie");
// Parse cookies into an object with a specific type
const cookies: { [key: string]: string } = cookieHeader
? cookieHeader.split(";").reduce((acc: { [key: string]: string }, cookie) => {
const [key, value] = cookie.trim().split("=");
acc[key] = value;
return acc;
}, {})
: {};
// Access the session_id cookie
const sessionId = cookies["session_id"];
if (req.method === "GET" && (pathname === "/" || pathname === "/login")) {
try {
// Serve the HTML page
const htmlContent = await serveHtml();
return new Response(htmlContent, {
status: 200,
headers: { "Content-Type": "text/html" },
});
} catch (error) {
console.error("Error serving HTML:", error);
return new Response("Internal Server Error", { status: 500 });
}
}
if (req.method === "GET" && pathname ==="/favicon.ico") {
try {
const ico = await serveICO();
return new Response(ico, {
status: 200,
headers: { "Content-Type": "image/ico" },
});
} catch (error) {
console.error("Error serving favicon:",error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "GET" && pathname === "/register") {
try {
// Serve the HTML page
const htmlContent = await serveHtmlRegister();
return new Response(htmlContent, {
status: 200,
headers: { "Content-Type": "text/html" },
});
} catch (error) {
console.error("Error serving HTML:", error);
return new Response("Internal Server Error", { status: 500 });
}
}
if (req.method === "POST" && pathname === "/submit") {
try {
// Parse JSON body from the POST request
const body = await req.json();
// Log the data (for demonstration purposes)
console.log("Received data:", body);
try {
// We check if there is such a user in the database
const query = db.prepareQuery("SELECT id FROM people WHERE username = ?");
const row = query.first([body.username]);
console.log("Data in db:",row);
if (row === undefined) {
return new Response(
JSON.stringify({ message: "Login Failure!" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
} else {
const password = body.password;
const hashQuery = db.prepareQuery("SELECT password_hash FROM people WHERE username = ?");
const hashRow = hashQuery.first([body.username]);
const provided_hash = await hash(password);
if (hashRow === undefined) {
console.log("Race condition or entry disappeared.")
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
console.log("Provided hash", provided_hash)
console.log("Actual hash", hashRow[0])
if (provided_hash === hashRow[0]) {
// Create new session cookie
const newCookie = crypto.randomUUID();
db.query("INSERT INTO cookies (cookie,id) VALUES (?,?)", [newCookie,String(row[0])]);
console.log("Cookie we are sending:",newCookie)
// Respond with a success message
return new Response(
JSON.stringify({ message: "Data received successfully!"}),
{ status: 200, headers: { "Content-Type": "application/json",
"Set-Cookie":`session_id=${newCookie}; path=/; HttpOnly; SameSite=Strict; Max-Age=3600`}
}
);
} else {
return new Response(
JSON.stringify({ message: "Login Failure!" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
}
} catch (error) {
console.error("Internal Server Error", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "POST" && pathname === "/register") {
try {
// Parse JSON body from the POST request
const body = await req.json();
// Log the data (for demonstration purposes)
console.log("New user data:", body);
try {
// We check if there is such a user in the database
const query = db.prepareQuery("SELECT id FROM people WHERE username = ?");
const username = body.username;
const displayname = body.displayname;
const row = query.first([username]);
if (row === undefined) {
const password_hash = await hash(body.password);
console.log("Hash:", password_hash);
db.query("INSERT INTO people (id,username,password_hash,display_name) VALUES (?,?,?,?)", [bufferSourceToBase64Url(generateUserId()),username,password_hash,displayname]);
return new Response(
JSON.stringify({ message: `Successfully registered new user ${username}` }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
} else {
console.error(`User ${username} already exists.`);
return new Response(
JSON.stringify({ error: "User already exists." }),
{ status: 409, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "POST" && pathname === "/registerFido2options") {
const registrationOptions = await f2l.attestationOptions() as PublicKeyCredentialCreationOptions;
try {
const body = await req.json();
// Log the data (for demonstration purposes)
console.log("New user data:", body);
const username = body.username;
const displayname = body.displayname;
try {
// We check if there is such a user in the database
const query = db.prepareQuery("SELECT id FROM people WHERE username = ?");
const row = query.first([username]);
const uniqueID = generateUserId()
//If there's no Fido2 Credentials on the user entry -- and no password hash -- we can safely delete the user
//in the database and proceed with registering
let deleteUser = false;
try {
const queryPassword = db.prepareQuery("SELECT password_hash FROM people WHERE username = ?");
const rowPassword = queryPassword.first([username]);
const queryCreds = db.prepareQuery("SELECT id FROM credentials WHERE username = ?");
const rowCreds = queryCreds.first([username]);
if ((rowPassword === undefined || (rowPassword !== undefined && (rowPassword[0] == null || rowPassword[0] == ""))) && (rowCreds === undefined)) {
console.log(`Deleting ${username} from the database.`);
db.query("DELETE FROM people WHERE username = ?",[username]);
deleteUser = true;
}
} catch (error) {
console.error("JSON error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
if ( (row === undefined) || deleteUser ) {
const user = {
id: uniqueID,
name: username,
displayName: displayname
};
registrationOptions.user = user;
try {
//registrationOptions.challenge = toBase64Url(registrationOptions.challenge);
const encodedChallenge = bufferSourceToBase64Url(registrationOptions.challenge);
//registrationOptions.challenge = Buffer.from(registrationOptions.challenge);
//console.log('Check registration options challenge type',registrationOptions.challenge);
//console.log('Params before inserting session challenge',username,encodedChallenge);
db.query("INSERT INTO people (id,username,display_name) VALUES (?,?,?)", [bufferSourceToBase64Url(registrationOptions.user.id),username,displayname]);
db.query("INSERT INTO sessionChallenges (username,sessionChallenge) VALUES (?,?)", [username,encodedChallenge]);
const safeOptions = prepareRegistrationOptionsForClient(registrationOptions);
try {
return new Response(JSON.stringify(safeOptions), {
status: 200,
headers: {
"Content-Type": "application/json",
},
}); }
catch (error) {
console.error("JSON error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} else {
console.error(`User ${username} already exists.`);
return new Response(
JSON.stringify({ error: "User already exists." }),
{ status: 409, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "POST" && pathname === "/registerFido2") {
try {
const clientAttestationResponse = await req.json();
console.log(clientAttestationResponse);
// Let's decode the clientDataJSON to get more info
const clientDataJSON = JSON.parse(atob(clientAttestationResponse.response.clientDataJSON.replace(/-/g, '+').replace(/_/g, '/')));
console.log("Decoded client data:", clientDataJSON);
try {
const username = clientAttestationResponse.username;
const query2 = db.prepareQuery("SELECT sessionChallenge FROM sessionChallenges WHERE username = ?");
const challengeRow = query2.first([username]);
if (!challengeRow) {
console.error("Session challenge does not exist");
return new Response(
JSON.stringify({ error: "Invalid registration information." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
const sessionChallenge = challengeRow[0];
const expectations = {
challenge: sessionChallenge,
origin: "http://localhost:8000",
factor: "either" as const
};
console.log("Expectations:", expectations);
console.log("Challenge from client data:", clientDataJSON.challenge);
console.log("Expected challenge:", sessionChallenge);
try {
//clientAttestationResponse.id = base64urlToUint8Array(clientAttestationResponse.id).buffer;
//clientAttestationResponse.rawId = base64urlToUint8Array(clientAttestationResponse.rawId).buffer;
//clientAttestationResponse.rawId = base64urlToUint8Array(clientAttestationResponse.rawId).buffer;
//clientAttestationResponse.response.attestationObject = base64urlToUint8Array(clientAttestationResponse.response.attestationObject).buffer;
//clientAttestationResponse.response.clientDataJSON = base64urlToUint8Array(clientAttestationResponse.response.clientDataJSON).buffer;
const attestationResult = {
id: base64urlToUint8Array(clientAttestationResponse.rawId).buffer,
rawId: base64urlToUint8Array(clientAttestationResponse.rawId).buffer,
response: {
attestationObject: clientAttestationResponse.response.attestationObject,
clientDataJSON: clientAttestationResponse.response.clientDataJSON
}
};
const regResult = await f2l.attestationResult(attestationResult, expectations); // will throw on error
console.log("Registration result:", regResult);
// Save regResult.authnrData.get("credentialPublicKeyPem") and counter
if (regResult.authnrData?.get('credentialPublicKeyPem') !== undefined && regResult.authnrData?.get('counter') !== undefined && regResult.authnrData?.get('credId') !== undefined) {
console.log("Registration result:", regResult);
const credId = toBase64Url(regResult.authnrData.get('credId'));
//const publicKey = toBase64Url(regResult.authnrData.get('credentialPublicKeyCose'));
const publicKey = regResult.authnrData.get('credentialPublicKeyPem');
const counter = regResult.authnrData.get('counter');
try {
db.query("INSERT INTO credentials (username, cred_id, public_key, counter) VALUES (?, ?, ?, ?)",[username, credId, publicKey, counter]);
// Clean up the session challenge
db.query("DELETE FROM sessionChallenges WHERE username = ?", [username]);
return new Response(
JSON.stringify({ success: true, message: `Successfully registered new user ${username}` }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} else {
throw "Result of regResult is empty, or properties of authnrData have changed.";
}
} catch (error) {
console.error("Error registering credentials:", error);
return new Response(
JSON.stringify({ error: "Invalid registration information." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "POST" && pathname === "/Fido2-Begin") {
try {
const userRequest = await req.json();
console.log('Fido2 auth begin user request:',userRequest);
try {
const authnOptions = await f2l.assertionOptions() as PublicKeyCredentialRequestOptions;
if (authnOptions) {
try {
console.log("New Fido2 login request:", userRequest);
const username = userRequest.username;
const query3 = db.prepareQuery("SELECT cred_id FROM credentials WHERE username = ?");
const credIDRow = query3.first([username]);
if (!credIDRow) {
console.error("Fido2 credentials don't exist for",username);
return new Response(
JSON.stringify({ error: "Invalid login information." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
} else {
const credId = credIDRow[0];
const encodedChallenge = bufferSourceToBase64Url(authnOptions.challenge);
setChallenge(username,encodedChallenge);
const safeAuthnOptions = prepareAuthenticationOptionsForClient(authnOptions);
const safeAuthnOptions2 = {
allowCredentials: [ // force only specific credentials
{
id: credId,
type: "public-key",
},
],
...safeAuthnOptions,
};
console.log('Sending authnOptions to user:',safeAuthnOptions2);
return new Response(JSON.stringify(safeAuthnOptions2), {
status: 200,
headers: {
"Content-Type": "application/json",
}
});
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} else {
console.error("Error in instantiating authnOptions");
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "POST" && pathname === "/Fido2-End") {
try {
const userRequest = await req.json();
console.log('User request from client for final Fido2 step: ',userRequest);
const username = userRequest.username;
if (!username) {
throw "Username not supplied."
}
try {
const query = db.prepareQuery("SELECT id FROM people WHERE username = ?");
const row = query.first([username]);
if (row === undefined) {
return new Response(
JSON.stringify({ message: "Login Failure!" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
try {
const challenge = getChallenge(username);
if (!challenge) {
throw `Challenge doesn't exist for username ${username}`
} else {
try {
const query = db.prepareQuery("SELECT cred_id FROM credentials WHERE username = ?");
const query2 = db.prepareQuery("SELECT public_key FROM credentials WHERE username = ?");
const query3 = db.prepareQuery("SELECT counter FROM credentials WHERE username = ?");
const query4 = db.prepareQuery("SELECT id FROM people WHERE username = ?");
const row = query.first([username]);
const row2 = query2.first([username]);
const row3 = query3.first([username]);
const row4 = query4.first([username]);
if (row && row2 && row3 && row4) {
const credID = row[0]
const publicKey = String(row2[0]);
const prevCounter = Number(row3[0]);
const userHandle = String(row4[0]);
const assertionExpectations = {
allowCredentials: [{
id: credID,
type: "public-key"
}],
challenge: challenge,
origin: "http://localhost:8000",
factor: "either",
publicKey: publicKey,
prevCounter: prevCounter,
userHandle: userHandle
};
try {
const clientAssertionResponse = {
id: base64urlToUint8Array(userRequest.rawId).buffer,
rawId: base64urlToUint8Array(userRequest.rawId).buffer,
response: {
clientDataJSON: userRequest.response.clientDataJSON,
authenticatorData: base64urlToUint8Array(userRequest.response.authenticatorData).buffer,
signature: userRequest.response.signature,
userHandle: userRequest.response.userHandle
}
};
const authnResult = await f2l.assertionResult(clientAssertionResponse, assertionExpectations); // will throw on error
console.log('End Fido2 authnResult success result: ',authnResult);
if (authnResult.authnrData) {
const newCounter = authnResult.authnrData.get("counter");
//From the WebAuthn Spec:
//If authData.signCount is nonzero or storedSignCount is nonzero, then run the following sub-step:
//If authData.signCount is
//greater than storedSignCount:
//Update storedSignCount to be the value of authData.signCount.
//less than or equal to storedSignCount:
//This is a signal that the authenticator may be cloned, i.e. at least two copies of the credential
// private key may exist and are being used in parallel. Relying Parties should incorporate this
// information into their risk scoring. Whether the Relying Party updates storedSignCount in this case,
// or not, or fails the authentication ceremony or not, is Relying Party-specific.
if (newCounter != 0 || prevCounter != 0) {
if (!(newCounter > prevCounter)) {
throw "Error: counter mismatch! Might be a risk."
} else {
try {
db.query("UPDATE credentials SET counter = ? WHERE username = ?",[newCounter,username]);
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
}
}
try {
deleteChallenge(username);
} catch (error) {
console.log("error in deleting challenge: ",error)
}
const newCookie = crypto.randomUUID();
try {
db.query("INSERT INTO cookies (cookie,id) VALUES (?,?)", [newCookie,userHandle]);
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
console.log("Cookie we are sending:",newCookie)
// Respond with a success message
return new Response(
JSON.stringify({ message: "Data received successfully!"}),
{ status: 200, headers: { "Content-Type": "application/json",
"Set-Cookie":`session_id=${newCookie}; path=/; HttpOnly; SameSite=Strict; Max-Age=3600`}
}
);
} else {
console.error("Counter value not present in authentication result.");
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error: ", error);
return new Response(
JSON.stringify({ error: "Login error." }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
} else {
console.error("Error: Fido2 not registered for user");
return new Response(
JSON.stringify({ error: "Login error." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("SQLite error:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
}
} catch (error) {
console.error("Error: ", error);
return new Response(
JSON.stringify({ error: "Login error." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error parsing JSON:", error);
return new Response(
JSON.stringify({ error: "Invalid JSON format" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
}
if (req.method === "GET" && pathname.substring(0,4) === "/Box") {
console.log("Service.png queried");
if (pathname.substring(4) === "/Service.png") {
try {
// Serve the HTML page
console.log("cookie header is:",String(cookieHeader))
console.log("Session ID is:",sessionId);
if (sessionId === undefined) {
//Forbidden
console.log("Session does not exist!")
return new Response(
JSON.stringify({ message: "Forbidden!" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
if (checkSessionExists(db,sessionId)) {
//Serve Box/index.html if session cookie exists
console.log("Session exists!")
const png = await servePNG();
return new Response(png, {
status: 200,
headers: { "Content-Type": "image/png" },
});
} else {
//Forbidden
console.log("Session does not exist!")
return new Response(
JSON.stringify({ message: "Forbidden!" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
} catch (error) {
console.error("Error serving HTML:", error);
return new Response("Internal Server Error", { status: 500 });
}
} else {
return new Response("404 Not Found", { status: 404 });
}
}
// Handle other methods or URLs (404 Not Found)
return new Response("404 Not Found", { status: 404 });
});