samlesa 2.12.113 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of samlesa might be problematic. Click here for more details.

Files changed (145) hide show
  1. package/build/index.js +18 -54
  2. package/build/index.js.map +1 -1
  3. package/build/src/api.js +18 -24
  4. package/build/src/api.js.map +1 -1
  5. package/build/src/binding-post.js +337 -365
  6. package/build/src/binding-post.js.map +1 -1
  7. package/build/src/binding-redirect.js +312 -340
  8. package/build/src/binding-redirect.js.map +1 -1
  9. package/build/src/binding-simplesign.js +201 -229
  10. package/build/src/binding-simplesign.js.map +1 -1
  11. package/build/src/entity-idp.js +119 -127
  12. package/build/src/entity-idp.js.map +1 -1
  13. package/build/src/entity-sp.js +88 -96
  14. package/build/src/entity-sp.js.map +1 -1
  15. package/build/src/entity.js +193 -225
  16. package/build/src/entity.js.map +1 -1
  17. package/build/src/extractor.js +361 -369
  18. package/build/src/extractor.js.map +1 -1
  19. package/build/src/flow.js +313 -320
  20. package/build/src/flow.js.map +1 -1
  21. package/build/src/libsaml.js +693 -721
  22. package/build/src/libsaml.js.map +1 -1
  23. package/build/src/metadata-idp.js +119 -127
  24. package/build/src/metadata-idp.js.map +1 -1
  25. package/build/src/metadata-sp.js +223 -231
  26. package/build/src/metadata-sp.js.map +1 -1
  27. package/build/src/metadata.js +138 -166
  28. package/build/src/metadata.js.map +1 -1
  29. package/build/src/types.js +4 -11
  30. package/build/src/types.js.map +1 -1
  31. package/build/src/urn.js +204 -212
  32. package/build/src/urn.js.map +1 -1
  33. package/build/src/utility.js +277 -292
  34. package/build/src/utility.js.map +1 -1
  35. package/build/src/validator.js +24 -27
  36. package/build/src/validator.js.map +1 -1
  37. package/package.json +13 -7
  38. package/types/api.d.ts +15 -0
  39. package/types/api.d.ts.map +1 -0
  40. package/types/binding-post.d.ts +48 -0
  41. package/types/binding-post.d.ts.map +1 -0
  42. package/types/binding-redirect.d.ts +54 -0
  43. package/types/binding-redirect.d.ts.map +1 -0
  44. package/types/binding-simplesign.d.ts +41 -0
  45. package/types/binding-simplesign.d.ts.map +1 -0
  46. package/types/entity-idp.d.ts +38 -0
  47. package/types/entity-idp.d.ts.map +1 -0
  48. package/types/entity-sp.d.ts +38 -0
  49. package/types/entity-sp.d.ts.map +1 -0
  50. package/types/entity.d.ts +100 -0
  51. package/types/entity.d.ts.map +1 -0
  52. package/types/extractor.d.ts +26 -0
  53. package/types/extractor.d.ts.map +1 -0
  54. package/types/flow.d.ts +7 -0
  55. package/types/flow.d.ts.map +1 -0
  56. package/types/index.d.ts +11 -10
  57. package/types/index.d.ts.map +1 -0
  58. package/types/libsaml.d.ts +208 -0
  59. package/types/libsaml.d.ts.map +1 -0
  60. package/types/metadata-idp.d.ts +25 -0
  61. package/types/metadata-idp.d.ts.map +1 -0
  62. package/types/metadata-sp.d.ts +37 -0
  63. package/types/metadata-sp.d.ts.map +1 -0
  64. package/types/metadata.d.ts +58 -0
  65. package/types/metadata.d.ts.map +1 -0
  66. package/types/src/api.d.ts +15 -13
  67. package/types/src/api.d.ts.map +1 -0
  68. package/types/src/binding-post.d.ts +48 -47
  69. package/types/src/binding-post.d.ts.map +1 -0
  70. package/types/src/binding-redirect.d.ts +54 -53
  71. package/types/src/binding-redirect.d.ts.map +1 -0
  72. package/types/src/binding-simplesign.d.ts +41 -40
  73. package/types/src/binding-simplesign.d.ts.map +1 -0
  74. package/types/src/entity-idp.d.ts +38 -37
  75. package/types/src/entity-idp.d.ts.map +1 -0
  76. package/types/src/entity-sp.d.ts +38 -36
  77. package/types/src/entity-sp.d.ts.map +1 -0
  78. package/types/src/entity.d.ts +100 -101
  79. package/types/src/entity.d.ts.map +1 -0
  80. package/types/src/extractor.d.ts +26 -25
  81. package/types/src/extractor.d.ts.map +1 -0
  82. package/types/src/flow.d.ts +7 -6
  83. package/types/src/flow.d.ts.map +1 -0
  84. package/types/src/libsaml.d.ts +208 -209
  85. package/types/src/libsaml.d.ts.map +1 -0
  86. package/types/src/metadata-idp.d.ts +25 -24
  87. package/types/src/metadata-idp.d.ts.map +1 -0
  88. package/types/src/metadata-sp.d.ts +37 -36
  89. package/types/src/metadata-sp.d.ts.map +1 -0
  90. package/types/src/metadata.d.ts +58 -59
  91. package/types/src/metadata.d.ts.map +1 -0
  92. package/types/src/types.d.ts +128 -129
  93. package/types/src/types.d.ts.map +1 -0
  94. package/types/src/urn.d.ts +195 -194
  95. package/types/src/urn.d.ts.map +1 -0
  96. package/types/src/utility.d.ts +133 -134
  97. package/types/src/utility.d.ts.map +1 -0
  98. package/types/src/validator.d.ts +4 -3
  99. package/types/src/validator.d.ts.map +1 -0
  100. package/types/types.d.ts +128 -0
  101. package/types/types.d.ts.map +1 -0
  102. package/types/urn.d.ts +195 -0
  103. package/types/urn.d.ts.map +1 -0
  104. package/types/utility.d.ts +133 -0
  105. package/types/utility.d.ts.map +1 -0
  106. package/types/validator.d.ts +4 -0
  107. package/types/validator.d.ts.map +1 -0
  108. package/.editorconfig +0 -19
  109. package/.github/FUNDING.yml +0 -1
  110. package/.idea/inspectionProfiles/Project_Default.xml +0 -6
  111. package/.idea/modules.xml +0 -8
  112. package/.idea/samlify.iml +0 -12
  113. package/.idea/vcs.xml +0 -6
  114. package/.pre-commit.sh +0 -15
  115. package/.snyk +0 -8
  116. package/.travis.yml +0 -29
  117. package/Makefile +0 -25
  118. package/index.d.ts +0 -10
  119. package/index.js +0 -19
  120. package/index.js.map +0 -1
  121. package/index.ts +0 -28
  122. package/qodana.yaml +0 -29
  123. package/src/.idea/modules.xml +0 -8
  124. package/src/.idea/src.iml +0 -12
  125. package/src/.idea/vcs.xml +0 -6
  126. package/src/api.ts +0 -36
  127. package/src/binding-post.ts +0 -348
  128. package/src/binding-redirect.ts +0 -356
  129. package/src/binding-simplesign.ts +0 -238
  130. package/src/entity-idp.ts +0 -153
  131. package/src/entity-sp.ts +0 -114
  132. package/src/entity.ts +0 -243
  133. package/src/extractor.ts +0 -392
  134. package/src/flow.ts +0 -467
  135. package/src/libsaml.ts +0 -895
  136. package/src/metadata-idp.ts +0 -146
  137. package/src/metadata-sp.ts +0 -268
  138. package/src/metadata.ts +0 -166
  139. package/src/types.ts +0 -153
  140. package/src/urn.ts +0 -211
  141. package/src/utility.ts +0 -319
  142. package/src/validator.ts +0 -39
  143. package/tsconfig.json +0 -38
  144. package/tslint.json +0 -35
  145. package/types.d.ts +0 -2
@@ -1,366 +1,338 @@
1
- "use strict";
2
- /**
3
- * @file binding-post.ts
4
- * @author tngan
5
- * @desc Binding-level API, declare the functions using POST binding
6
- */
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || function (mod) {
24
- if (mod && mod.__esModule) return mod;
25
- var result = {};
26
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
27
- __setModuleDefault(result, mod);
28
- return result;
29
- };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
- Object.defineProperty(exports, "__esModule", { value: true });
34
- const urn_js_1 = require("./urn.js");
35
- const libsaml_js_1 = __importDefault(require("./libsaml.js"));
36
- const utility_js_1 = __importStar(require("./utility.js"));
37
- const binding = urn_js_1.wording.binding;
38
- /**
39
- * @desc Generate a base64 encoded login request
40
- * @param {string} referenceTagXPath reference uri
41
- * @param {object} entity object includes both idp and sp
42
- * @param {function} customTagReplacement used when developers have their own login response template
43
- */
44
- function base64LoginRequest(referenceTagXPath, entity, customTagReplacement) {
45
- const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
46
- const spSetting = entity.sp.entitySetting;
47
- let id = '';
48
- if (metadata && metadata.idp && metadata.sp) {
49
- const base = metadata.idp.getSingleSignOnService(binding.post);
50
- let rawSamlRequest;
51
- if (spSetting.loginRequestTemplate && customTagReplacement) {
52
- const info = customTagReplacement(spSetting.loginRequestTemplate.context);
53
- id = (0, utility_js_1.get)(info, 'id', null);
54
- rawSamlRequest = (0, utility_js_1.get)(info, 'context', null);
55
- }
56
- else {
57
- const nameIDFormat = spSetting.nameIDFormat;
58
- const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
59
- id = spSetting.generateID();
60
- rawSamlRequest = libsaml_js_1.default.replaceTagsByValue(libsaml_js_1.default.defaultLoginRequestTemplate.context, {
61
- ID: id,
62
- Destination: base,
63
- Issuer: metadata.sp.getEntityID(),
64
- IssueInstant: new Date().toISOString(),
65
- AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.post),
66
- EntityID: metadata.sp.getEntityID(),
67
- AllowCreate: spSetting.allowCreate,
68
- NameIDFormat: selectedNameIDFormat
69
- });
70
- }
71
- if (metadata.idp.isWantAuthnRequestsSigned()) {
72
- const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = spSetting;
73
- return {
74
- id,
75
- context: libsaml_js_1.default.constructSAMLSignature({
76
- referenceTagXPath,
77
- privateKey,
78
- privateKeyPass,
79
- signatureAlgorithm,
80
- transformationAlgorithms,
81
- rawSamlMessage: rawSamlRequest,
82
- signingCert: metadata.sp.getX509Certificate('signing'),
83
- signatureConfig: spSetting.signatureConfig || {
84
- prefix: 'ds',
85
- location: { reference: "/*[local-name(.)='AuthnRequest']/*[local-name(.)='Issuer']", action: 'after' },
86
- }
87
- }),
88
- };
89
- }
90
- // No need to embeded XML signature
91
- return {
92
- id,
93
- context: utility_js_1.default.base64Encode(rawSamlRequest),
94
- };
95
- }
96
- throw new Error('ERR_GENERATE_POST_LOGIN_REQUEST_MISSING_METADATA');
97
- }
98
- /**
99
- * @desc Generate a base64 encoded login response
100
- * @param {object} requestInfo corresponding request, used to obtain the id
101
- * @param {object} entity object includes both idp and sp
102
- * @param {object} user current logged user (e.g. req.user)
103
- * @param {function} customTagReplacement used when developers have their own login response template
104
- * @param {boolean} encryptThenSign whether or not to encrypt then sign first (if signing). Defaults to sign-then-encrypt
105
- * @param AttributeStatement
106
- */
107
- async function base64LoginResponse(requestInfo = {}, entity, user = {}, customTagReplacement, encryptThenSign = false, AttributeStatement = []) {
108
- const idpSetting = entity.idp.entitySetting;
109
- const spSetting = entity.sp.entitySetting;
110
- const id = idpSetting.generateID();
111
- const metadata = {
112
- idp: entity.idp.entityMeta,
113
- sp: entity.sp.entityMeta,
114
- };
115
- const nameIDFormat = idpSetting.nameIDFormat;
116
- const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
117
- if (metadata && metadata.idp && metadata.sp) {
118
- const base = metadata.sp.getAssertionConsumerService(binding.post);
119
- let rawSamlResponse;
120
- let nowTime = new Date();
121
- let spEntityID = metadata.sp.getEntityID();
122
- let oneMinutesLaterTime = new Date(nowTime.getTime());
123
- oneMinutesLaterTime.setMinutes(oneMinutesLaterTime.getMinutes() + 5);
124
- const OneMinutesLater = oneMinutesLaterTime.toISOString();
125
- const now = nowTime.toISOString();
126
- console.log(`现在是北京时间:${nowTime.toLocaleString()}`);
127
- console.log(`现在是两分钟时间:${oneMinutesLaterTime.toLocaleString()}`);
128
- const acl = metadata.sp.getAssertionConsumerService(binding.post);
129
- const sessionIndex = 'session' + idpSetting.generateID(); // 这个是当前系统的会话索引,用于单点注销
130
- const tenHoursLaterTime = new Date(nowTime.getTime());
131
- tenHoursLaterTime.setHours(tenHoursLaterTime.getHours() + 10);
132
- const tenHoursLater = tenHoursLaterTime.toISOString();
133
- const tvalue = {
134
- ID: id,
135
- AssertionID: idpSetting.generateID(),
136
- Destination: base,
137
- Audience: spEntityID,
138
- EntityID: spEntityID,
139
- SubjectRecipient: acl,
140
- Issuer: metadata.idp.getEntityID(),
141
- IssueInstant: now,
142
- AssertionConsumerServiceURL: acl,
143
- StatusCode: urn_js_1.StatusCode.Success,
144
- // can be customized
145
- ConditionsNotBefore: now,
146
- ConditionsNotOnOrAfter: OneMinutesLater,
147
- SubjectConfirmationDataNotOnOrAfter: OneMinutesLater,
148
- NameIDFormat: selectedNameIDFormat,
149
- NameID: user?.NameID || '',
150
- InResponseTo: (0, utility_js_1.get)(requestInfo, 'extract.request.id', ''),
151
- AuthnStatement: `<saml:AuthnStatement AuthnInstant="${now}" SessionNotOnOrAfter="${tenHoursLater}" SessionIndex="${sessionIndex}"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>`,
152
- AttributeStatement: libsaml_js_1.default.attributeStatementBuilder(AttributeStatement),
153
- };
154
- if (idpSetting.loginResponseTemplate && customTagReplacement) {
155
- const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
156
- rawSamlResponse = (0, utility_js_1.get)(template, 'context', null);
157
- }
158
- else {
159
- if (requestInfo !== null) {
160
- tvalue.InResponseTo = requestInfo?.extract?.request?.id ?? '';
161
- }
162
- rawSamlResponse = libsaml_js_1.default.replaceTagsByValue(libsaml_js_1.default.defaultLoginResponseTemplate.context, tvalue);
163
- }
164
- const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
165
- const config = {
166
- privateKey,
167
- privateKeyPass,
168
- signatureAlgorithm,
169
- signingCert: metadata.idp.getX509Certificate('signing'),
170
- isBase64Output: false,
171
- };
172
- // step: sign assertion ? -> encrypted ? -> sign message ?
173
- if (metadata.sp.isWantAssertionsSigned()) {
174
- // console.debug('sp wants assertion signed');
175
- rawSamlResponse = libsaml_js_1.default.constructSAMLSignature({
176
- ...config,
177
- rawSamlMessage: rawSamlResponse,
178
- transformationAlgorithms: spSetting.transformationAlgorithms,
179
- referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
180
- signatureConfig: {
181
- prefix: 'ds',
182
- location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
183
- },
184
- });
185
- }
186
- // console.debug('after assertion signed', rawSamlResponse);
187
- // SAML response must be signed sign message first, then encrypt
188
- if (!encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
189
- // console.debug('sign then encrypt and sign entire message');
190
- rawSamlResponse = libsaml_js_1.default.constructSAMLSignature({
191
- ...config,
192
- rawSamlMessage: rawSamlResponse,
193
- isMessageSigned: true,
194
- transformationAlgorithms: spSetting.transformationAlgorithms,
195
- signatureConfig: spSetting.signatureConfig || {
196
- prefix: 'ds',
197
- location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
198
- },
199
- });
200
- }
201
- // console.debug('after message signed', rawSamlResponse);
202
- if (idpSetting.isAssertionEncrypted) {
203
- // console.debug('idp is configured to do encryption');
204
- const context = await libsaml_js_1.default.encryptAssertion(entity.idp, entity.sp, rawSamlResponse);
205
- if (encryptThenSign) {
206
- //need to decode it
207
- rawSamlResponse = utility_js_1.default.base64Decode(context);
208
- }
209
- else {
210
- return Promise.resolve({ id, context });
211
- }
212
- }
213
- //sign after encrypting
214
- if (encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
215
- rawSamlResponse = libsaml_js_1.default.constructSAMLSignature({
216
- ...config,
217
- rawSamlMessage: rawSamlResponse,
218
- isMessageSigned: true,
219
- transformationAlgorithms: spSetting.transformationAlgorithms,
220
- signatureConfig: spSetting.signatureConfig || {
221
- prefix: 'ds',
222
- location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
223
- },
224
- });
225
- }
226
- console.log(rawSamlResponse);
227
- console.log("看一下---------------------------");
228
- return Promise.resolve({
229
- id,
230
- context: utility_js_1.default.base64Encode(rawSamlResponse),
231
- });
232
- }
233
- throw new Error('ERR_GENERATE_POST_LOGIN_RESPONSE_MISSING_METADATA');
234
- }
235
- /**
236
- * @desc Generate a base64 encoded logout request
237
- * @param {object} user current logged user (e.g. req.user)
238
- * @param {string} referenceTagXPath reference uri
239
- * @param {object} entity object includes both idp and sp
240
- * @param {function} customTagReplacement used when developers have their own login response template
241
- * @return {string} base64 encoded request
242
- */
243
- function base64LogoutRequest(user, referenceTagXPath, entity, customTagReplacement) {
244
- const metadata = { init: entity.init.entityMeta, target: entity.target.entityMeta };
245
- const initSetting = entity.init.entitySetting;
246
- const nameIDFormat = initSetting.nameIDFormat;
247
- const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
248
- let id = '';
249
- if (metadata && metadata.init && metadata.target) {
250
- let rawSamlRequest;
251
- if (initSetting.logoutRequestTemplate && customTagReplacement) {
252
- const template = customTagReplacement(initSetting.logoutRequestTemplate.context);
253
- id = (0, utility_js_1.get)(template, 'id', null);
254
- rawSamlRequest = (0, utility_js_1.get)(template, 'context', null);
255
- }
256
- else {
257
- id = initSetting.generateID();
258
- const tvalue = {
259
- ID: id,
260
- Destination: metadata.target.getSingleLogoutService(binding.post),
261
- Issuer: metadata.init.getEntityID(),
262
- IssueInstant: new Date().toISOString(),
263
- EntityID: metadata.init.getEntityID(),
264
- NameIDFormat: selectedNameIDFormat,
265
- NameID: user.NameID || '',
266
- };
267
- rawSamlRequest = libsaml_js_1.default.replaceTagsByValue(libsaml_js_1.default.defaultLogoutRequestTemplate.context, tvalue);
268
- }
269
- if (entity.target.entitySetting.wantLogoutRequestSigned) {
270
- // Need to embeded XML signature
271
- const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
272
- return {
273
- id,
274
- context: libsaml_js_1.default.constructSAMLSignature({
275
- referenceTagXPath,
276
- privateKey,
277
- privateKeyPass,
278
- signatureAlgorithm,
279
- transformationAlgorithms,
280
- rawSamlMessage: rawSamlRequest,
281
- signingCert: metadata.init.getX509Certificate('signing'),
282
- signatureConfig: initSetting.signatureConfig || {
283
- prefix: 'ds',
284
- location: { reference: "/*[local-name(.)='LogoutRequest']/*[local-name(.)='Issuer']", action: 'after' },
285
- }
286
- }),
287
- };
288
- }
289
- return {
290
- id,
291
- context: utility_js_1.default.base64Encode(rawSamlRequest),
292
- };
293
- }
294
- throw new Error('ERR_GENERATE_POST_LOGOUT_REQUEST_MISSING_METADATA');
295
- }
296
- /**
297
- * @desc Generate a base64 encoded logout response
298
- * @param {object} requestInfo corresponding request, used to obtain the id
299
- * @param {string} referenceTagXPath reference uri
300
- * @param {object} entity object includes both idp and sp
301
- * @param {function} customTagReplacement used when developers have their own login response template
302
- */
303
- function base64LogoutResponse(requestInfo, entity, customTagReplacement) {
304
- const metadata = {
305
- init: entity.init.entityMeta,
306
- target: entity.target.entityMeta,
307
- };
308
- let id = '';
309
- const initSetting = entity.init.entitySetting;
310
- if (metadata && metadata.init && metadata.target) {
311
- let rawSamlResponse;
312
- if (initSetting.logoutResponseTemplate) {
313
- const template = customTagReplacement(initSetting.logoutResponseTemplate.context);
314
- id = template.id;
315
- rawSamlResponse = template.context;
316
- }
317
- else {
318
- id = initSetting.generateID();
319
- const tvalue = {
320
- ID: id,
321
- Destination: metadata.target.getSingleLogoutService(binding.post),
322
- EntityID: metadata.init.getEntityID(),
323
- Issuer: metadata.init.getEntityID(),
324
- IssueInstant: new Date().toISOString(),
325
- StatusCode: urn_js_1.StatusCode.Success,
326
- InResponseTo: (0, utility_js_1.get)(requestInfo, 'extract.request.id', '')
327
- };
328
- rawSamlResponse = libsaml_js_1.default.replaceTagsByValue(libsaml_js_1.default.defaultLogoutResponseTemplate.context, tvalue);
329
- }
330
- if (entity.target.entitySetting.wantLogoutResponseSigned) {
331
- const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
332
- return {
333
- id,
334
- context: libsaml_js_1.default.constructSAMLSignature({
335
- isMessageSigned: true,
336
- transformationAlgorithms: transformationAlgorithms,
337
- privateKey,
338
- privateKeyPass,
339
- signatureAlgorithm,
340
- rawSamlMessage: rawSamlResponse,
341
- signingCert: metadata.init.getX509Certificate('signing'),
342
- signatureConfig: {
343
- prefix: 'ds',
344
- location: {
345
- reference: "/*[local-name(.)='LogoutResponse']/*[local-name(.)='Issuer']",
346
- action: 'after'
347
- }
348
- }
349
- }),
350
- };
351
- }
352
- return {
353
- id,
354
- context: utility_js_1.default.base64Encode(rawSamlResponse),
355
- };
356
- }
357
- throw new Error('ERR_GENERATE_POST_LOGOUT_RESPONSE_MISSING_METADATA');
358
- }
359
- const postBinding = {
360
- base64LoginRequest,
361
- base64LoginResponse,
362
- base64LogoutRequest,
363
- base64LogoutResponse,
364
- };
365
- exports.default = postBinding;
1
+ /**
2
+ * @file binding-post.ts
3
+ * @author tngan
4
+ * @desc Binding-level API, declare the functions using POST binding
5
+ */
6
+ import { wording, StatusCode } from './urn.js';
7
+ import libsaml from './libsaml.js';
8
+ import utility, { get } from './utility.js';
9
+ const binding = wording.binding;
10
+ /**
11
+ * @desc Generate a base64 encoded login request
12
+ * @param {string} referenceTagXPath reference uri
13
+ * @param {object} entity object includes both idp and sp
14
+ * @param {function} customTagReplacement used when developers have their own login response template
15
+ */
16
+ function base64LoginRequest(referenceTagXPath, entity, customTagReplacement) {
17
+ const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
18
+ const spSetting = entity.sp.entitySetting;
19
+ let id = '';
20
+ if (metadata && metadata.idp && metadata.sp) {
21
+ const base = metadata.idp.getSingleSignOnService(binding.post);
22
+ let rawSamlRequest;
23
+ if (spSetting.loginRequestTemplate && customTagReplacement) {
24
+ const info = customTagReplacement(spSetting.loginRequestTemplate.context);
25
+ id = get(info, 'id', null);
26
+ rawSamlRequest = get(info, 'context', null);
27
+ }
28
+ else {
29
+ const nameIDFormat = spSetting.nameIDFormat;
30
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
31
+ id = spSetting.generateID();
32
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLoginRequestTemplate.context, {
33
+ ID: id,
34
+ Destination: base,
35
+ Issuer: metadata.sp.getEntityID(),
36
+ IssueInstant: new Date().toISOString(),
37
+ AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.post),
38
+ EntityID: metadata.sp.getEntityID(),
39
+ AllowCreate: spSetting.allowCreate,
40
+ NameIDFormat: selectedNameIDFormat
41
+ });
42
+ }
43
+ if (metadata.idp.isWantAuthnRequestsSigned()) {
44
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = spSetting;
45
+ return {
46
+ id,
47
+ context: libsaml.constructSAMLSignature({
48
+ referenceTagXPath,
49
+ privateKey,
50
+ privateKeyPass,
51
+ signatureAlgorithm,
52
+ transformationAlgorithms,
53
+ rawSamlMessage: rawSamlRequest,
54
+ signingCert: metadata.sp.getX509Certificate('signing'),
55
+ signatureConfig: spSetting.signatureConfig || {
56
+ prefix: 'ds',
57
+ location: { reference: "/*[local-name(.)='AuthnRequest']/*[local-name(.)='Issuer']", action: 'after' },
58
+ }
59
+ }),
60
+ };
61
+ }
62
+ // No need to embeded XML signature
63
+ return {
64
+ id,
65
+ context: utility.base64Encode(rawSamlRequest),
66
+ };
67
+ }
68
+ throw new Error('ERR_GENERATE_POST_LOGIN_REQUEST_MISSING_METADATA');
69
+ }
70
+ /**
71
+ * @desc Generate a base64 encoded login response
72
+ * @param {object} requestInfo corresponding request, used to obtain the id
73
+ * @param {object} entity object includes both idp and sp
74
+ * @param {object} user current logged user (e.g. req.user)
75
+ * @param {function} customTagReplacement used when developers have their own login response template
76
+ * @param {boolean} encryptThenSign whether or not to encrypt then sign first (if signing). Defaults to sign-then-encrypt
77
+ * @param AttributeStatement
78
+ */
79
+ async function base64LoginResponse(requestInfo = {}, entity, user = {}, customTagReplacement, encryptThenSign = false, AttributeStatement = []) {
80
+ const idpSetting = entity.idp.entitySetting;
81
+ const spSetting = entity.sp.entitySetting;
82
+ const id = idpSetting.generateID();
83
+ const metadata = {
84
+ idp: entity.idp.entityMeta,
85
+ sp: entity.sp.entityMeta,
86
+ };
87
+ const nameIDFormat = idpSetting.nameIDFormat;
88
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
89
+ if (metadata && metadata.idp && metadata.sp) {
90
+ const base = metadata.sp.getAssertionConsumerService(binding.post);
91
+ let rawSamlResponse;
92
+ const nowTime = new Date();
93
+ const spEntityID = metadata.sp.getEntityID();
94
+ const oneMinutesLaterTime = new Date(nowTime.getTime());
95
+ oneMinutesLaterTime.setMinutes(oneMinutesLaterTime.getMinutes() + 5);
96
+ const OneMinutesLater = oneMinutesLaterTime.toISOString();
97
+ const now = nowTime.toISOString();
98
+ console.log(`现在是北京时间:${nowTime.toLocaleString()}`);
99
+ console.log(`现在是两分钟时间:${oneMinutesLaterTime.toLocaleString()}`);
100
+ const acl = metadata.sp.getAssertionConsumerService(binding.post);
101
+ const sessionIndex = 'session' + idpSetting.generateID(); // 这个是当前系统的会话索引,用于单点注销
102
+ const tenHoursLaterTime = new Date(nowTime.getTime());
103
+ tenHoursLaterTime.setHours(tenHoursLaterTime.getHours() + 10);
104
+ const tenHoursLater = tenHoursLaterTime.toISOString();
105
+ const tvalue = {
106
+ ID: id,
107
+ AssertionID: idpSetting.generateID(),
108
+ Destination: base,
109
+ Audience: spEntityID,
110
+ EntityID: spEntityID,
111
+ SubjectRecipient: acl,
112
+ Issuer: metadata.idp.getEntityID(),
113
+ IssueInstant: now,
114
+ AssertionConsumerServiceURL: acl,
115
+ StatusCode: StatusCode.Success,
116
+ // can be customized
117
+ ConditionsNotBefore: now,
118
+ ConditionsNotOnOrAfter: OneMinutesLater,
119
+ SubjectConfirmationDataNotOnOrAfter: OneMinutesLater,
120
+ NameIDFormat: selectedNameIDFormat,
121
+ NameID: user?.NameID || '',
122
+ InResponseTo: get(requestInfo, 'extract.request.id', ''),
123
+ AuthnStatement: `<saml:AuthnStatement AuthnInstant="${now}" SessionNotOnOrAfter="${tenHoursLater}" SessionIndex="${sessionIndex}"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>`,
124
+ AttributeStatement: libsaml.attributeStatementBuilder(AttributeStatement),
125
+ };
126
+ if (idpSetting.loginResponseTemplate && customTagReplacement) {
127
+ const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
128
+ rawSamlResponse = get(template, 'context', null);
129
+ }
130
+ else {
131
+ if (requestInfo !== null) {
132
+ tvalue.InResponseTo = requestInfo?.extract?.request?.id ?? '';
133
+ }
134
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLoginResponseTemplate.context, tvalue);
135
+ }
136
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
137
+ const config = {
138
+ privateKey,
139
+ privateKeyPass,
140
+ signatureAlgorithm,
141
+ signingCert: metadata.idp.getX509Certificate('signing'),
142
+ isBase64Output: false,
143
+ };
144
+ // step: sign assertion ? -> encrypted ? -> sign message ?
145
+ if (metadata.sp.isWantAssertionsSigned()) {
146
+ // console.debug('sp wants assertion signed');
147
+ rawSamlResponse = libsaml.constructSAMLSignature({
148
+ ...config,
149
+ rawSamlMessage: rawSamlResponse,
150
+ transformationAlgorithms: spSetting.transformationAlgorithms,
151
+ referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
152
+ signatureConfig: {
153
+ prefix: 'ds',
154
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
155
+ },
156
+ });
157
+ }
158
+ // console.debug('after assertion signed', rawSamlResponse);
159
+ // SAML response must be signed sign message first, then encrypt
160
+ if (!encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
161
+ // console.debug('sign then encrypt and sign entire message');
162
+ rawSamlResponse = libsaml.constructSAMLSignature({
163
+ ...config,
164
+ rawSamlMessage: rawSamlResponse,
165
+ isMessageSigned: true,
166
+ transformationAlgorithms: spSetting.transformationAlgorithms,
167
+ signatureConfig: spSetting.signatureConfig || {
168
+ prefix: 'ds',
169
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
170
+ },
171
+ });
172
+ }
173
+ // console.debug('after message signed', rawSamlResponse);
174
+ if (idpSetting.isAssertionEncrypted) {
175
+ // console.debug('idp is configured to do encryption');
176
+ const context = await libsaml.encryptAssertion(entity.idp, entity.sp, rawSamlResponse);
177
+ if (encryptThenSign) {
178
+ //need to decode it
179
+ rawSamlResponse = utility.base64Decode(context);
180
+ }
181
+ else {
182
+ return Promise.resolve({ id, context });
183
+ }
184
+ }
185
+ //sign after encrypting
186
+ if (encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
187
+ rawSamlResponse = libsaml.constructSAMLSignature({
188
+ ...config,
189
+ rawSamlMessage: rawSamlResponse,
190
+ isMessageSigned: true,
191
+ transformationAlgorithms: spSetting.transformationAlgorithms,
192
+ signatureConfig: spSetting.signatureConfig || {
193
+ prefix: 'ds',
194
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
195
+ },
196
+ });
197
+ }
198
+ console.log(rawSamlResponse);
199
+ console.log('看一下---------------------------');
200
+ return Promise.resolve({
201
+ id,
202
+ context: utility.base64Encode(rawSamlResponse),
203
+ });
204
+ }
205
+ throw new Error('ERR_GENERATE_POST_LOGIN_RESPONSE_MISSING_METADATA');
206
+ }
207
+ /**
208
+ * @desc Generate a base64 encoded logout request
209
+ * @param {object} user current logged user (e.g. req.user)
210
+ * @param {string} referenceTagXPath reference uri
211
+ * @param {object} entity object includes both idp and sp
212
+ * @param {function} customTagReplacement used when developers have their own login response template
213
+ * @return {string} base64 encoded request
214
+ */
215
+ function base64LogoutRequest(user, referenceTagXPath, entity, customTagReplacement) {
216
+ const metadata = { init: entity.init.entityMeta, target: entity.target.entityMeta };
217
+ const initSetting = entity.init.entitySetting;
218
+ const nameIDFormat = initSetting.nameIDFormat;
219
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
220
+ let id = '';
221
+ if (metadata && metadata.init && metadata.target) {
222
+ let rawSamlRequest;
223
+ if (initSetting.logoutRequestTemplate && customTagReplacement) {
224
+ const template = customTagReplacement(initSetting.logoutRequestTemplate.context);
225
+ id = get(template, 'id', null);
226
+ rawSamlRequest = get(template, 'context', null);
227
+ }
228
+ else {
229
+ id = initSetting.generateID();
230
+ const tvalue = {
231
+ ID: id,
232
+ Destination: metadata.target.getSingleLogoutService(binding.post),
233
+ Issuer: metadata.init.getEntityID(),
234
+ IssueInstant: new Date().toISOString(),
235
+ EntityID: metadata.init.getEntityID(),
236
+ NameIDFormat: selectedNameIDFormat,
237
+ NameID: user.NameID || '',
238
+ };
239
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLogoutRequestTemplate.context, tvalue);
240
+ }
241
+ if (entity.target.entitySetting.wantLogoutRequestSigned) {
242
+ // Need to embeded XML signature
243
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
244
+ return {
245
+ id,
246
+ context: libsaml.constructSAMLSignature({
247
+ referenceTagXPath,
248
+ privateKey,
249
+ privateKeyPass,
250
+ signatureAlgorithm,
251
+ transformationAlgorithms,
252
+ rawSamlMessage: rawSamlRequest,
253
+ signingCert: metadata.init.getX509Certificate('signing'),
254
+ signatureConfig: initSetting.signatureConfig || {
255
+ prefix: 'ds',
256
+ location: { reference: "/*[local-name(.)='LogoutRequest']/*[local-name(.)='Issuer']", action: 'after' },
257
+ }
258
+ }),
259
+ };
260
+ }
261
+ return {
262
+ id,
263
+ context: utility.base64Encode(rawSamlRequest),
264
+ };
265
+ }
266
+ throw new Error('ERR_GENERATE_POST_LOGOUT_REQUEST_MISSING_METADATA');
267
+ }
268
+ /**
269
+ * @desc Generate a base64 encoded logout response
270
+ * @param {object} requestInfo corresponding request, used to obtain the id
271
+ * @param {string} referenceTagXPath reference uri
272
+ * @param {object} entity object includes both idp and sp
273
+ * @param {function} customTagReplacement used when developers have their own login response template
274
+ */
275
+ function base64LogoutResponse(requestInfo, entity, customTagReplacement) {
276
+ const metadata = {
277
+ init: entity.init.entityMeta,
278
+ target: entity.target.entityMeta,
279
+ };
280
+ let id = '';
281
+ const initSetting = entity.init.entitySetting;
282
+ if (metadata && metadata.init && metadata.target) {
283
+ let rawSamlResponse;
284
+ if (initSetting.logoutResponseTemplate) {
285
+ const template = customTagReplacement(initSetting.logoutResponseTemplate.context);
286
+ id = template.id;
287
+ rawSamlResponse = template.context;
288
+ }
289
+ else {
290
+ id = initSetting.generateID();
291
+ const tvalue = {
292
+ ID: id,
293
+ Destination: metadata.target.getSingleLogoutService(binding.post),
294
+ EntityID: metadata.init.getEntityID(),
295
+ Issuer: metadata.init.getEntityID(),
296
+ IssueInstant: new Date().toISOString(),
297
+ StatusCode: StatusCode.Success,
298
+ InResponseTo: get(requestInfo, 'extract.request.id', '')
299
+ };
300
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLogoutResponseTemplate.context, tvalue);
301
+ }
302
+ if (entity.target.entitySetting.wantLogoutResponseSigned) {
303
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
304
+ return {
305
+ id,
306
+ context: libsaml.constructSAMLSignature({
307
+ isMessageSigned: true,
308
+ transformationAlgorithms: transformationAlgorithms,
309
+ privateKey,
310
+ privateKeyPass,
311
+ signatureAlgorithm,
312
+ rawSamlMessage: rawSamlResponse,
313
+ signingCert: metadata.init.getX509Certificate('signing'),
314
+ signatureConfig: {
315
+ prefix: 'ds',
316
+ location: {
317
+ reference: "/*[local-name(.)='LogoutResponse']/*[local-name(.)='Issuer']",
318
+ action: 'after'
319
+ }
320
+ }
321
+ }),
322
+ };
323
+ }
324
+ return {
325
+ id,
326
+ context: utility.base64Encode(rawSamlResponse),
327
+ };
328
+ }
329
+ throw new Error('ERR_GENERATE_POST_LOGOUT_RESPONSE_MISSING_METADATA');
330
+ }
331
+ const postBinding = {
332
+ base64LoginRequest,
333
+ base64LoginResponse,
334
+ base64LogoutRequest,
335
+ base64LogoutResponse,
336
+ };
337
+ export default postBinding;
366
338
  //# sourceMappingURL=binding-post.js.map