samlesa 2.12.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 (99) hide show
  1. package/.editorconfig +19 -0
  2. package/.github/FUNDING.yml +1 -0
  3. package/.idea/compiler.xml +6 -0
  4. package/.idea/deployment.xml +14 -0
  5. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  6. package/.idea/jsLibraryMappings.xml +6 -0
  7. package/.idea/modules.xml +8 -0
  8. package/.idea/samlify.iml +12 -0
  9. package/.idea/vcs.xml +6 -0
  10. package/.pre-commit.sh +15 -0
  11. package/.snyk +8 -0
  12. package/.travis.yml +29 -0
  13. package/LICENSE +22 -0
  14. package/Makefile +25 -0
  15. package/README.md +84 -0
  16. package/build/.idea/workspace.xml +58 -0
  17. package/build/index.js +65 -0
  18. package/build/index.js.map +1 -0
  19. package/build/src/api.js +24 -0
  20. package/build/src/api.js.map +1 -0
  21. package/build/src/binding-post.js +369 -0
  22. package/build/src/binding-post.js.map +1 -0
  23. package/build/src/binding-redirect.js +333 -0
  24. package/build/src/binding-redirect.js.map +1 -0
  25. package/build/src/binding-simplesign.js +233 -0
  26. package/build/src/binding-simplesign.js.map +1 -0
  27. package/build/src/entity-idp.js +131 -0
  28. package/build/src/entity-idp.js.map +1 -0
  29. package/build/src/entity-sp.js +97 -0
  30. package/build/src/entity-sp.js.map +1 -0
  31. package/build/src/entity.js +236 -0
  32. package/build/src/entity.js.map +1 -0
  33. package/build/src/extractor.js +370 -0
  34. package/build/src/extractor.js.map +1 -0
  35. package/build/src/flow.js +320 -0
  36. package/build/src/flow.js.map +1 -0
  37. package/build/src/libsaml.js +642 -0
  38. package/build/src/libsaml.js.map +1 -0
  39. package/build/src/metadata-idp.js +128 -0
  40. package/build/src/metadata-idp.js.map +1 -0
  41. package/build/src/metadata-sp.js +232 -0
  42. package/build/src/metadata-sp.js.map +1 -0
  43. package/build/src/metadata.js +177 -0
  44. package/build/src/metadata.js.map +1 -0
  45. package/build/src/types.js +12 -0
  46. package/build/src/types.js.map +1 -0
  47. package/build/src/urn.js +213 -0
  48. package/build/src/urn.js.map +1 -0
  49. package/build/src/utility.js +249 -0
  50. package/build/src/utility.js.map +1 -0
  51. package/build/src/validator.js +27 -0
  52. package/build/src/validator.js.map +1 -0
  53. package/index.d.ts +10 -0
  54. package/index.js +19 -0
  55. package/index.js.map +1 -0
  56. package/index.ts +28 -0
  57. package/package.json +74 -0
  58. package/qodana.yaml +29 -0
  59. package/src/.idea/modules.xml +8 -0
  60. package/src/.idea/src.iml +12 -0
  61. package/src/.idea/vcs.xml +6 -0
  62. package/src/api.ts +36 -0
  63. package/src/binding-post.ts +338 -0
  64. package/src/binding-redirect.ts +331 -0
  65. package/src/binding-simplesign.ts +231 -0
  66. package/src/entity-idp.ts +145 -0
  67. package/src/entity-sp.ts +114 -0
  68. package/src/entity.ts +243 -0
  69. package/src/extractor.ts +392 -0
  70. package/src/flow.ts +467 -0
  71. package/src/libsaml.ts +786 -0
  72. package/src/metadata-idp.ts +146 -0
  73. package/src/metadata-sp.ts +268 -0
  74. package/src/metadata.ts +166 -0
  75. package/src/types.ts +153 -0
  76. package/src/urn.ts +211 -0
  77. package/src/utility.ts +248 -0
  78. package/src/validator.ts +44 -0
  79. package/tsconfig.json +38 -0
  80. package/tslint.json +35 -0
  81. package/types/index.d.ts +10 -0
  82. package/types/src/api.d.ts +13 -0
  83. package/types/src/binding-post.d.ts +46 -0
  84. package/types/src/binding-redirect.d.ts +52 -0
  85. package/types/src/binding-simplesign.d.ts +39 -0
  86. package/types/src/entity-idp.d.ts +42 -0
  87. package/types/src/entity-sp.d.ts +36 -0
  88. package/types/src/entity.d.ts +99 -0
  89. package/types/src/extractor.d.ts +25 -0
  90. package/types/src/flow.d.ts +6 -0
  91. package/types/src/libsaml.d.ts +210 -0
  92. package/types/src/metadata-idp.d.ts +24 -0
  93. package/types/src/metadata-sp.d.ts +36 -0
  94. package/types/src/metadata.d.ts +57 -0
  95. package/types/src/types.d.ts +127 -0
  96. package/types/src/urn.d.ts +194 -0
  97. package/types/src/utility.d.ts +134 -0
  98. package/types/src/validator.d.ts +3 -0
  99. package/types.d.ts +2 -0
@@ -0,0 +1,331 @@
1
+ /**
2
+ * @file binding-redirect.ts
3
+ * @author tngan
4
+ * @desc Binding-level API, declare the functions using Redirect binding
5
+ */
6
+ import utility, { get } from './utility.js';
7
+ import libsaml from './libsaml.js';
8
+ import { BindingContext } from './entity.js';
9
+ import { IdentityProvider as Idp } from './entity-idp.js';
10
+ import { ServiceProvider as Sp } from './entity-sp.js';
11
+ import * as url from 'url';
12
+ import { wording, namespace } from './urn.js';
13
+
14
+ const binding = wording.binding;
15
+ const urlParams = wording.urlParams;
16
+
17
+ export interface BuildRedirectConfig {
18
+ baseUrl: string;
19
+ type: string;
20
+ isSigned: boolean;
21
+ context: string;
22
+ entitySetting: any;
23
+ relayState?: string;
24
+ }
25
+
26
+ /**
27
+ * @private
28
+ * @desc Helper of generating URL param/value pair
29
+ * @param {string} param key
30
+ * @param {string} value value of key
31
+ * @param {boolean} first determine whether the param is the starting one in order to add query header '?'
32
+ * @return {string}
33
+ */
34
+ function pvPair(param: string, value: string, first?: boolean): string {
35
+ return (first === true ? '?' : '&') + param + '=' + value;
36
+ }
37
+ /**
38
+ * @private
39
+ * @desc Refractored part of URL generation for login/logout request
40
+ * @param {string} type
41
+ * @param {boolean} isSigned
42
+ * @param {string} rawSamlRequest
43
+ * @param {object} entitySetting
44
+ * @return {string}
45
+ */
46
+ function buildRedirectURL(opts: BuildRedirectConfig) {
47
+ const {
48
+ baseUrl,
49
+ type,
50
+ isSigned,
51
+ context,
52
+ entitySetting,
53
+ } = opts;
54
+ let { relayState = '' } = opts;
55
+ const noParams = (url.parse(baseUrl).query || []).length === 0;
56
+ const queryParam = libsaml.getQueryParamByType(type);
57
+ // In general, this xmlstring is required to do deflate -> base64 -> urlencode
58
+ const samlRequest = encodeURIComponent(utility.base64Encode(utility.deflateString(context)));
59
+ if (relayState !== '') {
60
+ relayState = pvPair(urlParams.relayState, encodeURIComponent(relayState));
61
+ }
62
+ if (isSigned) {
63
+ const sigAlg = pvPair(urlParams.sigAlg, encodeURIComponent(entitySetting.requestSignatureAlgorithm));
64
+ const octetString = samlRequest + relayState + sigAlg;
65
+ return baseUrl
66
+ + pvPair(queryParam, octetString, noParams)
67
+ + pvPair(urlParams.signature, encodeURIComponent(
68
+ libsaml.constructMessageSignature(
69
+ queryParam + '=' + octetString,
70
+ entitySetting.privateKey,
71
+ entitySetting.privateKeyPass,
72
+ undefined,
73
+ entitySetting.requestSignatureAlgorithm
74
+ ).toString()
75
+ )
76
+ );
77
+ }
78
+ return baseUrl + pvPair(queryParam, samlRequest + relayState, noParams);
79
+ }
80
+ /**
81
+ * @desc Redirect URL for login request
82
+ * @param {object} entity object includes both idp and sp
83
+ * @param {function} customTagReplacement used when developers have their own login response template
84
+ * @return {string} redirect URL
85
+ */
86
+ function loginRequestRedirectURL(entity: { idp: Idp, sp: Sp }, customTagReplacement?: (template: string) => BindingContext): BindingContext {
87
+
88
+ const metadata: any = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
89
+ const spSetting: any = entity.sp.entitySetting;
90
+ let id: string = '';
91
+
92
+ if (metadata && metadata.idp && metadata.sp) {
93
+ const base = metadata.idp.getSingleSignOnService(binding.redirect);
94
+ let rawSamlRequest: string;
95
+ if (spSetting.loginRequestTemplate && customTagReplacement) {
96
+ const info = customTagReplacement(spSetting.loginRequestTemplate);
97
+ id = get(info, 'id', null);
98
+ rawSamlRequest = get(info, 'context', null);
99
+ } else {
100
+ const nameIDFormat = spSetting.nameIDFormat;
101
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
102
+ id = spSetting.generateID();
103
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLoginRequestTemplate.context, {
104
+ ID: id,
105
+ Destination: base,
106
+ Issuer: metadata.sp.getEntityID(),
107
+ IssueInstant: new Date().toISOString(),
108
+ NameIDFormat: selectedNameIDFormat,
109
+ AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.post),
110
+ EntityID: metadata.sp.getEntityID(),
111
+ AllowCreate: spSetting.allowCreate,
112
+ } as any);
113
+ }
114
+ return {
115
+ id,
116
+ context: buildRedirectURL({
117
+ context: rawSamlRequest,
118
+ type: urlParams.samlRequest,
119
+ isSigned: metadata.sp.isAuthnRequestSigned(),
120
+ entitySetting: spSetting,
121
+ baseUrl: base,
122
+ relayState: spSetting.relayState,
123
+ }),
124
+ };
125
+ }
126
+ throw new Error('ERR_GENERATE_REDIRECT_LOGIN_REQUEST_MISSING_METADATA');
127
+ }
128
+
129
+ /**
130
+ * @desc Redirect URL for login response
131
+ * @param {object} requestInfo corresponding request, used to obtain the id
132
+ * @param {object} entity object includes both idp and sp
133
+ * @param {object} user current logged user (e.g. req.user)
134
+ * @param {String} relayState the relaystate sent by sp corresponding request
135
+ * @param {function} customTagReplacement used when developers have their own login response template
136
+ */
137
+ function loginResponseRedirectURL(requestInfo: any, entity: any, user: any = {}, relayState?: string, customTagReplacement?: (template: string) => BindingContext): BindingContext {
138
+ const idpSetting = entity.idp.entitySetting;
139
+ const spSetting = entity.sp.entitySetting;
140
+ const metadata = {
141
+ idp: entity.idp.entityMeta,
142
+ sp: entity.sp.entityMeta,
143
+ };
144
+
145
+ let id: string = idpSetting.generateID();
146
+ if (metadata && metadata.idp && metadata.sp) {
147
+ const base = metadata.sp.getAssertionConsumerService(binding.redirect);
148
+ let rawSamlResponse: string;
149
+ //
150
+ const nameIDFormat = idpSetting.nameIDFormat;
151
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
152
+ const nowTime = new Date();
153
+ // Five minutes later : nowtime + 5 * 60 * 1000 (in milliseconds)
154
+ const fiveMinutesLaterTime = new Date(nowTime.getTime() + 300_000);
155
+ const tvalue: any = {
156
+ ID: id,
157
+ AssertionID: idpSetting.generateID(),
158
+ Destination: base,
159
+ SubjectRecipient: base,
160
+ Issuer: metadata.idp.getEntityID(),
161
+ Audience: metadata.sp.getEntityID(),
162
+ EntityID: metadata.sp.getEntityID(),
163
+ IssueInstant: nowTime.toISOString(),
164
+ AssertionConsumerServiceURL: base,
165
+ StatusCode: namespace.statusCode.success,
166
+ // can be customized
167
+ ConditionsNotBefore: nowTime.toISOString(),
168
+ ConditionsNotOnOrAfter: fiveMinutesLaterTime.toISOString(),
169
+ SubjectConfirmationDataNotOnOrAfter: fiveMinutesLaterTime.toISOString(),
170
+ NameIDFormat: selectedNameIDFormat,
171
+ NameID: user.email || '',
172
+ InResponseTo: get(requestInfo, 'extract.request.id', ''),
173
+ AuthnStatement: '',
174
+ AttributeStatement: '',
175
+ };
176
+
177
+ if (idpSetting.loginResponseTemplate && customTagReplacement) {
178
+ const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
179
+ id = get(template, 'id', null);
180
+ rawSamlResponse = get(template, 'context', null);
181
+ } else {
182
+
183
+ if (requestInfo !== null) {
184
+ tvalue.InResponseTo = requestInfo.extract.request.id;
185
+ }
186
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLoginResponseTemplate.context, tvalue);
187
+ }
188
+
189
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
190
+ const config = {
191
+ privateKey,
192
+ privateKeyPass,
193
+ signatureAlgorithm,
194
+ signingCert: metadata.idp.getX509Certificate('signing'),
195
+ isBase64Output: false,
196
+ };
197
+ // step: sign assertion ? -> encrypted ? -> sign message ?
198
+ if (metadata.sp.isWantAssertionsSigned()) {
199
+ rawSamlResponse = libsaml.constructSAMLSignature({
200
+ ...config,
201
+ rawSamlMessage: rawSamlResponse,
202
+ transformationAlgorithms: spSetting.transformationAlgorithms,
203
+ referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
204
+ signatureConfig: {
205
+ prefix: 'ds',
206
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
207
+ },
208
+ });
209
+ }
210
+
211
+ // Like in post binding, SAML response is always signed
212
+ return {
213
+ id,
214
+ context: buildRedirectURL({
215
+ baseUrl: base,
216
+ type: urlParams.samlResponse,
217
+ isSigned: true,
218
+ context: rawSamlResponse,
219
+ entitySetting: idpSetting,
220
+ relayState,
221
+ }),
222
+ };
223
+ }
224
+ throw new Error('ERR_GENERATE_REDIRECT_LOGIN_RESPONSE_MISSING_METADATA');
225
+ }
226
+
227
+ /**
228
+ * @desc Redirect URL for logout request
229
+ * @param {object} user current logged user (e.g. req.user)
230
+ * @param {object} entity object includes both idp and sp
231
+ * @param {function} customTagReplacement used when developers have their own login response template
232
+ * @return {string} redirect URL
233
+ */
234
+ function logoutRequestRedirectURL(user, entity, relayState?: string, customTagReplacement?: (template: string, tags: object) => BindingContext): BindingContext {
235
+ const metadata = { init: entity.init.entityMeta, target: entity.target.entityMeta };
236
+ const initSetting = entity.init.entitySetting;
237
+ let id: string = initSetting.generateID();
238
+ const nameIDFormat = initSetting.nameIDFormat;
239
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
240
+
241
+ if (metadata && metadata.init && metadata.target) {
242
+ const base = metadata.target.getSingleLogoutService(binding.redirect);
243
+ let rawSamlRequest: string = '';
244
+ const requiredTags = {
245
+ ID: id,
246
+ Destination: base,
247
+ EntityID: metadata.init.getEntityID(),
248
+ Issuer: metadata.init.getEntityID(),
249
+ IssueInstant: new Date().toISOString(),
250
+ NameIDFormat: selectedNameIDFormat,
251
+ NameID: user.logoutNameID,
252
+ SessionIndex: user.sessionIndex,
253
+ };
254
+ if (initSetting.logoutRequestTemplate && customTagReplacement) {
255
+ const info = customTagReplacement(initSetting.logoutRequestTemplate, requiredTags);
256
+ id = get(info, 'id', null);
257
+ rawSamlRequest = get(info, 'context', null);
258
+ } else {
259
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLogoutRequestTemplate.context, requiredTags as any);
260
+ }
261
+ return {
262
+ id,
263
+ context: buildRedirectURL({
264
+ context: rawSamlRequest,
265
+ relayState,
266
+ type: urlParams.logoutRequest,
267
+ isSigned: entity.target.entitySetting.wantLogoutRequestSigned,
268
+ entitySetting: initSetting,
269
+ baseUrl: base,
270
+ }),
271
+ };
272
+ }
273
+ throw new Error('ERR_GENERATE_REDIRECT_LOGOUT_REQUEST_MISSING_METADATA');
274
+ }
275
+ /**
276
+ * @desc Redirect URL for logout response
277
+ * @param {object} requescorresponding request, used to obtain the id
278
+ * @param {object} entity object includes both idp and sp
279
+ * @param {function} customTagReplacement used when developers have their own login response template
280
+ */
281
+ function logoutResponseRedirectURL(requestInfo: any, entity: any, relayState?: string, customTagReplacement?: (template: string) => BindingContext): BindingContext {
282
+ const metadata = {
283
+ init: entity.init.entityMeta,
284
+ target: entity.target.entityMeta,
285
+ };
286
+ const initSetting = entity.init.entitySetting;
287
+ let id: string = initSetting.generateID();
288
+ if (metadata && metadata.init && metadata.target) {
289
+ const base = metadata.target.getSingleLogoutService(binding.redirect);
290
+ let rawSamlResponse: string;
291
+ if (initSetting.logoutResponseTemplate && customTagReplacement) {
292
+ const template = customTagReplacement(initSetting.logoutResponseTemplate);
293
+ id = get(template, 'id', null);
294
+ rawSamlResponse = get(template, 'context', null);
295
+ } else {
296
+ const tvalue: any = {
297
+ ID: id,
298
+ Destination: base,
299
+ Issuer: metadata.init.getEntityID(),
300
+ EntityID: metadata.init.getEntityID(),
301
+ IssueInstant: new Date().toISOString(),
302
+ StatusCode: namespace.statusCode.success,
303
+ };
304
+ if (requestInfo && requestInfo.extract && requestInfo.extract.request) {
305
+ tvalue.InResponseTo = requestInfo.extract.request.id;
306
+ }
307
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLogoutResponseTemplate.context, tvalue);
308
+ }
309
+ return {
310
+ id,
311
+ context: buildRedirectURL({
312
+ baseUrl: base,
313
+ type: urlParams.logoutResponse,
314
+ isSigned: entity.target.entitySetting.wantLogoutResponseSigned,
315
+ context: rawSamlResponse,
316
+ entitySetting: initSetting,
317
+ relayState,
318
+ }),
319
+ };
320
+ }
321
+ throw new Error('ERR_GENERATE_REDIRECT_LOGOUT_RESPONSE_MISSING_METADATA');
322
+ }
323
+
324
+ const redirectBinding = {
325
+ loginRequestRedirectURL,
326
+ loginResponseRedirectURL,
327
+ logoutRequestRedirectURL,
328
+ logoutResponseRedirectURL,
329
+ };
330
+
331
+ export default redirectBinding;
@@ -0,0 +1,231 @@
1
+ /**
2
+ * @file binding-simplesign.ts
3
+ * @author Orange
4
+ * @desc Binding-level API, declare the functions using POST SimpleSign binding
5
+ */
6
+
7
+ import { wording, StatusCode } from './urn.js';
8
+ import { BindingContext, SimpleSignComputedContext } from './entity.js';
9
+ import libsaml from './libsaml.js';
10
+ import utility, { get } from './utility.js';
11
+
12
+ const binding = wording.binding;
13
+ const urlParams = wording.urlParams;
14
+
15
+ export interface BuildSimpleSignConfig {
16
+ type: string;
17
+ context: string;
18
+ entitySetting: any;
19
+ relayState?: string;
20
+ }
21
+
22
+ export interface BindingSimpleSignContext {
23
+ id: string;
24
+ context: string;
25
+ signature: any;
26
+ sigAlg: string;
27
+ }
28
+
29
+ /**
30
+ * @private
31
+ * @desc Helper of generating URL param/value pair
32
+ * @param {string} param key
33
+ * @param {string} value value of key
34
+ * @param {boolean} first determine whether the param is the starting one in order to add query header '?'
35
+ * @return {string}
36
+ */
37
+ function pvPair(param: string, value: string, first?: boolean): string {
38
+ return (first === true ? '?' : '&') + param + '=' + value;
39
+ }
40
+ /**
41
+ * @private
42
+ * @desc Refactored part of simple signature generation for login/logout request
43
+ * @param {string} type
44
+ * @param {string} rawSamlRequest
45
+ * @param {object} entitySetting
46
+ * @return {string}
47
+ */
48
+ function buildSimpleSignature(opts: BuildSimpleSignConfig) : string {
49
+ const {
50
+ type,
51
+ context,
52
+ entitySetting,
53
+ } = opts;
54
+ let { relayState = '' } = opts;
55
+ const queryParam = libsaml.getQueryParamByType(type);
56
+
57
+ if (relayState !== '') {
58
+ relayState = pvPair(urlParams.relayState, relayState);
59
+ }
60
+
61
+ const sigAlg = pvPair(urlParams.sigAlg, entitySetting.requestSignatureAlgorithm);
62
+ const octetString = context + relayState + sigAlg;
63
+ return libsaml.constructMessageSignature(
64
+ queryParam + '=' + octetString,
65
+ entitySetting.privateKey,
66
+ entitySetting.privateKeyPass,
67
+ undefined,
68
+ entitySetting.requestSignatureAlgorithm
69
+ ).toString();
70
+ }
71
+
72
+ /**
73
+ * @desc Generate a base64 encoded login request
74
+ * @param {string} referenceTagXPath reference uri
75
+ * @param {object} entity object includes both idp and sp
76
+ * @param {function} customTagReplacement used when developers have their own login response template
77
+ */
78
+ function base64LoginRequest(entity: any, customTagReplacement?: (template: string) => BindingContext): SimpleSignComputedContext {
79
+ const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
80
+ const spSetting = entity.sp.entitySetting;
81
+ let id: string = '';
82
+
83
+ if (metadata && metadata.idp && metadata.sp) {
84
+ const base = metadata.idp.getSingleSignOnService(binding.simpleSign);
85
+ let rawSamlRequest: string;
86
+ if (spSetting.loginRequestTemplate && customTagReplacement) {
87
+ const info = customTagReplacement(spSetting.loginRequestTemplate.context);
88
+ id = get(info, 'id', null);
89
+ rawSamlRequest = get(info, 'context', null);
90
+ } else {
91
+ const nameIDFormat = spSetting.nameIDFormat;
92
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
93
+ id = spSetting.generateID();
94
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLoginRequestTemplate.context, {
95
+ ID: id,
96
+ Destination: base,
97
+ Issuer: metadata.sp.getEntityID(),
98
+ IssueInstant: new Date().toISOString(),
99
+ AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.simpleSign),
100
+ EntityID: metadata.sp.getEntityID(),
101
+ AllowCreate: spSetting.allowCreate,
102
+ NameIDFormat: selectedNameIDFormat
103
+ } as any);
104
+ }
105
+
106
+ let simpleSignatureContext : any = null;
107
+ if (metadata.idp.isWantAuthnRequestsSigned()) {
108
+ const simpleSignature = buildSimpleSignature({
109
+ type: urlParams.samlRequest,
110
+ context: rawSamlRequest,
111
+ entitySetting: spSetting,
112
+ relayState: spSetting.relayState,
113
+ });
114
+
115
+ simpleSignatureContext = {
116
+ signature: simpleSignature,
117
+ sigAlg: spSetting.requestSignatureAlgorithm,
118
+ };
119
+ }
120
+ // No need to embeded XML signature
121
+ return {
122
+ id,
123
+ context: utility.base64Encode(rawSamlRequest),
124
+ ...simpleSignatureContext,
125
+ };
126
+ }
127
+ throw new Error('ERR_GENERATE_POST_SIMPLESIGN_LOGIN_REQUEST_MISSING_METADATA');
128
+ }
129
+ /**
130
+ * @desc Generate a base64 encoded login response
131
+ * @param {object} requestInfo corresponding request, used to obtain the id
132
+ * @param {object} entity object includes both idp and sp
133
+ * @param {object} user current logged user (e.g. req.user)
134
+ * @param {string} relayState the relay state
135
+ * @param {function} customTagReplacement used when developers have their own login response template
136
+ */
137
+ async function base64LoginResponse(requestInfo: any = {}, entity: any, user: any = {}, relayState?: string, customTagReplacement?: (template: string) => BindingContext): Promise<BindingSimpleSignContext> {
138
+ const idpSetting = entity.idp.entitySetting;
139
+ const spSetting = entity.sp.entitySetting;
140
+ const id = idpSetting.generateID();
141
+ const metadata = {
142
+ idp: entity.idp.entityMeta,
143
+ sp: entity.sp.entityMeta,
144
+ };
145
+ const nameIDFormat = idpSetting.nameIDFormat;
146
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
147
+ if (metadata && metadata.idp && metadata.sp) {
148
+ const base = metadata.sp.getAssertionConsumerService(binding.simpleSign);
149
+ let rawSamlResponse: string;
150
+ const nowTime = new Date();
151
+ // Five minutes later : nowtime + 5 * 60 * 1000 (in milliseconds)
152
+ const fiveMinutesLaterTime = new Date(nowTime.getTime() + 300_000 );
153
+ const tvalue: any = {
154
+ ID: id,
155
+ AssertionID: idpSetting.generateID(),
156
+ Destination: base,
157
+ Audience: metadata.sp.getEntityID(),
158
+ EntityID: metadata.sp.getEntityID(),
159
+ SubjectRecipient: base,
160
+ Issuer: metadata.idp.getEntityID(),
161
+ IssueInstant: nowTime.toISOString(),
162
+ AssertionConsumerServiceURL: base,
163
+ StatusCode: StatusCode.Success,
164
+ // can be customized
165
+ ConditionsNotBefore: nowTime.toISOString(),
166
+ ConditionsNotOnOrAfter: fiveMinutesLaterTime.toISOString(),
167
+ SubjectConfirmationDataNotOnOrAfter: fiveMinutesLaterTime.toISOString(),
168
+ NameIDFormat: selectedNameIDFormat,
169
+ NameID: user.email || '',
170
+ InResponseTo: get(requestInfo, 'extract.request.id', ''),
171
+ AuthnStatement: '',
172
+ AttributeStatement: '',
173
+ };
174
+ if (idpSetting.loginResponseTemplate && customTagReplacement) {
175
+ const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
176
+ rawSamlResponse = get(template, 'context', null);
177
+ } else {
178
+ if (requestInfo !== null) {
179
+ tvalue.InResponseTo = requestInfo.extract.request.id;
180
+ }
181
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLoginResponseTemplate.context, tvalue);
182
+ }
183
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
184
+ const config = {
185
+ privateKey,
186
+ privateKeyPass,
187
+ signatureAlgorithm,
188
+ signingCert: metadata.idp.getX509Certificate('signing'),
189
+ isBase64Output: false,
190
+ };
191
+ // step: sign assertion ? -> encrypted ? -> sign message ?
192
+ if (metadata.sp.isWantAssertionsSigned()) {
193
+ rawSamlResponse = libsaml.constructSAMLSignature({
194
+ ...config,
195
+ rawSamlMessage: rawSamlResponse,
196
+ transformationAlgorithms: spSetting.transformationAlgorithms,
197
+ referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
198
+ signatureConfig: {
199
+ prefix: 'ds',
200
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
201
+ },
202
+ });
203
+ }
204
+
205
+ // SAML response must be signed sign message first, then encrypt
206
+ let simpleSignature: string = '';
207
+ // like in post and redirect bindings, login response is always signed.
208
+ simpleSignature = buildSimpleSignature({
209
+ type: urlParams.samlResponse,
210
+ context: rawSamlResponse,
211
+ entitySetting: idpSetting,
212
+ relayState: relayState,
213
+ } );
214
+
215
+ return Promise.resolve({
216
+ id,
217
+ context: utility.base64Encode(rawSamlResponse),
218
+ signature: simpleSignature,
219
+ sigAlg: idpSetting.requestSignatureAlgorithm,
220
+ });
221
+
222
+ }
223
+ throw new Error('ERR_GENERATE_POST_SIMPLESIGN_LOGIN_RESPONSE_MISSING_METADATA');
224
+ }
225
+
226
+ const simpleSignBinding = {
227
+ base64LoginRequest,
228
+ base64LoginResponse,
229
+ };
230
+
231
+ export default simpleSignBinding;