@inrupt/solid-client-authn-browser 1.11.8-alpha.1 → 1.11.8-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/ClientAuthentication.d.ts +18 -17
  2. package/dist/Session.d.ts +35 -35
  3. package/dist/constant.d.ts +2 -2
  4. package/dist/defaultSession.d.ts +9 -9
  5. package/dist/dependencies.d.ts +6 -6
  6. package/dist/iframe.d.ts +3 -3
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.es.js +1693 -0
  9. package/dist/index.js +1717 -27
  10. package/dist/login/AggregateLoginHandler.d.ts +4 -4
  11. package/dist/login/oidc/AggregateOidcHandler.d.ts +4 -4
  12. package/dist/login/oidc/ClientRegistrar.d.ts +6 -6
  13. package/dist/login/oidc/IssuerConfigFetcher.d.ts +8 -8
  14. package/dist/login/oidc/OidcLoginHandler.d.ts +10 -10
  15. package/dist/login/oidc/Redirector.d.ts +4 -4
  16. package/dist/login/oidc/oidcHandlers/AuthorizationCodeWithPkceOidcHandler.d.ts +8 -8
  17. package/dist/login/oidc/oidcHandlers/OidcHandlerCanHandleTest.d.ts +9 -9
  18. package/dist/login/oidc/redirectHandler/AggregateRedirectHandler.d.ts +4 -4
  19. package/dist/login/oidc/redirectHandler/AuthCodeRedirectHandler.d.ts +15 -15
  20. package/dist/login/oidc/redirectHandler/ErrorOidcHandler.d.ts +9 -9
  21. package/dist/login/oidc/redirectHandler/FallbackRedirectHandler.d.ts +7 -7
  22. package/dist/login/oidc/refresh/TokenRefresher.d.ts +10 -10
  23. package/dist/login/webid/WebIdLoginHandler.d.ts +5 -5
  24. package/dist/logout/GeneralLogoutHandler.d.ts +7 -7
  25. package/dist/sessionInfo/SessionInfoManager.d.ts +16 -16
  26. package/dist/solid-client-authn.bundle.js +1720 -2
  27. package/dist/storage/BrowserStorage.d.ts +7 -7
  28. package/dist/storage/StorageUtility.d.ts +4 -4
  29. package/dist/util/UuidGenerator.d.ts +6 -6
  30. package/dist/util/urlPath.d.ts +1 -1
  31. package/examples/demoClientApp/package-lock.json +67 -0
  32. package/examples/demoClientApp/package.json +2 -1
  33. package/examples/demoClientApp/src/DemoClientApp.js +9 -1
  34. package/jest.config.js +2 -1
  35. package/package.json +13 -10
  36. package/rollup.config.js +57 -0
  37. package/src/ClientAuthentication.spec.ts +69 -1
  38. package/src/ClientAuthentication.ts +32 -14
  39. package/src/login/oidc/oidcHandlers/AuthorizationCodeWithPkceOidcHandler.spec.ts +2 -9
  40. package/src/login/oidc/redirectHandler/__mocks__/RedirectHandler.ts +13 -0
  41. package/src/index.browser.spec.ts +0 -27
  42. package/src/index.browser.ts +0 -24
  43. package/webpack.browser.js +0 -19
  44. package/webpack.common.js +0 -22
  45. package/webpack.config.js +0 -8
  46. package/webpack.dev.js +0 -17
  47. package/webpack.prod.js +0 -3
package/dist/index.js CHANGED
@@ -1,27 +1,1717 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.InMemoryStorage = exports.ConfigurationError = exports.NotImplementedError = exports.getClientAuthenticationWithDependencies = exports.Session = void 0;
18
- var Session_1 = require("./Session");
19
- Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return Session_1.Session; } });
20
- var dependencies_1 = require("./dependencies");
21
- Object.defineProperty(exports, "getClientAuthenticationWithDependencies", { enumerable: true, get: function () { return dependencies_1.getClientAuthenticationWithDependencies; } });
22
- __exportStar(require("./defaultSession"), exports);
23
- var solid_client_authn_core_1 = require("@inrupt/solid-client-authn-core");
24
- Object.defineProperty(exports, "NotImplementedError", { enumerable: true, get: function () { return solid_client_authn_core_1.NotImplementedError; } });
25
- Object.defineProperty(exports, "ConfigurationError", { enumerable: true, get: function () { return solid_client_authn_core_1.ConfigurationError; } });
26
- Object.defineProperty(exports, "InMemoryStorage", { enumerable: true, get: function () { return solid_client_authn_core_1.InMemoryStorage; } });
27
- //# sourceMappingURL=index.js.map
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var solidClientAuthnCore = require('@inrupt/solid-client-authn-core');
6
+ var oidcClient = require('@inrupt/oidc-client');
7
+
8
+ var domain;
9
+
10
+ // This constructor is used to store event handlers. Instantiating this is
11
+ // faster than explicitly calling `Object.create(null)` to get a "clean" empty
12
+ // object (tested with v8 v4.9).
13
+ function EventHandlers() {}
14
+ EventHandlers.prototype = Object.create(null);
15
+
16
+ function EventEmitter() {
17
+ EventEmitter.init.call(this);
18
+ }
19
+
20
+ // nodejs oddity
21
+ // require('events') === require('events').EventEmitter
22
+ EventEmitter.EventEmitter = EventEmitter;
23
+
24
+ EventEmitter.usingDomains = false;
25
+
26
+ EventEmitter.prototype.domain = undefined;
27
+ EventEmitter.prototype._events = undefined;
28
+ EventEmitter.prototype._maxListeners = undefined;
29
+
30
+ // By default EventEmitters will print a warning if more than 10 listeners are
31
+ // added to it. This is a useful default which helps finding memory leaks.
32
+ EventEmitter.defaultMaxListeners = 10;
33
+
34
+ EventEmitter.init = function() {
35
+ this.domain = null;
36
+ if (EventEmitter.usingDomains) {
37
+ // if there is an active domain, then attach to it.
38
+ if (domain.active ) ;
39
+ }
40
+
41
+ if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
42
+ this._events = new EventHandlers();
43
+ this._eventsCount = 0;
44
+ }
45
+
46
+ this._maxListeners = this._maxListeners || undefined;
47
+ };
48
+
49
+ // Obviously not all Emitters should be limited to 10. This function allows
50
+ // that to be increased. Set to zero for unlimited.
51
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
52
+ if (typeof n !== 'number' || n < 0 || isNaN(n))
53
+ throw new TypeError('"n" argument must be a positive number');
54
+ this._maxListeners = n;
55
+ return this;
56
+ };
57
+
58
+ function $getMaxListeners(that) {
59
+ if (that._maxListeners === undefined)
60
+ return EventEmitter.defaultMaxListeners;
61
+ return that._maxListeners;
62
+ }
63
+
64
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
65
+ return $getMaxListeners(this);
66
+ };
67
+
68
+ // These standalone emit* functions are used to optimize calling of event
69
+ // handlers for fast cases because emit() itself often has a variable number of
70
+ // arguments and can be deoptimized because of that. These functions always have
71
+ // the same number of arguments and thus do not get deoptimized, so the code
72
+ // inside them can execute faster.
73
+ function emitNone(handler, isFn, self) {
74
+ if (isFn)
75
+ handler.call(self);
76
+ else {
77
+ var len = handler.length;
78
+ var listeners = arrayClone(handler, len);
79
+ for (var i = 0; i < len; ++i)
80
+ listeners[i].call(self);
81
+ }
82
+ }
83
+ function emitOne(handler, isFn, self, arg1) {
84
+ if (isFn)
85
+ handler.call(self, arg1);
86
+ else {
87
+ var len = handler.length;
88
+ var listeners = arrayClone(handler, len);
89
+ for (var i = 0; i < len; ++i)
90
+ listeners[i].call(self, arg1);
91
+ }
92
+ }
93
+ function emitTwo(handler, isFn, self, arg1, arg2) {
94
+ if (isFn)
95
+ handler.call(self, arg1, arg2);
96
+ else {
97
+ var len = handler.length;
98
+ var listeners = arrayClone(handler, len);
99
+ for (var i = 0; i < len; ++i)
100
+ listeners[i].call(self, arg1, arg2);
101
+ }
102
+ }
103
+ function emitThree(handler, isFn, self, arg1, arg2, arg3) {
104
+ if (isFn)
105
+ handler.call(self, arg1, arg2, arg3);
106
+ else {
107
+ var len = handler.length;
108
+ var listeners = arrayClone(handler, len);
109
+ for (var i = 0; i < len; ++i)
110
+ listeners[i].call(self, arg1, arg2, arg3);
111
+ }
112
+ }
113
+
114
+ function emitMany(handler, isFn, self, args) {
115
+ if (isFn)
116
+ handler.apply(self, args);
117
+ else {
118
+ var len = handler.length;
119
+ var listeners = arrayClone(handler, len);
120
+ for (var i = 0; i < len; ++i)
121
+ listeners[i].apply(self, args);
122
+ }
123
+ }
124
+
125
+ EventEmitter.prototype.emit = function emit(type) {
126
+ var er, handler, len, args, i, events, domain;
127
+ var doError = (type === 'error');
128
+
129
+ events = this._events;
130
+ if (events)
131
+ doError = (doError && events.error == null);
132
+ else if (!doError)
133
+ return false;
134
+
135
+ domain = this.domain;
136
+
137
+ // If there is no 'error' event listener then throw.
138
+ if (doError) {
139
+ er = arguments[1];
140
+ if (domain) {
141
+ if (!er)
142
+ er = new Error('Uncaught, unspecified "error" event');
143
+ er.domainEmitter = this;
144
+ er.domain = domain;
145
+ er.domainThrown = false;
146
+ domain.emit('error', er);
147
+ } else if (er instanceof Error) {
148
+ throw er; // Unhandled 'error' event
149
+ } else {
150
+ // At least give some kind of context to the user
151
+ var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
152
+ err.context = er;
153
+ throw err;
154
+ }
155
+ return false;
156
+ }
157
+
158
+ handler = events[type];
159
+
160
+ if (!handler)
161
+ return false;
162
+
163
+ var isFn = typeof handler === 'function';
164
+ len = arguments.length;
165
+ switch (len) {
166
+ // fast cases
167
+ case 1:
168
+ emitNone(handler, isFn, this);
169
+ break;
170
+ case 2:
171
+ emitOne(handler, isFn, this, arguments[1]);
172
+ break;
173
+ case 3:
174
+ emitTwo(handler, isFn, this, arguments[1], arguments[2]);
175
+ break;
176
+ case 4:
177
+ emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
178
+ break;
179
+ // slower
180
+ default:
181
+ args = new Array(len - 1);
182
+ for (i = 1; i < len; i++)
183
+ args[i - 1] = arguments[i];
184
+ emitMany(handler, isFn, this, args);
185
+ }
186
+
187
+ return true;
188
+ };
189
+
190
+ function _addListener(target, type, listener, prepend) {
191
+ var m;
192
+ var events;
193
+ var existing;
194
+
195
+ if (typeof listener !== 'function')
196
+ throw new TypeError('"listener" argument must be a function');
197
+
198
+ events = target._events;
199
+ if (!events) {
200
+ events = target._events = new EventHandlers();
201
+ target._eventsCount = 0;
202
+ } else {
203
+ // To avoid recursion in the case that type === "newListener"! Before
204
+ // adding it to the listeners, first emit "newListener".
205
+ if (events.newListener) {
206
+ target.emit('newListener', type,
207
+ listener.listener ? listener.listener : listener);
208
+
209
+ // Re-assign `events` because a newListener handler could have caused the
210
+ // this._events to be assigned to a new object
211
+ events = target._events;
212
+ }
213
+ existing = events[type];
214
+ }
215
+
216
+ if (!existing) {
217
+ // Optimize the case of one listener. Don't need the extra array object.
218
+ existing = events[type] = listener;
219
+ ++target._eventsCount;
220
+ } else {
221
+ if (typeof existing === 'function') {
222
+ // Adding the second element, need to change to array.
223
+ existing = events[type] = prepend ? [listener, existing] :
224
+ [existing, listener];
225
+ } else {
226
+ // If we've already got an array, just append.
227
+ if (prepend) {
228
+ existing.unshift(listener);
229
+ } else {
230
+ existing.push(listener);
231
+ }
232
+ }
233
+
234
+ // Check for listener leak
235
+ if (!existing.warned) {
236
+ m = $getMaxListeners(target);
237
+ if (m && m > 0 && existing.length > m) {
238
+ existing.warned = true;
239
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
240
+ existing.length + ' ' + type + ' listeners added. ' +
241
+ 'Use emitter.setMaxListeners() to increase limit');
242
+ w.name = 'MaxListenersExceededWarning';
243
+ w.emitter = target;
244
+ w.type = type;
245
+ w.count = existing.length;
246
+ emitWarning(w);
247
+ }
248
+ }
249
+ }
250
+
251
+ return target;
252
+ }
253
+ function emitWarning(e) {
254
+ typeof console.warn === 'function' ? console.warn(e) : console.log(e);
255
+ }
256
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
257
+ return _addListener(this, type, listener, false);
258
+ };
259
+
260
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
261
+
262
+ EventEmitter.prototype.prependListener =
263
+ function prependListener(type, listener) {
264
+ return _addListener(this, type, listener, true);
265
+ };
266
+
267
+ function _onceWrap(target, type, listener) {
268
+ var fired = false;
269
+ function g() {
270
+ target.removeListener(type, g);
271
+ if (!fired) {
272
+ fired = true;
273
+ listener.apply(target, arguments);
274
+ }
275
+ }
276
+ g.listener = listener;
277
+ return g;
278
+ }
279
+
280
+ EventEmitter.prototype.once = function once(type, listener) {
281
+ if (typeof listener !== 'function')
282
+ throw new TypeError('"listener" argument must be a function');
283
+ this.on(type, _onceWrap(this, type, listener));
284
+ return this;
285
+ };
286
+
287
+ EventEmitter.prototype.prependOnceListener =
288
+ function prependOnceListener(type, listener) {
289
+ if (typeof listener !== 'function')
290
+ throw new TypeError('"listener" argument must be a function');
291
+ this.prependListener(type, _onceWrap(this, type, listener));
292
+ return this;
293
+ };
294
+
295
+ // emits a 'removeListener' event iff the listener was removed
296
+ EventEmitter.prototype.removeListener =
297
+ function removeListener(type, listener) {
298
+ var list, events, position, i, originalListener;
299
+
300
+ if (typeof listener !== 'function')
301
+ throw new TypeError('"listener" argument must be a function');
302
+
303
+ events = this._events;
304
+ if (!events)
305
+ return this;
306
+
307
+ list = events[type];
308
+ if (!list)
309
+ return this;
310
+
311
+ if (list === listener || (list.listener && list.listener === listener)) {
312
+ if (--this._eventsCount === 0)
313
+ this._events = new EventHandlers();
314
+ else {
315
+ delete events[type];
316
+ if (events.removeListener)
317
+ this.emit('removeListener', type, list.listener || listener);
318
+ }
319
+ } else if (typeof list !== 'function') {
320
+ position = -1;
321
+
322
+ for (i = list.length; i-- > 0;) {
323
+ if (list[i] === listener ||
324
+ (list[i].listener && list[i].listener === listener)) {
325
+ originalListener = list[i].listener;
326
+ position = i;
327
+ break;
328
+ }
329
+ }
330
+
331
+ if (position < 0)
332
+ return this;
333
+
334
+ if (list.length === 1) {
335
+ list[0] = undefined;
336
+ if (--this._eventsCount === 0) {
337
+ this._events = new EventHandlers();
338
+ return this;
339
+ } else {
340
+ delete events[type];
341
+ }
342
+ } else {
343
+ spliceOne(list, position);
344
+ }
345
+
346
+ if (events.removeListener)
347
+ this.emit('removeListener', type, originalListener || listener);
348
+ }
349
+
350
+ return this;
351
+ };
352
+
353
+ // Alias for removeListener added in NodeJS 10.0
354
+ // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
355
+ EventEmitter.prototype.off = function(type, listener){
356
+ return this.removeListener(type, listener);
357
+ };
358
+
359
+ EventEmitter.prototype.removeAllListeners =
360
+ function removeAllListeners(type) {
361
+ var listeners, events;
362
+
363
+ events = this._events;
364
+ if (!events)
365
+ return this;
366
+
367
+ // not listening for removeListener, no need to emit
368
+ if (!events.removeListener) {
369
+ if (arguments.length === 0) {
370
+ this._events = new EventHandlers();
371
+ this._eventsCount = 0;
372
+ } else if (events[type]) {
373
+ if (--this._eventsCount === 0)
374
+ this._events = new EventHandlers();
375
+ else
376
+ delete events[type];
377
+ }
378
+ return this;
379
+ }
380
+
381
+ // emit removeListener for all listeners on all events
382
+ if (arguments.length === 0) {
383
+ var keys = Object.keys(events);
384
+ for (var i = 0, key; i < keys.length; ++i) {
385
+ key = keys[i];
386
+ if (key === 'removeListener') continue;
387
+ this.removeAllListeners(key);
388
+ }
389
+ this.removeAllListeners('removeListener');
390
+ this._events = new EventHandlers();
391
+ this._eventsCount = 0;
392
+ return this;
393
+ }
394
+
395
+ listeners = events[type];
396
+
397
+ if (typeof listeners === 'function') {
398
+ this.removeListener(type, listeners);
399
+ } else if (listeners) {
400
+ // LIFO order
401
+ do {
402
+ this.removeListener(type, listeners[listeners.length - 1]);
403
+ } while (listeners[0]);
404
+ }
405
+
406
+ return this;
407
+ };
408
+
409
+ EventEmitter.prototype.listeners = function listeners(type) {
410
+ var evlistener;
411
+ var ret;
412
+ var events = this._events;
413
+
414
+ if (!events)
415
+ ret = [];
416
+ else {
417
+ evlistener = events[type];
418
+ if (!evlistener)
419
+ ret = [];
420
+ else if (typeof evlistener === 'function')
421
+ ret = [evlistener.listener || evlistener];
422
+ else
423
+ ret = unwrapListeners(evlistener);
424
+ }
425
+
426
+ return ret;
427
+ };
428
+
429
+ EventEmitter.listenerCount = function(emitter, type) {
430
+ if (typeof emitter.listenerCount === 'function') {
431
+ return emitter.listenerCount(type);
432
+ } else {
433
+ return listenerCount.call(emitter, type);
434
+ }
435
+ };
436
+
437
+ EventEmitter.prototype.listenerCount = listenerCount;
438
+ function listenerCount(type) {
439
+ var events = this._events;
440
+
441
+ if (events) {
442
+ var evlistener = events[type];
443
+
444
+ if (typeof evlistener === 'function') {
445
+ return 1;
446
+ } else if (evlistener) {
447
+ return evlistener.length;
448
+ }
449
+ }
450
+
451
+ return 0;
452
+ }
453
+
454
+ EventEmitter.prototype.eventNames = function eventNames() {
455
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
456
+ };
457
+
458
+ // About 1.5x faster than the two-arg version of Array#splice().
459
+ function spliceOne(list, index) {
460
+ for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
461
+ list[i] = list[k];
462
+ list.pop();
463
+ }
464
+
465
+ function arrayClone(arr, i) {
466
+ var copy = new Array(i);
467
+ while (i--)
468
+ copy[i] = arr[i];
469
+ return copy;
470
+ }
471
+
472
+ function unwrapListeners(arr) {
473
+ var ret = new Array(arr.length);
474
+ for (var i = 0; i < ret.length; ++i) {
475
+ ret[i] = arr[i].listener || arr[i];
476
+ }
477
+ return ret;
478
+ }
479
+
480
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
481
+ // require the crypto API and do not support built-in fallback to lower quality random number
482
+ // generators (like Math.random()).
483
+ var getRandomValues;
484
+ var rnds8 = new Uint8Array(16);
485
+ function rng() {
486
+ // lazy load so that environments that need to polyfill have a chance to do so
487
+ if (!getRandomValues) {
488
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
489
+ // find the complete implementation of crypto (msCrypto) on IE11.
490
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
491
+
492
+ if (!getRandomValues) {
493
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
494
+ }
495
+ }
496
+
497
+ return getRandomValues(rnds8);
498
+ }
499
+
500
+ var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
501
+
502
+ function validate(uuid) {
503
+ return typeof uuid === 'string' && REGEX.test(uuid);
504
+ }
505
+
506
+ /**
507
+ * Convert array of 16 byte values to UUID string format of the form:
508
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
509
+ */
510
+
511
+ var byteToHex = [];
512
+
513
+ for (var i = 0; i < 256; ++i) {
514
+ byteToHex.push((i + 0x100).toString(16).substr(1));
515
+ }
516
+
517
+ function stringify(arr) {
518
+ var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
519
+ // Note: Be careful editing this code! It's been tuned for performance
520
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
521
+ var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
522
+ // of the following:
523
+ // - One or more input array values don't map to a hex octet (leading to
524
+ // "undefined" in the uuid)
525
+ // - Invalid input values for the RFC `version` or `variant` fields
526
+
527
+ if (!validate(uuid)) {
528
+ throw TypeError('Stringified UUID is invalid');
529
+ }
530
+
531
+ return uuid;
532
+ }
533
+
534
+ function v4(options, buf, offset) {
535
+ options = options || {};
536
+ var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
537
+
538
+ rnds[6] = rnds[6] & 0x0f | 0x40;
539
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
540
+
541
+ if (buf) {
542
+ offset = offset || 0;
543
+
544
+ for (var i = 0; i < 16; ++i) {
545
+ buf[offset + i] = rnds[i];
546
+ }
547
+
548
+ return buf;
549
+ }
550
+
551
+ return stringify(rnds);
552
+ }
553
+
554
+ class StorageUtilityBrowser extends solidClientAuthnCore.StorageUtility {
555
+ constructor(secureStorage, insecureStorage) {
556
+ super(secureStorage, insecureStorage);
557
+ }
558
+ }
559
+
560
+ function processErrorResponse(responseBody, options) {
561
+ var _a, _b, _c, _d;
562
+ if (responseBody.error === "invalid_redirect_uri") {
563
+ throw new Error(`Dynamic client registration failed: the provided redirect uri [${(_a = options.redirectUrl) === null || _a === void 0 ? void 0 : _a.toString()}] is invalid - ${(_b = responseBody.error_description) !== null && _b !== void 0 ? _b : ""}`);
564
+ }
565
+ if (responseBody.error === "invalid_client_metadata") {
566
+ throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(options)} is invalid - ${(_c = responseBody.error_description) !== null && _c !== void 0 ? _c : ""}`);
567
+ }
568
+ throw new Error(`Dynamic client registration failed: ${responseBody.error} - ${(_d = responseBody.error_description) !== null && _d !== void 0 ? _d : ""}`);
569
+ }
570
+ function validateRegistrationResponse(responseBody, options) {
571
+ if (responseBody.client_id === undefined) {
572
+ throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(responseBody)}`);
573
+ }
574
+ if (options.redirectUrl &&
575
+ (responseBody.redirect_uris === undefined ||
576
+ responseBody.redirect_uris[0] !== options.redirectUrl.toString())) {
577
+ throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(responseBody.redirect_uris)} don't match the provided ${JSON.stringify([
578
+ options.redirectUrl.toString(),
579
+ ])}`);
580
+ }
581
+ }
582
+ async function registerClient(options, issuerConfig) {
583
+ var _a;
584
+ if (!issuerConfig.registrationEndpoint) {
585
+ throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");
586
+ }
587
+ if (!Array.isArray(issuerConfig.idTokenSigningAlgValuesSupported)) {
588
+ throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");
589
+ }
590
+ const signingAlg = solidClientAuthnCore.determineSigningAlg(issuerConfig.idTokenSigningAlgValuesSupported, solidClientAuthnCore.PREFERRED_SIGNING_ALG);
591
+ const config = {
592
+ client_name: options.clientName,
593
+ application_type: "web",
594
+ redirect_uris: [(_a = options.redirectUrl) === null || _a === void 0 ? void 0 : _a.toString()],
595
+ subject_type: "public",
596
+ token_endpoint_auth_method: "client_secret_basic",
597
+ id_token_signed_response_alg: signingAlg,
598
+ grant_types: ["authorization_code", "refresh_token"],
599
+ };
600
+ const headers = {
601
+ "Content-Type": "application/json",
602
+ };
603
+ if (options.registrationAccessToken) {
604
+ headers.Authorization = `Bearer ${options.registrationAccessToken}`;
605
+ }
606
+ const registerResponse = await fetch(issuerConfig.registrationEndpoint.toString(), {
607
+ method: "POST",
608
+ headers,
609
+ body: JSON.stringify(config),
610
+ });
611
+ if (registerResponse.ok) {
612
+ const responseBody = await registerResponse.json();
613
+ validateRegistrationResponse(responseBody, options);
614
+ return {
615
+ clientId: responseBody.client_id,
616
+ clientSecret: responseBody.client_secret,
617
+ idTokenSignedResponseAlg: responseBody.id_token_signed_response_alg,
618
+ clientType: "dynamic",
619
+ };
620
+ }
621
+ if (registerResponse.status === 400) {
622
+ processErrorResponse(await registerResponse.json(), options);
623
+ }
624
+ throw new Error(`Dynamic client registration failed: the server returned ${registerResponse.status} ${registerResponse.statusText} - ${await registerResponse.text()}`);
625
+ }
626
+
627
+ function hasError(value) {
628
+ return value.error !== undefined && typeof value.error === "string";
629
+ }
630
+ function hasErrorDescription(value) {
631
+ return (value.error_description !== undefined &&
632
+ typeof value.error_description === "string");
633
+ }
634
+ function hasErrorUri(value) {
635
+ return value.error_uri !== undefined && typeof value.error_uri === "string";
636
+ }
637
+ function hasAccessToken(value) {
638
+ return (value.access_token !== undefined && typeof value.access_token === "string");
639
+ }
640
+ function hasIdToken(value) {
641
+ return value.id_token !== undefined && typeof value.id_token === "string";
642
+ }
643
+ function hasRefreshToken(value) {
644
+ return (value.refresh_token !== undefined && typeof value.refresh_token === "string");
645
+ }
646
+ function hasTokenType(value) {
647
+ return value.token_type !== undefined && typeof value.token_type === "string";
648
+ }
649
+ function hasExpiresIn(value) {
650
+ return value.expires_in === undefined || typeof value.expires_in === "number";
651
+ }
652
+ function validatePreconditions(issuer, data) {
653
+ if (data.grantType &&
654
+ (!issuer.grantTypesSupported ||
655
+ !issuer.grantTypesSupported.includes(data.grantType))) {
656
+ throw new Error(`The issuer [${issuer.issuer}] does not support the [${data.grantType}] grant`);
657
+ }
658
+ if (!issuer.tokenEndpoint) {
659
+ throw new Error(`This issuer [${issuer.issuer}] does not have a token endpoint`);
660
+ }
661
+ }
662
+ function validateTokenEndpointResponse(tokenResponse, dpop) {
663
+ if (hasError(tokenResponse)) {
664
+ throw new solidClientAuthnCore.OidcProviderError(`Token endpoint returned error [${tokenResponse.error}]${hasErrorDescription(tokenResponse)
665
+ ? `: ${tokenResponse.error_description}`
666
+ : ""}${hasErrorUri(tokenResponse) ? ` (see ${tokenResponse.error_uri})` : ""}`, tokenResponse.error, hasErrorDescription(tokenResponse)
667
+ ? tokenResponse.error_description
668
+ : undefined);
669
+ }
670
+ if (!hasAccessToken(tokenResponse)) {
671
+ throw new solidClientAuthnCore.InvalidResponseError(["access_token"]);
672
+ }
673
+ if (!hasIdToken(tokenResponse)) {
674
+ throw new solidClientAuthnCore.InvalidResponseError(["id_token"]);
675
+ }
676
+ if (!hasTokenType(tokenResponse)) {
677
+ throw new solidClientAuthnCore.InvalidResponseError(["token_type"]);
678
+ }
679
+ if (!hasExpiresIn(tokenResponse)) {
680
+ throw new solidClientAuthnCore.InvalidResponseError(["expires_in"]);
681
+ }
682
+ if (!dpop && tokenResponse.token_type.toLowerCase() !== "bearer") {
683
+ throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${tokenResponse.token_type}].`);
684
+ }
685
+ return tokenResponse;
686
+ }
687
+ async function getTokens(issuer, client, data, dpop) {
688
+ validatePreconditions(issuer, data);
689
+ const headers = {
690
+ "content-type": "application/x-www-form-urlencoded",
691
+ };
692
+ let dpopKey;
693
+ if (dpop) {
694
+ dpopKey = await solidClientAuthnCore.generateDpopKeyPair();
695
+ headers.DPoP = await solidClientAuthnCore.createDpopHeader(issuer.tokenEndpoint, "POST", dpopKey);
696
+ }
697
+ if (client.clientSecret) {
698
+ headers.Authorization = `Basic ${btoa(`${client.clientId}:${client.clientSecret}`)}`;
699
+ }
700
+ const requestBody = {
701
+ grant_type: data.grantType,
702
+ redirect_uri: data.redirectUrl,
703
+ code: data.code,
704
+ code_verifier: data.codeVerifier,
705
+ client_id: client.clientId,
706
+ };
707
+ const tokenRequestInit = {
708
+ method: "POST",
709
+ headers,
710
+ body: new URLSearchParams(requestBody).toString(),
711
+ };
712
+ const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
713
+ const jsonTokenResponse = (await rawTokenResponse.json());
714
+ const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
715
+ const webId = await solidClientAuthnCore.getWebidFromTokenPayload(tokenResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);
716
+ return {
717
+ accessToken: tokenResponse.access_token,
718
+ idToken: tokenResponse.id_token,
719
+ refreshToken: hasRefreshToken(tokenResponse)
720
+ ? tokenResponse.refresh_token
721
+ : undefined,
722
+ webId,
723
+ dpopKey,
724
+ expiresIn: tokenResponse.expires_in,
725
+ };
726
+ }
727
+ async function getBearerToken(redirectUrl) {
728
+ let signinResponse;
729
+ try {
730
+ const client = new oidcClient.OidcClient({
731
+ response_mode: "query",
732
+ loadUserInfo: false,
733
+ });
734
+ signinResponse = await client.processSigninResponse(redirectUrl);
735
+ if (client.settings.metadata === undefined) {
736
+ throw new Error("Cannot retrieve issuer metadata from client information in storage.");
737
+ }
738
+ if (client.settings.metadata.jwks_uri === undefined) {
739
+ throw new Error("Missing some issuer metadata from client information in storage: 'jwks_uri' is undefined");
740
+ }
741
+ if (client.settings.metadata.issuer === undefined) {
742
+ throw new Error("Missing some issuer metadata from client information in storage: 'issuer' is undefined");
743
+ }
744
+ if (client.settings.client_id === undefined) {
745
+ throw new Error("Missing some client information in storage: 'client_id' is undefined");
746
+ }
747
+ const webId = await solidClientAuthnCore.getWebidFromTokenPayload(signinResponse.id_token, client.settings.metadata.jwks_uri, client.settings.metadata.issuer, client.settings.client_id);
748
+ return {
749
+ accessToken: signinResponse.access_token,
750
+ idToken: signinResponse.id_token,
751
+ webId,
752
+ refreshToken: signinResponse.refresh_token,
753
+ };
754
+ }
755
+ catch (err) {
756
+ throw new Error(`Problem handling Auth Code Grant (Flow) redirect - URL [${redirectUrl}]: ${err}`);
757
+ }
758
+ }
759
+ async function getDpopToken(issuer, client, data) {
760
+ return getTokens(issuer, client, data, true);
761
+ }
762
+
763
+ async function refresh(refreshToken, issuer, client, dpopKey) {
764
+ const requestBody = {
765
+ grant_type: "refresh_token",
766
+ refresh_token: refreshToken,
767
+ scope: "openid offline_access",
768
+ };
769
+ let dpopHeader = {};
770
+ if (dpopKey !== undefined) {
771
+ dpopHeader = {
772
+ DPoP: await solidClientAuthnCore.createDpopHeader(issuer.tokenEndpoint, "POST", dpopKey),
773
+ };
774
+ }
775
+ let authHeader = {};
776
+ if (client.clientSecret !== undefined) {
777
+ authHeader = {
778
+ Authorization: `Basic ${btoa(`${client.clientId}:${client.clientSecret}`)}`,
779
+ };
780
+ }
781
+ const rawResponse = await fetch(issuer.tokenEndpoint, {
782
+ method: "POST",
783
+ body: new URLSearchParams(requestBody).toString(),
784
+ headers: {
785
+ ...dpopHeader,
786
+ ...authHeader,
787
+ "Content-Type": "application/x-www-form-urlencoded",
788
+ },
789
+ });
790
+ let response;
791
+ try {
792
+ response = await rawResponse.json();
793
+ }
794
+ catch (e) {
795
+ throw new Error(`The token endpoint of issuer ${issuer.issuer} returned a malformed response.`);
796
+ }
797
+ const validatedResponse = validateTokenEndpointResponse(response, dpopKey !== undefined);
798
+ const webId = await solidClientAuthnCore.getWebidFromTokenPayload(validatedResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);
799
+ return {
800
+ accessToken: validatedResponse.access_token,
801
+ idToken: validatedResponse.id_token,
802
+ refreshToken: typeof validatedResponse.refresh_token === "string"
803
+ ? validatedResponse.refresh_token
804
+ : undefined,
805
+ webId,
806
+ dpopKey,
807
+ expiresIn: validatedResponse.expires_in,
808
+ };
809
+ }
810
+
811
+ function removeOidcQueryParam(redirectUrl) {
812
+ const cleanedUrl = new URL(redirectUrl);
813
+ cleanedUrl.searchParams.delete("code");
814
+ cleanedUrl.searchParams.delete("state");
815
+ cleanedUrl.hash = "";
816
+ return cleanedUrl.toString();
817
+ }
818
+ async function clearOidcPersistentStorage() {
819
+ const client = new oidcClient.OidcClient({
820
+ response_mode: "query",
821
+ });
822
+ await client.clearStaleState(new oidcClient.WebStorageStateStore({}));
823
+ const myStorage = window.localStorage;
824
+ const itemsToRemove = [];
825
+ for (let i = 0; i <= myStorage.length; i += 1) {
826
+ const key = myStorage.key(i);
827
+ if (key &&
828
+ (key.match(/^oidc\..+$/) ||
829
+ key.match(/^solidClientAuthenticationUser:.+$/))) {
830
+ itemsToRemove.push(key);
831
+ }
832
+ }
833
+ itemsToRemove.forEach((key) => myStorage.removeItem(key));
834
+ }
835
+
836
+ const globalFetch = (request, init) => window.fetch(request, init);
837
+ class ClientAuthentication {
838
+ constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
839
+ this.loginHandler = loginHandler;
840
+ this.redirectHandler = redirectHandler;
841
+ this.logoutHandler = logoutHandler;
842
+ this.sessionInfoManager = sessionInfoManager;
843
+ this.issuerConfigFetcher = issuerConfigFetcher;
844
+ this.login = async (options, eventEmitter) => {
845
+ var _a, _b;
846
+ await this.sessionInfoManager.clear(options.sessionId);
847
+ const redirectUrl = removeOidcQueryParam((_a = options.redirectUrl) !== null && _a !== void 0 ? _a : window.location.href);
848
+ await this.loginHandler.handle({
849
+ ...options,
850
+ redirectUrl,
851
+ clientName: (_b = options.clientName) !== null && _b !== void 0 ? _b : options.clientId,
852
+ eventEmitter,
853
+ });
854
+ };
855
+ this.fetch = globalFetch;
856
+ this.logout = async (sessionId) => {
857
+ await this.logoutHandler.handle(sessionId);
858
+ this.fetch = globalFetch;
859
+ };
860
+ this.getSessionInfo = async (sessionId) => {
861
+ return this.sessionInfoManager.get(sessionId);
862
+ };
863
+ this.getAllSessionInfo = async () => {
864
+ return this.sessionInfoManager.getAll();
865
+ };
866
+ this.validateCurrentSession = async (currentSessionId) => {
867
+ const sessionInfo = await this.sessionInfoManager.get(currentSessionId);
868
+ if (sessionInfo === undefined ||
869
+ sessionInfo.clientAppId === undefined ||
870
+ sessionInfo.issuer === undefined) {
871
+ return null;
872
+ }
873
+ return sessionInfo;
874
+ };
875
+ this.handleIncomingRedirect = async (url, eventEmitter) => {
876
+ try {
877
+ const redirectInfo = await this.redirectHandler.handle(url, eventEmitter);
878
+ this.fetch = redirectInfo.fetch.bind(window);
879
+ this.cleanUrlAfterRedirect(url);
880
+ return {
881
+ isLoggedIn: redirectInfo.isLoggedIn,
882
+ webId: redirectInfo.webId,
883
+ sessionId: redirectInfo.sessionId,
884
+ expirationDate: redirectInfo.expirationDate,
885
+ };
886
+ }
887
+ catch (err) {
888
+ this.cleanUrlAfterRedirect(url);
889
+ eventEmitter.emit(solidClientAuthnCore.EVENTS.ERROR, "redirect", err);
890
+ }
891
+ };
892
+ }
893
+ cleanUrlAfterRedirect(url) {
894
+ const cleanedUpUrl = new URL(url);
895
+ cleanedUpUrl.searchParams.delete("state");
896
+ cleanedUpUrl.searchParams.delete("code");
897
+ cleanedUpUrl.searchParams.delete("id_token");
898
+ cleanedUpUrl.searchParams.delete("access_token");
899
+ cleanedUpUrl.searchParams.delete("error");
900
+ cleanedUpUrl.searchParams.delete("error_description");
901
+ window.history.replaceState(null, "", cleanedUpUrl.toString());
902
+ }
903
+ }
904
+
905
+ function hasIssuer(options) {
906
+ return typeof options.oidcIssuer === "string";
907
+ }
908
+ function hasRedirectUrl(options) {
909
+ return typeof options.redirectUrl === "string";
910
+ }
911
+ class OidcLoginHandler {
912
+ constructor(storageUtility, oidcHandler, issuerConfigFetcher, clientRegistrar) {
913
+ this.storageUtility = storageUtility;
914
+ this.oidcHandler = oidcHandler;
915
+ this.issuerConfigFetcher = issuerConfigFetcher;
916
+ this.clientRegistrar = clientRegistrar;
917
+ }
918
+ async canHandle(options) {
919
+ return hasIssuer(options) && hasRedirectUrl(options);
920
+ }
921
+ async handle(options) {
922
+ if (!hasIssuer(options)) {
923
+ throw new solidClientAuthnCore.ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(options)}`);
924
+ }
925
+ if (!hasRedirectUrl(options)) {
926
+ throw new solidClientAuthnCore.ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(options)}`);
927
+ }
928
+ const issuerConfig = await this.issuerConfigFetcher.fetchConfig(options.oidcIssuer);
929
+ const clientRegistration = await solidClientAuthnCore.handleRegistration(options, issuerConfig, this.storageUtility, this.clientRegistrar);
930
+ const OidcOptions = {
931
+ issuer: issuerConfig.issuer,
932
+ dpop: options.tokenType.toLowerCase() === "dpop",
933
+ ...options,
934
+ issuerConfiguration: issuerConfig,
935
+ client: clientRegistration,
936
+ };
937
+ return this.oidcHandler.handle(OidcOptions);
938
+ }
939
+ }
940
+
941
+ class AuthorizationCodeWithPkceOidcHandler {
942
+ constructor(storageUtility, redirector) {
943
+ this.storageUtility = storageUtility;
944
+ this.redirector = redirector;
945
+ }
946
+ async canHandle(oidcLoginOptions) {
947
+ return !!(oidcLoginOptions.issuerConfiguration.grantTypesSupported &&
948
+ oidcLoginOptions.issuerConfiguration.grantTypesSupported.indexOf("authorization_code") > -1);
949
+ }
950
+ async handle(oidcLoginOptions) {
951
+ var _a;
952
+ const oidcOptions = {
953
+ authority: oidcLoginOptions.issuer.toString(),
954
+ client_id: oidcLoginOptions.client.clientId,
955
+ client_secret: oidcLoginOptions.client.clientSecret,
956
+ redirect_uri: oidcLoginOptions.redirectUrl.toString(),
957
+ post_logout_redirect_uri: oidcLoginOptions.redirectUrl.toString(),
958
+ response_type: "code",
959
+ scope: "openid offline_access webid",
960
+ filterProtocolClaims: true,
961
+ loadUserInfo: false,
962
+ code_verifier: true,
963
+ prompt: (_a = oidcLoginOptions.prompt) !== null && _a !== void 0 ? _a : "consent",
964
+ };
965
+ const oidcClientLibrary = new oidcClient.OidcClient(oidcOptions);
966
+ const { redirector } = this;
967
+ const storage = this.storageUtility;
968
+ try {
969
+ const signingRequest = await oidcClientLibrary.createSigninRequest();
970
+ await Promise.all([
971
+ storage.setForUser(signingRequest.state._id, {
972
+ sessionId: oidcLoginOptions.sessionId,
973
+ }),
974
+ storage.setForUser(oidcLoginOptions.sessionId, {
975
+ codeVerifier: signingRequest.state._code_verifier,
976
+ issuer: oidcLoginOptions.issuer.toString(),
977
+ redirectUrl: oidcLoginOptions.redirectUrl,
978
+ dpop: oidcLoginOptions.dpop ? "true" : "false",
979
+ }),
980
+ ]);
981
+ redirector.redirect(signingRequest.url.toString(), {
982
+ handleRedirect: oidcLoginOptions.handleRedirect,
983
+ redirectInIframe: oidcLoginOptions.inIframe,
984
+ });
985
+ }
986
+ catch (err) {
987
+ console.error(err);
988
+ }
989
+ return undefined;
990
+ }
991
+ }
992
+
993
+ function appendToUrlPathname(url, append) {
994
+ const parsedUrl = new URL(url);
995
+ const path = parsedUrl.pathname;
996
+ parsedUrl.pathname = `${path}${path.endsWith("/") ? "" : "/"}${append.startsWith("/") ? append.substring(1) : append}`;
997
+ return parsedUrl.toString();
998
+ }
999
+
1000
+ const WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
1001
+ const issuerConfigKeyMap = {
1002
+ issuer: {
1003
+ toKey: "issuer",
1004
+ convertToUrl: true,
1005
+ },
1006
+ authorization_endpoint: {
1007
+ toKey: "authorizationEndpoint",
1008
+ convertToUrl: true,
1009
+ },
1010
+ token_endpoint: {
1011
+ toKey: "tokenEndpoint",
1012
+ convertToUrl: true,
1013
+ },
1014
+ userinfo_endpoint: {
1015
+ toKey: "userinfoEndpoint",
1016
+ convertToUrl: true,
1017
+ },
1018
+ jwks_uri: {
1019
+ toKey: "jwksUri",
1020
+ convertToUrl: true,
1021
+ },
1022
+ registration_endpoint: {
1023
+ toKey: "registrationEndpoint",
1024
+ convertToUrl: true,
1025
+ },
1026
+ scopes_supported: { toKey: "scopesSupported" },
1027
+ response_types_supported: { toKey: "responseTypesSupported" },
1028
+ response_modes_supported: { toKey: "responseModesSupported" },
1029
+ grant_types_supported: { toKey: "grantTypesSupported" },
1030
+ acr_values_supported: { toKey: "acrValuesSupported" },
1031
+ subject_types_supported: { toKey: "subjectTypesSupported" },
1032
+ id_token_signing_alg_values_supported: {
1033
+ toKey: "idTokenSigningAlgValuesSupported",
1034
+ },
1035
+ id_token_encryption_alg_values_supported: {
1036
+ toKey: "idTokenEncryptionAlgValuesSupported",
1037
+ },
1038
+ id_token_encryption_enc_values_supported: {
1039
+ toKey: "idTokenEncryptionEncValuesSupported",
1040
+ },
1041
+ userinfo_signing_alg_values_supported: {
1042
+ toKey: "userinfoSigningAlgValuesSupported",
1043
+ },
1044
+ userinfo_encryption_alg_values_supported: {
1045
+ toKey: "userinfoEncryptionAlgValuesSupported",
1046
+ },
1047
+ userinfo_encryption_enc_values_supported: {
1048
+ toKey: "userinfoEncryptionEncValuesSupported",
1049
+ },
1050
+ request_object_signing_alg_values_supported: {
1051
+ toKey: "requestObjectSigningAlgValuesSupported",
1052
+ },
1053
+ request_object_encryption_alg_values_supported: {
1054
+ toKey: "requestObjectEncryptionAlgValuesSupported",
1055
+ },
1056
+ request_object_encryption_enc_values_supported: {
1057
+ toKey: "requestObjectEncryptionEncValuesSupported",
1058
+ },
1059
+ token_endpoint_auth_methods_supported: {
1060
+ toKey: "tokenEndpointAuthMethodsSupported",
1061
+ },
1062
+ token_endpoint_auth_signing_alg_values_supported: {
1063
+ toKey: "tokenEndpointAuthSigningAlgValuesSupported",
1064
+ },
1065
+ display_values_supported: { toKey: "displayValuesSupported" },
1066
+ claim_types_supported: { toKey: "claimTypesSupported" },
1067
+ claims_supported: { toKey: "claimsSupported" },
1068
+ service_documentation: { toKey: "serviceDocumentation" },
1069
+ claims_locales_supported: { toKey: "claimsLocalesSupported" },
1070
+ ui_locales_supported: { toKey: "uiLocalesSupported" },
1071
+ claims_parameter_supported: { toKey: "claimsParameterSupported" },
1072
+ request_parameter_supported: { toKey: "requestParameterSupported" },
1073
+ request_uri_parameter_supported: { toKey: "requestUriParameterSupported" },
1074
+ require_request_uri_registration: { toKey: "requireRequestUriRegistration" },
1075
+ op_policy_uri: {
1076
+ toKey: "opPolicyUri",
1077
+ convertToUrl: true,
1078
+ },
1079
+ op_tos_uri: {
1080
+ toKey: "opTosUri",
1081
+ convertToUrl: true,
1082
+ },
1083
+ };
1084
+ function processConfig(config) {
1085
+ const parsedConfig = {};
1086
+ Object.keys(config).forEach((key) => {
1087
+ if (issuerConfigKeyMap[key]) {
1088
+ parsedConfig[issuerConfigKeyMap[key].toKey] = config[key];
1089
+ }
1090
+ });
1091
+ if (!Array.isArray(parsedConfig.scopesSupported)) {
1092
+ parsedConfig.scopesSupported = ["openid"];
1093
+ }
1094
+ return parsedConfig;
1095
+ }
1096
+ class IssuerConfigFetcher {
1097
+ constructor(storageUtility) {
1098
+ this.storageUtility = storageUtility;
1099
+ }
1100
+ static getLocalStorageKey(issuer) {
1101
+ return `issuerConfig:${issuer}`;
1102
+ }
1103
+ async fetchConfig(issuer) {
1104
+ let issuerConfig;
1105
+ const openIdConfigUrl = appendToUrlPathname(issuer, WELL_KNOWN_OPENID_CONFIG);
1106
+ const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
1107
+ try {
1108
+ issuerConfig = processConfig(await issuerConfigRequestBody.json());
1109
+ }
1110
+ catch (err) {
1111
+ throw new solidClientAuthnCore.ConfigurationError(`[${issuer.toString()}] has an invalid configuration: ${err.message}`);
1112
+ }
1113
+ await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(issuer), JSON.stringify(issuerConfig));
1114
+ return issuerConfig;
1115
+ }
1116
+ }
1117
+
1118
+ function getUnauthenticatedSession() {
1119
+ return {
1120
+ isLoggedIn: false,
1121
+ sessionId: v4(),
1122
+ fetch,
1123
+ };
1124
+ }
1125
+ async function clear(sessionId, storage) {
1126
+ await Promise.all([
1127
+ storage.deleteAllUserData(sessionId, { secure: false }),
1128
+ storage.deleteAllUserData(sessionId, { secure: true }),
1129
+ storage.delete("clientKey", { secure: false }),
1130
+ ]);
1131
+ await clearOidcPersistentStorage();
1132
+ }
1133
+ class SessionInfoManager {
1134
+ constructor(storageUtility) {
1135
+ this.storageUtility = storageUtility;
1136
+ }
1137
+ update(_sessionId, _options) {
1138
+ throw new Error("Not Implemented");
1139
+ }
1140
+ async get(sessionId) {
1141
+ var _a;
1142
+ const isLoggedIn = await this.storageUtility.getForUser(sessionId, "isLoggedIn", {
1143
+ secure: true,
1144
+ });
1145
+ const webId = await this.storageUtility.getForUser(sessionId, "webId", {
1146
+ secure: true,
1147
+ });
1148
+ const clientId = await this.storageUtility.getForUser(sessionId, "clientId", {
1149
+ secure: false,
1150
+ });
1151
+ const clientSecret = await this.storageUtility.getForUser(sessionId, "clientSecret", {
1152
+ secure: false,
1153
+ });
1154
+ const redirectUrl = await this.storageUtility.getForUser(sessionId, "redirectUrl", {
1155
+ secure: false,
1156
+ });
1157
+ const refreshToken = await this.storageUtility.getForUser(sessionId, "refreshToken", {
1158
+ secure: true,
1159
+ });
1160
+ const issuer = await this.storageUtility.getForUser(sessionId, "issuer", {
1161
+ secure: false,
1162
+ });
1163
+ const tokenType = (_a = (await this.storageUtility.getForUser(sessionId, "tokenType", {
1164
+ secure: false,
1165
+ }))) !== null && _a !== void 0 ? _a : "DPoP";
1166
+ if (!solidClientAuthnCore.isSupportedTokenType(tokenType)) {
1167
+ throw new Error(`Tokens of type [${tokenType}] are not supported.`);
1168
+ }
1169
+ if (clientId === undefined &&
1170
+ isLoggedIn === undefined &&
1171
+ webId === undefined &&
1172
+ refreshToken === undefined) {
1173
+ return undefined;
1174
+ }
1175
+ return {
1176
+ sessionId,
1177
+ webId,
1178
+ isLoggedIn: isLoggedIn === "true",
1179
+ redirectUrl,
1180
+ refreshToken,
1181
+ issuer,
1182
+ clientAppId: clientId,
1183
+ clientAppSecret: clientSecret,
1184
+ tokenType,
1185
+ };
1186
+ }
1187
+ async getAll() {
1188
+ throw new Error("Not implemented");
1189
+ }
1190
+ async clear(sessionId) {
1191
+ return clear(sessionId, this.storageUtility);
1192
+ }
1193
+ async register(_sessionId) {
1194
+ throw new Error("Not implemented");
1195
+ }
1196
+ async getRegisteredSessionIdAll() {
1197
+ throw new Error("Not implemented");
1198
+ }
1199
+ async clearAll() {
1200
+ throw new Error("Not implemented");
1201
+ }
1202
+ }
1203
+
1204
+ class FallbackRedirectHandler {
1205
+ async canHandle(redirectUrl) {
1206
+ try {
1207
+ new URL(redirectUrl);
1208
+ return true;
1209
+ }
1210
+ catch (e) {
1211
+ throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);
1212
+ }
1213
+ }
1214
+ async handle(_redirectUrl) {
1215
+ return getUnauthenticatedSession();
1216
+ }
1217
+ }
1218
+
1219
+ class GeneralLogoutHandler {
1220
+ constructor(sessionInfoManager) {
1221
+ this.sessionInfoManager = sessionInfoManager;
1222
+ }
1223
+ async canHandle() {
1224
+ return true;
1225
+ }
1226
+ async handle(userId) {
1227
+ await this.sessionInfoManager.clear(userId);
1228
+ }
1229
+ }
1230
+
1231
+ class AuthCodeRedirectHandler {
1232
+ constructor(storageUtility, sessionInfoManager, issuerConfigFetcher, clientRegistrar, tokerRefresher) {
1233
+ this.storageUtility = storageUtility;
1234
+ this.sessionInfoManager = sessionInfoManager;
1235
+ this.issuerConfigFetcher = issuerConfigFetcher;
1236
+ this.clientRegistrar = clientRegistrar;
1237
+ this.tokerRefresher = tokerRefresher;
1238
+ }
1239
+ async canHandle(redirectUrl) {
1240
+ try {
1241
+ const myUrl = new URL(redirectUrl);
1242
+ return (myUrl.searchParams.get("code") !== null &&
1243
+ myUrl.searchParams.get("state") !== null);
1244
+ }
1245
+ catch (e) {
1246
+ throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);
1247
+ }
1248
+ }
1249
+ async handle(redirectUrl, eventEmitter) {
1250
+ if (!(await this.canHandle(redirectUrl))) {
1251
+ throw new Error(`AuthCodeRedirectHandler cannot handle [${redirectUrl}]: it is missing one of [code, state].`);
1252
+ }
1253
+ const url = new URL(redirectUrl);
1254
+ const oauthState = url.searchParams.get("state");
1255
+ const storedSessionId = (await this.storageUtility.getForUser(oauthState, "sessionId", {
1256
+ errorIfNull: true,
1257
+ }));
1258
+ const { issuerConfig, codeVerifier, redirectUrl: storedRedirectIri, dpop: isDpop, } = await solidClientAuthnCore.loadOidcContextFromStorage(storedSessionId, this.storageUtility, this.issuerConfigFetcher);
1259
+ if (codeVerifier === undefined) {
1260
+ throw new Error(`The code verifier for session ${storedSessionId} is missing from storage.`);
1261
+ }
1262
+ if (storedRedirectIri === undefined) {
1263
+ throw new Error(`The redirect URL for session ${storedSessionId} is missing from storage.`);
1264
+ }
1265
+ const client = await this.clientRegistrar.getClient({ sessionId: storedSessionId }, issuerConfig);
1266
+ let tokens;
1267
+ const tokenCreatedAt = Date.now();
1268
+ if (isDpop) {
1269
+ tokens = await getDpopToken(issuerConfig, client, {
1270
+ grantType: "authorization_code",
1271
+ code: url.searchParams.get("code"),
1272
+ codeVerifier,
1273
+ redirectUrl: storedRedirectIri,
1274
+ });
1275
+ window.localStorage.removeItem(`oidc.${oauthState}`);
1276
+ }
1277
+ else {
1278
+ tokens = await getBearerToken(url.toString());
1279
+ }
1280
+ let refreshOptions;
1281
+ if (tokens.refreshToken !== undefined) {
1282
+ refreshOptions = {
1283
+ sessionId: storedSessionId,
1284
+ refreshToken: tokens.refreshToken,
1285
+ tokenRefresher: this.tokerRefresher,
1286
+ };
1287
+ }
1288
+ const authFetch = await solidClientAuthnCore.buildAuthenticatedFetch(fetch, tokens.accessToken, {
1289
+ dpopKey: tokens.dpopKey,
1290
+ refreshOptions,
1291
+ eventEmitter,
1292
+ expiresIn: tokens.expiresIn,
1293
+ });
1294
+ await this.storageUtility.setForUser(storedSessionId, {
1295
+ webId: tokens.webId,
1296
+ isLoggedIn: "true",
1297
+ }, { secure: true });
1298
+ url.searchParams.delete("code");
1299
+ await this.storageUtility.setForUser(storedSessionId, {
1300
+ redirectUrl: url.toString(),
1301
+ }, {
1302
+ secure: false,
1303
+ });
1304
+ const sessionInfo = await this.sessionInfoManager.get(storedSessionId);
1305
+ if (!sessionInfo) {
1306
+ throw new Error(`Could not retrieve session: [${storedSessionId}].`);
1307
+ }
1308
+ return Object.assign(sessionInfo, {
1309
+ fetch: authFetch,
1310
+ expirationDate: typeof tokens.expiresIn === "number"
1311
+ ? tokenCreatedAt + tokens.expiresIn * 1000
1312
+ : null,
1313
+ });
1314
+ }
1315
+ }
1316
+
1317
+ class AggregateRedirectHandler extends solidClientAuthnCore.AggregateHandler {
1318
+ constructor(redirectHandlers) {
1319
+ super(redirectHandlers);
1320
+ }
1321
+ }
1322
+
1323
+ class BrowserStorage {
1324
+ get storage() {
1325
+ return window.localStorage;
1326
+ }
1327
+ async get(key) {
1328
+ return this.storage.getItem(key) || undefined;
1329
+ }
1330
+ async set(key, value) {
1331
+ this.storage.setItem(key, value);
1332
+ }
1333
+ async delete(key) {
1334
+ this.storage.removeItem(key);
1335
+ }
1336
+ }
1337
+
1338
+ let redirectIframe;
1339
+ function getRedirectIframe() {
1340
+ if (typeof redirectIframe === "undefined") {
1341
+ redirectIframe = window.document.createElement("iframe");
1342
+ redirectIframe.setAttribute("hidden", "true");
1343
+ redirectIframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
1344
+ }
1345
+ return redirectIframe;
1346
+ }
1347
+ function redirectInIframe(redirectUrl) {
1348
+ const iframe = getRedirectIframe();
1349
+ window.document.body.appendChild(iframe);
1350
+ iframe.src = redirectUrl;
1351
+ }
1352
+ function setupIframeListener(handleIframeRedirect) {
1353
+ if (typeof window === "undefined") {
1354
+ return;
1355
+ }
1356
+ window.addEventListener("message", async (evt) => {
1357
+ const iframe = getRedirectIframe();
1358
+ if (evt.origin === window.location.origin &&
1359
+ evt.source === iframe.contentWindow) {
1360
+ if (typeof evt.data.redirectUrl === "string") {
1361
+ await handleIframeRedirect(evt.data.redirectUrl);
1362
+ }
1363
+ }
1364
+ if (window.document.body.contains(iframe)) {
1365
+ window.document.body.removeChild(iframe);
1366
+ }
1367
+ });
1368
+ }
1369
+ function postRedirectUrlToParent(redirectUrl) {
1370
+ window.top.postMessage({
1371
+ redirectUrl,
1372
+ }, window.location.origin);
1373
+ }
1374
+
1375
+ class Redirector {
1376
+ redirect(redirectUrl, options) {
1377
+ if (options && options.handleRedirect) {
1378
+ options.handleRedirect(redirectUrl);
1379
+ }
1380
+ else if (options && options.redirectByReplacingState) {
1381
+ window.history.replaceState({}, "", redirectUrl);
1382
+ }
1383
+ else if (options === null || options === void 0 ? void 0 : options.redirectInIframe) {
1384
+ redirectInIframe(redirectUrl);
1385
+ }
1386
+ else {
1387
+ window.location.href = redirectUrl;
1388
+ }
1389
+ }
1390
+ }
1391
+
1392
+ class ClientRegistrar {
1393
+ constructor(storageUtility) {
1394
+ this.storageUtility = storageUtility;
1395
+ }
1396
+ async getClient(options, issuerConfig) {
1397
+ var _a;
1398
+ const [storedClientId, storedClientSecret,] = await Promise.all([
1399
+ this.storageUtility.getForUser(options.sessionId, "clientId", {
1400
+ secure: false,
1401
+ }),
1402
+ this.storageUtility.getForUser(options.sessionId, "clientSecret", {
1403
+ secure: false,
1404
+ }),
1405
+ ]);
1406
+ if (storedClientId) {
1407
+ return {
1408
+ clientId: storedClientId,
1409
+ clientSecret: storedClientSecret,
1410
+ clientType: "dynamic",
1411
+ };
1412
+ }
1413
+ const extendedOptions = { ...options };
1414
+ extendedOptions.registrationAccessToken =
1415
+ (_a = extendedOptions.registrationAccessToken) !== null && _a !== void 0 ? _a : (await this.storageUtility.getForUser(options.sessionId, "registrationAccessToken"));
1416
+ try {
1417
+ const registeredClient = await registerClient(extendedOptions, issuerConfig);
1418
+ const infoToSave = {
1419
+ clientId: registeredClient.clientId,
1420
+ };
1421
+ if (registeredClient.clientSecret) {
1422
+ infoToSave.clientSecret = registeredClient.clientSecret;
1423
+ }
1424
+ if (registeredClient.idTokenSignedResponseAlg) {
1425
+ infoToSave.idTokenSignedResponseAlg =
1426
+ registeredClient.idTokenSignedResponseAlg;
1427
+ }
1428
+ await this.storageUtility.setForUser(extendedOptions.sessionId, infoToSave, {
1429
+ secure: false,
1430
+ });
1431
+ return registeredClient;
1432
+ }
1433
+ catch (error) {
1434
+ throw new Error(`Client registration failed: [${error}]`);
1435
+ }
1436
+ }
1437
+ }
1438
+
1439
+ class ErrorOidcHandler {
1440
+ async canHandle(redirectUrl) {
1441
+ try {
1442
+ return new URL(redirectUrl).searchParams.has("error");
1443
+ }
1444
+ catch (e) {
1445
+ throw new Error(`[${redirectUrl}] is not a valid URL, and cannot be used as a redirect URL: ${e}`);
1446
+ }
1447
+ }
1448
+ async handle(redirectUrl, eventEmitter) {
1449
+ if (eventEmitter !== undefined) {
1450
+ const url = new URL(redirectUrl);
1451
+ const errorUrl = url.searchParams.get("error");
1452
+ const errorDescriptionUrl = url.searchParams.get("error_description");
1453
+ eventEmitter.emit(solidClientAuthnCore.EVENTS.ERROR, errorUrl, errorDescriptionUrl);
1454
+ }
1455
+ return getUnauthenticatedSession();
1456
+ }
1457
+ }
1458
+
1459
+ class TokenRefresher {
1460
+ constructor(storageUtility, issuerConfigFetcher, clientRegistrar) {
1461
+ this.storageUtility = storageUtility;
1462
+ this.issuerConfigFetcher = issuerConfigFetcher;
1463
+ this.clientRegistrar = clientRegistrar;
1464
+ }
1465
+ async refresh(sessionId, refreshToken, dpopKey, eventEmitter) {
1466
+ const oidcContext = await solidClientAuthnCore.loadOidcContextFromStorage(sessionId, this.storageUtility, this.issuerConfigFetcher);
1467
+ const clientInfo = await this.clientRegistrar.getClient({ sessionId }, oidcContext.issuerConfig);
1468
+ if (refreshToken === undefined) {
1469
+ throw new Error(`Session [${sessionId}] has no refresh token to allow it to refresh its access token.`);
1470
+ }
1471
+ if (oidcContext.dpop && dpopKey === undefined) {
1472
+ throw new Error(`For session [${sessionId}], the key bound to the DPoP access token must be provided to refresh said access token.`);
1473
+ }
1474
+ const tokenSet = await refresh(refreshToken, oidcContext.issuerConfig, clientInfo, dpopKey);
1475
+ if (tokenSet.refreshToken !== undefined) {
1476
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(solidClientAuthnCore.EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
1477
+ await this.storageUtility.setForUser(sessionId, {
1478
+ refreshToken: tokenSet.refreshToken,
1479
+ });
1480
+ }
1481
+ return tokenSet;
1482
+ }
1483
+ }
1484
+
1485
+ function getClientAuthenticationWithDependencies(dependencies) {
1486
+ const inMemoryStorage = new solidClientAuthnCore.InMemoryStorage();
1487
+ const secureStorage = dependencies.secureStorage || inMemoryStorage;
1488
+ const insecureStorage = dependencies.insecureStorage || new BrowserStorage();
1489
+ const storageUtility = new StorageUtilityBrowser(secureStorage, insecureStorage);
1490
+ const issuerConfigFetcher = new IssuerConfigFetcher(storageUtility);
1491
+ const clientRegistrar = new ClientRegistrar(storageUtility);
1492
+ const sessionInfoManager = new SessionInfoManager(storageUtility);
1493
+ const tokenRefresher = new TokenRefresher(storageUtility, issuerConfigFetcher, clientRegistrar);
1494
+ const loginHandler = new OidcLoginHandler(storageUtility, new AuthorizationCodeWithPkceOidcHandler(storageUtility, new Redirector()), issuerConfigFetcher, clientRegistrar);
1495
+ const redirectHandler = new AggregateRedirectHandler([
1496
+ new ErrorOidcHandler(),
1497
+ new AuthCodeRedirectHandler(storageUtility, sessionInfoManager, issuerConfigFetcher, clientRegistrar, tokenRefresher),
1498
+ new FallbackRedirectHandler(),
1499
+ ]);
1500
+ return new ClientAuthentication(loginHandler, redirectHandler, new GeneralLogoutHandler(sessionInfoManager), sessionInfoManager, issuerConfigFetcher);
1501
+ }
1502
+
1503
+ const KEY_CURRENT_SESSION = `${solidClientAuthnCore.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`;
1504
+ const KEY_CURRENT_URL = `${solidClientAuthnCore.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;
1505
+
1506
+ async function silentlyAuthenticate(sessionId, clientAuthn, options = {
1507
+ inIframe: false,
1508
+ }, session) {
1509
+ var _a;
1510
+ const storedSessionInfo = await clientAuthn.validateCurrentSession(sessionId);
1511
+ if (storedSessionInfo !== null) {
1512
+ window.localStorage.setItem(KEY_CURRENT_URL, window.location.href);
1513
+ await clientAuthn.login({
1514
+ sessionId,
1515
+ prompt: "none",
1516
+ oidcIssuer: storedSessionInfo.issuer,
1517
+ redirectUrl: storedSessionInfo.redirectUrl,
1518
+ clientId: storedSessionInfo.clientAppId,
1519
+ clientSecret: storedSessionInfo.clientAppSecret,
1520
+ tokenType: (_a = storedSessionInfo.tokenType) !== null && _a !== void 0 ? _a : "DPoP",
1521
+ inIframe: options.inIframe,
1522
+ }, session);
1523
+ return true;
1524
+ }
1525
+ return false;
1526
+ }
1527
+ function isLoggedIn(sessionInfo) {
1528
+ return !!(sessionInfo === null || sessionInfo === void 0 ? void 0 : sessionInfo.isLoggedIn);
1529
+ }
1530
+ class Session extends EventEmitter {
1531
+ constructor(sessionOptions = {}, sessionId) {
1532
+ super();
1533
+ this.tokenRequestInProgress = false;
1534
+ this.login = async (options) => {
1535
+ var _a;
1536
+ await this.clientAuthentication.login({
1537
+ sessionId: this.info.sessionId,
1538
+ ...options,
1539
+ tokenType: (_a = options.tokenType) !== null && _a !== void 0 ? _a : "DPoP",
1540
+ }, this);
1541
+ return new Promise(() => undefined);
1542
+ };
1543
+ this.fetch = async (url, init) => {
1544
+ return this.clientAuthentication.fetch(url, init);
1545
+ };
1546
+ this.internalLogout = async (emitSignal) => {
1547
+ window.localStorage.removeItem(KEY_CURRENT_SESSION);
1548
+ await this.clientAuthentication.logout(this.info.sessionId);
1549
+ this.info.isLoggedIn = false;
1550
+ if (emitSignal) {
1551
+ this.emit(solidClientAuthnCore.EVENTS.LOGOUT);
1552
+ }
1553
+ };
1554
+ this.logout = async () => this.internalLogout(true);
1555
+ this.handleIncomingRedirect = async (inputOptions = {}) => {
1556
+ var _a;
1557
+ if (this.info.isLoggedIn) {
1558
+ return this.info;
1559
+ }
1560
+ if (this.tokenRequestInProgress) {
1561
+ return undefined;
1562
+ }
1563
+ const options = typeof inputOptions === "string" ? { url: inputOptions } : inputOptions;
1564
+ const url = (_a = options.url) !== null && _a !== void 0 ? _a : window.location.href;
1565
+ if (window.frameElement !== null) {
1566
+ postRedirectUrlToParent(url);
1567
+ return undefined;
1568
+ }
1569
+ this.tokenRequestInProgress = true;
1570
+ const sessionInfo = await this.clientAuthentication.handleIncomingRedirect(url, this);
1571
+ if (isLoggedIn(sessionInfo)) {
1572
+ this.setSessionInfo(sessionInfo);
1573
+ const currentUrl = window.localStorage.getItem(KEY_CURRENT_URL);
1574
+ if (currentUrl === null) {
1575
+ this.emit(solidClientAuthnCore.EVENTS.LOGIN);
1576
+ }
1577
+ else {
1578
+ window.localStorage.removeItem(KEY_CURRENT_URL);
1579
+ this.emit(solidClientAuthnCore.EVENTS.SESSION_RESTORED, currentUrl);
1580
+ }
1581
+ }
1582
+ else if (options.restorePreviousSession === true) {
1583
+ const storedSessionId = window.localStorage.getItem(KEY_CURRENT_SESSION);
1584
+ if (storedSessionId !== null) {
1585
+ const attemptedSilentAuthentication = await silentlyAuthenticate(storedSessionId, this.clientAuthentication, undefined, this);
1586
+ if (attemptedSilentAuthentication) {
1587
+ return new Promise(() => { });
1588
+ }
1589
+ }
1590
+ }
1591
+ this.tokenRequestInProgress = false;
1592
+ return sessionInfo;
1593
+ };
1594
+ if (sessionOptions.clientAuthentication) {
1595
+ this.clientAuthentication = sessionOptions.clientAuthentication;
1596
+ }
1597
+ else if (sessionOptions.secureStorage && sessionOptions.insecureStorage) {
1598
+ this.clientAuthentication = getClientAuthenticationWithDependencies({
1599
+ secureStorage: sessionOptions.secureStorage,
1600
+ insecureStorage: sessionOptions.insecureStorage,
1601
+ });
1602
+ }
1603
+ else {
1604
+ this.clientAuthentication = getClientAuthenticationWithDependencies({});
1605
+ }
1606
+ if (sessionOptions.sessionInfo) {
1607
+ this.info = {
1608
+ sessionId: sessionOptions.sessionInfo.sessionId,
1609
+ isLoggedIn: false,
1610
+ webId: sessionOptions.sessionInfo.webId,
1611
+ };
1612
+ }
1613
+ else {
1614
+ this.info = {
1615
+ sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : v4(),
1616
+ isLoggedIn: false,
1617
+ };
1618
+ }
1619
+ setupIframeListener(async (redirectUrl) => {
1620
+ const sessionInfo = await this.clientAuthentication.handleIncomingRedirect(redirectUrl, this);
1621
+ if (!isLoggedIn(sessionInfo)) {
1622
+ return;
1623
+ }
1624
+ this.setSessionInfo(sessionInfo);
1625
+ });
1626
+ this.on("tokenRenewal", () => silentlyAuthenticate(this.info.sessionId, this.clientAuthentication, {
1627
+ inIframe: true,
1628
+ }, this));
1629
+ this.on(solidClientAuthnCore.EVENTS.LOGIN, () => window.localStorage.setItem(KEY_CURRENT_SESSION, this.info.sessionId));
1630
+ this.on(solidClientAuthnCore.EVENTS.SESSION_EXPIRED, () => this.internalLogout(false));
1631
+ this.on(solidClientAuthnCore.EVENTS.ERROR, () => this.internalLogout(false));
1632
+ window.localStorage.removeItem("tmp-resource-server-session-enabled");
1633
+ }
1634
+ onLogin(callback) {
1635
+ this.on(solidClientAuthnCore.EVENTS.LOGIN, callback);
1636
+ }
1637
+ onLogout(callback) {
1638
+ this.on(solidClientAuthnCore.EVENTS.LOGOUT, callback);
1639
+ }
1640
+ onError(callback) {
1641
+ this.on(solidClientAuthnCore.EVENTS.ERROR, callback);
1642
+ }
1643
+ onSessionRestore(callback) {
1644
+ this.on(solidClientAuthnCore.EVENTS.SESSION_RESTORED, callback);
1645
+ }
1646
+ onSessionExpiration(callback) {
1647
+ this.on(solidClientAuthnCore.EVENTS.SESSION_EXPIRED, callback);
1648
+ }
1649
+ setSessionInfo(sessionInfo) {
1650
+ this.info.isLoggedIn = sessionInfo.isLoggedIn;
1651
+ this.info.webId = sessionInfo.webId;
1652
+ this.info.sessionId = sessionInfo.sessionId;
1653
+ this.info.expirationDate = sessionInfo.expirationDate;
1654
+ this.on(solidClientAuthnCore.EVENTS.SESSION_EXTENDED, (expiresIn) => {
1655
+ this.info.expirationDate = Date.now() + expiresIn * 1000;
1656
+ });
1657
+ }
1658
+ }
1659
+
1660
+ let defaultSession;
1661
+ function getDefaultSession() {
1662
+ if (typeof defaultSession === "undefined") {
1663
+ defaultSession = new Session();
1664
+ }
1665
+ return defaultSession;
1666
+ }
1667
+ const fetch$1 = (...args) => {
1668
+ const session = getDefaultSession();
1669
+ return session.fetch(...args);
1670
+ };
1671
+ const login = (...args) => {
1672
+ const session = getDefaultSession();
1673
+ return session.login(...args);
1674
+ };
1675
+ const logout = (...args) => {
1676
+ const session = getDefaultSession();
1677
+ return session.logout(...args);
1678
+ };
1679
+ const handleIncomingRedirect = (...args) => {
1680
+ const session = getDefaultSession();
1681
+ return session.handleIncomingRedirect(...args);
1682
+ };
1683
+ const onLogin = (...args) => {
1684
+ const session = getDefaultSession();
1685
+ return session.onLogin(...args);
1686
+ };
1687
+ const onLogout = (...args) => {
1688
+ const session = getDefaultSession();
1689
+ return session.onLogout(...args);
1690
+ };
1691
+ const onSessionRestore = (...args) => {
1692
+ const session = getDefaultSession();
1693
+ return session.onSessionRestore(...args);
1694
+ };
1695
+
1696
+ Object.defineProperty(exports, 'ConfigurationError', {
1697
+ enumerable: true,
1698
+ get: function () { return solidClientAuthnCore.ConfigurationError; }
1699
+ });
1700
+ Object.defineProperty(exports, 'InMemoryStorage', {
1701
+ enumerable: true,
1702
+ get: function () { return solidClientAuthnCore.InMemoryStorage; }
1703
+ });
1704
+ Object.defineProperty(exports, 'NotImplementedError', {
1705
+ enumerable: true,
1706
+ get: function () { return solidClientAuthnCore.NotImplementedError; }
1707
+ });
1708
+ exports.Session = Session;
1709
+ exports.fetch = fetch$1;
1710
+ exports.getClientAuthenticationWithDependencies = getClientAuthenticationWithDependencies;
1711
+ exports.getDefaultSession = getDefaultSession;
1712
+ exports.handleIncomingRedirect = handleIncomingRedirect;
1713
+ exports.login = login;
1714
+ exports.logout = logout;
1715
+ exports.onLogin = onLogin;
1716
+ exports.onLogout = onLogout;
1717
+ exports.onSessionRestore = onSessionRestore;