samlesa 2.16.1 → 2.16.6

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 (75) hide show
  1. package/build/src/binding-artifact.js +333 -0
  2. package/build/src/binding-redirect.js +97 -2
  3. package/build/src/entity-sp.js +138 -21
  4. package/build/src/extractor.js +13 -0
  5. package/build/src/flow.js +225 -5
  6. package/build/src/libsaml.js +233 -2
  7. package/build/src/metadata-idp.js +22 -0
  8. package/build/src/metadata-sp.js +19 -15
  9. package/build/src/metadata.js +50 -31
  10. package/build/src/schema/saml-schema-ecp-2.0.xsd +1 -1
  11. package/build/src/schema/saml-schema-metadata-2.0.xsd +3 -3
  12. package/build/src/schema/saml-schema-protocol-2.0.xsd +1 -1
  13. package/build/src/schema/soap-envelope.xsd +68 -0
  14. package/build/src/schema/xml.xsd +88 -0
  15. package/build/src/schemaValidator.js +28 -6
  16. package/build/src/soap.js +25 -0
  17. package/build/src/urn.js +5 -3
  18. package/package.json +2 -1
  19. package/types/{binding-post.d.ts → src/binding-artifact.d.ts} +25 -25
  20. package/types/src/binding-artifact.d.ts.map +1 -0
  21. package/types/src/binding-redirect.d.ts +14 -1
  22. package/types/src/binding-redirect.d.ts.map +1 -1
  23. package/types/src/entity-sp.d.ts +50 -20
  24. package/types/src/entity-sp.d.ts.map +1 -1
  25. package/types/src/extractor.d.ts +5 -0
  26. package/types/src/extractor.d.ts.map +1 -1
  27. package/types/src/flow.d.ts.map +1 -1
  28. package/types/src/libsaml.d.ts +16 -0
  29. package/types/src/libsaml.d.ts.map +1 -1
  30. package/types/src/metadata-idp.d.ts +6 -0
  31. package/types/src/metadata-idp.d.ts.map +1 -1
  32. package/types/src/metadata-sp.d.ts.map +1 -1
  33. package/types/src/metadata.d.ts +34 -27
  34. package/types/src/metadata.d.ts.map +1 -1
  35. package/types/src/schemaValidator.d.ts.map +1 -1
  36. package/types/src/soap.d.ts +2 -0
  37. package/types/src/soap.d.ts.map +1 -0
  38. package/types/src/urn.d.ts +2 -0
  39. package/types/src/urn.d.ts.map +1 -1
  40. package/build/.idea/build.iml +0 -12
  41. package/build/.idea/deployment.xml +0 -14
  42. package/build/.idea/modules.xml +0 -8
  43. package/types/api.d.ts +0 -15
  44. package/types/api.d.ts.map +0 -1
  45. package/types/binding-post.d.ts.map +0 -1
  46. package/types/binding-redirect.d.ts +0 -54
  47. package/types/binding-redirect.d.ts.map +0 -1
  48. package/types/binding-simplesign.d.ts +0 -41
  49. package/types/binding-simplesign.d.ts.map +0 -1
  50. package/types/entity-idp.d.ts +0 -38
  51. package/types/entity-idp.d.ts.map +0 -1
  52. package/types/entity-sp.d.ts +0 -38
  53. package/types/entity-sp.d.ts.map +0 -1
  54. package/types/entity.d.ts +0 -100
  55. package/types/entity.d.ts.map +0 -1
  56. package/types/extractor.d.ts +0 -26
  57. package/types/extractor.d.ts.map +0 -1
  58. package/types/flow.d.ts +0 -7
  59. package/types/flow.d.ts.map +0 -1
  60. package/types/libsaml.d.ts +0 -208
  61. package/types/libsaml.d.ts.map +0 -1
  62. package/types/metadata-idp.d.ts +0 -25
  63. package/types/metadata-idp.d.ts.map +0 -1
  64. package/types/metadata-sp.d.ts +0 -37
  65. package/types/metadata-sp.d.ts.map +0 -1
  66. package/types/metadata.d.ts +0 -58
  67. package/types/metadata.d.ts.map +0 -1
  68. package/types/types.d.ts +0 -128
  69. package/types/types.d.ts.map +0 -1
  70. package/types/urn.d.ts +0 -195
  71. package/types/urn.d.ts.map +0 -1
  72. package/types/utility.d.ts +0 -133
  73. package/types/utility.d.ts.map +0 -1
  74. package/types/validator.d.ts +0 -4
  75. package/types/validator.d.ts.map +0 -1
@@ -0,0 +1,333 @@
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
+ const acl = metadata.sp.getAssertionConsumerService(binding.post);
99
+ const sessionIndex = 'session' + idpSetting.generateID(); // 这个是当前系统的会话索引,用于单点注销
100
+ const tenHoursLaterTime = new Date(nowTime.getTime());
101
+ tenHoursLaterTime.setHours(tenHoursLaterTime.getHours() + 10);
102
+ const tenHoursLater = tenHoursLaterTime.toISOString();
103
+ const tvalue = {
104
+ ID: id,
105
+ AssertionID: idpSetting.generateID(),
106
+ Destination: base,
107
+ Audience: spEntityID,
108
+ EntityID: spEntityID,
109
+ SubjectRecipient: acl,
110
+ Issuer: metadata.idp.getEntityID(),
111
+ IssueInstant: now,
112
+ AssertionConsumerServiceURL: acl,
113
+ StatusCode: StatusCode.Success,
114
+ // can be customized
115
+ ConditionsNotBefore: now,
116
+ ConditionsNotOnOrAfter: OneMinutesLater,
117
+ SubjectConfirmationDataNotOnOrAfter: OneMinutesLater,
118
+ NameIDFormat: selectedNameIDFormat,
119
+ NameID: user?.NameID || '',
120
+ InResponseTo: get(requestInfo, 'extract.request.id', ''),
121
+ 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>`,
122
+ AttributeStatement: libsaml.attributeStatementBuilder(AttributeStatement),
123
+ };
124
+ if (idpSetting.loginResponseTemplate && customTagReplacement) {
125
+ const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
126
+ rawSamlResponse = get(template, 'context', null);
127
+ }
128
+ else {
129
+ if (requestInfo !== null) {
130
+ tvalue.InResponseTo = requestInfo?.extract?.request?.id ?? '';
131
+ }
132
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLoginResponseTemplate.context, tvalue);
133
+ }
134
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
135
+ const config = {
136
+ privateKey,
137
+ privateKeyPass,
138
+ signatureAlgorithm,
139
+ signingCert: metadata.idp.getX509Certificate('signing'),
140
+ isBase64Output: false,
141
+ };
142
+ // step: sign assertion ? -> encrypted ? -> sign message ?
143
+ if (metadata.sp.isWantAssertionsSigned()) {
144
+ // console.debug('sp wants assertion signed');
145
+ rawSamlResponse = libsaml.constructSAMLSignature({
146
+ ...config,
147
+ rawSamlMessage: rawSamlResponse,
148
+ transformationAlgorithms: spSetting.transformationAlgorithms,
149
+ referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
150
+ signatureConfig: {
151
+ prefix: 'ds',
152
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
153
+ },
154
+ });
155
+ }
156
+ // console.debug('after assertion signed', rawSamlResponse);
157
+ // SAML response must be signed sign message first, then encrypt
158
+ if (!encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
159
+ // console.debug('sign then encrypt and sign entire message');
160
+ rawSamlResponse = libsaml.constructSAMLSignature({
161
+ ...config,
162
+ rawSamlMessage: rawSamlResponse,
163
+ isMessageSigned: true,
164
+ transformationAlgorithms: spSetting.transformationAlgorithms,
165
+ signatureConfig: spSetting.signatureConfig || {
166
+ prefix: 'ds',
167
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
168
+ },
169
+ });
170
+ }
171
+ // console.debug('after message signed', rawSamlResponse);
172
+ if (idpSetting.isAssertionEncrypted) {
173
+ // console.debug('idp is configured to do encryption');
174
+ const context = await libsaml.encryptAssertion(entity.idp, entity.sp, rawSamlResponse);
175
+ if (encryptThenSign) {
176
+ //need to decode it
177
+ rawSamlResponse = utility.base64Decode(context);
178
+ }
179
+ else {
180
+ return Promise.resolve({ id, context });
181
+ }
182
+ }
183
+ //sign after encrypting
184
+ if (encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
185
+ rawSamlResponse = libsaml.constructSAMLSignature({
186
+ ...config,
187
+ rawSamlMessage: rawSamlResponse,
188
+ isMessageSigned: true,
189
+ transformationAlgorithms: spSetting.transformationAlgorithms,
190
+ signatureConfig: spSetting.signatureConfig || {
191
+ prefix: 'ds',
192
+ location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
193
+ },
194
+ });
195
+ }
196
+ return Promise.resolve({
197
+ id,
198
+ context: utility.base64Encode(rawSamlResponse),
199
+ });
200
+ }
201
+ throw new Error('ERR_GENERATE_POST_LOGIN_RESPONSE_MISSING_METADATA');
202
+ }
203
+ /**
204
+ * @desc Generate a base64 encoded logout request
205
+ * @param {object} user current logged user (e.g. req.user)
206
+ * @param {string} referenceTagXPath reference uri
207
+ * @param {object} entity object includes both idp and sp
208
+ * @param {function} customTagReplacement used when developers have their own login response template
209
+ * @return {string} base64 encoded request
210
+ */
211
+ function base64LogoutRequest(user, referenceTagXPath, entity, customTagReplacement) {
212
+ const metadata = { init: entity.init.entityMeta, target: entity.target.entityMeta };
213
+ const initSetting = entity.init.entitySetting;
214
+ const nameIDFormat = initSetting.nameIDFormat;
215
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
216
+ let id = '';
217
+ if (metadata && metadata.init && metadata.target) {
218
+ let rawSamlRequest;
219
+ if (initSetting.logoutRequestTemplate && customTagReplacement) {
220
+ const template = customTagReplacement(initSetting.logoutRequestTemplate.context);
221
+ id = get(template, 'id', null);
222
+ rawSamlRequest = get(template, 'context', null);
223
+ }
224
+ else {
225
+ id = initSetting.generateID();
226
+ const tvalue = {
227
+ ID: id,
228
+ Destination: metadata.target.getSingleLogoutService(binding.post),
229
+ Issuer: metadata.init.getEntityID(),
230
+ IssueInstant: new Date().toISOString(),
231
+ EntityID: metadata.init.getEntityID(),
232
+ NameIDFormat: selectedNameIDFormat,
233
+ NameID: user.NameID || '',
234
+ };
235
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLogoutRequestTemplate.context, tvalue);
236
+ }
237
+ if (entity.target.entitySetting.wantLogoutRequestSigned) {
238
+ // Need to embeded XML signature
239
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
240
+ return {
241
+ id,
242
+ context: libsaml.constructSAMLSignature({
243
+ referenceTagXPath,
244
+ privateKey,
245
+ privateKeyPass,
246
+ signatureAlgorithm,
247
+ transformationAlgorithms,
248
+ rawSamlMessage: rawSamlRequest,
249
+ signingCert: metadata.init.getX509Certificate('signing'),
250
+ signatureConfig: initSetting.signatureConfig || {
251
+ prefix: 'ds',
252
+ location: { reference: "/*[local-name(.)='LogoutRequest']/*[local-name(.)='Issuer']", action: 'after' },
253
+ }
254
+ }),
255
+ };
256
+ }
257
+ return {
258
+ id,
259
+ context: utility.base64Encode(rawSamlRequest),
260
+ };
261
+ }
262
+ throw new Error('ERR_GENERATE_POST_LOGOUT_REQUEST_MISSING_METADATA');
263
+ }
264
+ /**
265
+ * @desc Generate a base64 encoded logout response
266
+ * @param {object} requestInfo corresponding request, used to obtain the id
267
+ * @param {string} referenceTagXPath reference uri
268
+ * @param {object} entity object includes both idp and sp
269
+ * @param {function} customTagReplacement used when developers have their own login response template
270
+ */
271
+ function base64LogoutResponse(requestInfo, entity, customTagReplacement) {
272
+ const metadata = {
273
+ init: entity.init.entityMeta,
274
+ target: entity.target.entityMeta,
275
+ };
276
+ let id = '';
277
+ const initSetting = entity.init.entitySetting;
278
+ if (metadata && metadata.init && metadata.target) {
279
+ let rawSamlResponse;
280
+ if (initSetting.logoutResponseTemplate) {
281
+ const template = customTagReplacement(initSetting.logoutResponseTemplate.context);
282
+ id = template.id;
283
+ rawSamlResponse = template.context;
284
+ }
285
+ else {
286
+ id = initSetting.generateID();
287
+ const tvalue = {
288
+ ID: id,
289
+ Destination: metadata.target.getSingleLogoutService(binding.post),
290
+ EntityID: metadata.init.getEntityID(),
291
+ Issuer: metadata.init.getEntityID(),
292
+ IssueInstant: new Date().toISOString(),
293
+ StatusCode: StatusCode.Success,
294
+ InResponseTo: get(requestInfo, 'extract.request.id', '')
295
+ };
296
+ rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLogoutResponseTemplate.context, tvalue);
297
+ }
298
+ if (entity.target.entitySetting.wantLogoutResponseSigned) {
299
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
300
+ return {
301
+ id,
302
+ context: libsaml.constructSAMLSignature({
303
+ isMessageSigned: true,
304
+ transformationAlgorithms: transformationAlgorithms,
305
+ privateKey,
306
+ privateKeyPass,
307
+ signatureAlgorithm,
308
+ rawSamlMessage: rawSamlResponse,
309
+ signingCert: metadata.init.getX509Certificate('signing'),
310
+ signatureConfig: {
311
+ prefix: 'ds',
312
+ location: {
313
+ reference: "/*[local-name(.)='LogoutResponse']/*[local-name(.)='Issuer']",
314
+ action: 'after'
315
+ }
316
+ }
317
+ }),
318
+ };
319
+ }
320
+ return {
321
+ id,
322
+ context: utility.base64Encode(rawSamlResponse),
323
+ };
324
+ }
325
+ throw new Error('ERR_GENERATE_POST_LOGOUT_RESPONSE_MISSING_METADATA');
326
+ }
327
+ const artifactSignBinding = {
328
+ base64LoginRequest,
329
+ base64LoginResponse,
330
+ base64LogoutRequest,
331
+ base64LogoutResponse,
332
+ };
333
+ export default artifactSignBinding;
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import utility, { get } from './utility.js';
7
7
  import libsaml from './libsaml.js';
8
- import { wording, namespace } from './urn.js';
8
+ import { namespace, wording } from './urn.js';
9
9
  const binding = wording.binding;
10
10
  const urlParams = wording.urlParams;
11
11
  /**
@@ -59,8 +59,9 @@ function buildRedirectURL(opts) {
59
59
  * @param {function} customTagReplacement used when developers have their own login response template
60
60
  * @return {string} redirect URL
61
61
  */
62
+ // @ts-ignore
62
63
  function loginRequestRedirectURL(entity, customTagReplacement) {
63
- const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
64
+ const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta, soap: entity.soap ?? false };
64
65
  const spSetting = entity.sp.entitySetting;
65
66
  let id = '';
66
67
  if (metadata && metadata.idp && metadata.sp) {
@@ -100,6 +101,99 @@ function loginRequestRedirectURL(entity, customTagReplacement) {
100
101
  }
101
102
  throw new Error('ERR_GENERATE_REDIRECT_LOGIN_REQUEST_MISSING_METADATA');
102
103
  }
104
+ /**
105
+ * @desc Redirect URL for login request
106
+ * @param {object} entity object includes both idp and sp
107
+ * @param {function} customTagReplacement used when developers have their own login response template
108
+ * @return {string} redirect URL
109
+ */
110
+ // @ts-ignore
111
+ function loginRequestRedirectURLArt(entity, customTagReplacement) {
112
+ const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta, inResponse: entity.inResponse ?? false };
113
+ const spSetting = entity.sp.entitySetting;
114
+ let id = '';
115
+ if (metadata && metadata.idp && metadata.sp) {
116
+ const base = metadata.idp.getSingleSignOnService(binding.redirect);
117
+ let rawSamlRequest;
118
+ if (spSetting.loginRequestTemplate && customTagReplacement) {
119
+ const info = customTagReplacement(spSetting.loginRequestTemplate);
120
+ id = get(info, 'id', null);
121
+ rawSamlRequest = get(info, 'context', null);
122
+ }
123
+ else {
124
+ const nameIDFormat = spSetting.nameIDFormat;
125
+ const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
126
+ id = spSetting.generateID();
127
+ rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLoginRequestTemplate.context, {
128
+ ID: id,
129
+ Destination: base,
130
+ Issuer: metadata.sp.getEntityID(),
131
+ IssueInstant: new Date().toISOString(),
132
+ NameIDFormat: selectedNameIDFormat,
133
+ AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.post),
134
+ EntityID: metadata.sp.getEntityID(),
135
+ AllowCreate: spSetting.allowCreate,
136
+ });
137
+ }
138
+ console.log(rawSamlRequest);
139
+ console.log("-----------------这是原始请求模板-------------------");
140
+ const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = spSetting;
141
+ if (metadata.idp.isWantAuthnRequestsSigned()) {
142
+ let signAuthnRequest = libsaml.constructSAMLSignature({
143
+ referenceTagXPath: "/*[local-name(.)='AuthnRequest']",
144
+ privateKey,
145
+ privateKeyPass,
146
+ signatureAlgorithm,
147
+ transformationAlgorithms,
148
+ isBase64Output: false,
149
+ rawSamlMessage: rawSamlRequest,
150
+ signingCert: metadata.sp.getX509Certificate('signing'),
151
+ signatureConfig: spSetting.signatureConfig || {
152
+ prefix: 'ds',
153
+ location: {
154
+ reference: "/*[local-name(.)='AuthnRequest']/*[local-name(.)='Issuer']",
155
+ action: 'after'
156
+ },
157
+ }
158
+ });
159
+ console.log(signAuthnRequest);
160
+ console.log("签名后的模板");
161
+ rawSamlRequest = signAuthnRequest;
162
+ }
163
+ /* console.log(metadata.idp)
164
+ console.log(entity.idp.getEntitySetting())*/
165
+ let soapTemplate = libsaml.replaceTagsByValue(libsaml.defaultArtAuthnRequestTemplate.context, {
166
+ ID: id,
167
+ IssueInstant: new Date().toISOString(),
168
+ InResponseTo: metadata.inResponse ?? "",
169
+ Issuer: metadata.sp.getEntityID(),
170
+ AuthnRequest: rawSamlRequest
171
+ });
172
+ console.log(soapTemplate);
173
+ console.log("======================最后结果========================");
174
+ console.log("======================开始签名根节点========================");
175
+ let rootSignSoap = libsaml.constructSAMLSignature({
176
+ isMessageSigned: true,
177
+ isBase64Output: false,
178
+ privateKey,
179
+ privateKeyPass,
180
+ signatureAlgorithm,
181
+ transformationAlgorithms,
182
+ rawSamlMessage: soapTemplate,
183
+ signingCert: metadata.sp.getX509Certificate('signing'),
184
+ signatureConfig: {
185
+ prefix: 'ds',
186
+ location: { reference: "//*[local-name()='Header']", action: 'after' },
187
+ }
188
+ });
189
+ console.log(rootSignSoap);
190
+ console.log("======================已经签名========================");
191
+ return {
192
+ authnRequest: rootSignSoap
193
+ };
194
+ }
195
+ throw new Error('ERR_GENERATE_REDIRECT_LOGIN_REQUEST_MISSING_METADATA');
196
+ }
103
197
  /**
104
198
  * @desc Redirect URL for login response
105
199
  * @param {object} requestInfo corresponding request, used to obtain the id
@@ -304,6 +398,7 @@ function logoutResponseRedirectURL(requestInfo, entity, relayState, customTagRep
304
398
  throw new Error('ERR_GENERATE_REDIRECT_LOGOUT_RESPONSE_MISSING_METADATA');
305
399
  }
306
400
  const redirectBinding = {
401
+ loginRequestRedirectURLArt,
307
402
  loginRequestRedirectURL,
308
403
  loginResponseRedirectURL,
309
404
  logoutRequestRedirectURL,
@@ -1,13 +1,15 @@
1
1
  /**
2
- * @file entity-sp.ts
3
- * @author tngan
4
- * @desc Declares the actions taken by service provider
5
- */
2
+ * @file entity-sp.ts
3
+ * @author tngan
4
+ * @desc Declares the actions taken by service provider
5
+ */
6
6
  import Entity from './entity.js';
7
+ import * as crypto from "node:crypto";
7
8
  import { namespace } from './urn.js';
8
9
  import redirectBinding from './binding-redirect.js';
9
10
  import postBinding from './binding-post.js';
10
11
  import simpleSignBinding from './binding-simplesign.js';
12
+ import artifactSignBinding from './binding-artifact.js';
11
13
  import { flow } from './flow.js';
12
14
  /*
13
15
  * @desc interface function
@@ -16,15 +18,15 @@ export default function (props) {
16
18
  return new ServiceProvider(props);
17
19
  }
18
20
  /**
19
- * @desc Service provider can be configured using either metadata importing or spSetting
20
- * @param {object} spSettingimport { FlowResult } from '../types/src/flow.d';
21
+ * @desc Service provider can be configured using either metadata importing or spSetting
22
+ * @param {object} spSettingimport { FlowResult } from '../types/src/flow.d';
21
23
 
22
- */
24
+ */
23
25
  export class ServiceProvider extends Entity {
24
26
  /**
25
- * @desc Inherited from Entity
26
- * @param {object} spSetting setting of service provider
27
- */
27
+ * @desc Inherited from Entity
28
+ * @param {object} spSetting setting of service provider
29
+ */
28
30
  constructor(spSetting) {
29
31
  const entitySetting = Object.assign({
30
32
  authnRequestsSigned: false,
@@ -34,11 +36,11 @@ export class ServiceProvider extends Entity {
34
36
  super(entitySetting, 'sp');
35
37
  }
36
38
  /**
37
- * @desc Generates the login request for developers to design their own method
38
- * @param {IdentityProvider} idp object of identity provider
39
- * @param {string} binding protocol binding
40
- * @param {function} customTagReplacement used when developers have their own login response template
41
- */
39
+ * @desc Generates the login request for developers to design their own method
40
+ * @param {IdentityProvider} idp object of identity provider
41
+ * @param {string} binding protocol binding
42
+ * @param {function} customTagReplacement used when developers have their own login response template
43
+ */
42
44
  createLoginRequest(idp, binding = 'redirect', customTagReplacement) {
43
45
  const nsBinding = namespace.binding;
44
46
  const protocol = nsBinding[binding];
@@ -50,12 +52,21 @@ export class ServiceProvider extends Entity {
50
52
  case nsBinding.redirect:
51
53
  return redirectBinding.loginRequestRedirectURL({ idp, sp: this }, customTagReplacement);
52
54
  case nsBinding.post:
53
- context = postBinding.base64LoginRequest("/*[local-name(.)='AuthnRequest']", { idp, sp: this }, customTagReplacement);
55
+ context = postBinding.base64LoginRequest("/*[local-name(.)='AuthnRequest']", {
56
+ idp,
57
+ sp: this
58
+ }, customTagReplacement);
54
59
  break;
55
60
  case nsBinding.simpleSign:
56
61
  // Object context = {id, context, signature, sigAlg}
57
62
  context = simpleSignBinding.base64LoginRequest({ idp, sp: this }, customTagReplacement);
58
63
  break;
64
+ case nsBinding.artifact:
65
+ context = artifactSignBinding.base64LoginRequest("/*[local-name(.)='AuthnRequest']", {
66
+ idp,
67
+ sp: this
68
+ }, customTagReplacement);
69
+ break;
59
70
  default:
60
71
  // Will support artifact in the next release
61
72
  throw new Error('ERR_SP_LOGIN_REQUEST_UNDEFINED_BINDING');
@@ -68,11 +79,45 @@ export class ServiceProvider extends Entity {
68
79
  };
69
80
  }
70
81
  /**
71
- * @desc Validation of the parsed the URL parameters
72
- * @param {IdentityProvider} idp object of identity provider
73
- * @param {string} binding protocol binding
74
- * @param {request} req request
75
- */
82
+ * @desc Generates the Art login request for developers to design their own method
83
+ * @param {IdentityProvider} idp object of identity provider
84
+ * @param {string} binding protocol binding
85
+ * @param {function} customTagReplacement used when developers have their own login response template
86
+ */
87
+ createLoginRequestArt(idp, binding = 'redirect', customTagReplacement) {
88
+ const nsBinding = namespace.binding;
89
+ const protocol = nsBinding[binding];
90
+ if (this.entityMeta.isAuthnRequestSigned() !== idp.entityMeta.isWantAuthnRequestsSigned()) {
91
+ throw new Error('ERR_METADATA_CONFLICT_REQUEST_SIGNED_FLAG');
92
+ }
93
+ let context = null;
94
+ switch (protocol) {
95
+ case nsBinding.redirect:
96
+ return redirectBinding.loginRequestRedirectURLArt({ idp, sp: this }, customTagReplacement);
97
+ case nsBinding.post:
98
+ context = postBinding.base64LoginRequest("/*[local-name(.)='AuthnRequest']", {
99
+ idp,
100
+ sp: this,
101
+ soap: true
102
+ }, customTagReplacement);
103
+ break;
104
+ default:
105
+ // Will support artifact in the next release
106
+ throw new Error('ERR_SP_LOGIN_REQUEST_UNDEFINED_BINDING');
107
+ }
108
+ return {
109
+ ...context,
110
+ relayState: this.entitySetting.relayState,
111
+ entityEndpoint: idp.entityMeta.getSingleSignOnService(binding),
112
+ type: 'SAMLRequest',
113
+ };
114
+ }
115
+ /**
116
+ * @desc Validation of the parsed the URL parameters
117
+ * @param {IdentityProvider} idp object of identity provider
118
+ * @param {string} binding protocol binding
119
+ * @param {request} req request
120
+ */
76
121
  parseLoginResponse(idp, binding, request) {
77
122
  const self = this;
78
123
  return flow({
@@ -85,4 +130,76 @@ export class ServiceProvider extends Entity {
85
130
  request: request
86
131
  });
87
132
  }
133
+ /**
134
+ * @desc request SamlResponse by Arc id
135
+ * @param {IdentityProvider} idp object of identity provider
136
+ * @param {string} binding protocol binding
137
+ * @param {request} req request
138
+ */
139
+ parseLoginResponseArt(idp, binding, request) {
140
+ const self = this;
141
+ return flow({
142
+ soap: true,
143
+ from: idp,
144
+ self: self,
145
+ checkSignature: true, // saml response must have signature
146
+ parserType: 'SAMLResponse',
147
+ type: 'login',
148
+ binding: binding,
149
+ request: request
150
+ });
151
+ }
152
+ /**
153
+ * @desc generate Art id
154
+ *
155
+ * @param entityIDString
156
+ */
157
+ createArt(entityIDString, endpointIndex = 0) {
158
+ let sourceEntityId = entityIDString ? entityIDString : this.entityMeta.getEntityID();
159
+ console.log(sourceEntityId);
160
+ console.log("0000000000000000000000000000000000000000");
161
+ // 1. 固定类型代码 (0x0004 - 2字节)
162
+ const typeCode = Buffer.from([0x00, 0x04]);
163
+ // 2. 端点索引 (2字节,大端序)
164
+ if (endpointIndex < 0 || endpointIndex > 65535) {
165
+ throw new Error('Endpoint index must be between 0 and 65535');
166
+ }
167
+ const endpointBuf = Buffer.alloc(2);
168
+ endpointBuf.writeUInt16BE(endpointIndex);
169
+ // 3. Source ID - 实体ID的SHA-1哈希 (20字节)
170
+ const sourceId = crypto.createHash('sha1')
171
+ .update(sourceEntityId)
172
+ .digest();
173
+ // 4. Message Handler - 20字节随机值
174
+ const messageHandler = crypto.randomBytes(20);
175
+ // 组合所有组件 (2+2+20+20 = 44字节)
176
+ const artifact = Buffer.concat([typeCode, endpointBuf, sourceId, messageHandler]);
177
+ // 返回Base64编码的Artifact
178
+ return artifact.toString('base64');
179
+ }
180
+ /**
181
+ * @desc generate Art id
182
+ * @param artifact
183
+ */
184
+ parseArt(artifact) {
185
+ // 解码 Base64
186
+ const decoded = Buffer.from(artifact, 'base64');
187
+ // 确保长度正确(SAML 工件固定为 44 字节)
188
+ if (decoded.length !== 44) {
189
+ throw new Error(`Invalid artifact length: ${decoded.length}, expected 44 bytes`);
190
+ }
191
+ // 读取前 4 字节(TypeCode + EndpointIndex)
192
+ const typeCode = decoded.readUInt16BE(0);
193
+ const endpointIndex = decoded.readUInt16BE(2);
194
+ // 使用 Buffer.from() 替代 slice()
195
+ const sourceId = Buffer.from(decoded.buffer, // 底层 ArrayBuffer
196
+ decoded.byteOffset + 4, // 起始偏移量
197
+ 20 // 长度
198
+ ).toString('hex');
199
+ const messageHandle = Buffer.from(decoded.buffer, // 底层 ArrayBuffer
200
+ decoded.byteOffset + 24, // 起始偏移量
201
+ 20 // 长度
202
+ ).toString('hex');
203
+ return { typeCode, endpointIndex, sourceId, messageHandle };
204
+ }
88
205
  }