@muze-nl/metro-oidc 0.1.3 → 0.2.0

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.
@@ -1,1630 +0,0 @@
1
- (() => {
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
7
-
8
- // node_modules/@muze-nl/metro/src/metro.mjs
9
- var metro_exports = {};
10
- __export(metro_exports, {
11
- client: () => client,
12
- formdata: () => formdata,
13
- metroError: () => metroError,
14
- request: () => request,
15
- response: () => response,
16
- trace: () => trace,
17
- url: () => url
18
- });
19
- var metroURL = "https://metro.muze.nl/details/";
20
- if (!Symbol.metroProxy) {
21
- Symbol.metroProxy = Symbol("isProxy");
22
- }
23
- if (!Symbol.metroSource) {
24
- Symbol.metroSource = Symbol("source");
25
- }
26
- var Client = class _Client {
27
- #options = {
28
- url: typeof window != "undefined" ? window.location : "https://localhost"
29
- };
30
- #verbs = ["get", "post", "put", "delete", "patch", "head", "options", "query"];
31
- static tracers = {};
32
- /**
33
- * @typedef {Object} ClientOptions
34
- * @property {Array} middlewares - list of middleware functions
35
- * @property {string|URL} url - default url of the client
36
- * @property {[string]} verbs - a list of verb methods to expose, e.g. ['get','post']
37
- *
38
- * Constructs a new metro client. Can have any number of params.
39
- * @params {ClientOptions|URL|Function|Client}
40
- * @returns {Client} - A metro client object with given or default verb methods
41
- */
42
- constructor(...options) {
43
- for (let option of options) {
44
- if (typeof option == "string" || option instanceof String) {
45
- this.#options.url = "" + option;
46
- } else if (option instanceof _Client) {
47
- Object.assign(this.#options, option.#options);
48
- } else if (option instanceof Function) {
49
- this.#addMiddlewares([option]);
50
- } else if (option && typeof option == "object") {
51
- for (let param in option) {
52
- if (param == "middlewares") {
53
- this.#addMiddlewares(option[param]);
54
- } else if (typeof option[param] == "function") {
55
- this.#options[param] = option[param](this.#options[param], this.#options);
56
- } else {
57
- this.#options[param] = option[param];
58
- }
59
- }
60
- }
61
- }
62
- if (this.#options.verbs) {
63
- this.#verbs = this.#options.verbs;
64
- delete this.#options.verbs;
65
- }
66
- for (const verb of this.#verbs) {
67
- this[verb] = async function(...options2) {
68
- return this.fetch(request(
69
- this.#options,
70
- ...options2,
71
- { method: verb.toUpperCase() }
72
- ));
73
- };
74
- }
75
- Object.freeze(this);
76
- }
77
- #addMiddlewares(middlewares) {
78
- if (typeof middlewares == "function") {
79
- middlewares = [middlewares];
80
- }
81
- let index = middlewares.findIndex((m) => typeof m != "function");
82
- if (index >= 0) {
83
- throw metroError("metro.client: middlewares must be a function or an array of functions " + metroURL + "client/invalid-middlewares-value/", middlewares[index]);
84
- }
85
- if (!Array.isArray(this.#options.middlewares)) {
86
- this.#options.middlewares = [];
87
- }
88
- this.#options.middlewares = this.#options.middlewares.concat(middlewares);
89
- }
90
- /**
91
- * Mimics the standard browser fetch method, but uses any middleware installed through
92
- * the constructor.
93
- * @param {Request|string|Object} - Required. The URL or Request object, accepts all types that are accepted by metro.request
94
- * @param {Object} - Optional. Any object that is accepted by metro.request
95
- * @return {Promise<Response|*>} - The metro.response to this request, or any other result as changed by any included middleware.
96
- */
97
- fetch(req, options) {
98
- req = request(req, options);
99
- if (!req.url) {
100
- throw metroError("metro.client." + req.method.toLowerCase() + ": Missing url parameter " + metroURL + "client/missing-url-param/", req);
101
- }
102
- if (!options) {
103
- options = {};
104
- }
105
- if (!(typeof options === "object") || Array.isArray(options) || options instanceof String) {
106
- throw metroError("metro.client.fetch: Options is not an object");
107
- }
108
- const metrofetch = async function browserFetch(req2) {
109
- if (req2[Symbol.metroProxy]) {
110
- if (req2.body && req2.body[Symbol.metroSource]) {
111
- let body = req2.body[Symbol.metroSource];
112
- req2 = new Request(req2[Symbol.metroSource], { body });
113
- } else {
114
- req2 = req2[Symbol.metroSource];
115
- }
116
- }
117
- const res = await fetch(req2);
118
- return response(res);
119
- };
120
- let middlewares = [metrofetch].concat(this.#options?.middlewares?.slice() || []);
121
- options = Object.assign({}, this.#options, options);
122
- let next;
123
- for (let middleware of middlewares) {
124
- next = /* @__PURE__ */ function(next2, middleware2) {
125
- return async function(req2) {
126
- let res;
127
- let tracers = Object.values(_Client.tracers);
128
- for (let tracer of tracers) {
129
- if (tracer.request) {
130
- tracer.request.call(tracer, req2, middleware2);
131
- }
132
- }
133
- res = await middleware2(req2, next2);
134
- for (let tracer of tracers) {
135
- if (tracer.response) {
136
- tracer.response.call(tracer, res, middleware2);
137
- }
138
- }
139
- return res;
140
- };
141
- }(next, middleware);
142
- }
143
- return next(req);
144
- }
145
- with(...options) {
146
- return new _Client(this, ...options);
147
- }
148
- };
149
- function client(...options) {
150
- return new Client(...options);
151
- }
152
- function bodyProxy(body, r) {
153
- let source = r.body;
154
- if (!source) {
155
- if (body === null) {
156
- source = new ReadableStream();
157
- } else if (body instanceof ReadableStream) {
158
- source = body;
159
- } else if (body instanceof Blob) {
160
- source = body.stream();
161
- } else {
162
- source = new ReadableStream({
163
- start(controller) {
164
- let chunk;
165
- switch (typeof body) {
166
- case "object":
167
- if (typeof body.toString == "function") {
168
- chunk = body.toString();
169
- } else if (body instanceof FormData) {
170
- chunk = new URLSearchParams(body).toString();
171
- } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
172
- chunk = body;
173
- } else {
174
- throw metroError("Cannot convert body to ReadableStream", body);
175
- }
176
- break;
177
- case "string":
178
- case "number":
179
- case "boolean":
180
- chunk = body;
181
- break;
182
- default:
183
- throw metroError("Cannot convert body to ReadableStream", body);
184
- break;
185
- }
186
- controller.enqueue(chunk);
187
- controller.close();
188
- }
189
- });
190
- }
191
- }
192
- return new Proxy(source, {
193
- get(target, prop, receiver) {
194
- switch (prop) {
195
- case Symbol.metroProxy:
196
- return true;
197
- break;
198
- case Symbol.metroSource:
199
- return body;
200
- break;
201
- case "toString":
202
- return function() {
203
- return "" + body;
204
- };
205
- break;
206
- }
207
- if (body && typeof body == "object") {
208
- if (prop in body) {
209
- if (typeof body[prop] == "function") {
210
- return function(...args) {
211
- return body[prop].apply(body, args);
212
- };
213
- }
214
- return body[prop];
215
- }
216
- }
217
- if (prop in target && prop != "toString") {
218
- if (typeof target[prop] == "function") {
219
- return function(...args) {
220
- return target[prop].apply(target, args);
221
- };
222
- }
223
- return target[prop];
224
- }
225
- },
226
- has(target, prop) {
227
- if (body && typeof body == "object") {
228
- return prop in body;
229
- } else {
230
- return prop in target;
231
- }
232
- },
233
- ownKeys(target) {
234
- if (body && typeof body == "object") {
235
- return Reflect.ownKeys(body);
236
- } else {
237
- return Reflect.ownKeys(target);
238
- }
239
- },
240
- getOwnPropertyDescriptor(target, prop) {
241
- if (body && typeof body == "object") {
242
- return Object.getOwnPropertyDescriptor(body, prop);
243
- } else {
244
- return Object.getOwnPropertyDescriptor(target, prop);
245
- }
246
- }
247
- });
248
- }
249
- function getRequestParams(req, current) {
250
- let params2 = current || {};
251
- if (!params2.url && current.url) {
252
- params2.url = current.url;
253
- }
254
- for (let prop of [
255
- "method",
256
- "headers",
257
- "body",
258
- "mode",
259
- "credentials",
260
- "cache",
261
- "redirect",
262
- "referrer",
263
- "referrerPolicy",
264
- "integrity",
265
- "keepalive",
266
- "signal",
267
- "priority",
268
- "url"
269
- ]) {
270
- if (typeof req[prop] == "function") {
271
- req[prop](params2[prop], params2);
272
- } else if (typeof req[prop] != "undefined") {
273
- if (prop == "url") {
274
- params2.url = url(params2.url, req.url);
275
- } else if (prop == "headers") {
276
- params2.headers = new Headers(current.headers);
277
- if (!(req.headers instanceof Headers)) {
278
- req.headers = new Headers(req.headers);
279
- }
280
- for (let [key, value] of req.headers.entries()) {
281
- params2.headers.set(key, value);
282
- }
283
- } else {
284
- params2[prop] = req[prop];
285
- }
286
- }
287
- }
288
- return params2;
289
- }
290
- function request(...options) {
291
- let requestParams = {
292
- url: typeof window != "undefined" ? window.location : "https://localhost/",
293
- duplex: "half"
294
- // required when setting body to ReadableStream, just set it here by default already
295
- };
296
- for (let option of options) {
297
- if (typeof option == "string" || option instanceof URL || option instanceof URLSearchParams) {
298
- requestParams.url = url(requestParams.url, option);
299
- } else if (option && (option instanceof FormData || option instanceof ReadableStream || option instanceof Blob || option instanceof ArrayBuffer || option instanceof DataView)) {
300
- requestParams.body = option;
301
- } else if (option && typeof option == "object") {
302
- Object.assign(requestParams, getRequestParams(option, requestParams));
303
- }
304
- }
305
- let body = requestParams.body;
306
- if (body) {
307
- if (typeof body == "object" && !(body instanceof String) && !(body instanceof ReadableStream) && !(body instanceof Blob) && !(body instanceof ArrayBuffer) && !(body instanceof DataView) && !(body instanceof FormData) && !(body instanceof URLSearchParams) && (typeof TypedArray == "undefined" || !(body instanceof TypedArray))) {
308
- requestParams.body = JSON.stringify(body);
309
- }
310
- }
311
- let r = new Request(requestParams.url, requestParams);
312
- Object.freeze(r);
313
- return new Proxy(r, {
314
- get(target, prop, receiver) {
315
- switch (prop) {
316
- case Symbol.metroSource:
317
- return target;
318
- break;
319
- case Symbol.metroProxy:
320
- return true;
321
- break;
322
- case "with":
323
- return function(...options2) {
324
- if (body) {
325
- options2.unshift({ body });
326
- }
327
- return request(target, ...options2);
328
- };
329
- break;
330
- case "body":
331
- if (!body) {
332
- body = target.body;
333
- }
334
- if (body) {
335
- if (body[Symbol.metroProxy]) {
336
- return body;
337
- }
338
- return bodyProxy(body, target);
339
- }
340
- break;
341
- }
342
- if (target[prop] instanceof Function) {
343
- return target[prop].bind(target);
344
- }
345
- return target[prop];
346
- }
347
- });
348
- }
349
- function getResponseParams(res, current) {
350
- let params2 = current || {};
351
- if (!params2.url && current.url) {
352
- params2.url = current.url;
353
- }
354
- for (let prop of ["status", "statusText", "headers", "body", "url", "type", "redirected"]) {
355
- if (typeof res[prop] == "function") {
356
- res[prop](params2[prop], params2);
357
- } else if (typeof res[prop] != "undefined") {
358
- if (prop == "url") {
359
- params2.url = new URL(res.url, params2.url || "https://localhost/");
360
- } else {
361
- params2[prop] = res[prop];
362
- }
363
- }
364
- }
365
- return params2;
366
- }
367
- function response(...options) {
368
- let responseParams = {};
369
- for (let option of options) {
370
- if (typeof option == "string") {
371
- responseParams.body = option;
372
- } else if (option instanceof Response) {
373
- Object.assign(responseParams, getResponseParams(option, responseParams));
374
- } else if (option && typeof option == "object") {
375
- if (option instanceof FormData || option instanceof Blob || option instanceof ArrayBuffer || option instanceof DataView || option instanceof ReadableStream || option instanceof URLSearchParams || option instanceof String || typeof TypedArray != "undefined" && option instanceof TypedArray) {
376
- responseParams.body = option;
377
- } else {
378
- Object.assign(responseParams, getResponseParams(option, responseParams));
379
- }
380
- }
381
- }
382
- let r = new Response(responseParams.body, responseParams);
383
- Object.freeze(r);
384
- return new Proxy(r, {
385
- get(target, prop, receiver) {
386
- switch (prop) {
387
- case Symbol.metroProxy:
388
- return true;
389
- break;
390
- case Symbol.metroSource:
391
- return target;
392
- break;
393
- case "with":
394
- return function(...options2) {
395
- return response(target, ...options2);
396
- };
397
- break;
398
- case "body":
399
- if (responseParams.body) {
400
- if (responseParams.body[Symbol.metroProxy]) {
401
- return responseParams.body;
402
- }
403
- return bodyProxy(responseParams.body, target);
404
- } else {
405
- return bodyProxy("", target);
406
- }
407
- break;
408
- case "ok":
409
- return target.status >= 200 && target.status < 400;
410
- break;
411
- case "headers":
412
- return target.headers;
413
- break;
414
- default:
415
- if (prop in responseParams && prop != "toString") {
416
- return responseParams[prop];
417
- }
418
- if (prop in target && prop != "toString") {
419
- if (typeof target[prop] == "function") {
420
- return function(...args) {
421
- return target[prop].apply(target, args);
422
- };
423
- }
424
- return target[prop];
425
- }
426
- break;
427
- }
428
- return void 0;
429
- }
430
- });
431
- }
432
- function appendSearchParams(url2, params2) {
433
- if (typeof params2 == "function") {
434
- params2(url2.searchParams, url2);
435
- } else {
436
- params2 = new URLSearchParams(params2);
437
- params2.forEach((value, key) => {
438
- url2.searchParams.append(key, value);
439
- });
440
- }
441
- }
442
- function url(...options) {
443
- let validParams = [
444
- "hash",
445
- "host",
446
- "hostname",
447
- "href",
448
- "password",
449
- "pathname",
450
- "port",
451
- "protocol",
452
- "username",
453
- "search",
454
- "searchParams"
455
- ];
456
- let u = new URL("https://localhost/");
457
- for (let option of options) {
458
- if (typeof option == "string" || option instanceof String) {
459
- u = new URL(option, u);
460
- } else if (option instanceof URL || typeof Location != "undefined" && option instanceof Location) {
461
- u = new URL(option);
462
- } else if (option instanceof URLSearchParams) {
463
- appendSearchParams(u, option);
464
- } else if (option && typeof option == "object") {
465
- for (let param in option) {
466
- if (param == "search") {
467
- if (typeof option.search == "function") {
468
- option.search(u.search, u);
469
- } else {
470
- u.search = new URLSearchParams(option.search);
471
- }
472
- } else if (param == "searchParams") {
473
- appendSearchParams(u, option.searchParams);
474
- } else {
475
- if (!validParams.includes(param)) {
476
- throw metroError("metro.url: unknown url parameter " + metroURL + "url/unknown-param-name/", param);
477
- }
478
- if (typeof option[param] == "function") {
479
- option[param](u[param], u);
480
- } else if (typeof option[param] == "string" || option[param] instanceof String || typeof option[param] == "number" || option[param] instanceof Number || typeof option[param] == "boolean" || option[param] instanceof Boolean) {
481
- u[param] = "" + option[param];
482
- } else if (typeof option[param] == "object" && option[param].toString) {
483
- u[param] = option[param].toString();
484
- } else {
485
- throw metroError("metro.url: unsupported value for " + param + " " + metroURL + "url/unsupported-param-value/", options[param]);
486
- }
487
- }
488
- }
489
- } else {
490
- throw metroError("metro.url: unsupported option value " + metroURL + "url/unsupported-option-value/", option);
491
- }
492
- }
493
- Object.freeze(u);
494
- return new Proxy(u, {
495
- get(target, prop, receiver) {
496
- switch (prop) {
497
- case Symbol.metroProxy:
498
- return true;
499
- break;
500
- case Symbol.metroSource:
501
- return target;
502
- break;
503
- case "with":
504
- return function(...options2) {
505
- return url(target, ...options2);
506
- };
507
- break;
508
- }
509
- if (target[prop] instanceof Function) {
510
- return target[prop].bind(target);
511
- }
512
- return target[prop];
513
- }
514
- });
515
- }
516
- function formdata(...options) {
517
- var params2 = new FormData();
518
- for (let option of options) {
519
- if (option instanceof FormData) {
520
- for (let entry of option.entries()) {
521
- params2.append(entry[0], entry[1]);
522
- }
523
- } else if (option && typeof option == "object") {
524
- for (let entry of Object.entries(option)) {
525
- if (Array.isArray(entry[1])) {
526
- for (let value of entry[1]) {
527
- params2.append(entry[0], value);
528
- }
529
- } else {
530
- params2.append(entry[0], entry[1]);
531
- }
532
- }
533
- } else {
534
- throw new metroError("metro.formdata: unknown option type, only FormData or Object supported", option);
535
- }
536
- }
537
- Object.freeze(params2);
538
- return new Proxy(params2, {
539
- get: (target, prop, receiver) => {
540
- switch (prop) {
541
- case Symbol.metroProxy:
542
- return true;
543
- break;
544
- case Symbol.metroSource:
545
- return target;
546
- break;
547
- case "with":
548
- return function(...options2) {
549
- return formdata(target, ...options2);
550
- };
551
- break;
552
- }
553
- if (target[prop] instanceof Function) {
554
- return target[prop].bind(target);
555
- }
556
- return target[prop];
557
- }
558
- });
559
- }
560
- var metroConsole = {
561
- error: (message, ...details) => {
562
- console.error("\u24C2\uFE0F ", message, ...details);
563
- },
564
- info: (message, ...details) => {
565
- console.info("\u24C2\uFE0F ", message, ...details);
566
- },
567
- group: (name) => {
568
- console.group("\u24C2\uFE0F " + name);
569
- },
570
- groupEnd: (name) => {
571
- console.groupEnd("\u24C2\uFE0F " + name);
572
- }
573
- };
574
- function metroError(message, ...details) {
575
- metroConsole.error(message, ...details);
576
- return new Error(message, ...details);
577
- }
578
- var trace = {
579
- /**
580
- * Adds a named tracer function
581
- * @param {string} name - the name of the tracer
582
- * @param {Function} tracer - the tracer function to call
583
- */
584
- add(name, tracer) {
585
- Client.tracers[name] = tracer;
586
- },
587
- /**
588
- * Removes a named tracer function
589
- * @param {string} name
590
- */
591
- delete(name) {
592
- delete Client.tracers[name];
593
- },
594
- /**
595
- * Removes all tracer functions
596
- */
597
- clear() {
598
- Client.tracers = {};
599
- },
600
- /**
601
- * Returns a set of request and response tracer functions that use the
602
- * console.group feature to shows nested request/response pairs, with
603
- * most commonly needed information for debugging
604
- */
605
- group() {
606
- let group = 0;
607
- return {
608
- request: (req, middleware) => {
609
- group++;
610
- metroConsole.group(group);
611
- metroConsole.info(req?.url, req, middleware);
612
- },
613
- response: (res, middleware) => {
614
- metroConsole.info(res?.body ? res.body[Symbol.metroSource] : null, res, middleware);
615
- metroConsole.groupEnd(group);
616
- group--;
617
- }
618
- };
619
- }
620
- };
621
-
622
- // node_modules/@muze-nl/metro/src/mw/json.mjs
623
- function jsonmw(options) {
624
- options = Object.assign({
625
- reviver: null,
626
- replacer: null,
627
- space: ""
628
- }, options);
629
- return async (req, next) => {
630
- if (["POST", "PUT", "PATCH", "QUERY"].includes(req.method)) {
631
- req = req.with({
632
- headers: {
633
- "Content-Type": "application/json",
634
- "Accept": "application/json"
635
- }
636
- });
637
- if (req.body && typeof req.body[Symbol.metroSource] == "object") {
638
- req = req.with({
639
- body: JSON.stringify(req.body[Symbol.metroSource], options.replacer, options.space)
640
- });
641
- }
642
- } else {
643
- req = req.with({
644
- headers: {
645
- "Accept": "application/json"
646
- }
647
- });
648
- }
649
- let res = await next(req);
650
- let body = await res.text();
651
- let json = JSON.parse(body, options.reviver);
652
- return res.with({
653
- body: json
654
- });
655
- };
656
- }
657
-
658
- // node_modules/@muze-nl/metro/src/mw/thrower.mjs
659
- function thrower(options) {
660
- return async (req, next) => {
661
- let res = await next(req);
662
- if (!res.ok) {
663
- if (options && typeof options[res.status] == "function") {
664
- res = options[res.status].apply(res, req);
665
- } else {
666
- throw new Error(res.status + ": " + res.statusText, {
667
- cause: res
668
- });
669
- }
670
- }
671
- return res;
672
- };
673
- }
674
-
675
- // node_modules/@muze-nl/metro/src/everything.mjs
676
- var metro = Object.assign({}, metro_exports, {
677
- mw: {
678
- jsonmw,
679
- thrower
680
- }
681
- });
682
- window.metro = metro;
683
- var everything_default = metro;
684
-
685
- // node_modules/@muze-nl/assert/src/assert.mjs
686
- globalThis.assertEnabled = false;
687
- function assert(source, test) {
688
- if (globalThis.assertEnabled) {
689
- let problems = fails(source, test);
690
- if (problems) {
691
- console.error("\u{1F170}\uFE0F Assertions failed because of:", problems, "in this source:", source);
692
- throw new Error("Assertions failed", {
693
- cause: { problems, source }
694
- });
695
- }
696
- }
697
- }
698
- function Optional(pattern) {
699
- return function _Optional(data, root, path) {
700
- if (typeof data != "undefined" && data != null && typeof pattern != "undefined") {
701
- return fails(data, pattern, root, path);
702
- }
703
- };
704
- }
705
- function Required(pattern) {
706
- return function _Required(data, root, path) {
707
- if (data == null || typeof data == "undefined") {
708
- return error("data is required", data, pattern || "any value", path);
709
- } else if (typeof pattern != "undefined") {
710
- return fails(data, pattern, root, path);
711
- } else {
712
- return false;
713
- }
714
- };
715
- }
716
- function Recommended(pattern) {
717
- return function _Recommended(data, root, path) {
718
- if (data == null || typeof data == "undefined") {
719
- console.warn("data does not contain recommended value", data, pattern, path);
720
- return false;
721
- } else {
722
- return fails(data, pattern, root, path);
723
- }
724
- };
725
- }
726
- function oneOf(...patterns) {
727
- return function _oneOf(data, root, path) {
728
- for (let pattern of patterns) {
729
- if (!fails(data, pattern, root, path)) {
730
- return false;
731
- }
732
- }
733
- return error("data does not match oneOf patterns", data, patterns, path);
734
- };
735
- }
736
- function anyOf(...patterns) {
737
- return function _anyOf(data, root, path) {
738
- if (!Array.isArray(data)) {
739
- return error("data is not an array", data, "anyOf", path);
740
- }
741
- for (let value of data) {
742
- if (oneOf(...patterns)(value)) {
743
- return error("data does not match anyOf patterns", value, patterns, path);
744
- }
745
- }
746
- return false;
747
- };
748
- }
749
- function allOf(...patterns) {
750
- return function _allOf(data, root, path) {
751
- let problems = [];
752
- for (let pattern of patterns) {
753
- problems = problems.concat(fails(data, pattern, root, path));
754
- }
755
- problems = problems.filter(Boolean);
756
- if (problems.length) {
757
- return error("data does not match all given patterns", data, patterns, path, problems);
758
- }
759
- };
760
- }
761
- function validURL(data, root, path) {
762
- try {
763
- if (data instanceof URL) {
764
- data = data.href;
765
- }
766
- let url2 = new URL(data);
767
- if (url2.href != data) {
768
- if (!(url2.href + "/" == data || url2.href == data + "/")) {
769
- return error("data is not a valid url", data, "validURL", path);
770
- }
771
- }
772
- } catch (e) {
773
- return error("data is not a valid url", data, "validURL", path);
774
- }
775
- }
776
- function validEmail(data, root, path) {
777
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data)) {
778
- return error("data is not a valid email", data, "validEmail", path);
779
- }
780
- }
781
- function instanceOf(constructor) {
782
- return function _instanceOf(data, root, path) {
783
- if (!(data instanceof constructor)) {
784
- return error("data is not an instanceof pattern", data, constructor, path);
785
- }
786
- };
787
- }
788
- function not(pattern) {
789
- return function _not(data, root, path) {
790
- if (!fails(data, pattern, root, path)) {
791
- return error("data matches pattern, when required not to", data, pattern, path);
792
- }
793
- };
794
- }
795
- function fails(data, pattern, root, path = "") {
796
- if (!root) {
797
- root = data;
798
- }
799
- let problems = [];
800
- if (pattern === Boolean) {
801
- if (typeof data != "boolean" && !(data instanceof Boolean)) {
802
- problems.push(error("data is not a boolean", data, pattern, path));
803
- }
804
- } else if (pattern === Number) {
805
- if (typeof data != "number" && !(data instanceof Number)) {
806
- problems.push(error("data is not a number", data, pattern, path));
807
- }
808
- } else if (pattern === String) {
809
- if (typeof data != "string" && !(data instanceof String)) {
810
- problems.push(error("data is not a string", data, pattern, path));
811
- }
812
- if (data == "") {
813
- problems.push(error("data is an empty string, which is not allowed", data, pattern, path));
814
- }
815
- } else if (pattern instanceof RegExp) {
816
- if (Array.isArray(data)) {
817
- let index = data.findIndex((element, index2) => fails(element, pattern, root, path + "[" + index2 + "]"));
818
- if (index > -1) {
819
- problems.push(error("data[" + index + "] does not match pattern", data[index], pattern, path + "[" + index + "]"));
820
- }
821
- } else if (typeof data == "undefined") {
822
- problems.push(error("data is undefined, should match pattern", data, pattern, path));
823
- } else if (!pattern.test(data)) {
824
- problems.push(error("data does not match pattern", data, pattern, path));
825
- }
826
- } else if (pattern instanceof Function) {
827
- let problem = pattern(data, root, path);
828
- if (problem) {
829
- if (Array.isArray(problem)) {
830
- problems = problems.concat(problem);
831
- } else {
832
- problems.push(problem);
833
- }
834
- }
835
- } else if (Array.isArray(pattern)) {
836
- if (!Array.isArray(data)) {
837
- problems.push(error("data is not an array", data, [], path));
838
- }
839
- for (let p2 of pattern) {
840
- for (let index of data.keys()) {
841
- let problem = fails(data[index], p2, root, path + "[" + index + "]");
842
- if (Array.isArray(problem)) {
843
- problems = problems.concat(problem);
844
- } else if (problem) {
845
- problems.push(problem);
846
- }
847
- }
848
- }
849
- } else if (pattern && typeof pattern == "object") {
850
- if (Array.isArray(data)) {
851
- let index = data.findIndex((element, index2) => fails(element, pattern, root, path + "[" + index2 + "]"));
852
- if (index > -1) {
853
- problems.push(error("data[" + index + "] does not match pattern", data[index], pattern, path + "[" + index + "]"));
854
- }
855
- } else if (!data || typeof data != "object") {
856
- problems.push(error("data is not an object, pattern is", data, pattern, path));
857
- } else {
858
- if (data instanceof URLSearchParams) {
859
- data = Object.fromEntries(data);
860
- }
861
- if (pattern instanceof Function) {
862
- let result = fails(data, pattern, root, path);
863
- if (result) {
864
- problems = problems.concat(result);
865
- }
866
- } else {
867
- for (const [wKey, wVal] of Object.entries(pattern)) {
868
- let result = fails(data[wKey], wVal, root, path + "." + wKey);
869
- if (result) {
870
- problems = problems.concat(result);
871
- }
872
- }
873
- }
874
- }
875
- } else {
876
- if (pattern != data) {
877
- problems.push(error("data and pattern are not equal", data, pattern, path));
878
- }
879
- }
880
- if (problems.length) {
881
- return problems;
882
- }
883
- return false;
884
- }
885
- function error(message, found, expected, path, problems) {
886
- let result = {
887
- message,
888
- found,
889
- expected,
890
- path
891
- };
892
- if (problems) {
893
- result.problems = problems;
894
- }
895
- return result;
896
- }
897
-
898
- // src/oidc.util.mjs
899
- var MustHave = (...options) => (value, root) => {
900
- if (options.filter((o) => root.hasOwnKey(o)).length > 0) {
901
- return false;
902
- }
903
- return error("root data must have all of", root, options);
904
- };
905
- var MustInclude = (...options) => (value) => {
906
- if (Array.isArray(value) && options.filter((o) => !value.includes(o)).length == 0) {
907
- return false;
908
- } else {
909
- return error("data must be an array which includes", value, options);
910
- }
911
- };
912
- var validJWA = [
913
- "HS256",
914
- "HS384",
915
- "HS512",
916
- "RS256",
917
- "RS384",
918
- "RS512",
919
- "ES256",
920
- "ES384",
921
- "ES512"
922
- ];
923
- var validAuthMethods = [
924
- "client_secret_post",
925
- "client_secret_basic",
926
- "client_secret_jwt",
927
- "private_key_jwt"
928
- ];
929
-
930
- // src/oidc.discovery.mjs
931
- async function oidcDiscovery(options = {}) {
932
- assert(options, {
933
- client: Optional(instanceOf(everything_default.client().constructor)),
934
- issuer: Required(validURL)
935
- });
936
- const defaultOptions = {
937
- client: everything_default.client().with(thrower()).with(jsonmw()),
938
- requireDynamicRegistration: false
939
- };
940
- options = Object.assign({}, defaultOptions, options);
941
- const TestSucceeded = false;
942
- function MustUseHTTPS(url2) {
943
- return TestSucceeded;
944
- }
945
- const openid_provider_metadata = {
946
- issuer: Required(allOf(options.issuer, MustUseHTTPS)),
947
- authorization_endpoint: Required(validURL),
948
- token_endpoint: Required(validURL),
949
- userinfo_endpoint: Recommended(validURL),
950
- // todo: test for https protocol
951
- jwks_uri: Required(validURL),
952
- registration_endpoint: options.requireDynamicRegistration ? Required(validURL) : Recommended(validURL),
953
- scopes_supported: Recommended(MustInclude("openid")),
954
- response_types_supported: options.requireDynamicRegistration ? Required(MustInclude("code", "id_token", "id_token token")) : Required([]),
955
- response_modes_supported: Optional([]),
956
- grant_types_supported: options.requireDynamicRegistration ? Optional(MustInclude("authorization_code")) : Optional([]),
957
- acr_values_supported: Optional([]),
958
- subject_types_supported: Required([]),
959
- id_token_signing_alg_values_supported: Required(MustInclude("RS256")),
960
- id_token_encryption_alg_values_supported: Optional([]),
961
- id_token_encryption_enc_values_supported: Optional([]),
962
- userinfo_signing_alg_values_supported: Optional([]),
963
- userinfo_encryption_alg_values_supported: Optional([]),
964
- userinfo_encryption_enc_values_supported: Optional([]),
965
- request_object_signing_alg_values_supported: Optional(MustInclude("RS256")),
966
- // not testing for 'none'
967
- request_object_encryption_alg_values_supported: Optional([]),
968
- request_object_encryption_enc_values_supported: Optional([]),
969
- token_endpoint_auth_methods_supported: Optional(anyOf(...validAuthMethods)),
970
- token_endpoint_auth_signing_alg_values_supported: Optional(MustInclude("RS256"), not(MustInclude("none"))),
971
- display_values_supported: Optional(anyOf("page", "popup", "touch", "wap")),
972
- claim_types_supported: Optional(anyOf("normal", "aggregated", "distributed")),
973
- claims_supported: Recommended([]),
974
- service_documentation: Optional(validURL),
975
- claims_locales_supported: Optional([]),
976
- ui_locales_supported: Optional([]),
977
- claims_parameter_supported: Optional(Boolean),
978
- request_parameter_supported: Optional(Boolean),
979
- request_uri_parameter_supported: Optional(Boolean),
980
- op_policy_uri: Optional(validURL),
981
- op_tos_uri: Optional(validURL)
982
- };
983
- const configURL = everything_default.url(options.issuer, ".well-known/openid-configuration");
984
- const response2 = await options.client.get(
985
- // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest
986
- // note: this allows path components in the options.issuer url
987
- configURL
988
- );
989
- const openid_config = response2.body[Symbol.metroSource];
990
- assert(openid_config, openid_provider_metadata);
991
- assert(openid_config.issuer, options.issuer);
992
- return openid_config;
993
- }
994
-
995
- // src/oidc.register.mjs
996
- async function register(options) {
997
- const openid_client_metadata = {
998
- redirect_uris: Required([validURL]),
999
- response_types: Optional([]),
1000
- grant_types: Optional(anyOf("authorization_code", "refresh_token")),
1001
- //TODO: match response_types with grant_types
1002
- application_type: Optional(oneOf("native", "web")),
1003
- contacts: Optional([validEmail]),
1004
- client_name: Optional(String),
1005
- logo_uri: Optional(validURL),
1006
- client_uri: Optional(validURL),
1007
- policy_uri: Optional(validURL),
1008
- tos_uri: Optional(validURL),
1009
- jwks_uri: Optional(validURL, not(MustHave("jwks"))),
1010
- jwks: Optional(validURL, not(MustHave("jwks_uri"))),
1011
- sector_identifier_uri: Optional(validURL),
1012
- subject_type: Optional(String),
1013
- id_token_signed_response_alg: Optional(oneOf(...validJWA)),
1014
- id_token_encrypted_response_alg: Optional(oneOf(...validJWA)),
1015
- id_token_encrypted_response_enc: Optional(oneOf(...validJWA), MustHave("id_token_encrypted_response_alg")),
1016
- userinfo_signed_response_alg: Optional(oneOf(...validJWA)),
1017
- userinfo_encrypted_response_alg: Optional(oneOf(...validJWA)),
1018
- userinfo_encrypted_response_enc: Optional(oneOf(...validJWA), MustHave("userinfo_encrypted_response_alg")),
1019
- request_object_signing_alg: Optional(oneOf(...validJWA)),
1020
- request_object_encryption_alg: Optional(oneOf(...validJWA)),
1021
- request_object_encryption_enc: Optional(oneOf(...validJWA)),
1022
- token_endpoint_auth_method: Optional(oneOf(...validAuthMethods)),
1023
- token_endpoint_auth_signing_alg: Optional(oneOf(...validJWA)),
1024
- default_max_age: Optional(Number),
1025
- require_auth_time: Optional(Boolean),
1026
- default_acr_values: Optional([String]),
1027
- initiate_login_uri: Optional([validURL]),
1028
- request_uris: Optional([validURL])
1029
- };
1030
- assert(options, {
1031
- client: Optional(instanceOf(everything_default.client().constructor)),
1032
- registration_endpoint: validURL,
1033
- client_info: openid_client_metadata
1034
- });
1035
- const defaultOptions = {
1036
- client: everything_default.client().with(thrower()).with(jsonmw())
1037
- };
1038
- options = Object.assign({}, defaultOptions, options);
1039
- let response2 = await options.client.post(options.registration_endpoint, {
1040
- body: options.client_info
1041
- });
1042
- let info = response2.body;
1043
- if (!info.client_id || !info.client_secret) {
1044
- throw everything_default.metroError("metro.oidc: Error: dynamic registration of client failed, no client_id or client_secret returned", response2);
1045
- }
1046
- options.client_info = Object.assign(options.client_info, info);
1047
- return options.client_info;
1048
- }
1049
-
1050
- // node_modules/@muze-nl/metro-oauth2/node_modules/@muze-nl/assert/src/assert.mjs
1051
- globalThis.assertEnabled = false;
1052
- var assert2 = (source, test) => {
1053
- if (globalThis.assertEnabled) {
1054
- let problems = fails2(source, test);
1055
- if (problems) {
1056
- throw new assertError("Assertions failed", problems, source);
1057
- }
1058
- }
1059
- };
1060
- var Required2 = (pattern) => (data) => fails2(data, pattern);
1061
- function validURL2(data) {
1062
- try {
1063
- if (data instanceof URL) {
1064
- data = data.href;
1065
- }
1066
- let url2 = new URL(data);
1067
- if (url2.href != data) {
1068
- return error2("data is not a valid url", data, "validURL");
1069
- }
1070
- } catch (e) {
1071
- return error2("data is not a valid url", data, "validURL");
1072
- }
1073
- return false;
1074
- }
1075
- function fails2(data, pattern, root) {
1076
- if (!root) {
1077
- root = data;
1078
- }
1079
- let problems = [];
1080
- if (pattern === Boolean) {
1081
- if (typeof data != "boolean") {
1082
- problems.push(error2("data is not a boolean", data, pattern));
1083
- }
1084
- } else if (pattern === Number) {
1085
- if (typeof data != "number") {
1086
- problems.push(error2("data is not a number", data, pattern));
1087
- }
1088
- } else if (pattern instanceof RegExp) {
1089
- if (Array.isArray(data)) {
1090
- let index = data.findIndex((element) => fails2(element, pattern, root));
1091
- if (index > -1) {
1092
- problems.push(error2("data[" + index + "] does not match pattern", data[index], pattern));
1093
- }
1094
- } else if (!pattern.test(data)) {
1095
- problems.push(error2("data does not match pattern", data, pattern));
1096
- }
1097
- } else if (pattern instanceof Function) {
1098
- if (pattern(data, root)) {
1099
- problems.push(error2("data does not match function", data, pattern));
1100
- }
1101
- } else if (Array.isArray(pattern)) {
1102
- if (!Array.isArray(data)) {
1103
- problems.push(error2("data is not an array", data, []));
1104
- }
1105
- for (p of pattern) {
1106
- let problem = fails2(data, p, root);
1107
- if (Array.isArray(problem)) {
1108
- problems.concat(problem);
1109
- } else if (problem) {
1110
- problems.push(problem);
1111
- }
1112
- }
1113
- } else if (pattern && typeof pattern == "object") {
1114
- if (Array.isArray(data)) {
1115
- let index = data.findIndex((element) => fails2(element, pattern, root));
1116
- if (index > -1) {
1117
- problems.push(error2("data[" + index + "] does not match pattern", data[index], pattern));
1118
- }
1119
- } else if (!data || typeof data != "object") {
1120
- problems.push(error2("data is not an object, pattern is", data, pattern));
1121
- } else {
1122
- if (data instanceof URLSearchParams) {
1123
- data = Object.fromEntries(data);
1124
- }
1125
- let p2 = problems[problems.length - 1];
1126
- for (const [wKey, wVal] of Object.entries(pattern)) {
1127
- let result = fails2(data[wKey], wVal, root);
1128
- if (result) {
1129
- if (!p2 || typeof p2 == "string") {
1130
- p2 = {};
1131
- problems.push(error2(p2, data[wKey], wVal));
1132
- }
1133
- p2[wKey] = result.problems;
1134
- }
1135
- }
1136
- }
1137
- } else {
1138
- if (pattern != data) {
1139
- problems.push(error2("data and pattern are not equal", data, pattern));
1140
- }
1141
- }
1142
- if (problems.length) {
1143
- return problems;
1144
- }
1145
- return false;
1146
- }
1147
- var assertError = class extends Error {
1148
- constructor(message, problems, ...details) {
1149
- super(message);
1150
- this.problems = problems;
1151
- this.details = details;
1152
- }
1153
- };
1154
- function error2(message, found, expected) {
1155
- return {
1156
- message,
1157
- found,
1158
- expected
1159
- };
1160
- }
1161
-
1162
- // node_modules/@muze-nl/metro-oauth2/src/tokenstore.mjs
1163
- function tokenStore(site) {
1164
- let localState, localTokens;
1165
- if (typeof localStorage !== "undefined") {
1166
- localState = {
1167
- get: () => localStorage.getItem("metro/state:" + site),
1168
- set: (value) => localStorage.setItem("metro/state:" + site, value),
1169
- has: () => localStorage.getItem("metro/state:" + site) !== null
1170
- };
1171
- localTokens = {
1172
- get: (name) => JSON.parse(localStorage.getItem(site + ":" + name)),
1173
- set: (name, value) => localStorage.setItem(site + ":" + name, JSON.stringify(value)),
1174
- has: (name) => localStorage.getItem(site + ":" + name) !== null
1175
- };
1176
- } else {
1177
- let stateMap = /* @__PURE__ */ new Map();
1178
- localState = {
1179
- get: () => stateMap.get("metro/state:" + site),
1180
- set: (value) => stateMap.set("metro/state:" + site, value),
1181
- has: () => stateMap.has("metro/state:" + site)
1182
- };
1183
- localTokens = /* @__PURE__ */ new Map();
1184
- }
1185
- return {
1186
- state: localState,
1187
- tokens: localTokens
1188
- };
1189
- }
1190
-
1191
- // node_modules/@muze-nl/metro-oauth2/src/oauth2.mjs
1192
- function mwOAuth2(options) {
1193
- const defaultOptions = {
1194
- client: everything_default.client(),
1195
- force_authorization: false,
1196
- site: "default",
1197
- oauth2_configuration: {
1198
- authorization_endpoint: "/authorize",
1199
- token_endpoint: "/token",
1200
- redirect_uri: globalThis.document?.location.href,
1201
- grant_type: "authorization_code",
1202
- code_verifier: security.generateCodeVerifier(64)
1203
- },
1204
- callbacks: {
1205
- authorize: async (url2) => {
1206
- if (window.location.href != url2.href) {
1207
- window.location.replace(url2.href);
1208
- }
1209
- return false;
1210
- }
1211
- }
1212
- };
1213
- assert2(options, {});
1214
- const oauth2 = Object.assign({}, defaultOptions.oauth2_configuration, options?.oauth2_configuration);
1215
- options = Object.assign({}, defaultOptions, options);
1216
- options.oauth2_configuration = oauth2;
1217
- const store = tokenStore(options.site);
1218
- if (!options.tokens) {
1219
- options.tokens = store.tokens;
1220
- }
1221
- if (!options.state) {
1222
- options.state = store.state;
1223
- }
1224
- assert2(options, {
1225
- oauth2_configuration: {
1226
- client_id: Required2(/.+/),
1227
- grant_type: "authorization_code",
1228
- authorization_endpoint: Required2(validURL2),
1229
- token_endpoint: Required2(validURL2),
1230
- redirect_uri: Required2(validURL2)
1231
- }
1232
- });
1233
- for (let option in oauth2) {
1234
- switch (option) {
1235
- case "access_token":
1236
- case "authorization_code":
1237
- case "refresh_token":
1238
- options.tokens.set(option, oauth2[option]);
1239
- break;
1240
- }
1241
- }
1242
- return async function(req, next) {
1243
- if (options.force_authorization) {
1244
- return oauth2authorized(req, next);
1245
- }
1246
- let res;
1247
- try {
1248
- res = await next(req);
1249
- if (res.ok) {
1250
- return res;
1251
- }
1252
- } catch (err) {
1253
- switch (res.status) {
1254
- case 400:
1255
- // Oauth2.1 RFC 3.2.4
1256
- case 401:
1257
- return oauth2authorized(req, next);
1258
- break;
1259
- }
1260
- throw err;
1261
- }
1262
- return res;
1263
- };
1264
- async function oauth2authorized(req, next) {
1265
- getTokensFromLocation();
1266
- if (!options.tokens.has("access_token")) {
1267
- try {
1268
- let token = await fetchAccessToken();
1269
- if (!token) {
1270
- return everything_default.response("false");
1271
- }
1272
- } catch (e) {
1273
- console.log("caught", e);
1274
- throw e;
1275
- }
1276
- return oauth2authorized(req, next);
1277
- } else if (isExpired(req)) {
1278
- let token = await fetchRefreshToken();
1279
- if (!token) {
1280
- return everything_default.response("false");
1281
- }
1282
- return oauth2authorized(req, next);
1283
- } else {
1284
- let accessToken = options.tokens.get("access_token");
1285
- req = everything_default.request(req, {
1286
- headers: {
1287
- Authorization: accessToken.type + " " + accessToken.value
1288
- }
1289
- });
1290
- return next(req);
1291
- }
1292
- }
1293
- function getTokensFromLocation() {
1294
- if (typeof window !== "undefined" && window?.location) {
1295
- let url2 = everything_default.url(window.location);
1296
- let code, state, params2;
1297
- if (url2.searchParams.has("code")) {
1298
- params2 = url2.searchParams;
1299
- url2 = url2.with({ search: "" });
1300
- history.pushState({}, "", url2.href);
1301
- } else if (url2.hash) {
1302
- let query = url2.hash.substr(1);
1303
- params2 = new URLSearchParams("?" + query);
1304
- url2 = url2.with({ hash: "" });
1305
- history.pushState({}, "", url2.href);
1306
- }
1307
- if (params2) {
1308
- code = params2.get("code");
1309
- state = params2.get("state");
1310
- let storedState = options.state.get("metro/state");
1311
- if (!state || state !== storedState) {
1312
- return;
1313
- }
1314
- if (code) {
1315
- options.tokens.set("authorization_code", code);
1316
- }
1317
- }
1318
- }
1319
- }
1320
- async function fetchAccessToken() {
1321
- if (oauth2.grant_type === "authorization_code" && !options.tokens.has("authorization_code")) {
1322
- let authReqURL = getAuthorizationCodeURL();
1323
- if (!options.callbacks.authorize || typeof options.callbacks.authorize !== "function") {
1324
- throw everything_default.metroError("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.options.callbacks.authorize");
1325
- }
1326
- let token = await options.callbacks.authorize(authReqURL);
1327
- if (token) {
1328
- options.tokens.set("authorization_code", token);
1329
- } else {
1330
- return false;
1331
- }
1332
- }
1333
- let tokenReq = getAccessTokenRequest();
1334
- let response2 = await options.client.post(tokenReq);
1335
- if (!response2.ok) {
1336
- throw everything_default.metroError("OAuth2mw: fetch access_token: " + response2.status + ": " + response2.statusText, { cause: tokenReq });
1337
- }
1338
- let data = await response2.json();
1339
- options.tokens.set("access_token", {
1340
- value: data.access_token,
1341
- expires: getExpires(data.expires_in),
1342
- type: data.token_type,
1343
- scope: data.scope
1344
- });
1345
- if (data.refresh_token) {
1346
- let token = {
1347
- value: data.refresh_token
1348
- };
1349
- options.tokens.set("refresh_token", token);
1350
- }
1351
- return data;
1352
- }
1353
- async function fetchRefreshToken() {
1354
- let refreshTokenReq = getAccessTokenRequest("refresh_token");
1355
- let response2 = await options.client.post(refreshTokenReq);
1356
- if (!response2.ok) {
1357
- throw everything_default.metroError("OAuth2mw: refresh access_token: " + response2.status + ": " + response2.statusText, { cause: refreshTokenReq });
1358
- }
1359
- let data = await response2.json();
1360
- options.tokens.set("access_token", {
1361
- value: data.access_token,
1362
- expires: getExpires(data.expires_in),
1363
- type: data.token_type,
1364
- scope: data.scope
1365
- });
1366
- if (data.refresh_token) {
1367
- let token = {
1368
- value: data.refresh_token
1369
- };
1370
- options.tokens.set("refresh_token", token);
1371
- } else {
1372
- return false;
1373
- }
1374
- return data;
1375
- }
1376
- function getAuthorizationCodeURL() {
1377
- if (!oauth2.authorization_endpoint) {
1378
- throw everything_default.metroError("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");
1379
- }
1380
- let url2 = everything_default.url(oauth2.authorization_endpoint, { hash: "" });
1381
- assert2(oauth2, {
1382
- client_id: /.+/,
1383
- redirect_uri: /.+/,
1384
- scope: /.*/
1385
- });
1386
- let search = {
1387
- response_type: "code",
1388
- // implicit flow uses 'token' here, but is not considered safe, so not supported
1389
- client_id: oauth2.client_id,
1390
- client_secret: oauth2.client_secret,
1391
- redirect_uri: oauth2.redirect_uri,
1392
- state: oauth2.state || security.createState(40)
1393
- // OAuth2.1 RFC says optional, but its a good idea to always add/check it
1394
- };
1395
- options.state.set(search.state);
1396
- if (oauth2.code_verifier) {
1397
- delete search.client_secret;
1398
- search.code_challenge = security.generateCodeChallenge(oauth2.code_verifier);
1399
- search.code_challenge_method = "S256";
1400
- }
1401
- if (oauth2.scope) {
1402
- search.scope = oauth2.scope;
1403
- }
1404
- return everything_default.url(url2, { search });
1405
- }
1406
- function getAccessTokenRequest(grant_type = null) {
1407
- assert2(oauth2, {
1408
- client_id: /.+/,
1409
- redirect_uri: /.+/
1410
- });
1411
- if (!oauth2.token_endpoint) {
1412
- throw everything_default.metroError("oauth2mw: Missing options.endpoints.token url");
1413
- }
1414
- let url2 = everything_default.url(oauth2.token_endpoint, { hash: "" });
1415
- let params2 = {
1416
- grant_type: grant_type || oauth2.grant_type,
1417
- client_id: oauth2.client_id
1418
- };
1419
- if (oauth2.code_verifier) {
1420
- params2.code_verifier = oauth2.code_verifier;
1421
- } else {
1422
- params2.client_secret = oauth2.client_secret;
1423
- }
1424
- if (oauth2.scope) {
1425
- params2.scope = oauth2.scope;
1426
- }
1427
- switch (oauth2.grant_type) {
1428
- case "authorization_code":
1429
- params2.redirect_uri = oauth2.redirect_uri;
1430
- params2.code = options.tokens.get("authorization_code");
1431
- break;
1432
- case "client_credentials":
1433
- break;
1434
- case "refresh_token":
1435
- params2.refresh_token = oauth2.refresh_token;
1436
- break;
1437
- default:
1438
- throw new Error("Unknown grant_type: ".oauth2.grant_type);
1439
- break;
1440
- }
1441
- return everything_default.request(url2, { method: "POST", body: new URLSearchParams(params2) });
1442
- }
1443
- function isExpired(req) {
1444
- if (req.oauth2 && req.options.tokens && req.options.tokens.has("access_token")) {
1445
- let now = /* @__PURE__ */ new Date();
1446
- let token = req.options.tokens.get("access_token");
1447
- return now.getTime() > token.expires.getTime();
1448
- }
1449
- return false;
1450
- }
1451
- function getExpires(duration) {
1452
- if (duration instanceof Date) {
1453
- return new Date(duration.getTime());
1454
- }
1455
- if (typeof duration === "number") {
1456
- let date = /* @__PURE__ */ new Date();
1457
- date.setSeconds(date.getSeconds() + duration);
1458
- return date;
1459
- }
1460
- throw new TypeError("Unknown expires type " + duration);
1461
- }
1462
- }
1463
- var security = {
1464
- /**
1465
- * returns a PKCE code_verifier, as a hex encoded string
1466
- */
1467
- generateCodeVerifier: function(size = 64) {
1468
- const code_verifier = new Uint8Array(size);
1469
- globalThis.crypto.getRandomValues(code_verifier);
1470
- return code_verifier.toString("hex");
1471
- },
1472
- /**
1473
- * Returns a PKCE code_challenge derived from a code_verifier
1474
- */
1475
- generateCodeChallenge: async function(code_verifier) {
1476
- const b64encoded = security.base64url_encode(code_verifier);
1477
- const encoder = new TextEncoder();
1478
- const data = encoder.encode(b64encoded);
1479
- return await globalThis.crypto.subtle.digest("SHA-256", data);
1480
- },
1481
- /**
1482
- * Base64url encoding, which handles UTF-8 input strings correctly.
1483
- */
1484
- base64url_encode: function(buffer) {
1485
- const byteString = Array.from(new Uint8Array(buffer), (b) => String.fromCharCode(b)).join("");
1486
- return btoa(byteString).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1487
- },
1488
- /**
1489
- * Creates and stores a random state to use in the authorization code URL
1490
- */
1491
- createState: function(length) {
1492
- const validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1493
- let randomState = "";
1494
- let counter = 0;
1495
- while (counter < length) {
1496
- randomState += validChars.charAt(Math.floor(Math.random() * validChars.length));
1497
- counter++;
1498
- }
1499
- return randomState;
1500
- }
1501
- };
1502
- function isRedirected() {
1503
- let url2 = new URL(document.location.href);
1504
- if (!url2.searchParams.has("code")) {
1505
- if (url2.hash) {
1506
- let query = url2.hash.substr(1);
1507
- params = new URLSearchParams("?" + query);
1508
- if (params.has("code")) {
1509
- return true;
1510
- }
1511
- }
1512
- return false;
1513
- }
1514
- return true;
1515
- }
1516
-
1517
- // src/oidc.store.mjs
1518
- function oidcStore(site) {
1519
- let store;
1520
- if (typeof localStorage !== "undefined") {
1521
- store = {
1522
- get: (name) => JSON.parse(localStorage.getItem("metro/oidc:" + site + ":" + name)),
1523
- set: (name, value) => localStorage.setItem("metro/oidc:" + site + ":" + name, JSON.stringify(value)),
1524
- has: (name) => localStorage.getItem("metro/oidc:" + site + ":" + name) !== null
1525
- };
1526
- } else {
1527
- let storeMap = /* @__PURE__ */ new Map();
1528
- store = {
1529
- get: (name) => JSON.parse(storeMap.get("metro/oidc:" + site + ":" + name) || null),
1530
- set: (name, value) => storeMap.set("metro/oidc:" + site + ":" + name, JSON.stringify(value)),
1531
- has: (name) => storeMap.has("metro/oidc:" + site + ":" + name)
1532
- };
1533
- }
1534
- return store;
1535
- }
1536
-
1537
- // src/oidcmw.mjs
1538
- function oidcmw(options = {}) {
1539
- const defaultOptions = {
1540
- client: everything_default.client(),
1541
- force_authorization: false
1542
- };
1543
- options = Object.assign({}, defaultOptions, options);
1544
- assert(options, {
1545
- client: Required(instanceOf(everything_default.client().constructor)),
1546
- // required because it is set in defaultOptions
1547
- client_info: Required(),
1548
- issuer: Required(validURL),
1549
- oauth2: Optional({}),
1550
- openid_configuration: Optional()
1551
- });
1552
- if (!options.store) {
1553
- options.store = oidcStore(options.issuer);
1554
- }
1555
- if (!options.openid_configuration && options.store.has("openid_configuration")) {
1556
- options.openid_configuration = options.store.get("openid_configuration");
1557
- }
1558
- if (!options.client_info.client_id && options.store.has("client_info")) {
1559
- options.client_info = options.store.get("client_info");
1560
- }
1561
- return async (req, next) => {
1562
- let res;
1563
- if (!options.force_authorization) {
1564
- try {
1565
- res = await next(req);
1566
- } catch (err) {
1567
- if (res.status != 401 && res.status != 403) {
1568
- throw err;
1569
- }
1570
- }
1571
- if (res.ok || res.status != 401 && res.status != 403) {
1572
- return res;
1573
- }
1574
- }
1575
- if (!options.openid_configuration) {
1576
- options.openid_configuration = await oidcDiscovery({
1577
- issuer: options.issuer
1578
- });
1579
- options.store.set("openid_configuration", options.openid_configuration);
1580
- }
1581
- if (!options.client_info?.client_id) {
1582
- assert(options.client_info?.client_name, Required());
1583
- if (!options.openid_configuration.registration_endpoint) {
1584
- throw everything_default.metroError("metro.oidcmw: Error: issuer " + options.issuer + " does not support dynamic client registration, but you haven't specified a client_id");
1585
- }
1586
- options.client_info = await register({
1587
- registration_endpoint: options.openid_configuration.registration_endpoint,
1588
- client_info: options.client_info
1589
- });
1590
- options.store.set("client_info", options.client_info);
1591
- }
1592
- const oauth2Options = Object.assign(
1593
- {
1594
- site: options.issuer,
1595
- client: options.client,
1596
- force_authorization: true,
1597
- oauth2_configuration: {
1598
- client_id: options.client_info.client_id,
1599
- client_secret: options.client_info.client_secret,
1600
- code_verifier: false,
1601
- //disable pkce
1602
- grant_type: "authorization_code",
1603
- authorization_endpoint: options.openid_configuration.authorization_endpoint,
1604
- token_endpoint: options.openid_configuration.token_endpoint,
1605
- scope: options.openid_configuration.scope || "openid",
1606
- redirect_uri: options.client_info.redirect_uris[0]
1607
- //FIXME: find the best match?
1608
- }
1609
- }
1610
- //...
1611
- );
1612
- const oauth2client = options.client.with(options.issuer).with(mwOAuth2(oauth2Options));
1613
- res = await oauth2client.fetch(req);
1614
- return res;
1615
- };
1616
- }
1617
- function isRedirected2() {
1618
- return isRedirected();
1619
- }
1620
-
1621
- // src/browser.mjs
1622
- var oidc = {
1623
- discover: oidcDiscovery,
1624
- register,
1625
- oidcmw,
1626
- isRedirected: isRedirected2
1627
- };
1628
- globalThis.oidc = oidc;
1629
- })();
1630
- //# sourceMappingURL=browser-dev.js.map