FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
solid-oidc/solid-oidc.js at gh-pages · JavaScriptSolidServer/solid-oidc · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
JavaScriptSolidServer
/
solid-oidc
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
3
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
solid-oidc
/
solid-oidc.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
726 lines (616 loc) · 23.6 KB
Breadcrumbs
solid-oidc
/
solid-oidc.js
Copy path
File metadata and controls
726 lines (616 loc) · 23.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/**
* solid-oidc.js - Minimal Solid-OIDC client for browsers
*
* A zero-build, zero-dependency, single-file Solid-OIDC authentication library.
*
*
@license
AGPL-3.0-or-later
*
@author
Melvin Carvalho
*
@see
https://github.com/JavaScriptSolidServer/solid-oidc
*
* Based on solid-oidc-client-browser by uvdsl (Christoph Braun)
*
@see
https://github.com/uvdsl/solid-oidc-client-browser
*
* Implements:
* - RFC 6749 - OAuth 2.0
* - RFC 7636 - PKCE
* - RFC 7638 - JWK Thumbprint
* - RFC 9207 - OAuth 2.0 Authorization Server Issuer Identification
* - RFC 9449 - DPoP (Demonstration of Proof-of-Possession)
* - Solid-OIDC Specification
*/
// ============================================================================
// Base64url Helpers
// ============================================================================
function
base64urlEncode
(
data
)
{
if
(
data
instanceof
ArrayBuffer
)
data
=
new
Uint8Array
(
data
)
return
btoa
(
String
.
fromCharCode
(
...
data
)
)
.
replace
(
/
\+
/
g
,
'-'
)
.
replace
(
/
\/
/
g
,
'_'
)
.
replace
(
/
=
+
$
/
,
''
)
}
function
base64urlDecode
(
str
)
{
str
=
str
.
replace
(
/
-
/
g
,
'+'
)
.
replace
(
/
_
/
g
,
'/'
)
while
(
str
.
length
%
4
)
str
+=
'='
return
Uint8Array
.
from
(
atob
(
str
)
,
c
=>
c
.
charCodeAt
(
0
)
)
}
// ============================================================================
// URL Helpers
// ============================================================================
// Normalize URLs by trimming a single trailing slash, so iss/issuer
// comparisons survive trailing-slash variance between OIDC discovery doc,
// redirect `iss` parameter, and token `iss` claim. RFC 9207 §2.3 requires
// comparison after normalization.
const
trimSlash
=
(
s
)
=>
(
typeof
s
===
'string'
&&
s
.
endsWith
(
'/'
)
)
?
s
.
slice
(
0
,
-
1
)
:
s
// ============================================================================
// Web Crypto JWT Helpers (replaces jose dependency)
// ============================================================================
function
decodeJwt
(
token
)
{
const
parts
=
token
.
split
(
'.'
)
if
(
parts
.
length
!==
3
)
throw
new
Error
(
'Invalid JWT'
)
return
JSON
.
parse
(
new
TextDecoder
(
)
.
decode
(
base64urlDecode
(
parts
[
1
]
)
)
)
}
async
function
signJWT
(
payload
,
privateKey
,
protectedHeader
)
{
const
header
=
base64urlEncode
(
new
TextEncoder
(
)
.
encode
(
JSON
.
stringify
(
protectedHeader
)
)
)
const
body
=
base64urlEncode
(
new
TextEncoder
(
)
.
encode
(
JSON
.
stringify
(
payload
)
)
)
const
signingInput
=
new
TextEncoder
(
)
.
encode
(
`
${
header
}
.
${
body
}
`
)
const
signature
=
await
crypto
.
subtle
.
sign
(
{
name
:
'ECDSA'
,
hash
:
{
name
:
'SHA-256'
}
}
,
privateKey
,
signingInput
)
return
`
${
header
}
.
${
body
}
.
${
base64urlEncode
(
signature
)
}
`
}
function
getImportAlgorithm
(
alg
)
{
const
algorithms
=
{
ES256
:
{
name
:
'ECDSA'
,
namedCurve
:
'P-256'
}
,
ES384
:
{
name
:
'ECDSA'
,
namedCurve
:
'P-384'
}
,
RS256
:
{
name
:
'RSASSA-PKCS1-v1_5'
,
hash
:
{
name
:
'SHA-256'
}
}
,
RS384
:
{
name
:
'RSASSA-PKCS1-v1_5'
,
hash
:
{
name
:
'SHA-384'
}
}
,
RS512
:
{
name
:
'RSASSA-PKCS1-v1_5'
,
hash
:
{
name
:
'SHA-512'
}
}
,
PS256
:
{
name
:
'RSA-PSS'
,
hash
:
{
name
:
'SHA-256'
}
}
,
PS384
:
{
name
:
'RSA-PSS'
,
hash
:
{
name
:
'SHA-384'
}
}
,
PS512
:
{
name
:
'RSA-PSS'
,
hash
:
{
name
:
'SHA-512'
}
}
}
if
(
!
algorithms
[
alg
]
)
throw
new
Error
(
`Unsupported algorithm:
${
alg
}
`
)
return
algorithms
[
alg
]
}
function
getVerifyAlgorithm
(
alg
)
{
if
(
alg
.
startsWith
(
'ES'
)
)
return
{
name
:
'ECDSA'
,
hash
:
{
name
:
`SHA-
${
alg
.
slice
(
2
)
}
`
}
}
if
(
alg
.
startsWith
(
'RS'
)
)
return
{
name
:
'RSASSA-PKCS1-v1_5'
}
if
(
alg
.
startsWith
(
'PS'
)
)
return
{
name
:
'RSA-PSS'
,
saltLength
:
parseInt
(
alg
.
slice
(
2
)
)
/
8
}
throw
new
Error
(
`Unsupported algorithm:
${
alg
}
`
)
}
async
function
verifyJWT
(
token
,
jwksUri
,
options
=
{
}
)
{
const
parts
=
token
.
split
(
'.'
)
if
(
parts
.
length
!==
3
)
throw
new
Error
(
'Invalid JWT'
)
const
header
=
JSON
.
parse
(
new
TextDecoder
(
)
.
decode
(
base64urlDecode
(
parts
[
0
]
)
)
)
const
payload
=
JSON
.
parse
(
new
TextDecoder
(
)
.
decode
(
base64urlDecode
(
parts
[
1
]
)
)
)
if
(
options
.
issuer
&&
trimSlash
(
payload
.
iss
)
!==
trimSlash
(
options
.
issuer
)
)
{
throw
new
Error
(
`Issuer mismatch:
${
payload
.
iss
}
!==
${
options
.
issuer
}
`
)
}
if
(
options
.
audience
)
{
const
aud
=
Array
.
isArray
(
payload
.
aud
)
?
payload
.
aud
:
[
payload
.
aud
]
if
(
!
aud
.
includes
(
options
.
audience
)
)
throw
new
Error
(
'Audience mismatch'
)
}
// Time-based claims (exp, nbf) with 60s clock skew tolerance
const
now
=
Math
.
floor
(
Date
.
now
(
)
/
1000
)
const
skew
=
60
if
(
typeof
payload
.
exp
===
'number'
&&
now
-
skew
>
payload
.
exp
)
{
throw
new
Error
(
'Token expired'
)
}
if
(
typeof
payload
.
nbf
===
'number'
&&
now
+
skew
<
payload
.
nbf
)
{
throw
new
Error
(
'Token not yet valid'
)
}
// Fetch JWKS and find matching key
const
response
=
await
fetch
(
jwksUri
)
if
(
!
response
.
ok
)
throw
new
Error
(
`JWKS fetch failed:
${
response
.
status
}
`
)
const
jwks
=
await
response
.
json
(
)
const
jwk
=
header
.
kid
?
jwks
.
keys
.
find
(
k
=>
k
.
kid
===
header
.
kid
)
:
jwks
.
keys
.
find
(
k
=>
k
.
alg
===
header
.
alg
||
(
!
k
.
alg
&&
(
!
k
.
use
||
k
.
use
===
'sig'
)
)
)
if
(
!
jwk
)
throw
new
Error
(
'No matching key found in JWKS'
)
const
publicKey
=
await
crypto
.
subtle
.
importKey
(
'jwk'
,
jwk
,
getImportAlgorithm
(
header
.
alg
)
,
false
,
[
'verify'
]
)
const
valid
=
await
crypto
.
subtle
.
verify
(
getVerifyAlgorithm
(
header
.
alg
)
,
publicKey
,
base64urlDecode
(
parts
[
2
]
)
,
new
TextEncoder
(
)
.
encode
(
`
${
parts
[
0
]
}
.
${
parts
[
1
]
}
`
)
)
if
(
!
valid
)
throw
new
Error
(
'Invalid signature'
)
return
{
payload
,
protectedHeader
:
header
}
}
/** JWK Thumbprint per RFC 7638 */
async
function
calculateJwkThumbprint
(
jwk
)
{
// Required members in lexicographic order per key type
let
thumbprintInput
if
(
jwk
.
kty
===
'EC'
)
{
thumbprintInput
=
JSON
.
stringify
(
{
crv
:
jwk
.
crv
,
kty
:
jwk
.
kty
,
x
:
jwk
.
x
,
y
:
jwk
.
y
}
)
}
else
if
(
jwk
.
kty
===
'RSA'
)
{
thumbprintInput
=
JSON
.
stringify
(
{
e
:
jwk
.
e
,
kty
:
jwk
.
kty
,
n
:
jwk
.
n
}
)
}
else
{
throw
new
Error
(
`Unsupported key type:
${
jwk
.
kty
}
`
)
}
const
digest
=
await
crypto
.
subtle
.
digest
(
'SHA-256'
,
new
TextEncoder
(
)
.
encode
(
thumbprintInput
)
)
return
base64urlEncode
(
digest
)
}
// ============================================================================
// Session Events
// ============================================================================
export
const
SessionEvents
=
{
STATE_CHANGE
:
'sessionStateChange'
,
EXPIRATION_WARNING
:
'sessionExpirationWarning'
,
EXPIRATION
:
'sessionExpiration'
}
// ============================================================================
// Session Database Interface (IndexedDB Implementation)
// ============================================================================
export
class
SessionDatabase
{
constructor
(
dbName
=
'solid-oidc'
,
storeName
=
'session'
,
dbVersion
=
1
)
{
this
.
dbName
=
dbName
this
.
storeName
=
storeName
this
.
dbVersion
=
dbVersion
this
.
db
=
null
}
async
init
(
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
const
request
=
indexedDB
.
open
(
this
.
dbName
,
this
.
dbVersion
)
request
.
onerror
=
(
)
=>
reject
(
new
Error
(
`Database error:
${
request
.
error
}
`
)
)
request
.
onsuccess
=
(
)
=>
{
this
.
db
=
request
.
result
resolve
(
this
)
}
request
.
onupgradeneeded
=
(
event
)
=>
{
const
db
=
event
.
target
.
result
if
(
!
db
.
objectStoreNames
.
contains
(
this
.
storeName
)
)
{
db
.
createObjectStore
(
this
.
storeName
)
}
}
}
)
}
async
setItem
(
id
,
value
)
{
if
(
!
this
.
db
)
await
this
.
init
(
)
return
new
Promise
(
(
resolve
,
reject
)
=>
{
const
tx
=
this
.
db
.
transaction
(
this
.
storeName
,
'readwrite'
)
tx
.
oncomplete
=
(
)
=>
resolve
(
)
tx
.
onerror
=
(
)
=>
reject
(
new
Error
(
`Transaction error:
${
tx
.
error
}
`
)
)
tx
.
objectStore
(
this
.
storeName
)
.
put
(
value
,
id
)
}
)
}
async
getItem
(
id
)
{
if
(
!
this
.
db
)
await
this
.
init
(
)
return
new
Promise
(
(
resolve
,
reject
)
=>
{
const
tx
=
this
.
db
.
transaction
(
this
.
storeName
,
'readonly'
)
tx
.
onerror
=
(
)
=>
reject
(
new
Error
(
`Transaction error:
${
tx
.
error
}
`
)
)
const
request
=
tx
.
objectStore
(
this
.
storeName
)
.
get
(
id
)
request
.
onsuccess
=
(
)
=>
resolve
(
request
.
result
||
null
)
}
)
}
async
deleteItem
(
id
)
{
if
(
!
this
.
db
)
await
this
.
init
(
)
return
new
Promise
(
(
resolve
,
reject
)
=>
{
const
tx
=
this
.
db
.
transaction
(
this
.
storeName
,
'readwrite'
)
tx
.
oncomplete
=
(
)
=>
resolve
(
)
tx
.
onerror
=
(
)
=>
reject
(
new
Error
(
`Transaction error:
${
tx
.
error
}
`
)
)
tx
.
objectStore
(
this
.
storeName
)
.
delete
(
id
)
}
)
}
async
clear
(
)
{
if
(
!
this
.
db
)
await
this
.
init
(
)
return
new
Promise
(
(
resolve
,
reject
)
=>
{
const
tx
=
this
.
db
.
transaction
(
this
.
storeName
,
'readwrite'
)
tx
.
oncomplete
=
(
)
=>
resolve
(
)
tx
.
onerror
=
(
)
=>
reject
(
new
Error
(
`Transaction error:
${
tx
.
error
}
`
)
)
tx
.
objectStore
(
this
.
storeName
)
.
clear
(
)
}
)
}
close
(
)
{
if
(
this
.
db
)
{
this
.
db
.
close
(
)
this
.
db
=
null
}
}
}
// ============================================================================
// PKCE Helper (RFC 7636)
// ============================================================================
async
function
generatePKCE
(
)
{
const
verifier
=
crypto
.
randomUUID
(
)
+
'-'
+
crypto
.
randomUUID
(
)
const
digest
=
new
Uint8Array
(
await
crypto
.
subtle
.
digest
(
'SHA-256'
,
new
TextEncoder
(
)
.
encode
(
verifier
)
)
)
const
challenge
=
btoa
(
String
.
fromCharCode
(
...
digest
)
)
.
replace
(
/
\+
/
g
,
'-'
)
.
replace
(
/
\/
/
g
,
'_'
)
.
replace
(
/
=
+
$
/
,
''
)
return
{
verifier
,
challenge
}
}
// ============================================================================
// DPoP Helper (RFC 9449)
// ============================================================================
async
function
createDPoPToken
(
keyPair
,
htu
,
htm
,
ath
=
null
)
{
const
publicJwk
=
await
crypto
.
subtle
.
exportKey
(
'jwk'
,
keyPair
.
publicKey
)
// Strip non-required fields for cleaner header
const
jwk
=
{
kty
:
publicJwk
.
kty
,
crv
:
publicJwk
.
crv
,
x
:
publicJwk
.
x
,
y
:
publicJwk
.
y
}
const
payload
=
{
htu
,
htm
,
iat
:
Math
.
floor
(
Date
.
now
(
)
/
1000
)
,
jti
:
crypto
.
randomUUID
(
)
}
if
(
ath
)
payload
.
ath
=
ath
return
signJWT
(
payload
,
keyPair
.
privateKey
,
{
alg
:
'ES256'
,
typ
:
'dpop+jwt'
,
jwk
}
)
}
async
function
computeAth
(
accessToken
)
{
const
data
=
new
TextEncoder
(
)
.
encode
(
accessToken
)
const
hashBuffer
=
await
crypto
.
subtle
.
digest
(
'SHA-256'
,
data
)
const
hashArray
=
Array
.
from
(
new
Uint8Array
(
hashBuffer
)
)
return
btoa
(
String
.
fromCharCode
(
...
hashArray
)
)
.
replace
(
/
\+
/
g
,
'-'
)
.
replace
(
/
\/
/
g
,
'_'
)
.
replace
(
/
=
+
$
/
,
''
)
}
// ============================================================================
// OIDC Discovery
// ============================================================================
async
function
discoverOIDC
(
idp
)
{
const
origin
=
new
URL
(
idp
)
.
origin
const
response
=
await
fetch
(
`
${
origin
}
/.well-known/openid-configuration`
)
if
(
!
response
.
ok
)
throw
new
Error
(
`OIDC discovery failed:
${
response
.
status
}
`
)
return
response
.
json
(
)
}
// ============================================================================
// Dynamic Client Registration
// ============================================================================
async
function
registerClient
(
registrationEndpoint
,
redirectUris
)
{
const
response
=
await
fetch
(
registrationEndpoint
,
{
method
:
'POST'
,
headers
:
{
'Content-Type'
:
'application/json'
}
,
body
:
JSON
.
stringify
(
{
application_type
:
'web'
,
redirect_uris
:
redirectUris
,
token_endpoint_auth_method
:
'none'
,
grant_types
:
[
'authorization_code'
,
'refresh_token'
]
,
response_types
:
[
'code'
]
,
scope
:
'openid offline_access webid'
}
)
}
)
if
(
!
response
.
ok
)
throw
new
Error
(
`Client registration failed:
${
response
.
status
}
`
)
return
response
.
json
(
)
}
// ============================================================================
// Token Request
// ============================================================================
async
function
requestTokens
(
tokenEndpoint
,
params
,
keyPair
)
{
const
dpop
=
await
createDPoPToken
(
keyPair
,
tokenEndpoint
,
'POST'
)
const
response
=
await
fetch
(
tokenEndpoint
,
{
method
:
'POST'
,
headers
:
{
'Content-Type'
:
'application/x-www-form-urlencoded'
,
'DPoP'
:
dpop
}
,
body
:
new
URLSearchParams
(
params
)
}
)
if
(
!
response
.
ok
)
throw
new
Error
(
`Token request failed:
${
response
.
status
}
`
)
return
response
.
json
(
)
}
// ============================================================================
// Token Validation
// ============================================================================
async
function
validateAccessToken
(
accessToken
,
jwksUri
,
issuer
,
clientId
,
keyPair
)
{
const
{
payload
}
=
await
verifyJWT
(
accessToken
,
jwksUri
,
{
issuer
,
audience
:
'solid'
}
)
// Verify DPoP binding
const
publicJwk
=
await
crypto
.
subtle
.
exportKey
(
'jwk'
,
keyPair
.
publicKey
)
const
thumbprint
=
await
calculateJwkThumbprint
(
publicJwk
)
if
(
payload
.
cnf
?.
jkt
!==
thumbprint
)
{
throw
new
Error
(
'DPoP thumbprint mismatch'
)
}
// Verify client_id
if
(
payload
.
client_id
!==
clientId
)
{
throw
new
Error
(
'client_id mismatch'
)
}
return
payload
}
// ============================================================================
// Refresh Token Grant
// ============================================================================
async
function
refreshTokens
(
database
)
{
await
database
.
init
(
)
const
[
refreshToken
,
tokenEndpoint
,
clientId
,
keyPair
]
=
await
Promise
.
all
(
[
database
.
getItem
(
'refresh_token'
)
,
database
.
getItem
(
'token_endpoint'
)
,
database
.
getItem
(
'client_id'
)
,
database
.
getItem
(
'dpop_keypair'
)
]
)
if
(
!
refreshToken
||
!
tokenEndpoint
||
!
clientId
||
!
keyPair
)
{
throw
new
Error
(
'Missing refresh data'
)
}
const
tokens
=
await
requestTokens
(
tokenEndpoint
,
{
grant_type
:
'refresh_token'
,
refresh_token
:
refreshToken
,
client_id
:
clientId
}
,
keyPair
)
// Persist new refresh token if provided
if
(
tokens
.
refresh_token
)
{
await
database
.
setItem
(
'refresh_token'
,
tokens
.
refresh_token
)
}
database
.
close
(
)
return
{
...
tokens
,
dpop_key_pair
:
keyPair
}
}
// ============================================================================
// Main Session Class
// ============================================================================
export
class
Session
extends
EventTarget
{
constructor
(
options
=
{
}
)
{
super
(
)
this
.
clientId
=
options
.
clientId
||
null
this
.
database
=
options
.
database
||
new
SessionDatabase
(
)
this
.
onStateChange
=
options
.
onStateChange
||
null
this
.
onExpirationWarning
=
options
.
onExpirationWarning
||
null
this
.
onExpiration
=
options
.
onExpiration
||
null
// Internal state
this
.
_isActive
=
false
this
.
_webId
=
null
this
.
_exp
=
null
this
.
_ath
=
null
this
.
_tokens
=
null
this
.
_idpDetails
=
null
this
.
_refreshPromise
=
null
// Bind so authFetch survives being passed by reference (drop-in fetch):
// consumers hand it to rdflib / solid-logic / rdf-dereference as a bare
// `fetch`, which would otherwise lose `this`.
this
.
authFetch
=
this
.
authFetch
.
bind
(
this
)
// Set up event listeners
if
(
this
.
onStateChange
)
{
this
.
addEventListener
(
SessionEvents
.
STATE_CHANGE
,
this
.
onStateChange
)
}
if
(
this
.
onExpirationWarning
)
{
this
.
addEventListener
(
SessionEvents
.
EXPIRATION_WARNING
,
this
.
onExpirationWarning
)
}
if
(
this
.
onExpiration
)
{
this
.
addEventListener
(
SessionEvents
.
EXPIRATION
,
this
.
onExpiration
)
}
}
// ==========================================================================
// Public API
// ==========================================================================
get
isActive
(
)
{
return
this
.
_isActive
}
get
webId
(
)
{
return
this
.
_webId
}
isExpired
(
)
{
if
(
!
this
.
_exp
)
return
true
return
Math
.
floor
(
Date
.
now
(
)
/
1000
)
>=
this
.
_exp
}
getExpiresIn
(
)
{
if
(
!
this
.
_exp
)
return
-
1
return
this
.
_exp
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
}
/**
* Redirect user to identity provider for login
*/
async
login
(
idp
,
redirectUri
)
{
// Sanitize redirect URI (RFC 6749 Section 3.1.2)
const
redirectUrl
=
new
URL
(
redirectUri
)
const
sanitizedRedirect
=
redirectUrl
.
origin
+
redirectUrl
.
pathname
+
redirectUrl
.
search
// OIDC Discovery
const
config
=
await
discoverOIDC
(
idp
)
// RFC 9207: Verify issuer
const
issuer
=
config
.
issuer
if
(
trimSlash
(
idp
)
!==
trimSlash
(
issuer
)
)
{
throw
new
Error
(
`Issuer mismatch:
${
issuer
}
!==
${
idp
}
`
)
}
// Store IDP details
sessionStorage
.
setItem
(
'solid_oidc_idp'
,
issuer
)
sessionStorage
.
setItem
(
'solid_oidc_token_endpoint'
,
config
.
token_endpoint
)
sessionStorage
.
setItem
(
'solid_oidc_jwks_uri'
,
config
.
jwks_uri
)
// Get or register client_id
let
clientId
=
this
.
clientId
if
(
!
clientId
)
{
const
registration
=
await
registerClient
(
config
.
registration_endpoint
,
[
sanitizedRedirect
]
)
clientId
=
registration
.
client_id
sessionStorage
.
setItem
(
'solid_oidc_client_id'
,
clientId
)
}
// PKCE (RFC 7636)
const
pkce
=
await
generatePKCE
(
)
sessionStorage
.
setItem
(
'solid_oidc_pkce_verifier'
,
pkce
.
verifier
)
// CSRF token
const
csrfToken
=
crypto
.
randomUUID
(
)
sessionStorage
.
setItem
(
'solid_oidc_csrf'
,
csrfToken
)
// Build authorization URL
const
authUrl
=
new
URL
(
config
.
authorization_endpoint
)
authUrl
.
searchParams
.
set
(
'response_type'
,
'code'
)
authUrl
.
searchParams
.
set
(
'redirect_uri'
,
sanitizedRedirect
)
authUrl
.
searchParams
.
set
(
'scope'
,
'openid offline_access webid'
)
authUrl
.
searchParams
.
set
(
'client_id'
,
clientId
)
authUrl
.
searchParams
.
set
(
'code_challenge_method'
,
'S256'
)
authUrl
.
searchParams
.
set
(
'code_challenge'
,
pkce
.
challenge
)
authUrl
.
searchParams
.
set
(
'state'
,
csrfToken
)
authUrl
.
searchParams
.
set
(
'prompt'
,
'consent'
)
// Redirect to IDP
window
.
location
.
href
=
authUrl
.
toString
(
)
}
/**
* Handle redirect from identity provider after login
*/
async
handleRedirectFromLogin
(
)
{
const
url
=
new
URL
(
window
.
location
.
href
)
const
code
=
url
.
searchParams
.
get
(
'code'
)
// No code = not a redirect, nothing to do
if
(
!
code
)
return
// RFC 9207: Verify issuer
const
idp
=
sessionStorage
.
getItem
(
'solid_oidc_idp'
)
const
iss
=
url
.
searchParams
.
get
(
'iss'
)
if
(
!
idp
||
trimSlash
(
iss
)
!==
trimSlash
(
idp
)
)
{
throw
new
Error
(
`Issuer mismatch:
${
iss
}
!==
${
idp
}
`
)
}
// RFC 6749: Verify CSRF token
const
csrf
=
sessionStorage
.
getItem
(
'solid_oidc_csrf'
)
if
(
url
.
searchParams
.
get
(
'state'
)
!==
csrf
)
{
throw
new
Error
(
'CSRF token mismatch'
)
}
// Clean URL
url
.
searchParams
.
delete
(
'code'
)
url
.
searchParams
.
delete
(
'iss'
)
url
.
searchParams
.
delete
(
'state'
)
window
.
history
.
replaceState
(
{
}
,
document
.
title
,
url
.
toString
(
)
)
// Get stored values
const
pkceVerifier
=
sessionStorage
.
getItem
(
'solid_oidc_pkce_verifier'
)
const
tokenEndpoint
=
sessionStorage
.
getItem
(
'solid_oidc_token_endpoint'
)
const
jwksUri
=
sessionStorage
.
getItem
(
'solid_oidc_jwks_uri'
)
const
clientId
=
this
.
clientId
||
sessionStorage
.
getItem
(
'solid_oidc_client_id'
)
if
(
!
pkceVerifier
||
!
tokenEndpoint
||
!
clientId
)
{
throw
new
Error
(
'Missing session data'
)
}
// Generate DPoP key pair (ES256 / P-256)
const
keyPair
=
await
crypto
.
subtle
.
generateKey
(
{
name
:
'ECDSA'
,
namedCurve
:
'P-256'
}
,
true
,
[
'sign'
,
'verify'
]
)
// Exchange code for tokens
const
tokens
=
await
requestTokens
(
tokenEndpoint
,
{
grant_type
:
'authorization_code'
,
code
,
code_verifier
:
pkceVerifier
,
redirect_uri
:
url
.
origin
+
url
.
pathname
,
client_id
:
clientId
}
,
keyPair
)
// Validate access token
await
validateAccessToken
(
tokens
.
access_token
,
jwksUri
,
idp
,
clientId
,
keyPair
)
// Store IDP details
this
.
_idpDetails
=
{
idp
,
jwksUri
,
tokenEndpoint
}
// Persist for refresh
await
this
.
database
.
init
(
)
await
Promise
.
all
(
[
this
.
database
.
setItem
(
'idp'
,
idp
)
,
this
.
database
.
setItem
(
'jwks_uri'
,
jwksUri
)
,
this
.
database
.
setItem
(
'token_endpoint'
,
tokenEndpoint
)
,
this
.
database
.
setItem
(
'client_id'
,
clientId
)
,
this
.
database
.
setItem
(
'dpop_keypair'
,
keyPair
)
,
this
.
database
.
setItem
(
'refresh_token'
,
tokens
.
refresh_token
)
]
)
this
.
database
.
close
(
)
// Clean session storage
sessionStorage
.
removeItem
(
'solid_oidc_idp'
)
sessionStorage
.
removeItem
(
'solid_oidc_token_endpoint'
)
sessionStorage
.
removeItem
(
'solid_oidc_jwks_uri'
)
sessionStorage
.
removeItem
(
'solid_oidc_client_id'
)
sessionStorage
.
removeItem
(
'solid_oidc_pkce_verifier'
)
sessionStorage
.
removeItem
(
'solid_oidc_csrf'
)
// Update session state
await
this
.
_setTokens
(
{
...
tokens
,
dpop_key_pair
:
keyPair
}
)
this
.
_dispatchStateChange
(
)
}
/**
* Restore session using stored refresh token
*/
async
restore
(
)
{
if
(
this
.
_refreshPromise
)
return
this
.
_refreshPromise
this
.
_refreshPromise
=
(
async
(
)
=>
{
try
{
const
tokens
=
await
refreshTokens
(
this
.
database
)
await
this
.
_setTokens
(
tokens
)
this
.
_dispatchStateChange
(
)
}
catch
(
error
)
{
if
(
this
.
_isActive
)
{
if
(
!
this
.
isExpired
(
)
)
{
this
.
_dispatchExpirationWarning
(
)
}
else
{
this
.
_dispatchExpiration
(
)
}
}
throw
error
}
finally
{
this
.
_refreshPromise
=
null
}
}
)
(
)
return
this
.
_refreshPromise
}
/**
* Log out and clear all session data
*/
async
logout
(
)
{
this
.
_isActive
=
false
this
.
_webId
=
null
this
.
_exp
=
null
this
.
_ath
=
null
this
.
_tokens
=
null
this
.
_idpDetails
=
null
await
this
.
database
.
init
(
)
await
this
.
database
.
clear
(
)
this
.
database
.
close
(
)
this
.
_dispatchStateChange
(
)
}
/**
* Make authenticated fetch request with DPoP
*/
async
authFetch
(
input
,
init
=
{
}
)
{
// No session = regular fetch
if
(
!
this
.
_isActive
)
{
return
fetch
(
input
,
init
)
}
// Refresh if expired
if
(
this
.
isExpired
(
)
)
{
await
this
.
restore
(
)
}
// Parse request
let
url
,
method
,
headers
if
(
input
instanceof
Request
)
{
url
=
new
URL
(
input
.
url
)
method
=
init
.
method
||
input
.
method
||
'GET'
headers
=
new
Headers
(
input
.
headers
)
}
else
{
url
=
new
URL
(
input
.
toString
(
)
)
method
=
init
.
method
||
'GET'
headers
=
init
.
headers
?
new
Headers
(
init
.
headers
)
:
new
Headers
(
)
}
// Create DPoP proof
const
dpop
=
await
createDPoPToken
(
this
.
_tokens
.
dpop_key_pair
,
`
${
url
.
origin
}
${
url
.
pathname
}
`
,
method
.
toUpperCase
(
)
,
this
.
_ath
)
// Set auth headers
headers
.
set
(
'DPoP'
,
dpop
)
headers
.
set
(
'Authorization'
,
`DPoP
${
this
.
_tokens
.
access_token
}
`
)
// Make request
if
(
input
instanceof
Request
)
{
return
fetch
(
new
Request
(
input
,
{
...
init
,
headers
}
)
)
}
return
fetch
(
url
,
{
...
init
,
headers
}
)
}
// ==========================================================================
// Internal Methods
// ==========================================================================
async
_setTokens
(
tokens
)
{
this
.
_tokens
=
tokens
const
decoded
=
decodeJwt
(
tokens
.
access_token
)
if
(
!
decoded
.
webid
)
throw
new
Error
(
'Missing webid claim'
)
if
(
!
decoded
.
exp
)
throw
new
Error
(
'Missing exp claim'
)
this
.
_ath
=
await
computeAth
(
tokens
.
access_token
)
this
.
_webId
=
decoded
.
webid
this
.
_exp
=
decoded
.
exp
this
.
_isActive
=
true
}
_dispatchStateChange
(
)
{
this
.
dispatchEvent
(
new
CustomEvent
(
SessionEvents
.
STATE_CHANGE
,
{
detail
:
{
isActive
:
this
.
_isActive
,
webId
:
this
.
_webId
}
}
)
)
}
_dispatchExpirationWarning
(
)
{
this
.
dispatchEvent
(
new
CustomEvent
(
SessionEvents
.
EXPIRATION_WARNING
,
{
detail
:
{
expires_in
:
this
.
getExpiresIn
(
)
}
}
)
)
}
_dispatchExpiration
(
)
{
this
.
dispatchEvent
(
new
CustomEvent
(
SessionEvents
.
EXPIRATION
)
)
}
}
// ============================================================================
// Default Export
// ============================================================================
export
default
Session
Back
|
FazBrowse Home
|
New Git URL