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
package/src/types.ts ADDED
@@ -0,0 +1,153 @@
1
+ import { LoginResponseTemplate } from './libsaml.js';
2
+
3
+ export { IdentityProvider as IdentityProviderConstructor } from './entity-idp.js';
4
+ export { IdpMetadata as IdentityProviderMetadata } from './metadata-idp.js';
5
+
6
+ export { ServiceProvider as ServiceProviderConstructor } from './entity-sp.js';
7
+ export { SpMetadata as ServiceProviderMetadata } from './metadata-sp.js';
8
+
9
+ export type MetadataFile = string | Buffer;
10
+
11
+ type SSOService = {
12
+ isDefault?: boolean;
13
+ Binding: string;
14
+ Location: string;
15
+ };
16
+ // 1. 定义服务名称类型
17
+ export type ServiceName = {
18
+ value: string;
19
+ /** @description 语言标识符(如 en/zh-CN) */
20
+ lang?: string;
21
+ };
22
+
23
+ // 2. 定义请求属性类型
24
+ export type RequestedAttribute = {
25
+ name: string;
26
+ friendlyName?: string;
27
+ isRequired?: boolean;
28
+ nameFormat?: string;
29
+ attributeValue?: string[];
30
+ };
31
+
32
+ // 3. 定义属性消费服务类型
33
+ export type AttributeConsumingService = {
34
+ isDefault: boolean;
35
+ serviceName: ServiceName[]; // 修复点:确保属性名为 serviceName(驼峰命名)
36
+ serviceDescription: ServiceName[]; // 修复点:确保属性名为 serviceName(驼峰命名)
37
+ requestedAttributes: RequestedAttribute[];
38
+ };
39
+
40
+ // 4. 定义顶层服务配置类型
41
+ export type AttrService = AttributeConsumingService[];
42
+ export interface MetadataIdpOptions {
43
+ entityID?: string;
44
+ signingCert?: string | Buffer | (string | Buffer)[];
45
+ encryptCert?: string | Buffer | (string | Buffer)[];
46
+ wantAuthnRequestsSigned?: boolean;
47
+ nameIDFormat?: string[];
48
+ singleSignOnService?: SSOService[];
49
+ singleLogoutService?: SSOService[];
50
+ requestSignatureAlgorithm?: string;
51
+ }
52
+
53
+ export type MetadataIdpConstructor =
54
+ | MetadataIdpOptions
55
+ | MetadataFile;
56
+
57
+ export interface MetadataSpOptions {
58
+ entityID?: string;
59
+ signingCert?: string | Buffer | (string | Buffer)[];
60
+ encryptCert?: string | Buffer | (string | Buffer)[];
61
+ authnRequestsSigned?: boolean;
62
+ wantAssertionsSigned?: boolean;
63
+ wantMessageSigned?: boolean;
64
+ signatureConfig?: { [key: string]: any };
65
+ nameIDFormat?: string[];
66
+ singleSignOnService?: SSOService[];
67
+ singleLogoutService?: SSOService[];
68
+ assertionConsumerService?: SSOService[];
69
+ attributeConsumingService?: AttributeConsumingService[];
70
+ elementsOrder?: string[];
71
+ }
72
+
73
+ export type MetadataSpConstructor =
74
+ | MetadataSpOptions
75
+ | MetadataFile;
76
+
77
+ export type EntitySetting = ServiceProviderSettings & IdentityProviderSettings;
78
+
79
+ export interface SignatureConfig {
80
+ prefix?: string;
81
+ location?: {
82
+ reference?: string;
83
+ action?: 'append' | 'prepend' | 'before' | 'after';
84
+ };
85
+ }
86
+
87
+ export interface SAMLDocumentTemplate {
88
+ context?: string;
89
+ }
90
+
91
+ export type ServiceProviderSettings = {
92
+ metadata?: string | Buffer;
93
+ entityID?: string;
94
+ authnRequestsSigned?: boolean;
95
+ wantAssertionsSigned?: boolean;
96
+ wantMessageSigned?: boolean;
97
+ wantLogoutResponseSigned?: boolean;
98
+ wantLogoutRequestSigned?: boolean;
99
+ privateKey?: string | Buffer;
100
+ privateKeyPass?: string;
101
+ isAssertionEncrypted?: boolean;
102
+ requestSignatureAlgorithm?: string;
103
+ encPrivateKey?: string | Buffer;
104
+ encPrivateKeyPass?: string | Buffer;
105
+ assertionConsumerService?: SSOService[];
106
+ singleLogoutService?: SSOService[];
107
+ signatureConfig?: SignatureConfig;
108
+ loginRequestTemplate?: SAMLDocumentTemplate;
109
+ logoutRequestTemplate?: SAMLDocumentTemplate;
110
+ signingCert?: string | Buffer | (string | Buffer)[];
111
+ encryptCert?: string | Buffer | (string | Buffer)[];
112
+ transformationAlgorithms?: string[];
113
+ nameIDFormat?: string[];
114
+ allowCreate?: boolean;
115
+ // will be deprecated soon
116
+ relayState?: string;
117
+ // https://github.com/tngan/samlify/issues/337
118
+ clockDrifts?: [number, number];
119
+ };
120
+
121
+ export type IdentityProviderSettings = {
122
+ metadata?: string | Buffer;
123
+
124
+ /** signature algorithm */
125
+ requestSignatureAlgorithm?: string;
126
+
127
+ /** template of login response */
128
+ loginResponseTemplate?: LoginResponseTemplate;
129
+
130
+ /** template of logout request */
131
+ logoutRequestTemplate?: SAMLDocumentTemplate;
132
+
133
+ /** customized function used for generating request ID */
134
+ generateID?: () => string;
135
+
136
+ entityID?: string;
137
+ privateKey?: string | Buffer;
138
+ privateKeyPass?: string;
139
+ signingCert?: string | Buffer | (string | Buffer)[];
140
+ encryptCert?: string | Buffer | (string | Buffer)[];
141
+ nameIDFormat?: string[];
142
+ singleSignOnService?: SSOService[];
143
+ singleLogoutService?: SSOService[];
144
+ isAssertionEncrypted?: boolean;
145
+ encPrivateKey?: string | Buffer;
146
+ encPrivateKeyPass?: string;
147
+ messageSigningOrder?: string;
148
+ wantLogoutRequestSigned?: boolean;
149
+ wantLogoutResponseSigned?: boolean;
150
+ wantAuthnRequestsSigned?: boolean;
151
+ wantLogoutRequestSignedResponseSigned?: boolean;
152
+ tagPrefix?: { [key: string]: string };
153
+ };
package/src/urn.ts ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * @file urn.ts
3
+ * @author tngan
4
+ * @desc Includes all keywords need in samlify
5
+ */
6
+
7
+ export enum BindingNamespace {
8
+ Redirect = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
9
+ Post = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
10
+ SimpleSign = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign',
11
+ Artifact = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'
12
+ }
13
+
14
+ export enum MessageSignatureOrder {
15
+ STE = 'sign-then-encrypt',
16
+ ETS = 'encrypt-then-sign'
17
+ }
18
+
19
+ export enum StatusCode {
20
+ // top-tier
21
+ Success = 'urn:oasis:names:tc:SAML:2.0:status:Success',
22
+ Requester = 'urn:oasis:names:tc:SAML:2.0:status:Requester',
23
+ Responder = 'urn:oasis:names:tc:SAML:2.0:status:Responder',
24
+ VersionMismatch = 'urn:oasis:names:tc:SAML:2.0:status:VersionMismatch',
25
+ // second-tier to provide more information
26
+ AuthFailed = 'urn:oasis:names:tc:SAML:2.0:status:AuthnFailed',
27
+ InvalidAttrNameOrValue = 'urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue',
28
+ InvalidNameIDPolicy = 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy',
29
+ NoAuthnContext = 'urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext',
30
+ NoAvailableIDP = 'urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP',
31
+ NoPassive = 'urn:oasis:names:tc:SAML:2.0:status:NoPassive',
32
+ NoSupportedIDP = 'urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP',
33
+ PartialLogout = 'urn:oasis:names:tc:SAML:2.0:status:PartialLogout',
34
+ ProxyCountExceeded = 'urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded',
35
+ RequestDenied = 'urn:oasis:names:tc:SAML:2.0:status:RequestDenied',
36
+ RequestUnsupported = 'urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported',
37
+ RequestVersionDeprecated = 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated',
38
+ RequestVersionTooHigh = 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh',
39
+ RequestVersionTooLow = 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow',
40
+ ResourceNotRecognized = 'urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized',
41
+ TooManyResponses = 'urn:oasis:names:tc:SAML:2.0:status:TooManyResponses',
42
+ UnknownAttrProfile = 'urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile',
43
+ UnknownPrincipal = 'urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal',
44
+ UnsupportedBinding = 'urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding',
45
+ }
46
+
47
+ const namespace = {
48
+ binding: {
49
+ redirect: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
50
+ post: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
51
+ simpleSign: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign',
52
+ artifact: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact',
53
+ },
54
+ names: {
55
+ protocol: 'urn:oasis:names:tc:SAML:2.0:protocol',
56
+ assertion: 'urn:oasis:names:tc:SAML:2.0:assertion',
57
+ metadata: 'urn:oasis:names:tc:SAML:2.0:metadata',
58
+ userLogout: 'urn:oasis:names:tc:SAML:2.0:logout:user',
59
+ adminLogout: 'urn:oasis:names:tc:SAML:2.0:logout:admin',
60
+ },
61
+ authnContextClassRef: {
62
+ password: 'urn:oasis:names:tc:SAML:2.0:ac:classes:Password',
63
+ passwordProtectedTransport: 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport',
64
+ },
65
+ format: {
66
+ emailAddress: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
67
+ persistent: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
68
+ transient: 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient',
69
+ entity: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity',
70
+ unspecified: 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
71
+ kerberos: 'urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos',
72
+ windowsDomainQualifiedName: 'urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName',
73
+ x509SubjectName: 'urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName',
74
+ },
75
+ statusCode: {
76
+ // permissible top-level status codes
77
+ success: 'urn:oasis:names:tc:SAML:2.0:status:Success',
78
+ requester: 'urn:oasis:names:tc:SAML:2.0:status:Requester',
79
+ responder: 'urn:oasis:names:tc:SAML:2.0:status:Responder',
80
+ versionMismatch: 'urn:oasis:names:tc:SAML:2.0:status:VersionMismatch',
81
+ // second-level status codes
82
+ authFailed: 'urn:oasis:names:tc:SAML:2.0:status:AuthnFailed',
83
+ invalidAttrNameOrValue: 'urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue',
84
+ invalidNameIDPolicy: 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy',
85
+ noAuthnContext: 'urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext',
86
+ noAvailableIDP: 'urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP',
87
+ noPassive: 'urn:oasis:names:tc:SAML:2.0:status:NoPassive',
88
+ noSupportedIDP: 'urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP',
89
+ partialLogout: 'urn:oasis:names:tc:SAML:2.0:status:PartialLogout',
90
+ proxyCountExceeded: 'urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded',
91
+ requestDenied: 'urn:oasis:names:tc:SAML:2.0:status:RequestDenied',
92
+ requestUnsupported: 'urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported',
93
+ requestVersionDeprecated: 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated',
94
+ requestVersionTooHigh: 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh',
95
+ requestVersionTooLow: 'urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow',
96
+ resourceNotRecognized: 'urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized',
97
+ tooManyResponses: 'urn:oasis:names:tc:SAML:2.0:status:TooManyResponses',
98
+ unknownAttrProfile: 'urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile',
99
+ unknownPrincipal: 'urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal',
100
+ unsupportedBinding: 'urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding',
101
+ },
102
+ };
103
+
104
+ const tags = {
105
+ request: {
106
+ AllowCreate: '{AllowCreate}',
107
+ AssertionConsumerServiceURL: '{AssertionConsumerServiceURL}',
108
+ AuthnContextClassRef: '{AuthnContextClassRef}',
109
+ AssertionID: '{AssertionID}',
110
+ Audience: '{Audience}',
111
+ AuthnStatement: '{AuthnStatement}',
112
+ AttributeStatement: '{AttributeStatement}',
113
+ ConditionsNotBefore: '{ConditionsNotBefore}',
114
+ ConditionsNotOnOrAfter: '{ConditionsNotOnOrAfter}',
115
+ Destination: '{Destination}',
116
+ EntityID: '{EntityID}',
117
+ ID: '{ID}',
118
+ Issuer: '{Issuer}',
119
+ IssueInstant: '{IssueInstant}',
120
+ InResponseTo: '{InResponseTo}',
121
+ NameID: '{NameID}',
122
+ NameIDFormat: '{NameIDFormat}',
123
+ ProtocolBinding: '{ProtocolBinding}',
124
+ SessionIndex: '{SessionIndex}',
125
+ SubjectRecipient: '{SubjectRecipient}',
126
+ SubjectConfirmationDataNotOnOrAfter: '{SubjectConfirmationDataNotOnOrAfter}',
127
+ StatusCode: '{StatusCode}',
128
+ },
129
+ xmlTag: {
130
+ loginRequest: 'AuthnRequest',
131
+ logoutRequest: 'LogoutRequest',
132
+ loginResponse: 'Response',
133
+ logoutResponse: 'LogoutResponse',
134
+ },
135
+ };
136
+
137
+ const messageConfigurations = {
138
+ signingOrder: {
139
+ SIGN_THEN_ENCRYPT: 'sign-then-encrypt',
140
+ ENCRYPT_THEN_SIGN: 'encrypt-then-sign',
141
+ },
142
+ };
143
+
144
+ const algorithms = {
145
+ signature: {
146
+ RSA_SHA1: 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
147
+ RSA_SHA256: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
148
+ RSA_SHA512: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512',
149
+ },
150
+ encryption: {
151
+ data: {
152
+ AES_128: 'http://www.w3.org/2001/04/xmlenc#aes128-cbc',
153
+ AES_256: 'http://www.w3.org/2001/04/xmlenc#aes256-cbc',
154
+ AES_256_GCM: 'http://www.w3.org/2009/xmlenc11#aes256-gcm',
155
+ TRI_DEC: 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc',
156
+ AES_128_GCM: 'http://www.w3.org/2009/xmlenc11#aes128-gcm'
157
+ },
158
+ key: {
159
+ RSA_OAEP_MGF1P: 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p',
160
+ RSA_1_5: 'http://www.w3.org/2001/04/xmlenc#rsa-1_5',
161
+ },
162
+ },
163
+ digest: {
164
+ 'http://www.w3.org/2000/09/xmldsig#rsa-sha1': 'http://www.w3.org/2000/09/xmldsig#sha1',
165
+ 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256': 'http://www.w3.org/2001/04/xmlenc#sha256',
166
+ 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512': 'http://www.w3.org/2001/04/xmlenc#sha512', // support hashing algorithm sha512 in xml-crypto after 0.8.0
167
+ },
168
+ };
169
+
170
+ export enum ParserType {
171
+ SAMLRequest = 'SAMLRequest',
172
+ SAMLResponse = 'SAMLResponse',
173
+ LogoutRequest = 'LogoutRequest',
174
+ LogoutResponse = 'LogoutResponse'
175
+ }
176
+
177
+ const wording = {
178
+ urlParams: {
179
+ samlRequest: 'SAMLRequest',
180
+ samlResponse: 'SAMLResponse',
181
+ logoutRequest: 'LogoutRequest',
182
+ logoutResponse: 'LogoutResponse',
183
+ sigAlg: 'SigAlg',
184
+ signature: 'Signature',
185
+ relayState: 'RelayState',
186
+ },
187
+ binding: {
188
+ redirect: 'redirect',
189
+ post: 'post',
190
+ simpleSign: 'simpleSign',
191
+ artifact: 'artifact',
192
+ },
193
+ certUse: {
194
+ signing: 'signing',
195
+ encrypt: 'encryption',
196
+ },
197
+ metadata: {
198
+ sp: 'metadata-sp',
199
+ idp: 'metadata-idp',
200
+ },
201
+ };
202
+
203
+ // https://wiki.shibboleth.net/confluence/display/CONCEPT/MetadataForSP
204
+ // some idps restrict the order of elements in entity descriptors
205
+ const elementsOrder = {
206
+ default: ['KeyDescriptor', 'NameIDFormat', 'SingleLogoutService', 'AssertionConsumerService','AttributeConsumingService'],
207
+ onelogin: ['KeyDescriptor', 'NameIDFormat', 'SingleLogoutService', 'AssertionConsumerService','AttributeConsumingService'],
208
+ shibboleth: ['KeyDescriptor', 'SingleLogoutService', 'NameIDFormat', 'AssertionConsumerService', 'AttributeConsumingService'],
209
+ };
210
+
211
+ export { namespace, tags, algorithms, wording, elementsOrder, messageConfigurations };
package/src/utility.ts ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * @file utility.ts
3
+ * @author tngan
4
+ * @desc Library for some common functions (e.g. de/inflation, en/decoding)
5
+ */
6
+ import { pki, util, asn1 } from 'node-forge';
7
+ import { X509Certificate } from 'node:crypto';
8
+
9
+
10
+ import { inflate, deflate } from 'pako';
11
+
12
+ const BASE64_STR = 'base64';
13
+
14
+ /**
15
+ * @desc Mimic lodash.zipObject
16
+ * @param arr1 {string[]}
17
+ * @param arr2 {[]}
18
+ */
19
+ export function zipObject(arr1: string[], arr2: any[], skipDuplicated = true) {
20
+ return arr1.reduce((res, l, i) => {
21
+
22
+ if (skipDuplicated) {
23
+ res[l] = arr2[i];
24
+ return res;
25
+ }
26
+ // if key exists, aggregate with array in order to get rid of duplicate key
27
+ if (res[l] !== undefined) {
28
+ res[l] = Array.isArray(res[l])
29
+ ? res[l].concat(arr2[i])
30
+ : [res[l]].concat(arr2[i]);
31
+ return res;
32
+ }
33
+
34
+ res[l] = arr2[i];
35
+ return res;
36
+
37
+ }, {});
38
+ }
39
+ /**
40
+ * @desc Alternative to lodash.flattenDeep
41
+ * @reference https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_flattendeep
42
+ * @param input {[]}
43
+ */
44
+ export function flattenDeep(input: any[]) {
45
+ return Array.isArray(input)
46
+ ? input.reduce( (a, b) => a.concat(flattenDeep(b)) , [])
47
+ : [input];
48
+ }
49
+ /**
50
+ * @desc Alternative to lodash.last
51
+ * @reference https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_last
52
+ * @param input {[]}
53
+ */
54
+ export function last(input: any[]) {
55
+ return input.slice(-1)[0];
56
+ }
57
+ /**
58
+ * @desc Alternative to lodash.uniq
59
+ * @reference https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_uniq
60
+ * @param input {string[]}
61
+ */
62
+ export function uniq(input: string[]) {
63
+ const set = new Set(input);
64
+ return [... set];
65
+ }
66
+ /**
67
+ * @desc Alternative to lodash.get
68
+ * @reference https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_get
69
+ * @param obj
70
+ * @param path
71
+ * @param defaultValue
72
+ */
73
+ export function get(obj, path, defaultValue) {
74
+ return path.split('.')
75
+ .reduce((a, c) => (a && a[c] ? a[c] : (defaultValue || null)), obj);
76
+ }
77
+ /**
78
+ * @desc Check if the input is string
79
+ * @param {any} input
80
+ */
81
+ export function isString(input: any) {
82
+ return typeof input === 'string';
83
+ }
84
+ /**
85
+ * @desc Encode string with base64 format
86
+ * @param {string} message plain-text message
87
+ * @return {string} base64 encoded string
88
+ */
89
+ function base64Encode(message: string | number[]) {
90
+ return Buffer.from(message as string).toString(BASE64_STR);
91
+ }
92
+ /**
93
+ * @desc Decode string from base64 format
94
+ * @param {string} base64Message encoded string
95
+ * @param {boolean} isBytes determine the return value type (True: bytes False: string)
96
+ * @return {bytes/string} decoded bytes/string depends on isBytes, default is {string}
97
+ */
98
+ export function base64Decode(base64Message: string, isBytes?: boolean): string | Buffer {
99
+ const bytes = Buffer.from(base64Message, BASE64_STR);
100
+ return Boolean(isBytes) ? bytes : bytes.toString();
101
+ }
102
+ /**
103
+ * @desc Compress the string
104
+ * @param {string} message
105
+ * @return {string} compressed string
106
+ */
107
+ function deflateString(message: string): number[] {
108
+ const input = Array.prototype.map.call(message, char => char.charCodeAt(0));
109
+ return Array.from(deflate(input, { raw: true }));
110
+ }
111
+ /**
112
+ * @desc Decompress the compressed string
113
+ * @param {string} compressedString
114
+ * @return {string} decompressed string
115
+ */
116
+ export function inflateString(compressedString: string): string {
117
+ const inputBuffer = Buffer.from(compressedString, BASE64_STR);
118
+ const input = Array.prototype.map.call(inputBuffer.toString('binary'), char => char.charCodeAt(0));
119
+ return Array.from(inflate(input, { raw: true }))
120
+ .map((byte: number) => String.fromCharCode(byte))
121
+ .join('');
122
+ }
123
+ /**
124
+ * @desc Abstract the normalizeCerString and normalizePemString
125
+ * @param {buffer} File stream or string
126
+ * @param {string} String for header and tail
127
+ * @return {string} A formatted certificate string
128
+ */
129
+ function _normalizeCerString(bin: string | Buffer, format: string) {
130
+ return bin.toString().replace(/\n/g, '').replace(/\r/g, '').replace(`-----BEGIN ${format}-----`, '').replace(`-----END ${format}-----`, '').replace(/ /g, '').replace(/\t/g, '');
131
+ }
132
+ /**
133
+ * @desc Parse the .cer to string format without line break, header and footer
134
+ * @param {string} certString declares the certificate contents
135
+ * @return {string} certificiate in string format
136
+ */
137
+ function normalizeCerString(certString: string | Buffer) {
138
+ return _normalizeCerString(certString, 'CERTIFICATE');
139
+ }
140
+ /**
141
+ * @desc Normalize the string in .pem format without line break, header and footer
142
+ * @param {string} pemString
143
+ * @return {string} private key in string format
144
+ */
145
+ function normalizePemString(pemString: string | Buffer) {
146
+ return _normalizeCerString(pemString.toString(), 'RSA PRIVATE KEY');
147
+ }
148
+ /**
149
+ * @desc Return the complete URL
150
+ * @param {object} req HTTP request
151
+ * @return {string} URL
152
+ */
153
+ function getFullURL(req) {
154
+ return `${req.protocol}://${req.get('host')}${req.originalUrl}`;
155
+ }
156
+ /**
157
+ * @desc Parse input string, return default value if it is undefined
158
+ * @param {string/boolean}
159
+ * @return {boolean}
160
+ */
161
+ function parseString(str, defaultValue = '') {
162
+ return str || defaultValue;
163
+ }
164
+ /**
165
+ * @desc Override the object by another object (rtl)
166
+ * @param {object} default object
167
+ * @param {object} object applied to the default object
168
+ * @return {object} result object
169
+ */
170
+ function applyDefault(obj1, obj2) {
171
+ return Object.assign({}, obj1, obj2);
172
+ }
173
+ /**
174
+ * @desc Get public key in pem format from the certificate included in the metadata
175
+ * @param {string} x509 certificate
176
+ * @return {string} public key fetched from the certificate
177
+ */
178
+ function getPublicKeyPemFromCertificate(x509CertificateString: string) {
179
+ const certDerBytes = util.decode64(x509CertificateString);
180
+ const obj = asn1.fromDer(certDerBytes);
181
+ const cert = pki.certificateFromAsn1(obj);
182
+ return pki.publicKeyToPem(cert.publicKey);
183
+ }
184
+
185
+
186
+
187
+ /*function getPublicKeyPemFromCertificate(x509Certificate: string): string {
188
+ // 将 Base64 字符串转为 Buffer(DER 编码)
189
+ const derBuffer = Buffer.from(x509Certificate, 'base64');
190
+
191
+ // 解析 X.509 证书
192
+ const cert = new X509Certificate(derBuffer);
193
+
194
+ // 直接获取公钥的 PEM 格式
195
+ console.log(cert.publicKey?.toString())
196
+ console.log("这就是我的打印")
197
+ return cert.publicKey?.toString();
198
+ }*/
199
+ /**
200
+ * @desc Read private key from pem-formatted string
201
+ * @param {string | Buffer} keyString pem-formatted string
202
+ * @param {string} protected passphrase of the key
203
+ * @return {string} string in pem format
204
+ * If passphrase is used to protect the .pem content (recommend)
205
+ */
206
+ export function readPrivateKey(keyString: string | Buffer, passphrase: string | undefined, isOutputString?: boolean) {
207
+ return isString(passphrase) ? this.convertToString(pki.privateKeyToPem(pki.decryptRsaPrivateKey(String(keyString), passphrase)), isOutputString) : keyString;
208
+ }
209
+ /**
210
+ * @desc Inline syntax sugar
211
+ */
212
+ function convertToString(input, isOutputString) {
213
+ return Boolean(isOutputString) ? String(input) : input;
214
+ }
215
+ /**
216
+ * @desc Check if the input is an array with non-zero size
217
+ */
218
+ export function isNonEmptyArray(a:any) {
219
+ return Array.isArray(a) && a.length > 0;
220
+ }
221
+
222
+ export function castArrayOpt<T>(a?: T | T[]): T[] {
223
+ if (a === undefined) return []
224
+ return Array.isArray(a) ? a : [a]
225
+ }
226
+
227
+ export function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
228
+ return value !== null && value !== undefined;
229
+ }
230
+
231
+ const utility = {
232
+ isString,
233
+ base64Encode,
234
+ base64Decode,
235
+ deflateString,
236
+ inflateString,
237
+ normalizeCerString,
238
+ normalizePemString,
239
+ getFullURL,
240
+ parseString,
241
+ applyDefault,
242
+ getPublicKeyPemFromCertificate,
243
+ readPrivateKey,
244
+ convertToString,
245
+ isNonEmptyArray,
246
+ };
247
+
248
+ export default utility;
@@ -0,0 +1,44 @@
1
+ // unit is ms
2
+ type DriftTolerance = [number, number];
3
+
4
+ function verifyTime(
5
+ utcNotBefore: string | undefined,
6
+ utcNotOnOrAfter: string | undefined,
7
+ drift: DriftTolerance = [0, 0]
8
+ ): boolean {
9
+
10
+ const now = new Date();
11
+
12
+ if (!utcNotBefore && !utcNotOnOrAfter) {
13
+ // show warning because user intends to have time check but the document doesn't include corresponding information
14
+ console.warn('You intend to have time validation however the document doesn\'t include the valid range.');
15
+ return true;
16
+ }
17
+
18
+ let notBeforeLocal: Date | null = null;
19
+ let notOnOrAfterLocal: Date | null = null;
20
+
21
+ const [notBeforeDrift, notOnOrAfterDrift] = drift;
22
+
23
+ if (utcNotBefore && !utcNotOnOrAfter) {
24
+ notBeforeLocal = new Date(utcNotBefore);
25
+ return +notBeforeLocal + notBeforeDrift <= +now;
26
+ }
27
+ if (!utcNotBefore && utcNotOnOrAfter) {
28
+ notOnOrAfterLocal = new Date(utcNotOnOrAfter);
29
+ return +now < +notOnOrAfterLocal + notOnOrAfterDrift;
30
+ }
31
+
32
+ notBeforeLocal = new Date(utcNotBefore!);
33
+ notOnOrAfterLocal = new Date(utcNotOnOrAfter!);
34
+
35
+ return (
36
+ +notBeforeLocal + notBeforeDrift <= +now &&
37
+ +now < +notOnOrAfterLocal + notOnOrAfterDrift
38
+ );
39
+
40
+ }
41
+
42
+ export {
43
+ verifyTime
44
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "compilerOptions": {
3
+
4
+ "skipLibCheck": true,
5
+ "target": "ESNext",
6
+ "module": "NodeNext",
7
+ "moduleResolution": "nodenext",
8
+ "declaration": true,
9
+ "declarationDir": "types",
10
+ "emitDecoratorMetadata": true,
11
+ "experimentalDecorators": true,
12
+ "downlevelIteration": true,
13
+ "sourceMap": true,
14
+ "outDir": "./build",
15
+ "baseUrl": "./",
16
+ "removeComments": false,
17
+ "strictNullChecks": true,
18
+ "esModuleInterop": true,
19
+ "paths": {},
20
+ "types": [
21
+ "node"
22
+ ],
23
+ "lib": [
24
+ "dom",
25
+ ]
26
+ },
27
+ "atom": { "rewriteTsconfig": false },
28
+ "exclude": [
29
+ "dist",
30
+ "examples",
31
+ "build",
32
+ "node_modules",
33
+ "types/**/*.ts",
34
+ "test/**/*.ts"
35
+ ],
36
+ "compileOnSave": false,
37
+ "buildOnSave": false
38
+ }