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