@sphereon/ssi-express-support 0.14.2-next.25

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 (48) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +25 -0
  3. package/dist/auth-utils.d.ts +19 -0
  4. package/dist/auth-utils.d.ts.map +1 -0
  5. package/dist/auth-utils.js +118 -0
  6. package/dist/auth-utils.js.map +1 -0
  7. package/dist/entra-id-auth.d.ts +10 -0
  8. package/dist/entra-id-auth.d.ts.map +1 -0
  9. package/dist/entra-id-auth.js +61 -0
  10. package/dist/entra-id-auth.js.map +1 -0
  11. package/dist/express-builders.d.ts +94 -0
  12. package/dist/express-builders.d.ts.map +1 -0
  13. package/dist/express-builders.js +269 -0
  14. package/dist/express-builders.js.map +1 -0
  15. package/dist/express-utils.d.ts +4 -0
  16. package/dist/express-utils.d.ts.map +1 -0
  17. package/dist/express-utils.js +34 -0
  18. package/dist/express-utils.js.map +1 -0
  19. package/dist/functions.d.ts +2 -0
  20. package/dist/functions.d.ts.map +1 -0
  21. package/dist/functions.js +11 -0
  22. package/dist/functions.js.map +1 -0
  23. package/dist/index.d.ts +8 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +27 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/openid-connect-auth.d.ts +10 -0
  28. package/dist/openid-connect-auth.d.ts.map +1 -0
  29. package/dist/openid-connect-auth.js +61 -0
  30. package/dist/openid-connect-auth.js.map +1 -0
  31. package/dist/static-bearer-auth.d.ts +34 -0
  32. package/dist/static-bearer-auth.d.ts.map +1 -0
  33. package/dist/static-bearer-auth.js +146 -0
  34. package/dist/static-bearer-auth.js.map +1 -0
  35. package/dist/types.d.ts +179 -0
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/types.js +8 -0
  38. package/dist/types.js.map +1 -0
  39. package/package.json +70 -0
  40. package/src/auth-utils.ts +127 -0
  41. package/src/entra-id-auth.ts +47 -0
  42. package/src/express-builders.ts +320 -0
  43. package/src/express-utils.ts +30 -0
  44. package/src/functions.ts +6 -0
  45. package/src/index.ts +7 -0
  46. package/src/openid-connect-auth.ts +47 -0
  47. package/src/static-bearer-auth.ts +151 -0
  48. package/src/types.ts +192 -0
@@ -0,0 +1,146 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.MapBasedStaticBearerUserProvider = exports.StaticBearerAuth = void 0;
30
+ const passport_1 = __importDefault(require("passport"));
31
+ const u8a = __importStar(require("uint8arrays"));
32
+ class StaticBearerAuth {
33
+ static init(strategy, provider) {
34
+ return new StaticBearerAuth(strategy !== null && strategy !== void 0 ? strategy : 'bearer', provider !== null && provider !== void 0 ? provider : new MapBasedStaticBearerUserProvider(strategy));
35
+ }
36
+ constructor(strategy, provider) {
37
+ this.hashTokens = false;
38
+ this.strategy = strategy;
39
+ if (StaticBearerAuth.providers.has(strategy)) {
40
+ if (StaticBearerAuth.providers.get(strategy) !== provider) {
41
+ throw Error('Cannot register another user provider for strategy: ' + strategy);
42
+ }
43
+ }
44
+ else {
45
+ StaticBearerAuth.providers.set(strategy, provider);
46
+ }
47
+ }
48
+ get provider() {
49
+ const provider = StaticBearerAuth.providers.get(this.strategy);
50
+ if (!provider) {
51
+ throw Error('Could not get user provider for ' + this.strategy);
52
+ }
53
+ return provider;
54
+ }
55
+ withHashTokens(hashTokens) {
56
+ this.hashTokens = hashTokens;
57
+ return this;
58
+ }
59
+ withUsers(users) {
60
+ this.addUser(users);
61
+ return this;
62
+ }
63
+ addUser(user) {
64
+ this.provider.addUser(user);
65
+ return this;
66
+ }
67
+ withVerifyOptions(options) {
68
+ StaticBearerAuth.verifyOptions.set(this.strategy, options);
69
+ return this;
70
+ }
71
+ connectPassport() {
72
+ const _provider = this.provider;
73
+ function findUser(token, cb) {
74
+ const user = _provider.getUser(token);
75
+ if (user) {
76
+ return cb(null, user);
77
+ }
78
+ return cb('bearer token not found or incorrect', false);
79
+ }
80
+ Promise.resolve().then(() => __importStar(require('passport-http-bearer'))).then((httpBearer) => {
81
+ var _a;
82
+ const hashTokens = (_a = this.hashTokens) !== null && _a !== void 0 ? _a : false;
83
+ passport_1.default.use(this.strategy, new httpBearer.Strategy({ passReqToCallback: false }, function (token, cb) {
84
+ if (hashTokens) {
85
+ Promise.resolve().then(() => __importStar(require('@noble/hashes/sha256'))).then((hash) => {
86
+ findUser(u8a.toString(hash.sha256(token)), cb);
87
+ })
88
+ .catch((error) => {
89
+ console.log(`hash problem: ${error}`);
90
+ throw Error('Did you include @noble/hashes in package.json?');
91
+ });
92
+ }
93
+ else {
94
+ findUser(token, cb);
95
+ }
96
+ }));
97
+ })
98
+ .catch((error) => {
99
+ console.log(`passport-http-bearer package problem: ${error}`);
100
+ throw Error('Did you include passport-http-bearer in package.json?');
101
+ });
102
+ }
103
+ }
104
+ exports.StaticBearerAuth = StaticBearerAuth;
105
+ StaticBearerAuth.providers = new Map();
106
+ StaticBearerAuth.verifyOptions = new Map();
107
+ class MapBasedStaticBearerUserProvider {
108
+ constructor(strategy, hashedTokens) {
109
+ this._users = [];
110
+ this._strategy = strategy;
111
+ this._hashedTokens = hashedTokens !== null && hashedTokens !== void 0 ? hashedTokens : false;
112
+ }
113
+ get users() {
114
+ return this._users;
115
+ }
116
+ get hashedTokens() {
117
+ return this._hashedTokens;
118
+ }
119
+ get strategy() {
120
+ return this._strategy;
121
+ }
122
+ getUser(token) {
123
+ return this.users.find((user) => user.token === token);
124
+ }
125
+ addUser(user, hashToken) {
126
+ const users = Array.isArray(user) ? user : [user];
127
+ if (hashToken) {
128
+ if (!this.hashedTokens) {
129
+ throw Error('Cannot hash token, when hashed tokens is not enabled on the user provider for strategy ' + this.strategy);
130
+ }
131
+ Promise.resolve().then(() => __importStar(require('@noble/hashes/sha256'))).then((hash) => {
132
+ users.forEach((user) => (user.token = u8a.toString(hash.sha256(user.token))));
133
+ })
134
+ .catch((error) => {
135
+ console.log(`hash problem: ${error}`);
136
+ throw Error('Did you include @noble/hashes in package.json?');
137
+ });
138
+ }
139
+ this._users.push(...users);
140
+ }
141
+ getUsers() {
142
+ return this._users;
143
+ }
144
+ }
145
+ exports.MapBasedStaticBearerUserProvider = MapBasedStaticBearerUserProvider;
146
+ //# sourceMappingURL=static-bearer-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"static-bearer-auth.js","sourceRoot":"","sources":["../src/static-bearer-auth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA+B;AAC/B,iDAAkC;AAElC,MAAa,gBAAgB;IAMpB,MAAM,CAAC,IAAI,CAAC,QAAgB,EAAE,QAAmC;QACtE,OAAO,IAAI,gBAAgB,CAAC,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,QAAQ,EAAE,QAAQ,aAAR,QAAQ,cA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,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC/E,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;gBACf,OAAO,CAAC,GAAG,CAAC,iBAAiB,KAAK,EAAE,CAAC,CAAA;gBACrC,MAAM,KAAK,CAAC,gDAAgD,CAAC,CAAA;YAC/D,CAAC,CAAC,CAAA;SACL;QACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAA;IAC5B,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;CACF;AA/CD,4EA+CC"}
@@ -0,0 +1,179 @@
1
+ import { Enforcer } from 'casbin';
2
+ import { Express, RequestHandler } from 'express';
3
+ import { ParamsDictionary } from 'express-serve-static-core';
4
+ import { Strategy } from 'passport';
5
+ import { ParsedQs } from 'qs';
6
+ export interface IExpressServerOpts {
7
+ port?: number;
8
+ cookieSigningKey?: string;
9
+ hostname?: string;
10
+ basePath?: string;
11
+ existingExpress?: Express;
12
+ listenCallback?: () => void;
13
+ startListening?: boolean;
14
+ }
15
+ export declare function hasEndpointOpts(opts: any): any;
16
+ export type HasEndpointOpts = {
17
+ endpointOpts?: IEndpointOpts & SingleEndpoints;
18
+ } & Record<string, any>;
19
+ export type SingleEndpoints = Record<string, ISingleEndpointOpts | any>;
20
+ export interface IEndpointOpts {
21
+ basePath?: string;
22
+ globalAuth?: GenericAuthArgs;
23
+ }
24
+ export interface ExpressSupport {
25
+ express: Express;
26
+ port: number;
27
+ hostname: string;
28
+ userIsInRole?: string | string[];
29
+ startListening: boolean;
30
+ enforcer?: Enforcer;
31
+ start: (opts?: {
32
+ disableErrorHandler?: boolean;
33
+ }) => Express;
34
+ }
35
+ export interface ISingleEndpointOpts extends GenericAuthArgs {
36
+ endpoint?: EndpointArgs;
37
+ enabled?: boolean;
38
+ path?: string;
39
+ disableGlobalAuth?: boolean;
40
+ }
41
+ export interface GenericAuthArgs {
42
+ authentication?: {
43
+ enabled?: boolean;
44
+ strategy?: string | string[] | Strategy;
45
+ };
46
+ authorization?: {
47
+ enabled?: boolean;
48
+ requireUserInRoles?: string | string[];
49
+ enforcer?: Enforcer;
50
+ };
51
+ }
52
+ export interface EndpointArgs extends GenericAuthArgs {
53
+ resource?: string;
54
+ operation?: string;
55
+ handlers?: RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>[];
56
+ }
57
+ export interface BearerUser extends Express.User {
58
+ id: string | number;
59
+ name?: string;
60
+ token: string;
61
+ }
62
+ export interface IStaticBearerVerifyOptions {
63
+ message?: string | undefined;
64
+ scope: string | Array<string>;
65
+ }
66
+ export interface IBaseStrategyOption {
67
+ identityMetadata: string;
68
+ clientID: string;
69
+ isB2C?: boolean | undefined;
70
+ validateIssuer?: boolean | undefined;
71
+ issuer?: string | string[] | undefined;
72
+ loggingLevel?: 'info' | 'warn' | 'error' | undefined;
73
+ loggingNoPII?: boolean | undefined;
74
+ clockSkew?: number | undefined;
75
+ }
76
+ export interface ITokenPayload {
77
+ /** An App ID URI. Identifies the intended recipient of the token. */
78
+ aud?: string | undefined;
79
+ /** A security token service(STS) URI. Identifies the STS that constructs and returns the token,
80
+ * and the Azure AD tenant in which the user was authenticated.*/
81
+ iss?: string | undefined;
82
+ /** The identity provider that authenticated the subject of the token*/
83
+ idp?: string | undefined;
84
+ /** "Issued At" indicates when the authentication for this token occurred. */
85
+ iat?: number | undefined;
86
+ /** The "nbf" (not before) claim identifies the time before which the JWT must not be accepted for processing. */
87
+ nbf?: number | undefined;
88
+ /** The "exp" (expiration time) claim identifies the expiration time on or after which the JWT must not be accepted for processing. */
89
+ exp?: number | undefined;
90
+ /** An internal claim used by Azure AD to record data for token reuse. */
91
+ aio?: string | undefined;
92
+ /** Only present in v1.0 tokens. The "Authentication context class" claim. A value of "0" indicates the end-user authentication did not meet the requirements of ISO/IEC 29115. */
93
+ acr?: '0' | '1' | undefined;
94
+ /** Only present in v1.0 tokens. Identifies how the subject of the token was authenticated. */
95
+ amr?: string[] | undefined;
96
+ /** Only present in v1.0 tokens. GUID represents the application ID of the client using the token. */
97
+ appid?: string | undefined;
98
+ /** Only present in v2.0 tokens. The application ID of the client using the token. */
99
+ azp?: string | undefined;
100
+ /** Only present in v1.0 tokens. Indicates how the client was authenticated. For a public client, the value is "0".
101
+ * If client ID and client secret are used, the value is "1". If a client certificate was used for authentication, the value is "2". */
102
+ appidacr?: '0' | '1' | '2' | undefined;
103
+ /** Only present in v2.0 tokens. Indicates how the client was authenticated.
104
+ * For a public client, the value is "0". If client ID and client secret are used, the value is "1". If a client certificate was used for authentication, the value is "2". */
105
+ azpacr?: '0' | '1' | '2' | undefined;
106
+ /** Only present in v2.0 tokens. The primary username that represents the user. It could be an email address, phone number, or a generic username without a specified format */
107
+ preferred_username?: string | undefined;
108
+ /** Provides a human-readable value that identifies the subject of the token.
109
+ * The value is not guaranteed to be unique, it is mutable, and it's designed to be used only for display purposes. The profile scope is required in order to receive this claim. */
110
+ name?: string | undefined;
111
+ /** The set of scopes exposed by your application for which the client application has requested (and received) consent. */
112
+ scp?: string | undefined;
113
+ /** The set of permissions exposed by your application that the requesting application has been given permission to call. */
114
+ roles?: string[] | undefined;
115
+ /** Provides object IDs that represent the subject's group memberships. */
116
+ groups?: string | string[] | undefined;
117
+ /** Denoting the user is in at least one group. */
118
+ hasgroups?: true | undefined;
119
+ /** The principal about which the token asserts information, such as the user of an app. This value is immutable and cannot be reassigned or reused.
120
+ * It can be used to perform authorization checks safely, such as when the token is used to access a resource,
121
+ * and can be used as a key in database tables. Because the subject is always present in the tokens that Azure AD issues,
122
+ * we recommend using this value in a general-purpose authorization system. The subject is, however, a pairwise identifier - it is unique to a particular application ID. */
123
+ sub?: string | undefined;
124
+ /** GUID represents a user. This ID uniquely identifies the user across applications. */
125
+ oid?: string | undefined;
126
+ /** Represents the Azure AD tenant that the user is from. */
127
+ tid?: string | undefined;
128
+ /** Only present in v1.0 tokens. Provides a human readable value that identifies the subject of the token. */
129
+ unique_name?: string | undefined;
130
+ /** An internal claim used by Azure to revalidate tokens. */
131
+ uti?: string | undefined;
132
+ /** An internal claim used by Azure to revalidate tokens. */
133
+ rh?: string | undefined;
134
+ /** Indicates the version of the access token. */
135
+ ver?: '1.0' | '2.0' | undefined;
136
+ /** v1.0 basic claims */
137
+ /** The IP address the user authenticated from. */
138
+ ipaddr?: string | undefined;
139
+ /** In cases where the user has an on-premises authentication, this claim provides their SID. */
140
+ onprem_sid?: string | undefined;
141
+ /** Indicates when the user's password expires. */
142
+ pwd_exp?: number | undefined;
143
+ /** A URL where users can be sent to reset their password. */
144
+ pwd_url?: string | undefined;
145
+ /** Signals if the client is logging in from the corporate network. If they aren't, the claim isn't included. */
146
+ in_corp?: string | undefined;
147
+ /** An additional name for the user, separate from first or last name */
148
+ nickname?: string | undefined;
149
+ /** Provides the last name, surname, or family name of the user as defined on the user object. */
150
+ family_name?: string | undefined;
151
+ /** Provides the first or given name of the user, as set on the user object. */
152
+ given_name?: string | undefined;
153
+ /** The username of the user. May be a phone number, email address, or unformatted string. */
154
+ upn?: string | undefined;
155
+ }
156
+ export interface IBaseStrategyOption {
157
+ identityMetadata: string;
158
+ clientID: string;
159
+ isB2C?: boolean | undefined;
160
+ validateIssuer?: boolean | undefined;
161
+ issuer?: string | string[] | undefined;
162
+ loggingLevel?: 'info' | 'warn' | 'error' | undefined;
163
+ loggingNoPII?: boolean | undefined;
164
+ clockSkew?: number | undefined;
165
+ }
166
+ export interface IBearerStrategyOption extends IBaseStrategyOption {
167
+ audience?: string | string[] | undefined;
168
+ policyName?: String | undefined;
169
+ allowMultiAudiencesInToken?: boolean | undefined;
170
+ scope?: string[] | undefined;
171
+ }
172
+ export interface IBearerStrategyOptionWithRequest extends IBearerStrategyOption {
173
+ passReqToCallback: boolean;
174
+ }
175
+ export type VerifyBearerFunction = (token: ITokenPayload, done: VerifyCallback) => void;
176
+ export interface VerifyCallback {
177
+ (error: any, user?: any, info?: any): void;
178
+ }
179
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AACjC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAA;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAA;AAE7B,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAA;CAEzB;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,GAAG,OAExC;AAED,MAAM,MAAM,eAAe,GAAG;IAAE,YAAY,CAAC,EAAE,aAAa,GAAG,eAAe,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;AAEtG,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,mBAAmB,GAAG,GAAG,CAAC,CAAA;AACvE,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,eAAe,CAAA;CAC7B;AACD,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,MAAM,CAAA;IAChB,YAAY,CAAC,EAAE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AE,aAAa,EAAE,IAAI,EAAE,cAAc,KAAK,IAAI,CAAA;AACvF,MAAM,WAAW,cAAc;IAC7B,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,IAAI,CAAA;CAC3C"}
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasEndpointOpts = void 0;
4
+ function hasEndpointOpts(opts) {
5
+ return 'endpointOpts' in opts && opts.endpointOpts;
6
+ }
7
+ exports.hasEndpointOpts = hasEndpointOpts;
8
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAiBA,SAAgB,eAAe,CAAC,IAAS;IACvC,OAAO,cAAc,IAAI,IAAI,IAAI,IAAI,CAAC,YAAY,CAAA;AACpD,CAAC;AAFD,0CAEC"}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@sphereon/ssi-express-support",
3
+ "version": "0.14.2-next.25+e1ec641",
4
+ "source": "src/index.ts",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc --build",
9
+ "build:clean": "tsc --build --clean && tsc --build"
10
+ },
11
+ "dependencies": {
12
+ "body-parser": "^1.20.2",
13
+ "casbin": "^5.26.1",
14
+ "cors": "^2.8.5",
15
+ "dotenv-flow": "^3.2.0",
16
+ "express": "^4.18.2",
17
+ "express-session": "^1.17.3",
18
+ "morgan": "^1.10.0",
19
+ "passport": "^0.6.0",
20
+ "qs": "^6.11.2",
21
+ "uint8arrays": "^3.1.1"
22
+ },
23
+ "peerDependencies": {
24
+ "@noble/hashes": "^1.3.1",
25
+ "passport-azure-ad": "^4.3.5",
26
+ "passport-http-bearer": "^1.0.1"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "passport-http-bearer": {
30
+ "optional": true
31
+ },
32
+ "@noble/hashes": {
33
+ "optional": true
34
+ },
35
+ "passport-azure-ad": {
36
+ "optional": true
37
+ }
38
+ },
39
+ "devDependencies": {
40
+ "@types/body-parser": "^1.19.2",
41
+ "@types/cors": "^2.8.13",
42
+ "@types/dotenv-flow": "^3.2.0",
43
+ "@types/express": "^4.17.17",
44
+ "@types/express-serve-static-core": "^4.17.35",
45
+ "@types/express-session": "^1.17.7",
46
+ "@types/morgan": "^1.9.4",
47
+ "@types/passport": "^1.0.12",
48
+ "@types/passport-azure-ad": "^4.3.1",
49
+ "@types/passport-http-bearer": "^1.0.37",
50
+ "@types/qs": "^6.9.7"
51
+ },
52
+ "files": [
53
+ "dist/**/*",
54
+ "src/**/*",
55
+ "README.md",
56
+ "LICENSE"
57
+ ],
58
+ "publishConfig": {
59
+ "access": "public"
60
+ },
61
+ "repository": "git@github.com:Sphereon-Opensource/SSI-SDK.git",
62
+ "author": "Sphereon <dev@sphereon.com>",
63
+ "license": "Apache-2.0",
64
+ "keywords": [
65
+ "Sphereon",
66
+ "SSI",
67
+ "Agent"
68
+ ],
69
+ "gitHead": "e1ec6418e1a4f139970e4c3e87bfbefb4bd0686d"
70
+ }
@@ -0,0 +1,127 @@
1
+ import express, { NextFunction, RequestHandler } from 'express'
2
+ import { ParamsDictionary } from 'express-serve-static-core'
3
+ import passport from 'passport'
4
+ import { ParsedQs } from 'qs'
5
+ import { EndpointArgs, hasEndpointOpts, HasEndpointOpts } from './types'
6
+
7
+ export const checkUserIsInRole = (opts: { roles: string | string[] }) => (req: express.Request, res: express.Response, next: NextFunction) => {
8
+ if (!opts?.roles || opts.roles.length === 0) {
9
+ return next()
10
+ }
11
+ const roles = Array.isArray(opts.roles) ? opts.roles : [opts.roles]
12
+ if (!req?.user || !('role' in req.user)) {
13
+ return res.status(401).end()
14
+ }
15
+
16
+ // @ts-ignore
17
+ const hasRole = roles.find((role) => req.user.role.toLowerCase() === role.toLowerCase())
18
+ if (!hasRole) {
19
+ return res.status(403).end()
20
+ }
21
+
22
+ return next()
23
+ }
24
+
25
+ const checkAuthenticationImpl = (req: express.Request, res: express.Response, next: express.NextFunction, opts?: EndpointArgs) => {
26
+ if (!opts || !opts.authentication || opts.authentication.enabled === false) {
27
+ return next()
28
+ }
29
+ if (!opts.authentication.strategy) {
30
+ console.log(`Authentication enabled, but no strategy configured. All auth request will be denied!`)
31
+ return res.status(401).end()
32
+ }
33
+ const options = { authInfo: true, session: false }
34
+ passport
35
+ .authenticate(
36
+ opts.authentication.strategy,
37
+ options,
38
+ (
39
+ err: any,
40
+ user?: Express.User | false | null,
41
+ _info?: object | string | Array<string | undefined>,
42
+ _status?: number | Array<number | undefined>
43
+ ) => {
44
+ if (err) {
45
+ return next({ statusCode: 403, message: err })
46
+ } else if (!user) {
47
+ console.log('Authentication failed, no user object present in request')
48
+ return next({ statusCode: 401, message: 'authentication failed' })
49
+ }
50
+ if (options.session) {
51
+ req.logIn(user, function (err) {
52
+ if (err) {
53
+ return next(err)
54
+ }
55
+ return res.send(user)
56
+ })
57
+ }
58
+ return next()
59
+ }
60
+ )
61
+ .call(this, req, res, next)
62
+ // next()
63
+ }
64
+ const checkAuthorizationImpl = (req: express.Request, res: express.Response, next: express.NextFunction, opts?: EndpointArgs) => {
65
+ if (!opts || !opts.authentication || !opts.authorization || opts.authentication.enabled === false || opts?.authorization.enabled === false) {
66
+ return next()
67
+ }
68
+ /*if (!req.isAuthenticated()) {
69
+ return sendErrorResponse(res, 403, 'Authorization with an unauthenticated request is not possible')
70
+ }*/
71
+ const authorization = opts.authorization
72
+
73
+ if (!authorization.enforcer && (!authorization.requireUserInRoles || authorization.requireUserInRoles.length === 0)) {
74
+ console.log(`Authorization enabled for endpoint, but no enforcer or roles supplied`)
75
+ return res.status(401).end()
76
+ }
77
+ if (authorization.requireUserInRoles && authorization.requireUserInRoles.length > 0) {
78
+ checkUserIsInRole({ roles: authorization.requireUserInRoles })
79
+ }
80
+ if (authorization.enforcer) {
81
+ const enforcer = authorization.enforcer
82
+ const permitted = enforcer.enforceSync(req.user, opts.resource, opts.operation)
83
+ if (!permitted) {
84
+ console.log(`Access to ${opts.resource} and op ${opts.operation} not allowed for ${req.user}`)
85
+ return res.status(403).end()
86
+ }
87
+ }
88
+ return next()
89
+ }
90
+
91
+ export const checkAuthenticationOnly = (opts?: EndpointArgs) => (req: express.Request, res: express.Response, next: express.NextFunction) => {
92
+ // executeRequestHandlers(req, res, next, opts)
93
+ return checkAuthenticationImpl(req, res, next, opts)
94
+ }
95
+
96
+ export const checkAuthorizationOnly = (opts?: EndpointArgs) => (req: express.Request, res: express.Response, next: express.NextFunction) => {
97
+ // executeRequestHandlers(req, res, next, opts)
98
+ return checkAuthorizationImpl(req, res, next, opts)
99
+ }
100
+ export const checkAuth = (opts?: EndpointArgs): RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>[] => {
101
+ const handlers: RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>[] = []
102
+ handlers.push(checkAuthenticationOnly(opts))
103
+ handlers.push(checkAuthorizationOnly(opts))
104
+ opts?.handlers && handlers.push(...opts.handlers)
105
+ return handlers
106
+ }
107
+
108
+ export function copyGlobalAuthToEndpoint(args?: { opts?: HasEndpointOpts; key: string }) {
109
+ const opts = args?.opts
110
+ const key = args?.key
111
+ if (!opts || !key || !hasEndpointOpts(opts)) {
112
+ return
113
+ }
114
+ if (opts.endpointOpts?.globalAuth) {
115
+ if (opts.endpointOpts[key]?.disableGlobalAuth === true) {
116
+ return
117
+ }
118
+ opts.endpointOpts[key] = {
119
+ ...opts.endpointOpts[key],
120
+ endpoint: { ...opts.endpointOpts.globalAuth, ...opts.endpointOpts[key]?.endpoint },
121
+ }
122
+ }
123
+ }
124
+
125
+ export function copyGlobalAuthToEndpoints(args?: { opts?: HasEndpointOpts; keys: string[] }) {
126
+ args?.keys.forEach((key) => copyGlobalAuthToEndpoint({ opts: args?.opts, key }))
127
+ }
@@ -0,0 +1,47 @@
1
+ import passport from 'passport'
2
+ import { IBearerStrategyOption, IBearerStrategyOptionWithRequest, ITokenPayload, VerifyCallback } from './types'
3
+
4
+ export class EntraIDAuth {
5
+ private readonly strategy: string
6
+ private options?: IBearerStrategyOptionWithRequest
7
+
8
+ public static init(strategy: string) {
9
+ return new EntraIDAuth(strategy)
10
+ }
11
+
12
+ private constructor(strategy: string) {
13
+ this.strategy = strategy
14
+ }
15
+
16
+ public withOptions(options: IBearerStrategyOption | IBearerStrategyOptionWithRequest): this {
17
+ this.options = {
18
+ ...options,
19
+ passReqToCallback: 'passReqToCallback' in options ? options.passReqToCallback : false,
20
+ }
21
+ return this
22
+ }
23
+
24
+ connectPassport() {
25
+ const _options = this.options
26
+ if (!_options) {
27
+ throw Error('No options supplied for EntraID')
28
+ }
29
+ import('passport-azure-ad')
30
+ .then((entraID) =>
31
+ passport.use(
32
+ this.strategy,
33
+ new entraID.BearerStrategy(_options, function (token: ITokenPayload, cb: VerifyCallback): void {
34
+ if (token) {
35
+ // console.log(`token: ${JSON.stringify(token, null, 2)}`)
36
+ return cb(null, token)
37
+ }
38
+ return cb('bearer token not found or incorrect', null)
39
+ })
40
+ )
41
+ )
42
+ .catch((reason) => {
43
+ console.log(reason)
44
+ throw Error('Could not create bearer strategy. Did you include the "passport-azure-ad/bearer-strategy" dependency in package.json?')
45
+ })
46
+ }
47
+ }