@sphereon/ssi-express-support 0.33.1-feature.vcdm2.tsup.32 → 0.33.1-next.3

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 (42) hide show
  1. package/dist/auth-utils.d.ts +21 -0
  2. package/dist/auth-utils.d.ts.map +1 -0
  3. package/dist/auth-utils.js +148 -0
  4. package/dist/auth-utils.js.map +1 -0
  5. package/dist/entra-id-auth.d.ts +10 -0
  6. package/dist/entra-id-auth.d.ts.map +1 -0
  7. package/dist/entra-id-auth.js +61 -0
  8. package/dist/entra-id-auth.js.map +1 -0
  9. package/dist/express-builders.d.ts +99 -0
  10. package/dist/express-builders.d.ts.map +1 -0
  11. package/dist/express-builders.js +281 -0
  12. package/dist/express-builders.js.map +1 -0
  13. package/dist/express-utils.d.ts +4 -0
  14. package/dist/express-utils.d.ts.map +1 -0
  15. package/dist/express-utils.js +55 -0
  16. package/dist/express-utils.js.map +1 -0
  17. package/dist/functions.d.ts +2 -0
  18. package/dist/functions.d.ts.map +1 -0
  19. package/dist/functions.js +10 -0
  20. package/dist/functions.js.map +1 -0
  21. package/dist/index.d.ts +9 -403
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +26 -911
  24. package/dist/index.js.map +1 -1
  25. package/dist/openid-connect-rp.d.ts +54 -0
  26. package/dist/openid-connect-rp.d.ts.map +1 -0
  27. package/dist/openid-connect-rp.js +214 -0
  28. package/dist/openid-connect-rp.js.map +1 -0
  29. package/dist/static-bearer-auth.d.ts +34 -0
  30. package/dist/static-bearer-auth.d.ts.map +1 -0
  31. package/dist/static-bearer-auth.js +146 -0
  32. package/dist/static-bearer-auth.js.map +1 -0
  33. package/dist/types.d.ts +193 -0
  34. package/dist/types.d.ts.map +1 -0
  35. package/dist/types.js +7 -0
  36. package/dist/types.js.map +1 -0
  37. package/package.json +10 -22
  38. package/src/openid-connect-rp.ts +0 -1
  39. package/src/static-bearer-auth.ts +3 -5
  40. package/dist/index.cjs +0 -944
  41. package/dist/index.cjs.map +0 -1
  42. package/dist/index.d.cts +0 -403
package/dist/index.js CHANGED
@@ -1,913 +1,28 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/entra-id-auth.ts
5
- import passport from "passport";
6
- var EntraIDAuth = class _EntraIDAuth {
7
- static {
8
- __name(this, "EntraIDAuth");
9
- }
10
- strategy;
11
- options;
12
- static init(strategy) {
13
- return new _EntraIDAuth(strategy);
14
- }
15
- constructor(strategy) {
16
- this.strategy = strategy;
17
- }
18
- withOptions(options) {
19
- this.options = {
20
- ...options,
21
- passReqToCallback: "passReqToCallback" in options ? options.passReqToCallback : false
22
- };
23
- return this;
24
- }
25
- connectPassport() {
26
- const _options = this.options;
27
- if (!_options) {
28
- throw Error("No options supplied for EntraID");
29
- }
30
- import("passport-azure-ad").then((entraID) => passport.use(this.strategy, new entraID.BearerStrategy(_options, function(token, cb) {
31
- if (token) {
32
- return cb(null, token);
33
- }
34
- return cb("bearer token not found or incorrect", null);
35
- }))).catch((reason) => {
36
- console.log(reason);
37
- throw Error('Could not create bearer strategy. Did you include the "passport-azure-ad/bearer-strategy" dependency in package.json?');
38
- });
39
- }
40
- };
41
-
42
- // src/static-bearer-auth.ts
43
- import passport2 from "passport";
44
- import { toString } from "uint8arrays/to-string";
45
- var StaticBearerAuth = class _StaticBearerAuth {
46
- static {
47
- __name(this, "StaticBearerAuth");
48
- }
49
- strategy;
50
- static providers = /* @__PURE__ */ new Map();
51
- static verifyOptions = /* @__PURE__ */ new Map();
52
- hashTokens = false;
53
- static init(strategy, provider) {
54
- return new _StaticBearerAuth(strategy ?? "bearer", provider ?? new MapBasedStaticBearerUserProvider(strategy));
55
- }
56
- constructor(strategy, provider) {
57
- this.strategy = strategy;
58
- if (_StaticBearerAuth.providers.has(strategy)) {
59
- if (_StaticBearerAuth.providers.get(strategy) !== provider) {
60
- throw Error("Cannot register another user provider for strategy: " + strategy);
61
- }
62
- } else {
63
- _StaticBearerAuth.providers.set(strategy, provider);
64
- }
65
- }
66
- get provider() {
67
- const provider = _StaticBearerAuth.providers.get(this.strategy);
68
- if (!provider) {
69
- throw Error("Could not get user provider for " + this.strategy);
70
- }
71
- return provider;
72
- }
73
- withHashTokens(hashTokens) {
74
- this.hashTokens = hashTokens;
75
- return this;
76
- }
77
- withUsers(users) {
78
- this.addUser(users);
79
- return this;
80
- }
81
- addUser(user) {
82
- this.provider.addUser(user);
83
- return this;
84
- }
85
- withVerifyOptions(options) {
86
- _StaticBearerAuth.verifyOptions.set(this.strategy, options);
87
- return this;
88
- }
89
- connectPassport() {
90
- const _provider = this.provider;
91
- function findUser(token, cb) {
92
- const user = _provider.getUser(token);
93
- if (user) {
94
- return cb(null, user);
95
- }
96
- return cb("bearer token not found or incorrect", false);
97
- }
98
- __name(findUser, "findUser");
99
- import("passport-http-bearer").then((httpBearer) => {
100
- const hashTokens = this.hashTokens ?? false;
101
- passport2.use(this.strategy, new httpBearer.Strategy({
102
- passReqToCallback: false
103
- }, function(token, cb) {
104
- if (hashTokens) {
105
- import("@noble/hashes/sha256").then((hash) => {
106
- findUser(toString(hash.sha256(token)), cb);
107
- }).catch((error) => {
108
- console.log(`hash problem: ${error}`);
109
- throw Error("Did you include @noble/hashes in package.json?");
110
- });
111
- } else {
112
- findUser(token, cb);
113
- }
114
- }));
115
- }).catch((error) => {
116
- console.log(`passport-http-bearer package problem: ${error}`);
117
- throw Error("Did you include passport-http-bearer in package.json?");
118
- });
119
- }
120
- };
121
- var MapBasedStaticBearerUserProvider = class {
122
- static {
123
- __name(this, "MapBasedStaticBearerUserProvider");
124
- }
125
- _strategy;
126
- _users = [];
127
- _hashedTokens;
128
- constructor(strategy, hashedTokens) {
129
- this._strategy = strategy;
130
- this._hashedTokens = hashedTokens ?? false;
131
- }
132
- get users() {
133
- return this._users;
134
- }
135
- get hashedTokens() {
136
- return this._hashedTokens;
137
- }
138
- get strategy() {
139
- return this._strategy;
140
- }
141
- getUser(token) {
142
- return this.users.find((user) => user.token === token);
143
- }
144
- addUser(user, hashToken) {
145
- const users = Array.isArray(user) ? user : [
146
- user
147
- ];
148
- if (hashToken) {
149
- if (!this.hashedTokens) {
150
- throw Error("Cannot hash token, when hashed tokens is not enabled on the user provider for strategy " + this.strategy);
151
- }
152
- import("@noble/hashes/sha256").then((hash) => {
153
- users.forEach((user2) => user2.token = toString(hash.sha256(user2.token)));
154
- }).catch((error) => {
155
- console.log(`hash problem: ${error}`);
156
- throw Error("Did you include @noble/hashes in package.json?");
157
- });
158
- }
159
- this._users.push(...users);
160
- }
161
- getUsers() {
162
- return this._users;
163
- }
164
- };
165
-
166
- // src/auth-utils.ts
167
- import passport3 from "passport";
168
-
169
- // src/express-utils.ts
170
- function sendErrorResponse(response, statusCode, message, error) {
171
- let msg = message;
172
- if (!msg) {
173
- console.error("Message was null when calling sendErrorResponse. This should not happen");
174
- msg = "An unexpected error occurred";
175
- statusCode = 500;
176
- } else {
177
- console.error(`sendErrorResponse (${statusCode}): ${typeof msg === "string" ? msg : JSON.stringify(msg)}`);
178
- }
179
- if (error) {
180
- if (error instanceof Error) {
181
- console.error(`error message: ${error.message}`);
182
- }
183
- console.error(`error object: ${JSON.stringify(error)}`);
184
- }
185
- if (statusCode >= 500) {
186
- console.error("Original error stack (if any) and REST API error stack:");
187
- console.error(error?.stack);
188
- console.error(Error().stack);
189
- }
190
- if (response.headersSent) {
191
- console.error(`sendErrorResponse headers already sent`);
192
- return response;
193
- }
194
- response.statusCode = statusCode;
195
- if (typeof msg === "string" && !msg.startsWith("{")) {
196
- msg = {
197
- error: msg
198
- };
199
- }
200
- if (typeof msg === "string" && msg.startsWith("{")) {
201
- response.header("Content-Type", "application/json");
202
- return response.status(statusCode).end(msg);
203
- }
204
- return response.status(statusCode).json(msg);
205
- }
206
- __name(sendErrorResponse, "sendErrorResponse");
207
- var jsonErrorHandler = /* @__PURE__ */ __name((err, req, res, next) => {
208
- const statusCode = "statusCode" in err ? err.statusCode : 500;
209
- let errorMsg = typeof err === "string" ? err : err.message ?? err;
210
- if (typeof errorMsg !== "string") {
211
- errorMsg = JSON.stringify(errorMsg);
212
- }
213
- if (res.headersSent) {
214
- console.log("Headers already sent, when calling error handler. Will defer to next error handler");
215
- console.log(`Error was: ${JSON.stringify(err)}`);
216
- return next(err);
217
- }
218
- return sendErrorResponse(res, statusCode, errorMsg, err);
219
- }, "jsonErrorHandler");
220
-
221
- // src/types.ts
222
- function hasEndpointOpts(opts) {
223
- return "endpointOpts" in opts && opts.endpointOpts;
224
- }
225
- __name(hasEndpointOpts, "hasEndpointOpts");
226
-
227
- // src/auth-utils.ts
228
- var checkUserIsInRole = /* @__PURE__ */ __name((opts) => (req, res, next) => {
229
- if (!opts?.roles || opts.roles.length === 0) {
230
- return next();
231
- }
232
- const roles = Array.isArray(opts.roles) ? opts.roles : [
233
- opts.roles
234
- ];
235
- if (!req?.user || !("role" in req.user)) {
236
- return res.status(401).end();
237
- }
238
- const hasRole = roles.find((role) => req.user.role.toLowerCase() === role.toLowerCase());
239
- if (!hasRole) {
240
- return res.status(403).end();
241
- }
242
- return next();
243
- }, "checkUserIsInRole");
244
- var checkAuthenticationImpl = /* @__PURE__ */ __name((req, res, next, opts) => {
245
- const defaultCallback = /* @__PURE__ */ __name((err, user, _info, _status) => {
246
- if (err) {
247
- const message = "message" in err ? err.message : err;
248
- console.log("Authentication failed, error: " + JSON.stringify(message));
249
- return next({
250
- statusCode: 403,
251
- message
252
- });
253
- } else if (!user) {
254
- console.log("Authentication failed, no user object present in request. Redirecting to /login");
255
- return res.redirect("/authentication/login");
256
- }
257
- if (options.session) {
258
- req.logIn(user, function(err2) {
259
- if (err2) {
260
- return next(err2);
261
- }
262
- });
263
- }
264
- return next();
265
- }, "defaultCallback");
266
- if (!opts || !opts.authentication || opts.authentication.enabled === false) {
267
- return next();
268
- }
269
- if (!opts.authentication.strategy) {
270
- console.log(`Authentication enabled, but no strategy configured. All auth request will be denied!`);
271
- return res.status(401).end();
272
- }
273
- const options = {
274
- ...opts?.authentication?.strategyOptions,
275
- authInfo: opts?.authentication?.authInfo !== false,
276
- session: opts?.authentication?.session !== false
277
- };
278
- const callback = opts?.authentication?.callback ?? (opts?.authentication?.useDefaultCallback ? defaultCallback : void 0);
279
- passport3.authenticate(opts.authentication.strategy, options, callback).call(void 0, req, res, next);
280
- }, "checkAuthenticationImpl");
281
- var checkAuthorizationImpl = /* @__PURE__ */ __name((req, res, next, opts) => {
282
- if (!opts || !opts.authentication || !opts.authorization || opts.authentication.enabled === false || opts?.authorization.enabled === false) {
283
- return next();
284
- }
285
- const authorization = opts.authorization;
286
- if (!authorization.enforcer && (!authorization.requireUserInRoles || authorization.requireUserInRoles.length === 0)) {
287
- console.log(`Authorization enabled for endpoint, but no enforcer or roles supplied`);
288
- return res.status(401).end();
289
- }
290
- if (authorization.requireUserInRoles && authorization.requireUserInRoles.length > 0) {
291
- checkUserIsInRole({
292
- roles: authorization.requireUserInRoles
293
- });
294
- }
295
- if (authorization.enforcer) {
296
- const enforcer = authorization.enforcer;
297
- const permitted = enforcer.enforceSync(req.user, opts.resource, opts.operation);
298
- if (!permitted) {
299
- console.log(`Access to ${opts.resource} and op ${opts.operation} not allowed for ${req.user}`);
300
- return res.status(403).end();
301
- }
302
- }
303
- return next();
304
- }, "checkAuthorizationImpl");
305
- var checkAuthenticationOnly = /* @__PURE__ */ __name((opts) => (req, res, next) => {
306
- return checkAuthenticationImpl(req, res, next, opts);
307
- }, "checkAuthenticationOnly");
308
- var checkAuthorizationOnly = /* @__PURE__ */ __name((opts) => (req, res, next) => {
309
- return checkAuthorizationImpl(req, res, next, opts);
310
- }, "checkAuthorizationOnly");
311
- var isUserNotAuthenticated = /* @__PURE__ */ __name((req, res, next) => {
312
- if (!req.user) {
313
- next();
314
- }
315
- }, "isUserNotAuthenticated");
316
- var isUserAuthenticated = /* @__PURE__ */ __name((req, res, next) => {
317
- if (!req.user) {
318
- return sendErrorResponse(res, 401, "Authentication required");
319
- } else {
320
- return next();
321
- }
322
- }, "isUserAuthenticated");
323
- var checkAuth = /* @__PURE__ */ __name((opts) => {
324
- const handlers = [];
325
- handlers.push(checkAuthenticationOnly(opts));
326
- handlers.push(checkAuthorizationOnly(opts));
327
- opts?.handlers && handlers.push(...opts.handlers);
328
- return handlers;
329
- }, "checkAuth");
330
- function copyGlobalAuthToEndpoint(args) {
331
- const opts = args?.opts;
332
- const key = args?.key;
333
- if (!opts || !key || !hasEndpointOpts(opts)) {
334
- return;
335
- }
336
- if (key === "basePath") {
337
- return;
338
- }
339
- if (opts.endpointOpts?.globalAuth) {
340
- if (opts.endpointOpts[key]?.disableGlobalAuth === true) {
341
- return;
342
- }
343
- opts.endpointOpts[key] = {
344
- ...opts.endpointOpts[key],
345
- endpoint: {
346
- ...opts.endpointOpts.globalAuth,
347
- ...opts.endpointOpts[key]?.endpoint
348
- }
349
- };
350
- }
351
- }
352
- __name(copyGlobalAuthToEndpoint, "copyGlobalAuthToEndpoint");
353
- function copyGlobalAuthToEndpoints(args) {
354
- args?.keys.forEach((key) => copyGlobalAuthToEndpoint({
355
- opts: args?.opts,
356
- key
357
- }));
358
- }
359
- __name(copyGlobalAuthToEndpoints, "copyGlobalAuthToEndpoints");
360
-
361
- // src/express-builders.ts
362
- import bodyParser from "body-parser";
363
- import cors from "cors";
364
- import express from "express";
365
- import expressSession from "express-session";
366
- import { createHttpTerminator } from "http-terminator";
367
- import morgan from "morgan";
368
- import passport4 from "passport";
369
-
370
- // src/functions.ts
371
- function env(key, prefix) {
372
- if (!key) {
373
- return void 0;
374
- }
375
- return process.env[`${prefix ? prefix.trim() : ""}${key}`];
376
- }
377
- __name(env, "env");
378
-
379
- // src/express-builders.ts
380
- var ExpressBuilder = class _ExpressBuilder {
381
- static {
382
- __name(this, "ExpressBuilder");
383
- }
384
- existingExpress;
385
- hostnameOrIP;
386
- port;
387
- _handlers = [];
388
- listenCallback;
389
- _startListen = void 0;
390
- envVarPrefix;
391
- _corsConfigurer;
392
- _sessionOpts;
393
- _usePassportAuth = false;
394
- _passportInitOpts;
395
- _userIsInRole;
396
- _enforcer;
397
- _server;
398
- _terminator;
399
- _morgan;
400
- constructor(opts) {
401
- const { existingExpress, envVarPrefix } = opts ?? {};
402
- if (existingExpress) {
403
- this.withExpress(existingExpress);
404
- }
405
- this.envVarPrefix = envVarPrefix ?? "";
406
- }
407
- static fromExistingExpress(opts) {
408
- return new _ExpressBuilder(opts ?? {});
409
- }
410
- static fromServerOpts(opts) {
411
- const builder = new _ExpressBuilder({
412
- existingExpress: opts?.existingExpress,
413
- envVarPrefix: opts?.envVarPrefix
414
- });
415
- return builder.withEnableListenOpts({
416
- ...opts,
417
- hostnameOrIP: opts.hostname,
418
- startOnBuild: opts.startListening ?? false
419
- });
420
- }
421
- enableListen(startOnBuild) {
422
- if (startOnBuild !== void 0) {
423
- this._startListen = startOnBuild;
424
- }
425
- return this;
426
- }
427
- withMorganLogging(opts) {
428
- if (opts?.existingMorgan && (opts.format || opts.options)) {
429
- throw Error("Cannot using an existing morgan with either a format or options");
430
- }
431
- this._morgan = opts?.existingMorgan ?? morgan(opts?.format ?? "dev", opts?.options);
432
- return this;
433
- }
434
- withEnableListenOpts({ port, hostnameOrIP, callback, startOnBuild }) {
435
- port && this.withPort(port);
436
- hostnameOrIP && this.withHostname(hostnameOrIP);
437
- if (typeof callback === "function") {
438
- this.withListenCallback(callback);
439
- }
440
- this._startListen = startOnBuild === true;
441
- return this;
442
- }
443
- withPort(port) {
444
- this.port = port;
445
- return this;
446
- }
447
- withHostname(hostnameOrIP) {
448
- this.hostnameOrIP = hostnameOrIP;
449
- return this;
450
- }
451
- withListenCallback(callback) {
452
- this.listenCallback = callback;
453
- return this;
454
- }
455
- withExpress(existingExpress) {
456
- this.existingExpress = existingExpress;
457
- this._startListen = false;
458
- return this;
459
- }
460
- withCorsConfigurer(configurer) {
461
- this._corsConfigurer = configurer;
462
- return this;
463
- }
464
- withPassportAuth(usePassport, initializeOptions) {
465
- this._usePassportAuth = usePassport;
466
- this._passportInitOpts = initializeOptions;
467
- return this;
468
- }
469
- withGlobalUserIsInRole(userIsInRole) {
470
- this._userIsInRole = userIsInRole;
471
- return this;
472
- }
473
- withEnforcer(enforcer) {
474
- this._enforcer = enforcer;
475
- return this;
476
- }
477
- startListening(express3) {
478
- this._server = express3.listen(this.getPort(), this.getHostname(), this.listenCallback);
479
- this._terminator = createHttpTerminator({
480
- server: this._server
481
- });
482
- return {
483
- server: this._server,
484
- terminator: this._terminator
485
- };
486
- }
487
- getHostname() {
488
- return this.hostnameOrIP ?? env("HOSTNAME", this.envVarPrefix) ?? "0.0.0.0";
489
- }
490
- getPort() {
491
- return this.port ?? env("PORT", this.envVarPrefix) ?? 5e3;
492
- }
493
- setHandlers(handlers) {
494
- if (Array.isArray(handlers)) {
495
- this._handlers = handlers;
496
- } else if (handlers) {
497
- if (!this._handlers) {
498
- this._handlers = [];
499
- }
500
- this._handlers.push(handlers);
501
- } else {
502
- this._handlers = [];
503
- }
504
- return this;
505
- }
506
- addHandler(handler) {
507
- if (!this._handlers) {
508
- this._handlers = [];
509
- }
510
- this._handlers.push(handler);
511
- return this;
512
- }
513
- withSessionOptions(sessionOpts) {
514
- this._sessionOpts = sessionOpts;
515
- return this;
516
- }
517
- build(opts) {
518
- const express3 = this.buildExpress(opts);
519
- const startListening = opts?.startListening === void 0 ? this._startListen !== true : opts.startListening;
520
- let started = this._server !== void 0;
521
- if (startListening && !started) {
522
- this.startListening(express3);
523
- started = true;
524
- }
525
- return {
526
- express: express3,
527
- port: this.getPort(),
528
- hostname: this.getHostname(),
529
- userIsInRole: this._userIsInRole,
530
- startListening,
531
- enforcer: this._enforcer,
532
- start: /* @__PURE__ */ __name((opts2) => {
533
- if (opts2?.doNotStartListening) {
534
- console.log("Express will not start listening. You will have to start it yourself");
535
- } else {
536
- if (!started) {
537
- this.startListening(express3);
538
- started = true;
539
- }
540
- }
541
- if (opts2?.disableErrorHandler !== true) {
542
- express3.use(jsonErrorHandler);
543
- }
544
- return {
545
- server: this._server,
546
- terminator: this._terminator
547
- };
548
- }, "start"),
549
- stop: /* @__PURE__ */ __name(async (terminator) => {
550
- const term = terminator ?? this._terminator;
551
- if (!term) {
552
- return false;
553
- }
554
- return await term.terminate().then(() => true);
555
- }, "stop")
556
- };
557
- }
558
- buildExpress(opts) {
559
- const app = opts?.express ?? this.existingExpress ?? express();
560
- if (this._morgan) {
561
- app.use(this._morgan);
562
- }
563
- if (this._sessionOpts) {
564
- const store = this._sessionOpts.store ?? new expressSession.MemoryStore();
565
- this._sessionOpts.store = store;
566
- app.use(expressSession(this._sessionOpts));
567
- }
568
- if (this._usePassportAuth) {
569
- app.use(passport4.initialize(this._passportInitOpts));
570
- if (this._sessionOpts) {
571
- app.use(passport4.session());
572
- }
573
- }
574
- if (this._userIsInRole) {
575
- app.use(checkUserIsInRole({
576
- roles: this._userIsInRole
577
- }));
578
- }
579
- if (this._corsConfigurer) {
580
- this._corsConfigurer.configure({
581
- existingExpress: app
582
- });
583
- }
584
- this._handlers && this._handlers.length > 0 && app.use(this._handlers);
585
- opts?.handlers && app.use(opts.handlers);
586
- app.use(bodyParser.urlencoded({
587
- extended: true
588
- }));
589
- app.use(bodyParser.json({
590
- limit: "5mb"
591
- }));
592
- return app;
593
- }
594
- };
595
- var ExpressCorsConfigurer = class {
596
- static {
597
- __name(this, "ExpressCorsConfigurer");
598
- }
599
- _disableCors;
600
- _enablePreflightOptions;
601
- _allowOrigin;
602
- _allowMethods;
603
- _allowedHeaders;
604
- _allowCredentials;
605
- _express;
606
- _envVarPrefix;
607
- constructor(args) {
608
- const { existingExpress, envVarPrefix } = args ?? {};
609
- this._express = existingExpress;
610
- this._envVarPrefix = envVarPrefix;
611
- }
612
- allowOrigin(value) {
613
- this._allowOrigin = value;
614
- return this;
615
- }
616
- disableCors(value) {
617
- this._disableCors = value;
618
- return this;
619
- }
620
- allowMethods(value) {
621
- this._allowMethods = value;
622
- return this;
623
- }
624
- allowedHeaders(value) {
625
- this._allowedHeaders = value;
626
- return this;
627
- }
628
- allowCredentials(value) {
629
- this._allowCredentials = value;
630
- return this;
631
- }
632
- configure({ existingExpress }) {
633
- const express3 = existingExpress ?? this._express;
634
- if (!express3) {
635
- throw Error("No express passed in during construction or configure");
636
- }
637
- const disableCorsEnv = env("CORS_DISABLE", this._envVarPrefix);
638
- const corsDisabled = this._disableCors ?? (disableCorsEnv ? /true/.test(disableCorsEnv) : false);
639
- if (corsDisabled) {
640
- return;
641
- }
642
- const envAllowOriginStr = env("CORS_ALLOW_ORIGIN", this._envVarPrefix) ?? "*";
643
- let envAllowOrigin;
644
- if (envAllowOriginStr.includes(",")) {
645
- envAllowOrigin = envAllowOriginStr.split(",");
646
- } else if (envAllowOriginStr.includes(" ")) {
647
- envAllowOrigin = envAllowOriginStr.split(" ");
648
- } else {
649
- envAllowOrigin = envAllowOriginStr;
650
- }
651
- if (Array.isArray(envAllowOrigin) && envAllowOrigin.length === 1) {
652
- envAllowOrigin = envAllowOrigin[0];
653
- }
654
- const corsOptions = {
655
- origin: this._allowOrigin ?? envAllowOrigin,
656
- // todo: env vars
657
- ...this._allowMethods && {
658
- methods: this._allowMethods
659
- },
660
- ...this._allowedHeaders && {
661
- allowedHeaders: this._allowedHeaders
662
- },
663
- ...this._allowCredentials !== void 0 && {
664
- credentials: this._allowCredentials
665
- },
666
- optionsSuccessStatus: 204
667
- };
668
- if (this._enablePreflightOptions) {
669
- express3.options("*", cors(corsOptions));
670
- }
671
- express3.use(cors(corsOptions));
672
- }
673
- };
674
-
675
- // src/openid-connect-rp.ts
676
- import express2 from "express";
677
- import { Issuer } from "openid-client";
678
- import passport5 from "passport";
679
- var PREFIX = process.env.PREFIX ?? "";
680
- async function oidcDiscoverIssuer(opts) {
681
- const issuerUrl = opts?.issuerUrl ?? env("OIDC_ISSUER", PREFIX) ?? "https://auth01.test.sphereon.com/auth/realms/energy-shr";
682
- const issuer = await Issuer.discover(issuerUrl);
683
- console.log("Discovered issuer %s %O", issuer.issuer, issuer.metadata);
684
- return {
685
- issuer,
686
- issuerUrl
687
- };
688
- }
689
- __name(oidcDiscoverIssuer, "oidcDiscoverIssuer");
690
- async function oidcGetClient(issuer, metadata, opts) {
691
- return new issuer.Client(metadata, opts?.jwks, opts?.options);
692
- }
693
- __name(oidcGetClient, "oidcGetClient");
694
- function getLoginEndpoint(router, opts) {
695
- if (opts?.enabled === false) {
696
- console.log(`Login endpoint is disabled`);
697
- return;
698
- }
699
- const strategy = opts?.endpoint?.authentication?.strategy;
700
- if (!strategy) {
701
- throw Error("strategy needs to be provided");
702
- }
703
- const path = opts?.path ?? "/authentication/login";
704
- router.get(path, (req, res, next) => {
705
- const redirectPage = req.get("referer") ?? "/";
706
- req.session.redirectPage = redirectPage;
707
- next();
708
- }, passport5.authenticate(strategy, {
709
- ...opts.authentication?.strategyOptions,
710
- ...opts.endpoint?.authentication?.strategyOptions,
711
- keepSessionInfo: false
712
- }, void 0));
713
- }
714
- __name(getLoginEndpoint, "getLoginEndpoint");
715
- function getLoginCallbackEndpoint(router, opts) {
716
- if (opts?.enabled === false) {
717
- console.log(`Auth callback endpoint is disabled`);
718
- return;
719
- }
720
- const strategy = opts?.endpoint?.authentication?.strategy;
721
- if (!strategy) {
722
- throw Error("strategy needs to be provided");
723
- }
724
- const path = opts?.path ?? "/authentication/callback";
725
- router.get(path, passport5.authenticate(strategy, {
726
- ...opts.authentication?.strategyOptions,
727
- ...opts.endpoint?.authentication?.strategyOptions,
728
- keepSessionInfo: true
729
- }, void 0), (req, res, next) => {
730
- if (req.user) {
731
- console.log("User authenticated", req.user?.name);
732
- const redirectPage = req.session.redirectPage ?? "/search";
733
- delete req.session.redirectPage;
734
- return res.redirect(redirectPage);
735
- } else {
736
- return res.redirect(env("OIDC_FRONTEND_LOGIN_URL", PREFIX) ?? "http://localhost:3001/authentication/login");
737
- }
738
- });
739
- }
740
- __name(getLoginCallbackEndpoint, "getLoginCallbackEndpoint");
741
- function getLogoutEndpoint(router, client, opts) {
742
- if (opts?.enabled === false) {
743
- console.log(`Logout endpoint is disabled`);
744
- return;
745
- }
746
- const path = opts?.path ?? "/authentication/logout";
747
- router.get(path, (req, res) => {
748
- try {
749
- if (client.endSessionUrl()) {
750
- return res.redirect(client.endSessionUrl());
751
- } else {
752
- console.log("IDP does not support end session url");
753
- return res.redirect("/authentication/logout-callback");
754
- }
755
- } catch (error) {
756
- console.log(error);
757
- return res.redirect("/authentication/logout-callback");
758
- }
759
- });
760
- }
761
- __name(getLogoutEndpoint, "getLogoutEndpoint");
762
- function getLogoutCallbackEndpoint(router, opts) {
763
- if (opts?.enabled === false) {
764
- console.log(`Logout callback endpoint is disabled`);
765
- return;
766
- }
767
- const path = opts?.path ?? "/authentication/logout-callback";
768
- router.get(path, (req, res, next) => {
769
- try {
770
- req.logout((err) => {
771
- if (err) {
772
- console.log(`Error during calling logout-callback: ${JSON.stringify(err)}`);
773
- }
774
- });
775
- return res.redirect(env("OIDC_FRONTEND_LOGOUT_REDIRECT_URL", PREFIX) ?? "/");
776
- } catch (e) {
777
- return sendErrorResponse(res, 500, "An unexpected error occurred during logout callback", e);
778
- }
779
- });
780
- }
781
- __name(getLogoutCallbackEndpoint, "getLogoutCallbackEndpoint");
782
- function getIdTokenEndpoint(router, client, opts) {
783
- if (opts?.enabled === false) {
784
- console.log(`ID Token endpoint is disabled`);
785
- return;
786
- }
787
- const path = opts.path ?? "/authentication/tokens/id";
788
- router.get(path, isUserAuthenticated, (req, res) => {
789
- if (req.session.tokens.id_token) {
790
- return res.json({
791
- id_token: req.session.tokens.id_token
792
- });
793
- } else {
794
- return sendErrorResponse(res, 401, "Authentication required");
795
- }
796
- });
797
- }
798
- __name(getIdTokenEndpoint, "getIdTokenEndpoint");
799
- function getAuthenticatedUserEndpoint(router, opts) {
800
- if (opts?.enabled === false) {
801
- console.log(`Authenticated User endpoint is disabled`);
802
- return;
803
- }
804
- const path = opts?.path ?? "/authentication/user";
805
- router.get(path, isUserAuthenticated, (req, res, next) => {
806
- if (!req.user) {
807
- return sendErrorResponse(res, 401, "Authentication required");
808
- }
809
- let user = req.user;
810
- return res.json(user);
811
- });
812
- }
813
- __name(getAuthenticatedUserEndpoint, "getAuthenticatedUserEndpoint");
814
- var OpenIDConnectAuthApi = class {
815
- static {
816
- __name(this, "OpenIDConnectAuthApi");
817
- }
818
- get router() {
819
- return this._router;
820
- }
821
- _express;
822
- _agent;
823
- _opts;
824
- _router;
825
- constructor(args) {
826
- const { agent, opts } = args;
827
- this._agent = agent;
828
- copyGlobalAuthToEndpoints({
829
- opts,
830
- keys: [
831
- "getLogin"
832
- ]
833
- });
834
- copyGlobalAuthToEndpoints({
835
- opts,
836
- keys: [
837
- "getIdToken"
838
- ]
839
- });
840
- copyGlobalAuthToEndpoints({
841
- opts,
842
- keys: [
843
- "getAuthenticatedUser"
844
- ]
845
- });
846
- this._opts = opts;
847
- this._express = args.expressSupport.express;
848
- this._router = express2.Router();
849
- const features = opts?.enabledFeatures ?? [
850
- "login",
851
- "logout",
852
- "id-token",
853
- "authenticated-user"
854
- ];
855
- console.log(`Authentication API enabled`);
856
- if (features.includes("login")) {
857
- getLoginEndpoint(this.router, opts?.endpointOpts?.getLogin);
858
- getLoginCallbackEndpoint(this.router, opts?.endpointOpts?.getLogin);
859
- }
860
- if (features.includes("logout")) {
861
- getLogoutEndpoint(this.router, args.client, opts?.endpointOpts?.getLogout);
862
- getLogoutCallbackEndpoint(this.router, opts?.endpointOpts?.getLogout);
863
- }
864
- if (features.includes("id-token")) {
865
- if (opts.endpointOpts?.getIdToken === void 0) {
866
- throw Error("Cannot enable id-token endpoint without providing id-token endpoint options");
867
- }
868
- getIdTokenEndpoint(this.router, args.client, opts?.endpointOpts?.getIdToken);
869
- }
870
- if (features.includes("authenticated-user")) {
871
- getAuthenticatedUserEndpoint(this.router, opts?.endpointOpts?.getAuthenticatedUser);
872
- }
873
- this._express.use(opts?.endpointOpts?.basePath ?? "", this.router);
874
- }
875
- get agent() {
876
- return this._agent;
877
- }
878
- get opts() {
879
- return this._opts;
880
- }
881
- get express() {
882
- return this._express;
883
- }
884
- };
885
- export {
886
- EntraIDAuth,
887
- ExpressBuilder,
888
- ExpressCorsConfigurer,
889
- MapBasedStaticBearerUserProvider,
890
- OpenIDConnectAuthApi,
891
- StaticBearerAuth,
892
- checkAuth,
893
- checkAuthenticationOnly,
894
- checkAuthorizationOnly,
895
- checkUserIsInRole,
896
- copyGlobalAuthToEndpoint,
897
- copyGlobalAuthToEndpoints,
898
- env,
899
- getAuthenticatedUserEndpoint,
900
- getIdTokenEndpoint,
901
- getLoginCallbackEndpoint,
902
- getLoginEndpoint,
903
- getLogoutCallbackEndpoint,
904
- getLogoutEndpoint,
905
- hasEndpointOpts,
906
- isUserAuthenticated,
907
- isUserNotAuthenticated,
908
- jsonErrorHandler,
909
- oidcDiscoverIssuer,
910
- oidcGetClient,
911
- sendErrorResponse
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);
912
15
  };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.jsonErrorHandler = exports.sendErrorResponse = void 0;
18
+ __exportStar(require("./entra-id-auth"), exports);
19
+ __exportStar(require("./static-bearer-auth"), exports);
20
+ __exportStar(require("./auth-utils"), exports);
21
+ __exportStar(require("./express-builders"), exports);
22
+ __exportStar(require("./types"), exports);
23
+ var express_utils_1 = require("./express-utils");
24
+ Object.defineProperty(exports, "sendErrorResponse", { enumerable: true, get: function () { return express_utils_1.sendErrorResponse; } });
25
+ Object.defineProperty(exports, "jsonErrorHandler", { enumerable: true, get: function () { return express_utils_1.jsonErrorHandler; } });
26
+ __exportStar(require("./functions"), exports);
27
+ __exportStar(require("./openid-connect-rp"), exports);
913
28
  //# sourceMappingURL=index.js.map