cloudcms-server 3.3.1-beta.9 → 4.0.0-beta.2

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 (108) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/broadcast/broadcast.js +6 -3
  4. package/broadcast/providers/redis.js +24 -49
  5. package/clients/nrp.js +117 -0
  6. package/clients/redis.js +64 -0
  7. package/d1/index.js +629 -0
  8. package/d1/index.js.works +203 -0
  9. package/d1/package.json +86 -0
  10. package/d1/package.json.works +14 -0
  11. package/duster/helpers/sample/nyt.js +2 -1
  12. package/framework/controllers.js +4 -4
  13. package/index.js +21 -14
  14. package/insight/insight.js +1 -1
  15. package/launchpad/index.js +203 -11
  16. package/launchpad/launchers/cluster.js +103 -110
  17. package/launchpad/launchers/redis.js +70 -0
  18. package/launchpad/launchers/single.js +36 -22
  19. package/locks/locks.js +63 -9
  20. package/locks/providers/cluster.js +3 -1
  21. package/locks/providers/memory.js +10 -7
  22. package/locks/providers/redis.js +62 -82
  23. package/middleware/admin/admin.js +3 -3
  24. package/middleware/authentication/adapters/session.js +11 -8
  25. package/middleware/authentication/authentication.js +28 -16
  26. package/middleware/authentication/authenticators/default.js +5 -2
  27. package/middleware/authentication/authenticators/session.js +5 -2
  28. package/middleware/authentication/providers/saml.js +1 -1
  29. package/middleware/authorization/authorization.js +11 -8
  30. package/middleware/awareness/awareness.js +55 -31
  31. package/middleware/awareness/plugins/editorial.js +4 -4
  32. package/middleware/awareness/providers/abstract-async.js +107 -84
  33. package/middleware/awareness/providers/abstract.js +1 -1
  34. package/middleware/awareness/providers/memory.js +0 -14
  35. package/middleware/awareness/providers/redis.js +186 -279
  36. package/middleware/cache/cache.js +4 -2
  37. package/middleware/cache/providers/redis.js +127 -89
  38. package/middleware/cache/providers/shared-memory.js +3 -3
  39. package/middleware/cloudcms/cloudcms.js +22 -16
  40. package/middleware/form/form.js +3 -3
  41. package/middleware/modules/modules.js +6 -3
  42. package/middleware/proxy/proxy.js +8 -21
  43. package/middleware/stores/stores.js +2 -2
  44. package/middleware/virtual-config/virtual-config.js +11 -8
  45. package/middleware/wcm/wcm.js +4 -4
  46. package/notifications/notifications.js +2 -2
  47. package/package.json +29 -25
  48. package/server/index.js +504 -415
  49. package/server/standalone.js +9 -0
  50. package/temp/clusterlock/index.js +3 -3
  51. package/temp/clusterlock/package.json +1 -1
  52. package/temp/passport-saml/LICENSE +23 -0
  53. package/temp/passport-saml/README.md +406 -0
  54. package/temp/passport-saml/lib/node-saml/algorithms.d.ts +5 -0
  55. package/temp/passport-saml/lib/node-saml/algorithms.js +41 -0
  56. package/temp/passport-saml/lib/node-saml/algorithms.js.map +1 -0
  57. package/temp/passport-saml/lib/node-saml/index.d.ts +3 -0
  58. package/temp/passport-saml/lib/node-saml/index.js +6 -0
  59. package/temp/passport-saml/lib/node-saml/index.js.map +1 -0
  60. package/temp/passport-saml/lib/node-saml/inmemory-cache-provider.d.ts +45 -0
  61. package/temp/passport-saml/lib/node-saml/inmemory-cache-provider.js +86 -0
  62. package/temp/passport-saml/lib/node-saml/inmemory-cache-provider.js.map +1 -0
  63. package/temp/passport-saml/lib/node-saml/saml-post-signing.d.ts +3 -0
  64. package/temp/passport-saml/lib/node-saml/saml-post-signing.js +15 -0
  65. package/temp/passport-saml/lib/node-saml/saml-post-signing.js.map +1 -0
  66. package/temp/passport-saml/lib/node-saml/saml.d.ts +77 -0
  67. package/temp/passport-saml/lib/node-saml/saml.js +1170 -0
  68. package/temp/passport-saml/lib/node-saml/saml.js.map +1 -0
  69. package/temp/passport-saml/lib/node-saml/types.d.ts +95 -0
  70. package/temp/passport-saml/lib/node-saml/types.js +8 -0
  71. package/temp/passport-saml/lib/node-saml/types.js.map +1 -0
  72. package/temp/passport-saml/lib/node-saml/utility.d.ts +3 -0
  73. package/temp/passport-saml/lib/node-saml/utility.js +19 -0
  74. package/temp/passport-saml/lib/node-saml/utility.js.map +1 -0
  75. package/temp/passport-saml/lib/node-saml/xml.d.ts +21 -0
  76. package/temp/passport-saml/lib/node-saml/xml.js +140 -0
  77. package/temp/passport-saml/lib/node-saml/xml.js.map +1 -0
  78. package/temp/passport-saml/lib/passport-saml/index.d.ts +6 -0
  79. package/temp/passport-saml/lib/passport-saml/index.js +11 -0
  80. package/temp/passport-saml/lib/passport-saml/index.js.map +1 -0
  81. package/temp/passport-saml/lib/passport-saml/multiSamlStrategy.d.ts +13 -0
  82. package/temp/passport-saml/lib/passport-saml/multiSamlStrategy.js +63 -0
  83. package/temp/passport-saml/lib/passport-saml/multiSamlStrategy.js.map +1 -0
  84. package/temp/passport-saml/lib/passport-saml/strategy.d.ts +20 -0
  85. package/temp/passport-saml/lib/passport-saml/strategy.js +167 -0
  86. package/temp/passport-saml/lib/passport-saml/strategy.js.map +1 -0
  87. package/temp/passport-saml/lib/passport-saml/types.d.ts +51 -0
  88. package/temp/passport-saml/lib/passport-saml/types.js +11 -0
  89. package/temp/passport-saml/lib/passport-saml/types.js.map +1 -0
  90. package/temp/passport-saml/package.json +96 -0
  91. package/util/auth.js +6 -6
  92. package/util/cloudcms.js +106 -118
  93. package/util/proxy-factory.js +159 -268
  94. package/util/redis.js +113 -0
  95. package/util/renditions.js +12 -6
  96. package/util/request.js +12 -6
  97. package/util/util.js +16 -2
  98. package/launchpad/launchers/sticky-cluster.js +0 -43
  99. package/temp/memored/.jshintrc +0 -4
  100. package/temp/memored/README.md +0 -240
  101. package/temp/memored/demo/demo1.js +0 -37
  102. package/temp/memored/demo/demo2.js +0 -32
  103. package/temp/memored/gulpfile.js +0 -8
  104. package/temp/memored/index.js +0 -343
  105. package/temp/memored/package.json +0 -54
  106. package/temp/memored/spec/memored.spec.js +0 -265
  107. package/web/cms/ice.js +0 -109
  108. package/web/cms/preview.js +0 -106
@@ -0,0 +1 @@
1
+ {"version":3,"file":"saml.js","sourceRoot":"","sources":["../../src/node-saml/saml.ts"],"names":[],"mappings":";;;AAAA,iCAA0B;AAC1B,MAAM,KAAK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node-saml\");\nimport * as zlib from \"zlib\";\nimport * as crypto from \"crypto\";\nimport { URL } from \"url\";\nimport * as querystring from \"querystring\";\nimport * as util from \"util\";\nimport { CacheProvider as InMemoryCacheProvider } from \"./inmemory-cache-provider\";\nimport * as algorithms from \"./algorithms\";\nimport { signAuthnRequestPost } from \"./saml-post-signing\";\nimport { ParsedQs } from \"qs\";\nimport {\n isValidSamlSigningOptions,\n AudienceRestrictionXML,\n AuthorizeRequestXML,\n CertCallback,\n LogoutRequestXML,\n SamlIDPListConfig,\n SamlIDPEntryConfig,\n SamlOptions,\n ServiceMetadataXML,\n XMLInput,\n XMLObject,\n XMLOutput,\n} from \"./types\";\nimport {\n AuthenticateOptions,\n AuthorizeOptions,\n Profile,\n SamlConfig,\n ErrorWithXmlStatus,\n} from \"../passport-saml/types\";\nimport { assertRequired } from \"./utility\";\nimport {\n buildXml2JsObject,\n buildXmlBuilderObject,\n decryptXml,\n parseDomFromString,\n parseXml2JsFromString,\n validateXmlSignatureForCert,\n xpath,\n} from \"./xml\";\n\nconst inflateRawAsync = util.promisify(zlib.inflateRaw);\nconst deflateRawAsync = util.promisify(zlib.deflateRaw);\n\ninterface NameID {\n value: string | null;\n format: string | null;\n}\n\nasync function processValidlySignedPostRequestAsync(\n self: SAML,\n doc: XMLOutput,\n dom: Document\n): Promise<{ profile?: Profile; loggedOut?: boolean }> {\n const request = doc.LogoutRequest;\n if (request) {\n const profile = {} as Profile;\n if (request.$.ID) {\n profile.ID = request.$.ID;\n } else {\n throw new Error(\"Missing SAML LogoutRequest ID\");\n }\n const issuer = request.Issuer;\n if (issuer && issuer[0]._) {\n profile.issuer = issuer[0]._;\n } else {\n throw new Error(\"Missing SAML issuer\");\n }\n const nameID = await self._getNameIdAsync(self, dom);\n if (nameID) {\n profile.nameID = nameID.value!;\n if (nameID.format) {\n profile.nameIDFormat = nameID.format;\n }\n } else {\n throw new Error(\"Missing SAML NameID\");\n }\n const sessionIndex = request.SessionIndex;\n if (sessionIndex) {\n profile.sessionIndex = sessionIndex[0]._;\n }\n return { profile, loggedOut: true };\n } else {\n throw new Error(\"Unknown SAML request message\");\n }\n}\n\nasync function processValidlySignedSamlLogoutAsync(\n self: SAML,\n doc: XMLOutput,\n dom: Document\n): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {\n const response = doc.LogoutResponse;\n const request = doc.LogoutRequest;\n\n if (response) {\n return { profile: null, loggedOut: true };\n } else if (request) {\n return await processValidlySignedPostRequestAsync(self, doc, dom);\n } else {\n throw new Error(\"Unknown SAML response message\");\n }\n}\n\nasync function promiseWithNameID(nameid: Node): Promise<NameID> {\n const format = xpath.selectAttributes(nameid, \"@Format\");\n return {\n value: nameid.textContent,\n format: format && format[0] && format[0].nodeValue,\n };\n}\n\nclass SAML {\n // note that some methods in SAML are not yet marked as private as they are used in testing.\n // those methods start with an underscore, e.g. _generateUniqueID\n options: SamlOptions;\n // This is only for testing\n cacheProvider!: InMemoryCacheProvider;\n\n constructor(ctorOptions: SamlConfig) {\n this.options = this.initialize(ctorOptions);\n this.cacheProvider = this.options.cacheProvider;\n }\n\n initialize(ctorOptions: SamlConfig): SamlOptions {\n if (!ctorOptions) {\n throw new TypeError(\"SamlOptions required on construction\");\n }\n\n const options = {\n ...ctorOptions,\n passive: ctorOptions.passive ?? false,\n disableRequestedAuthnContext: ctorOptions.disableRequestedAuthnContext ?? false,\n additionalParams: ctorOptions.additionalParams ?? {},\n additionalAuthorizeParams: ctorOptions.additionalAuthorizeParams ?? {},\n additionalLogoutParams: ctorOptions.additionalLogoutParams ?? {},\n forceAuthn: ctorOptions.forceAuthn ?? false,\n skipRequestCompression: ctorOptions.skipRequestCompression ?? false,\n disableRequestAcsUrl: ctorOptions.disableRequestAcsUrl ?? false,\n acceptedClockSkewMs: ctorOptions.acceptedClockSkewMs ?? 0,\n maxAssertionAgeMs: ctorOptions.maxAssertionAgeMs ?? 0,\n path: ctorOptions.path ?? \"/saml/consume\",\n host: ctorOptions.host ?? \"localhost\",\n issuer: ctorOptions.issuer ?? \"onelogin_saml\",\n identifierFormat:\n ctorOptions.identifierFormat === undefined\n ? \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n : ctorOptions.identifierFormat,\n wantAssertionsSigned: ctorOptions.wantAssertionsSigned ?? false,\n authnContext: ctorOptions.authnContext ?? [\n \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\",\n ],\n validateInResponseTo: ctorOptions.validateInResponseTo ?? false,\n cert: assertRequired(ctorOptions.cert, \"cert is required\"),\n requestIdExpirationPeriodMs: ctorOptions.requestIdExpirationPeriodMs ?? 28800000, // 8 hours\n cacheProvider:\n ctorOptions.cacheProvider ??\n new InMemoryCacheProvider({\n keyExpirationPeriodMs: ctorOptions.requestIdExpirationPeriodMs,\n }),\n logoutUrl: ctorOptions.logoutUrl ?? ctorOptions.entryPoint ?? \"\", // Default to Entry Point\n signatureAlgorithm: ctorOptions.signatureAlgorithm ?? \"sha1\", // sha1, sha256, or sha512\n authnRequestBinding: ctorOptions.authnRequestBinding ?? \"HTTP-Redirect\",\n\n racComparison: ctorOptions.racComparison ?? \"exact\",\n };\n\n /**\n * List of possible values:\n * - exact : Assertion context must exactly match a context in the list\n * - minimum: Assertion context must be at least as strong as a context in the list\n * - maximum: Assertion context must be no stronger than a context in the list\n * - better: Assertion context must be stronger than all contexts in the list\n */\n if (![\"exact\", \"minimum\", \"maximum\", \"better\"].includes(options.racComparison)) {\n throw new TypeError(\"racComparison must be one of ['exact', 'minimum', 'maximum', 'better']\");\n }\n\n return options;\n }\n\n private getCallbackUrl(host?: string | undefined) {\n // Post-auth destination\n if (this.options.callbackUrl) {\n return this.options.callbackUrl;\n } else {\n const url = new URL(\"http://localhost\");\n if (host) {\n url.host = host;\n } else {\n url.host = this.options.host;\n }\n if (this.options.protocol) {\n url.protocol = this.options.protocol;\n }\n url.pathname = this.options.path;\n return url.toString();\n }\n }\n\n _generateUniqueID() {\n return crypto.randomBytes(10).toString(\"hex\");\n }\n\n private generateInstant() {\n return new Date().toISOString();\n }\n\n private signRequest(samlMessage: querystring.ParsedUrlQueryInput): void {\n this.options.privateKey = assertRequired(this.options.privateKey, \"privateKey is required\");\n\n const samlMessageToSign: querystring.ParsedUrlQueryInput = {};\n samlMessage.SigAlg = algorithms.getSigningAlgorithm(this.options.signatureAlgorithm);\n const signer = algorithms.getSigner(this.options.signatureAlgorithm);\n if (samlMessage.SAMLRequest) {\n samlMessageToSign.SAMLRequest = samlMessage.SAMLRequest;\n }\n if (samlMessage.SAMLResponse) {\n samlMessageToSign.SAMLResponse = samlMessage.SAMLResponse;\n }\n if (samlMessage.RelayState) {\n samlMessageToSign.RelayState = samlMessage.RelayState;\n }\n if (samlMessage.SigAlg) {\n samlMessageToSign.SigAlg = samlMessage.SigAlg;\n }\n signer.update(querystring.stringify(samlMessageToSign));\n samlMessage.Signature = signer.sign(this._keyToPEM(this.options.privateKey), \"base64\");\n }\n\n private async generateAuthorizeRequestAsync(\n isPassive: boolean,\n isHttpPostBinding: boolean,\n host: string | undefined\n ): Promise<string | undefined> {\n this.options.entryPoint = assertRequired(this.options.entryPoint, \"entryPoint is required\");\n\n const id = \"_\" + this._generateUniqueID();\n const instant = this.generateInstant();\n\n if (this.options.validateInResponseTo) {\n await this.cacheProvider.saveAsync(id, instant);\n }\n const request: AuthorizeRequestXML = {\n \"samlp:AuthnRequest\": {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"@ID\": id,\n \"@Version\": \"2.0\",\n \"@IssueInstant\": instant,\n \"@ProtocolBinding\": \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\",\n \"@Destination\": this.options.entryPoint,\n \"saml:Issuer\": {\n \"@xmlns:saml\": \"urn:oasis:names:tc:SAML:2.0:assertion\",\n \"#text\": this.options.issuer,\n },\n },\n };\n\n if (isPassive) request[\"samlp:AuthnRequest\"][\"@IsPassive\"] = true;\n\n if (this.options.forceAuthn) {\n request[\"samlp:AuthnRequest\"][\"@ForceAuthn\"] = true;\n }\n\n if (!this.options.disableRequestAcsUrl) {\n request[\"samlp:AuthnRequest\"][\"@AssertionConsumerServiceURL\"] = this.getCallbackUrl(host);\n }\n\n if (this.options.identifierFormat != null) {\n request[\"samlp:AuthnRequest\"][\"samlp:NameIDPolicy\"] = {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"@Format\": this.options.identifierFormat,\n \"@AllowCreate\": \"true\",\n };\n }\n\n if (!this.options.disableRequestedAuthnContext) {\n const authnContextClassRefs: XMLInput[] = [];\n (this.options.authnContext as string[]).forEach(function (value) {\n authnContextClassRefs.push({\n \"@xmlns:saml\": \"urn:oasis:names:tc:SAML:2.0:assertion\",\n \"#text\": value,\n });\n });\n\n request[\"samlp:AuthnRequest\"][\"samlp:RequestedAuthnContext\"] = {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"@Comparison\": this.options.racComparison,\n \"saml:AuthnContextClassRef\": authnContextClassRefs,\n };\n }\n\n if (this.options.attributeConsumingServiceIndex != null) {\n request[\"samlp:AuthnRequest\"][\"@AttributeConsumingServiceIndex\"] =\n this.options.attributeConsumingServiceIndex;\n }\n\n if (this.options.providerName != null) {\n request[\"samlp:AuthnRequest\"][\"@ProviderName\"] = this.options.providerName;\n }\n\n if (this.options.scoping != null) {\n const scoping: XMLInput = {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n };\n\n if (typeof this.options.scoping.proxyCount === \"number\") {\n scoping[\"@ProxyCount\"] = this.options.scoping.proxyCount;\n }\n\n if (this.options.scoping.idpList) {\n scoping[\"samlp:IDPList\"] = this.options.scoping.idpList.map(\n (idpListItem: SamlIDPListConfig) => {\n const formattedIdpListItem: XMLInput = {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n };\n\n if (idpListItem.entries) {\n formattedIdpListItem[\"samlp:IDPEntry\"] = idpListItem.entries.map(\n (entry: SamlIDPEntryConfig) => {\n const formattedEntry: XMLInput = {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n };\n\n formattedEntry[\"@ProviderID\"] = entry.providerId;\n\n if (entry.name) {\n formattedEntry[\"@Name\"] = entry.name;\n }\n\n if (entry.loc) {\n formattedEntry[\"@Loc\"] = entry.loc;\n }\n\n return formattedEntry;\n }\n );\n }\n\n if (idpListItem.getComplete) {\n formattedIdpListItem[\"samlp:GetComplete\"] = idpListItem.getComplete;\n }\n\n return formattedIdpListItem;\n }\n );\n }\n\n if (this.options.scoping.requesterId) {\n scoping[\"samlp:RequesterID\"] = this.options.scoping.requesterId;\n }\n\n request[\"samlp:AuthnRequest\"][\"samlp:Scoping\"] = scoping;\n }\n\n let stringRequest = buildXmlBuilderObject(request, false);\n // TODO: maybe we should always sign here\n if (isHttpPostBinding && isValidSamlSigningOptions(this.options)) {\n stringRequest = signAuthnRequestPost(stringRequest, this.options);\n }\n return stringRequest;\n }\n\n async _generateLogoutRequest(user: Profile) {\n const id = \"_\" + this._generateUniqueID();\n const instant = this.generateInstant();\n\n const request = {\n \"samlp:LogoutRequest\": {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"@xmlns:saml\": \"urn:oasis:names:tc:SAML:2.0:assertion\",\n \"@ID\": id,\n \"@Version\": \"2.0\",\n \"@IssueInstant\": instant,\n \"@Destination\": this.options.logoutUrl,\n \"saml:Issuer\": {\n \"@xmlns:saml\": \"urn:oasis:names:tc:SAML:2.0:assertion\",\n \"#text\": this.options.issuer,\n },\n \"saml:NameID\": {\n \"@Format\": user!.nameIDFormat,\n \"#text\": user!.nameID,\n },\n },\n } as LogoutRequestXML;\n\n if (user!.nameQualifier != null) {\n request[\"samlp:LogoutRequest\"][\"saml:NameID\"][\"@NameQualifier\"] = user!.nameQualifier;\n }\n\n if (user!.spNameQualifier != null) {\n request[\"samlp:LogoutRequest\"][\"saml:NameID\"][\"@SPNameQualifier\"] = user!.spNameQualifier;\n }\n\n if (user!.sessionIndex) {\n request[\"samlp:LogoutRequest\"][\"saml2p:SessionIndex\"] = {\n \"@xmlns:saml2p\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"#text\": user!.sessionIndex,\n };\n }\n\n await this.cacheProvider.saveAsync(id, instant);\n return buildXmlBuilderObject(request, false);\n }\n\n _generateLogoutResponse(logoutRequest: Profile) {\n const id = \"_\" + this._generateUniqueID();\n const instant = this.generateInstant();\n\n const request = {\n \"samlp:LogoutResponse\": {\n \"@xmlns:samlp\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n \"@xmlns:saml\": \"urn:oasis:names:tc:SAML:2.0:assertion\",\n \"@ID\": id,\n \"@Version\": \"2.0\",\n \"@IssueInstant\": instant,\n \"@Destination\": this.options.logoutUrl,\n \"@InResponseTo\": logoutRequest.ID,\n \"saml:Issuer\": {\n \"#text\": this.options.issuer,\n },\n \"samlp:Status\": {\n \"samlp:StatusCode\": {\n \"@Value\": \"urn:oasis:names:tc:SAML:2.0:status:Success\",\n },\n },\n },\n };\n\n return buildXmlBuilderObject(request, false);\n }\n\n async _requestToUrlAsync(\n request: string | null | undefined,\n response: string | null,\n operation: string,\n additionalParameters: querystring.ParsedUrlQuery\n ): Promise<string> {\n this.options.entryPoint = assertRequired(this.options.entryPoint, \"entryPoint is required\");\n\n let buffer: Buffer;\n if (this.options.skipRequestCompression) {\n buffer = Buffer.from((request || response)!, \"utf8\");\n } else {\n buffer = await deflateRawAsync((request || response)!);\n }\n\n const base64 = buffer.toString(\"base64\");\n let target = new URL(this.options.entryPoint);\n\n if (operation === \"logout\") {\n if (this.options.logoutUrl) {\n target = new URL(this.options.logoutUrl);\n }\n } else if (operation !== \"authorize\") {\n throw new Error(\"Unknown operation: \" + operation);\n }\n\n const samlMessage: querystring.ParsedUrlQuery = request\n ? {\n SAMLRequest: base64,\n }\n : {\n SAMLResponse: base64,\n };\n Object.keys(additionalParameters).forEach((k) => {\n samlMessage[k] = additionalParameters[k];\n });\n if (this.options.privateKey != null) {\n if (!this.options.entryPoint) {\n throw new Error('\"entryPoint\" config parameter is required for signed messages');\n }\n\n // sets .SigAlg and .Signature\n this.signRequest(samlMessage);\n }\n Object.keys(samlMessage).forEach((k) => {\n target.searchParams.set(k, samlMessage[k] as string);\n });\n\n return target.toString();\n }\n\n _getAdditionalParams(\n RelayState: string,\n operation: string,\n overrideParams?: querystring.ParsedUrlQuery\n ): querystring.ParsedUrlQuery {\n const additionalParams: querystring.ParsedUrlQuery = {};\n\n if (typeof RelayState === \"string\" && RelayState.length > 0) {\n additionalParams.RelayState = RelayState;\n }\n\n const optionsAdditionalParams = this.options.additionalParams;\n Object.keys(optionsAdditionalParams).forEach(function (k) {\n additionalParams[k] = optionsAdditionalParams[k];\n });\n\n let optionsAdditionalParamsForThisOperation: Record<string, string> = {};\n if (operation == \"authorize\") {\n optionsAdditionalParamsForThisOperation = this.options.additionalAuthorizeParams;\n }\n if (operation == \"logout\") {\n optionsAdditionalParamsForThisOperation = this.options.additionalLogoutParams;\n }\n\n Object.keys(optionsAdditionalParamsForThisOperation).forEach(function (k) {\n additionalParams[k] = optionsAdditionalParamsForThisOperation[k];\n });\n\n overrideParams = overrideParams ?? {};\n Object.keys(overrideParams).forEach(function (k) {\n additionalParams[k] = overrideParams![k];\n });\n\n return additionalParams;\n }\n\n async getAuthorizeUrlAsync(\n RelayState: string,\n host: string | undefined,\n options: AuthorizeOptions\n ): Promise<string> {\n const request = await this.generateAuthorizeRequestAsync(this.options.passive, false, host);\n const operation = \"authorize\";\n const overrideParams = options ? options.additionalParams || {} : {};\n return await this._requestToUrlAsync(\n request,\n null,\n operation,\n this._getAdditionalParams(RelayState, operation, overrideParams)\n );\n }\n\n async getAuthorizeFormAsync(RelayState: string, host?: string): Promise<string> {\n this.options.entryPoint = assertRequired(this.options.entryPoint, \"entryPoint is required\");\n\n // The quoteattr() function is used in a context, where the result will not be evaluated by javascript\n // but must be interpreted by an XML or HTML parser, and it must absolutely avoid breaking the syntax\n // of an element attribute.\n const quoteattr = function (\n s:\n | string\n | number\n | boolean\n | undefined\n | null\n | readonly string[]\n | readonly number[]\n | readonly boolean[],\n preserveCR?: boolean\n ) {\n const preserveCRChar = preserveCR ? \"&#13;\" : \"\\n\";\n return (\n (\"\" + s) // Forces the conversion to string.\n .replace(/&/g, \"&amp;\") // This MUST be the 1st replacement.\n .replace(/'/g, \"&apos;\") // The 4 other predefined entities, required.\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n // Add other replacements here for HTML only\n // Or for XML, only if the named entities are defined in its DTD.\n .replace(/\\r\\n/g, preserveCRChar) // Must be before the next replacement.\n .replace(/[\\r\\n]/g, preserveCRChar)\n );\n };\n\n const request = await this.generateAuthorizeRequestAsync(this.options.passive, true, host);\n let buffer: Buffer;\n if (this.options.skipRequestCompression) {\n buffer = Buffer.from(request!, \"utf8\");\n } else {\n buffer = await deflateRawAsync(request!);\n }\n\n const operation = \"authorize\";\n const additionalParameters = this._getAdditionalParams(RelayState, operation);\n const samlMessage: querystring.ParsedUrlQueryInput = {\n SAMLRequest: buffer!.toString(\"base64\"),\n };\n\n Object.keys(additionalParameters).forEach((k) => {\n samlMessage[k] = additionalParameters[k] || \"\";\n });\n\n const formInputs = Object.keys(samlMessage)\n .map((k) => {\n return '<input type=\"hidden\" name=\"' + k + '\" value=\"' + quoteattr(samlMessage[k]) + '\" />';\n })\n .join(\"\\r\\n\");\n\n return [\n \"<!DOCTYPE html>\",\n \"<html>\",\n \"<head>\",\n '<meta charset=\"utf-8\">',\n '<meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\">',\n \"</head>\",\n '<body onload=\"document.forms[0].submit()\">',\n \"<noscript>\",\n \"<p><strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.</p>\",\n \"</noscript>\",\n '<form method=\"post\" action=\"' + encodeURI(this.options.entryPoint) + '\">',\n formInputs,\n '<input type=\"submit\" value=\"Submit\" />',\n \"</form>\",\n '<script>document.forms[0].style.display=\"none\";</script>', // Hide the form if JavaScript is enabled\n \"</body>\",\n \"</html>\",\n ].join(\"\\r\\n\");\n }\n\n async getLogoutUrlAsync(\n user: Profile,\n RelayState: string,\n options: AuthenticateOptions & AuthorizeOptions\n ) {\n const request = await this._generateLogoutRequest(user);\n const operation = \"logout\";\n const overrideParams = options ? options.additionalParams || {} : {};\n return await this._requestToUrlAsync(\n request,\n null,\n operation,\n this._getAdditionalParams(RelayState, operation, overrideParams)\n );\n }\n\n getLogoutResponseUrl(\n samlLogoutRequest: Profile,\n RelayState: string,\n options: AuthenticateOptions & AuthorizeOptions,\n callback: (err: Error | null, url?: string | null) => void\n ): void {\n util.callbackify(() => this.getLogoutResponseUrlAsync(samlLogoutRequest, RelayState, options))(\n callback\n );\n }\n private async getLogoutResponseUrlAsync(\n samlLogoutRequest: Profile,\n RelayState: string,\n options: AuthenticateOptions & AuthorizeOptions // add RelayState,\n ): Promise<string> {\n const response = this._generateLogoutResponse(samlLogoutRequest);\n const operation = \"logout\";\n const overrideParams = options ? options.additionalParams || {} : {};\n return await this._requestToUrlAsync(\n null,\n response,\n operation,\n this._getAdditionalParams(RelayState, operation, overrideParams)\n );\n }\n\n _certToPEM(cert: string): string {\n cert = cert.match(/.{1,64}/g)!.join(\"\\n\");\n\n if (cert.indexOf(\"-BEGIN CERTIFICATE-\") === -1) cert = \"-----BEGIN CERTIFICATE-----\\n\" + cert;\n if (cert.indexOf(\"-END CERTIFICATE-\") === -1) cert = cert + \"\\n-----END CERTIFICATE-----\\n\";\n\n return cert;\n }\n\n private async certsToCheck(): Promise<string[]> {\n let checkedCerts: string[];\n\n if (typeof this.options.cert === \"function\") {\n checkedCerts = await util\n .promisify(this.options.cert as CertCallback)()\n .then((certs) => {\n certs = assertRequired(certs, \"callback didn't return cert\");\n if (!Array.isArray(certs)) {\n certs = [certs];\n }\n return certs;\n });\n } else if (Array.isArray(this.options.cert)) {\n checkedCerts = this.options.cert;\n } else {\n checkedCerts = [this.options.cert];\n }\n\n checkedCerts.forEach((cert) => {\n assertRequired(cert, \"unknown cert found\");\n });\n\n return checkedCerts;\n }\n\n // This function checks that the |currentNode| in the |fullXml| document contains exactly 1 valid\n // signature of the |currentNode|.\n //\n // See https://github.com/bergie/passport-saml/issues/19 for references to some of the attack\n // vectors against SAML signature verification.\n validateSignature(fullXml: string, currentNode: Element, certs: string[]): boolean {\n const xpathSigQuery =\n \".//*[\" +\n \"local-name(.)='Signature' and \" +\n \"namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#' and \" +\n \"descendant::*[local-name(.)='Reference' and @URI='#\" +\n currentNode.getAttribute(\"ID\") +\n \"']\" +\n \"]\";\n const signatures = xpath.selectElements(currentNode, xpathSigQuery);\n // This function is expecting to validate exactly one signature, so if we find more or fewer\n // than that, reject.\n if (signatures.length !== 1) {\n return false;\n }\n const xpathTransformQuery =\n \".//*[\" +\n \"local-name(.)='Transform' and \" +\n \"namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#' and \" +\n \"ancestor::*[local-name(.)='Reference' and @URI='#\" +\n currentNode.getAttribute(\"ID\") +\n \"']\" +\n \"]\";\n const transforms = xpath.selectElements(currentNode, xpathTransformQuery);\n // Reject also XMLDSIG with more than 2 Transform\n if (transforms.length > 2) {\n // do not return false, throw an error so that it can be caught by tests differently\n throw new Error(\"Invalid signature, too many transforms\");\n }\n\n const signature = signatures[0];\n return certs.some((certToCheck) => {\n return validateXmlSignatureForCert(\n signature,\n this._certToPEM(certToCheck),\n fullXml,\n currentNode\n );\n });\n }\n\n async validatePostResponseAsync(\n container: Record<string, string>\n ): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {\n let xml: string, doc: Document, inResponseTo: string | null;\n try {\n xml = Buffer.from(container.SAMLResponse, \"base64\").toString(\"utf8\");\n doc = parseDomFromString(xml);\n\n if (!Object.prototype.hasOwnProperty.call(doc, \"documentElement\"))\n throw new Error(\"SAMLResponse is not valid base64-encoded XML\");\n\n const inResponseToNodes = xpath.selectAttributes(\n doc,\n \"/*[local-name()='Response']/@InResponseTo\"\n );\n\n if (inResponseToNodes) {\n inResponseTo = inResponseToNodes.length ? inResponseToNodes[0].nodeValue : null;\n\n await this.validateInResponseTo(inResponseTo);\n }\n const certs = await this.certsToCheck();\n // Check if this document has a valid top-level signature\n let validSignature = false;\n if (this.validateSignature(xml, doc.documentElement, certs)) {\n validSignature = true;\n }\n\n const assertions = xpath.selectElements(\n doc,\n \"/*[local-name()='Response']/*[local-name()='Assertion']\"\n );\n const encryptedAssertions = xpath.selectElements(\n doc,\n \"/*[local-name()='Response']/*[local-name()='EncryptedAssertion']\"\n );\n\n if (assertions.length + encryptedAssertions.length > 1) {\n // There's no reason I know of that we want to handle multiple assertions, and it seems like a\n // potential risk vector for signature scope issues, so treat this as an invalid signature\n throw new Error(\"Invalid signature: multiple assertions\");\n }\n\n if (assertions.length == 1) {\n if (\n (this.options.wantAssertionsSigned || !validSignature) &&\n !this.validateSignature(xml, assertions[0], certs)\n ) {\n throw new Error(\"Invalid signature\");\n }\n return await this.processValidlySignedAssertionAsync(\n assertions[0].toString(),\n xml,\n inResponseTo!\n );\n }\n\n if (encryptedAssertions.length == 1) {\n this.options.decryptionPvk = assertRequired(\n this.options.decryptionPvk,\n \"No decryption key for encrypted SAML response\"\n );\n\n const encryptedAssertionXml = encryptedAssertions[0].toString();\n\n const decryptedXml = await decryptXml(encryptedAssertionXml, this.options.decryptionPvk);\n const decryptedDoc = parseDomFromString(decryptedXml);\n const decryptedAssertions = xpath.selectElements(\n decryptedDoc,\n \"/*[local-name()='Assertion']\"\n );\n if (decryptedAssertions.length != 1) throw new Error(\"Invalid EncryptedAssertion content\");\n\n if (\n (this.options.wantAssertionsSigned || !validSignature) &&\n !this.validateSignature(decryptedXml, decryptedAssertions[0], certs)\n ) {\n throw new Error(\"Invalid signature from encrypted assertion\");\n }\n\n return await this.processValidlySignedAssertionAsync(\n decryptedAssertions[0].toString(),\n xml,\n inResponseTo!\n );\n }\n\n // If there's no assertion, fall back on xml2js response parsing for the status &\n // LogoutResponse code.\n\n const xmljsDoc = await parseXml2JsFromString(xml);\n const response = xmljsDoc.Response;\n if (response) {\n const assertion = response.Assertion;\n if (!assertion) {\n const status = response.Status;\n if (status) {\n const statusCode = status[0].StatusCode;\n if (\n statusCode &&\n statusCode[0].$.Value === \"urn:oasis:names:tc:SAML:2.0:status:Responder\"\n ) {\n const nestedStatusCode = statusCode[0].StatusCode;\n if (\n nestedStatusCode &&\n nestedStatusCode[0].$.Value === \"urn:oasis:names:tc:SAML:2.0:status:NoPassive\"\n ) {\n if (!validSignature) {\n throw new Error(\"Invalid signature: NoPassive\");\n }\n return { profile: null, loggedOut: false };\n }\n }\n\n // Note that we're not requiring a valid signature before this logic -- since we are\n // throwing an error in any case, and some providers don't sign error results,\n // let's go ahead and give the potentially more helpful error.\n if (statusCode && statusCode[0].$.Value) {\n const msgType = statusCode[0].$.Value.match(/[^:]*$/)[0];\n if (msgType != \"Success\") {\n let msg = \"unspecified\";\n if (status[0].StatusMessage) {\n msg = status[0].StatusMessage[0]._;\n } else if (statusCode[0].StatusCode) {\n msg = statusCode[0].StatusCode[0].$.Value.match(/[^:]*$/)[0];\n }\n const statusXml = buildXml2JsObject(\"Status\", status[0]);\n throw new ErrorWithXmlStatus(\n \"SAML provider returned \" + msgType + \" error: \" + msg,\n statusXml\n );\n }\n }\n }\n }\n throw new Error(\"Missing SAML assertion\");\n } else {\n if (!validSignature) {\n throw new Error(\"Invalid signature: No response found\");\n }\n const logoutResponse = xmljsDoc.LogoutResponse;\n if (logoutResponse) {\n return { profile: null, loggedOut: true };\n } else {\n throw new Error(\"Unknown SAML response message\");\n }\n }\n } catch (err) {\n debug(\"validatePostResponse resulted in an error: %s\", err);\n if (this.options.validateInResponseTo) {\n await this.cacheProvider.removeAsync(inResponseTo!);\n }\n throw err;\n }\n }\n\n private async validateInResponseTo(inResponseTo: string | null): Promise<undefined> {\n if (this.options.validateInResponseTo) {\n if (inResponseTo) {\n const result = await this.cacheProvider.getAsync(inResponseTo);\n if (!result) throw new Error(\"InResponseTo is not valid\");\n return;\n } else {\n throw new Error(\"InResponseTo is missing from response\");\n }\n } else {\n return;\n }\n }\n\n async validateRedirectAsync(\n container: ParsedQs,\n originalQuery: string | null\n ): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {\n const samlMessageType = container.SAMLRequest ? \"SAMLRequest\" : \"SAMLResponse\";\n\n const data = Buffer.from(container[samlMessageType] as string, \"base64\");\n const inflated = await inflateRawAsync(data);\n\n const dom = parseDomFromString(inflated.toString());\n const doc: XMLOutput = await parseXml2JsFromString(inflated);\n samlMessageType === \"SAMLResponse\"\n ? await this.verifyLogoutResponse(doc)\n : this.verifyLogoutRequest(doc);\n await this.hasValidSignatureForRedirect(container, originalQuery);\n return await processValidlySignedSamlLogoutAsync(this, doc, dom);\n }\n\n private async hasValidSignatureForRedirect(\n container: ParsedQs,\n originalQuery: string | null\n ): Promise<boolean | void> {\n const tokens = originalQuery!.split(\"&\");\n const getParam = (key: string) => {\n const exists = tokens.filter((t) => {\n return new RegExp(key).test(t);\n });\n return exists[0];\n };\n\n if (container.Signature) {\n let urlString = getParam(\"SAMLRequest\") || getParam(\"SAMLResponse\");\n\n if (getParam(\"RelayState\")) {\n urlString += \"&\" + getParam(\"RelayState\");\n }\n\n urlString += \"&\" + getParam(\"SigAlg\");\n\n const certs = await this.certsToCheck();\n const hasValidQuerySignature = certs.some((cert) => {\n return this.validateSignatureForRedirect(\n urlString,\n container.Signature as string,\n container.SigAlg as string,\n cert\n );\n });\n if (!hasValidQuerySignature) {\n throw new Error(\"Invalid query signature\");\n }\n } else {\n return true;\n }\n }\n\n private validateSignatureForRedirect(\n urlString: crypto.BinaryLike,\n signature: string,\n alg: string,\n cert: string\n ) {\n // See if we support a matching algorithm, case-insensitive. Otherwise, throw error.\n function hasMatch(ourAlgo: string) {\n // The incoming algorithm is forwarded as a URL.\n // We trim everything before the last # get something we can compare to the Node.js list\n const algFromURI = alg.toLowerCase().replace(/.*#(.*)$/, \"$1\");\n return ourAlgo.toLowerCase() === algFromURI;\n }\n const i = crypto.getHashes().findIndex(hasMatch);\n let matchingAlgo;\n if (i > -1) {\n matchingAlgo = crypto.getHashes()[i];\n } else {\n throw new Error(alg + \" is not supported\");\n }\n\n const verifier = crypto.createVerify(matchingAlgo);\n verifier.update(urlString);\n\n return verifier.verify(this._certToPEM(cert), signature, \"base64\");\n }\n\n private verifyLogoutRequest(doc: XMLOutput) {\n this.verifyIssuer(doc.LogoutRequest);\n const nowMs = new Date().getTime();\n const conditions = doc.LogoutRequest.$;\n const conErr = this.checkTimestampsValidityError(\n nowMs,\n conditions.NotBefore,\n conditions.NotOnOrAfter\n );\n if (conErr) {\n throw conErr;\n }\n }\n\n private async verifyLogoutResponse(doc: XMLOutput) {\n const statusCode = doc.LogoutResponse.Status[0].StatusCode[0].$.Value;\n if (statusCode !== \"urn:oasis:names:tc:SAML:2.0:status:Success\")\n throw new Error(\"Bad status code: \" + statusCode);\n\n this.verifyIssuer(doc.LogoutResponse);\n const inResponseTo = doc.LogoutResponse.$.InResponseTo;\n if (inResponseTo) {\n return this.validateInResponseTo(inResponseTo);\n }\n\n return true;\n }\n\n private verifyIssuer(samlMessage: XMLOutput) {\n if (this.options.idpIssuer != null) {\n const issuer = samlMessage.Issuer;\n if (issuer) {\n if (issuer[0]._ !== this.options.idpIssuer)\n throw new Error(\n \"Unknown SAML issuer. Expected: \" + this.options.idpIssuer + \" Received: \" + issuer[0]._\n );\n } else {\n throw new Error(\"Missing SAML issuer\");\n }\n }\n }\n\n private async processValidlySignedAssertionAsync(\n xml: string,\n samlResponseXml: string,\n inResponseTo: string\n ) {\n let msg;\n const nowMs = new Date().getTime();\n const profile = {} as Profile;\n const doc: XMLOutput = await parseXml2JsFromString(xml);\n const parsedAssertion: XMLOutput = doc;\n const assertion: XMLOutput = doc.Assertion;\n getInResponseTo: {\n const issuer = assertion.Issuer;\n if (issuer && issuer[0]._) {\n profile.issuer = issuer[0]._;\n }\n\n if (inResponseTo) {\n profile.inResponseTo = inResponseTo;\n }\n\n const authnStatement = assertion.AuthnStatement;\n if (authnStatement) {\n if (authnStatement[0].$ && authnStatement[0].$.SessionIndex) {\n profile.sessionIndex = authnStatement[0].$.SessionIndex;\n }\n }\n\n const subject = assertion.Subject;\n let subjectConfirmation, confirmData;\n if (subject) {\n const nameID = subject[0].NameID;\n if (nameID && nameID[0]._) {\n profile.nameID = nameID[0]._;\n\n if (nameID[0].$ && nameID[0].$.Format) {\n profile.nameIDFormat = nameID[0].$.Format;\n profile.nameQualifier = nameID[0].$.NameQualifier;\n profile.spNameQualifier = nameID[0].$.SPNameQualifier;\n }\n }\n\n subjectConfirmation = subject[0].SubjectConfirmation\n ? subject[0].SubjectConfirmation[0]\n : null;\n confirmData =\n subjectConfirmation && subjectConfirmation.SubjectConfirmationData\n ? subjectConfirmation.SubjectConfirmationData[0]\n : null;\n if (subject[0].SubjectConfirmation && subject[0].SubjectConfirmation.length > 1) {\n msg = \"Unable to process multiple SubjectConfirmations in SAML assertion\";\n throw new Error(msg);\n }\n\n if (subjectConfirmation) {\n if (confirmData && confirmData.$) {\n const subjectNotBefore = confirmData.$.NotBefore;\n const subjectNotOnOrAfter = confirmData.$.NotOnOrAfter;\n const maxTimeLimitMs = this.processMaxAgeAssertionTime(\n this.options.maxAssertionAgeMs,\n subjectNotOnOrAfter,\n assertion.$.IssueInstant\n );\n\n const subjErr = this.checkTimestampsValidityError(\n nowMs,\n subjectNotBefore,\n subjectNotOnOrAfter,\n maxTimeLimitMs\n );\n if (subjErr) {\n throw subjErr;\n }\n }\n }\n }\n\n // Test to see that if we have a SubjectConfirmation InResponseTo that it matches\n // the 'InResponseTo' attribute set in the Response\n if (this.options.validateInResponseTo) {\n if (subjectConfirmation) {\n if (confirmData && confirmData.$) {\n const subjectInResponseTo = confirmData.$.InResponseTo;\n if (inResponseTo && subjectInResponseTo && subjectInResponseTo != inResponseTo) {\n await this.cacheProvider.removeAsync(inResponseTo);\n throw new Error(\"InResponseTo is not valid\");\n } else if (subjectInResponseTo) {\n let foundValidInResponseTo = false;\n const result = await this.cacheProvider.getAsync(subjectInResponseTo);\n if (result) {\n const createdAt = new Date(result);\n if (nowMs < createdAt.getTime() + this.options.requestIdExpirationPeriodMs)\n foundValidInResponseTo = true;\n }\n await this.cacheProvider.removeAsync(inResponseTo);\n if (!foundValidInResponseTo) {\n throw new Error(\"InResponseTo is not valid\");\n }\n break getInResponseTo;\n }\n }\n } else {\n await this.cacheProvider.removeAsync(inResponseTo);\n break getInResponseTo;\n }\n } else {\n break getInResponseTo;\n }\n }\n const conditions = assertion.Conditions ? assertion.Conditions[0] : null;\n if (assertion.Conditions && assertion.Conditions.length > 1) {\n msg = \"Unable to process multiple conditions in SAML assertion\";\n throw new Error(msg);\n }\n if (conditions && conditions.$) {\n const maxTimeLimitMs = this.processMaxAgeAssertionTime(\n this.options.maxAssertionAgeMs,\n conditions.$.NotOnOrAfter,\n assertion.$.IssueInstant\n );\n const conErr = this.checkTimestampsValidityError(\n nowMs,\n conditions.$.NotBefore,\n conditions.$.NotOnOrAfter,\n maxTimeLimitMs\n );\n if (conErr) throw conErr;\n }\n\n if (this.options.audience != null) {\n const audienceErr = this.checkAudienceValidityError(\n this.options.audience,\n conditions.AudienceRestriction\n );\n if (audienceErr) throw audienceErr;\n }\n\n const attributeStatement = assertion.AttributeStatement;\n if (attributeStatement) {\n const attributes: XMLOutput[] = [].concat(\n ...attributeStatement\n .filter((attr: XMLObject) => Array.isArray(attr.Attribute))\n .map((attr: XMLObject) => attr.Attribute)\n );\n\n const attrValueMapper = (value: XMLObject) => {\n const hasChildren = Object.keys(value).some((cur) => {\n return cur !== \"_\" && cur !== \"$\";\n });\n return hasChildren ? value : value._;\n };\n\n if (attributes) {\n const profileAttributes: Record<string, unknown> = {};\n\n attributes.forEach((attribute) => {\n if (!Object.prototype.hasOwnProperty.call(attribute, \"AttributeValue\")) {\n // if attributes has no AttributeValue child, continue\n return;\n }\n\n const name = attribute.$.Name;\n const value =\n attribute.AttributeValue.length === 1\n ? attrValueMapper(attribute.AttributeValue[0])\n : attribute.AttributeValue.map(attrValueMapper);\n\n profileAttributes[name] = value;\n\n // If any property is already present in profile and is also present\n // in attributes, then skip the one from attributes. Handle this\n // conflict gracefully without returning any error\n if (Object.prototype.hasOwnProperty.call(profile, name)) {\n return;\n }\n\n profile[name] = value;\n });\n\n profile.attributes = profileAttributes;\n }\n }\n\n if (!profile.mail && profile[\"urn:oid:0.9.2342.19200300.100.1.3\"]) {\n // See https://spaces.internet2.edu/display/InCFederation/Supported+Attribute+Summary\n // for definition of attribute OIDs\n profile.mail = profile[\"urn:oid:0.9.2342.19200300.100.1.3\"];\n }\n\n if (!profile.email && profile.mail) {\n profile.email = profile.mail;\n }\n\n profile.getAssertionXml = () => xml.toString();\n profile.getAssertion = () => parsedAssertion;\n profile.getSamlResponseXml = () => samlResponseXml;\n\n return { profile, loggedOut: false };\n }\n\n private checkTimestampsValidityError(\n nowMs: number,\n notBefore: string,\n notOnOrAfter: string,\n maxTimeLimitMs?: number\n ) {\n if (this.options.acceptedClockSkewMs == -1) return null;\n\n if (notBefore) {\n const notBeforeMs = this.dateStringToTimestamp(notBefore, \"NotBefore\");\n if (nowMs + this.options.acceptedClockSkewMs < notBeforeMs)\n return new Error(\"SAML assertion not yet valid\");\n }\n if (notOnOrAfter) {\n const notOnOrAfterMs = this.dateStringToTimestamp(notOnOrAfter, \"NotOnOrAfter\");\n if (nowMs - this.options.acceptedClockSkewMs >= notOnOrAfterMs)\n return new Error(\"SAML assertion expired: clocks skewed too much\");\n }\n if (maxTimeLimitMs) {\n if (nowMs - this.options.acceptedClockSkewMs >= maxTimeLimitMs)\n return new Error(\"SAML assertion expired: assertion too old\");\n }\n\n return null;\n }\n\n private checkAudienceValidityError(\n expectedAudience: string,\n audienceRestrictions: AudienceRestrictionXML[]\n ) {\n if (!audienceRestrictions || audienceRestrictions.length < 1) {\n return new Error(\"SAML assertion has no AudienceRestriction\");\n }\n const errors = audienceRestrictions\n .map((restriction) => {\n if (!restriction.Audience || !restriction.Audience[0] || !restriction.Audience[0]._) {\n return new Error(\"SAML assertion AudienceRestriction has no Audience value\");\n }\n if (restriction.Audience[0]._ !== expectedAudience) {\n return new Error(\"SAML assertion audience mismatch\");\n }\n return null;\n })\n .filter((result) => {\n return result !== null;\n });\n if (errors.length > 0) {\n return errors[0];\n }\n return null;\n }\n\n async validatePostRequestAsync(\n container: Record<string, string>\n ): Promise<{ profile?: Profile; loggedOut?: boolean }> {\n const xml = Buffer.from(container.SAMLRequest, \"base64\").toString(\"utf8\");\n const dom = parseDomFromString(xml);\n const doc = await parseXml2JsFromString(xml);\n const certs = await this.certsToCheck();\n if (!this.validateSignature(xml, dom.documentElement, certs)) {\n throw new Error(\"Invalid signature on documentElement\");\n }\n return await processValidlySignedPostRequestAsync(this, doc, dom);\n }\n\n async _getNameIdAsync(self: SAML, doc: Node): Promise<NameID> {\n const nameIds = xpath.selectElements(\n doc,\n \"/*[local-name()='LogoutRequest']/*[local-name()='NameID']\"\n );\n const encryptedIds = xpath.selectElements(\n doc,\n \"/*[local-name()='LogoutRequest']/*[local-name()='EncryptedID']\"\n );\n\n if (nameIds.length + encryptedIds.length > 1) {\n throw new Error(\"Invalid LogoutRequest\");\n }\n if (nameIds.length === 1) {\n return promiseWithNameID(nameIds[0]);\n }\n if (encryptedIds.length === 1) {\n self.options.decryptionPvk = assertRequired(\n self.options.decryptionPvk,\n \"No decryption key found getting name ID for encrypted SAML response\"\n );\n\n const encryptedDatas = xpath.selectElements(\n encryptedIds[0],\n \"./*[local-name()='EncryptedData']\"\n );\n\n if (encryptedDatas.length !== 1) {\n throw new Error(\"Invalid LogoutRequest\");\n }\n const encryptedDataXml = encryptedDatas[0].toString();\n\n const decryptedXml = await decryptXml(encryptedDataXml, self.options.decryptionPvk);\n const decryptedDoc = parseDomFromString(decryptedXml);\n const decryptedIds = xpath.selectElements(decryptedDoc, \"/*[local-name()='NameID']\");\n if (decryptedIds.length !== 1) {\n throw new Error(\"Invalid EncryptedAssertion content\");\n }\n return await promiseWithNameID(decryptedIds[0]);\n }\n throw new Error(\"Missing SAML NameID\");\n }\n\n generateServiceProviderMetadata(decryptionCert: string | null, signingCert?: string | null) {\n const metadata: ServiceMetadataXML = {\n EntityDescriptor: {\n \"@xmlns\": \"urn:oasis:names:tc:SAML:2.0:metadata\",\n \"@xmlns:ds\": \"http://www.w3.org/2000/09/xmldsig#\",\n \"@entityID\": this.options.issuer,\n \"@ID\": this.options.issuer.replace(/\\W/g, \"_\"),\n SPSSODescriptor: {\n \"@protocolSupportEnumeration\": \"urn:oasis:names:tc:SAML:2.0:protocol\",\n },\n },\n };\n\n if (this.options.decryptionPvk != null) {\n if (!decryptionCert) {\n throw new Error(\n \"Missing decryptionCert while generating metadata for decrypting service provider\"\n );\n }\n }\n if (this.options.privateKey != null) {\n if (!signingCert) {\n throw new Error(\n \"Missing signingCert while generating metadata for signing service provider messages\"\n );\n }\n }\n\n if (this.options.decryptionPvk != null || this.options.privateKey != null) {\n metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor = [];\n if (this.options.privateKey != null) {\n signingCert = signingCert!.replace(/-+BEGIN CERTIFICATE-+\\r?\\n?/, \"\");\n signingCert = signingCert.replace(/-+END CERTIFICATE-+\\r?\\n?/, \"\");\n signingCert = signingCert.replace(/\\r\\n/g, \"\\n\");\n\n metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor.push({\n \"@use\": \"signing\",\n \"ds:KeyInfo\": {\n \"ds:X509Data\": {\n \"ds:X509Certificate\": {\n \"#text\": signingCert,\n },\n },\n },\n });\n }\n\n if (this.options.decryptionPvk != null) {\n decryptionCert = decryptionCert!.replace(/-+BEGIN CERTIFICATE-+\\r?\\n?/, \"\");\n decryptionCert = decryptionCert.replace(/-+END CERTIFICATE-+\\r?\\n?/, \"\");\n decryptionCert = decryptionCert.replace(/\\r\\n/g, \"\\n\");\n\n metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor.push({\n \"@use\": \"encryption\",\n \"ds:KeyInfo\": {\n \"ds:X509Data\": {\n \"ds:X509Certificate\": {\n \"#text\": decryptionCert,\n },\n },\n },\n EncryptionMethod: [\n // this should be the set that the xmlenc library supports\n { \"@Algorithm\": \"http://www.w3.org/2009/xmlenc11#aes256-gcm\" },\n { \"@Algorithm\": \"http://www.w3.org/2009/xmlenc11#aes128-gcm\" },\n { \"@Algorithm\": \"http://www.w3.org/2001/04/xmlenc#aes256-cbc\" },\n { \"@Algorithm\": \"http://www.w3.org/2001/04/xmlenc#aes128-cbc\" },\n ],\n });\n }\n }\n\n if (this.options.logoutCallbackUrl != null) {\n metadata.EntityDescriptor.SPSSODescriptor.SingleLogoutService = {\n \"@Binding\": \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\",\n \"@Location\": this.options.logoutCallbackUrl,\n };\n }\n\n if (this.options.identifierFormat != null) {\n metadata.EntityDescriptor.SPSSODescriptor.NameIDFormat = this.options.identifierFormat;\n }\n\n if (this.options.wantAssertionsSigned) {\n metadata.EntityDescriptor.SPSSODescriptor[\"@WantAssertionsSigned\"] = true;\n }\n\n metadata.EntityDescriptor.SPSSODescriptor.AssertionConsumerService = {\n \"@index\": \"1\",\n \"@isDefault\": \"true\",\n \"@Binding\": \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\",\n \"@Location\": this.getCallbackUrl(),\n };\n return buildXmlBuilderObject(metadata, true);\n }\n\n _keyToPEM(key: string | Buffer): typeof key extends string | Buffer ? string | Buffer : Error {\n key = assertRequired(key, \"key is required\");\n\n if (typeof key !== \"string\") return key;\n if (key.split(/\\r?\\n/).length !== 1) return key;\n\n const matchedKey = key.match(/.{1,64}/g);\n\n if (matchedKey) {\n const wrappedKey = [\n \"-----BEGIN PRIVATE KEY-----\",\n ...matchedKey,\n \"-----END PRIVATE KEY-----\",\n \"\",\n ].join(\"\\n\");\n return wrappedKey;\n }\n\n throw new Error(\"Invalid key\");\n }\n\n /**\n * Process max age assertion and use it if it is more restrictive than the NotOnOrAfter age\n * assertion received in the SAMLResponse.\n *\n * @param maxAssertionAgeMs Max time after IssueInstant that we will accept assertion, in Ms.\n * @param notOnOrAfter Expiration provided in response.\n * @param issueInstant Time when response was issued.\n * @returns {*} The expiration time to be used, in Ms.\n */\n private processMaxAgeAssertionTime(\n maxAssertionAgeMs: number,\n notOnOrAfter: string,\n issueInstant: string\n ): number {\n const notOnOrAfterMs = this.dateStringToTimestamp(notOnOrAfter, \"NotOnOrAfter\");\n const issueInstantMs = this.dateStringToTimestamp(issueInstant, \"IssueInstant\");\n\n if (maxAssertionAgeMs === 0) {\n return notOnOrAfterMs;\n }\n\n const maxAssertionTimeMs = issueInstantMs + maxAssertionAgeMs;\n return maxAssertionTimeMs < notOnOrAfterMs ? maxAssertionTimeMs : notOnOrAfterMs;\n }\n\n /**\n * Convert a date string to a timestamp (in milliseconds).\n *\n * @param dateString A string representation of a date\n * @param label Descriptive name of the date being passed in, e.g. \"NotOnOrAfter\"\n * @throws Will throw an error if parsing `dateString` returns `NaN`\n * @returns {number} The timestamp (in milliseconds) representation of the given date\n */\n private dateStringToTimestamp(dateString: string, label: string): number {\n const dateMs = Date.parse(dateString);\n\n if (isNaN(dateMs)) {\n throw new Error(`Error parsing ${label}: '${dateString}' is not a valid date`);\n }\n\n return dateMs;\n }\n}\n\nexport { SAML };\n"]}
@@ -0,0 +1,95 @@
1
+ /// <reference types="node" />
2
+ import type { CacheProvider } from "./inmemory-cache-provider";
3
+ export declare type SignatureAlgorithm = "sha1" | "sha256" | "sha512";
4
+ export interface SamlSigningOptions {
5
+ privateKey: string | Buffer;
6
+ signatureAlgorithm?: SignatureAlgorithm;
7
+ xmlSignatureTransforms?: string[];
8
+ digestAlgorithm?: string;
9
+ }
10
+ export declare const isValidSamlSigningOptions: (options: Partial<SamlSigningOptions>) => options is SamlSigningOptions;
11
+ export interface AudienceRestrictionXML {
12
+ Audience?: XMLObject[];
13
+ }
14
+ export declare type XMLValue = string | number | boolean | null | XMLObject | XMLValue[];
15
+ export declare type XMLObject = {
16
+ [key: string]: XMLValue;
17
+ };
18
+ export declare type XMLInput = XMLObject;
19
+ export declare type XMLOutput = Record<string, any>;
20
+ export interface AuthorizeRequestXML {
21
+ "samlp:AuthnRequest": XMLInput;
22
+ }
23
+ export declare type CertCallback = (callback: (err: Error | null, cert?: string | string[]) => void) => void;
24
+ /**
25
+ * These are SAML options that must be provided to construct a new SAML Strategy
26
+ */
27
+ export interface MandatorySamlOptions {
28
+ cert: string | string[] | CertCallback;
29
+ }
30
+ export interface SamlIDPListConfig {
31
+ entries: SamlIDPEntryConfig[];
32
+ getComplete?: string;
33
+ }
34
+ export interface SamlIDPEntryConfig {
35
+ providerId: string;
36
+ name?: string;
37
+ loc?: string;
38
+ }
39
+ export interface LogoutRequestXML {
40
+ "samlp:LogoutRequest": {
41
+ "saml:NameID": XMLInput;
42
+ [key: string]: XMLValue;
43
+ };
44
+ }
45
+ export interface ServiceMetadataXML {
46
+ EntityDescriptor: {
47
+ [key: string]: XMLValue;
48
+ SPSSODescriptor: XMLObject;
49
+ };
50
+ }
51
+ export declare type RacComparision = "exact" | "minimum" | "maximum" | "better";
52
+ interface SamlScopingConfig {
53
+ idpList?: SamlIDPListConfig[];
54
+ proxyCount?: number;
55
+ requesterId?: string[] | string;
56
+ }
57
+ /**
58
+ * The options required to use a SAML strategy
59
+ * These may be provided by means of defaults specified in the constructor
60
+ */
61
+ export interface SamlOptions extends Partial<SamlSigningOptions>, MandatorySamlOptions {
62
+ callbackUrl?: string;
63
+ path: string;
64
+ protocol?: string;
65
+ host: string;
66
+ entryPoint?: string;
67
+ issuer: string;
68
+ decryptionPvk?: string | Buffer;
69
+ additionalParams: Record<string, string>;
70
+ additionalAuthorizeParams: Record<string, string>;
71
+ identifierFormat?: string | null;
72
+ acceptedClockSkewMs: number;
73
+ attributeConsumingServiceIndex?: string;
74
+ disableRequestedAuthnContext: boolean;
75
+ authnContext: string[];
76
+ forceAuthn: boolean;
77
+ skipRequestCompression: boolean;
78
+ authnRequestBinding?: string;
79
+ racComparison: RacComparision;
80
+ providerName?: string;
81
+ passive: boolean;
82
+ idpIssuer?: string;
83
+ audience?: string;
84
+ scoping?: SamlScopingConfig;
85
+ wantAssertionsSigned?: boolean;
86
+ maxAssertionAgeMs: number;
87
+ validateInResponseTo: boolean;
88
+ requestIdExpirationPeriodMs: number;
89
+ cacheProvider: CacheProvider;
90
+ logoutUrl: string;
91
+ additionalLogoutParams: Record<string, string>;
92
+ logoutCallbackUrl?: string;
93
+ disableRequestAcsUrl: boolean;
94
+ }
95
+ export {};
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidSamlSigningOptions = void 0;
4
+ const isValidSamlSigningOptions = (options) => {
5
+ return options.privateKey != null;
6
+ };
7
+ exports.isValidSamlSigningOptions = isValidSamlSigningOptions;
8
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/node-saml/types.ts"],"names":[],"mappings":";;;AAWO,MAAM,yBAAyB,GAAG,CACvC,OAAoC,EACL,EAAE;IACjC,OAAO,OAAO,CAAC,UAAU,IAAI,IAAI,CAAC;AACpC,CAAC,CAAC;AAJW,QAAA,yBAAyB,6BAIpC","sourcesContent":["import type { CacheProvider } from \"./inmemory-cache-provider\";\n\nexport type SignatureAlgorithm = \"sha1\" | \"sha256\" | \"sha512\";\n\nexport interface SamlSigningOptions {\n privateKey: string | Buffer;\n signatureAlgorithm?: SignatureAlgorithm;\n xmlSignatureTransforms?: string[];\n digestAlgorithm?: string;\n}\n\nexport const isValidSamlSigningOptions = (\n options: Partial<SamlSigningOptions>\n): options is SamlSigningOptions => {\n return options.privateKey != null;\n};\n\nexport interface AudienceRestrictionXML {\n Audience?: XMLObject[];\n}\n\nexport type XMLValue = string | number | boolean | null | XMLObject | XMLValue[];\n\nexport type XMLObject = {\n [key: string]: XMLValue;\n};\n\nexport type XMLInput = XMLObject;\n\nexport type XMLOutput = Record<string, any>;\n\nexport interface AuthorizeRequestXML {\n \"samlp:AuthnRequest\": XMLInput;\n}\n\nexport type CertCallback = (\n callback: (err: Error | null, cert?: string | string[]) => void\n) => void;\n\n/**\n * These are SAML options that must be provided to construct a new SAML Strategy\n */\nexport interface MandatorySamlOptions {\n cert: string | string[] | CertCallback;\n}\n\nexport interface SamlIDPListConfig {\n entries: SamlIDPEntryConfig[];\n getComplete?: string;\n}\n\nexport interface SamlIDPEntryConfig {\n providerId: string;\n name?: string;\n loc?: string;\n}\n\nexport interface LogoutRequestXML {\n \"samlp:LogoutRequest\": {\n \"saml:NameID\": XMLInput;\n [key: string]: XMLValue;\n };\n}\n\nexport interface ServiceMetadataXML {\n EntityDescriptor: {\n [key: string]: XMLValue;\n SPSSODescriptor: XMLObject;\n };\n}\n\nexport type RacComparision = \"exact\" | \"minimum\" | \"maximum\" | \"better\";\n\ninterface SamlScopingConfig {\n idpList?: SamlIDPListConfig[];\n proxyCount?: number;\n requesterId?: string[] | string;\n}\n\n/**\n * The options required to use a SAML strategy\n * These may be provided by means of defaults specified in the constructor\n */\nexport interface SamlOptions extends Partial<SamlSigningOptions>, MandatorySamlOptions {\n // Core\n callbackUrl?: string;\n path: string;\n protocol?: string;\n host: string;\n entryPoint?: string;\n issuer: string;\n decryptionPvk?: string | Buffer;\n\n // Additional SAML behaviors\n additionalParams: Record<string, string>;\n additionalAuthorizeParams: Record<string, string>;\n identifierFormat?: string | null;\n acceptedClockSkewMs: number;\n attributeConsumingServiceIndex?: string;\n disableRequestedAuthnContext: boolean;\n authnContext: string[];\n forceAuthn: boolean;\n skipRequestCompression: boolean;\n authnRequestBinding?: string;\n racComparison: RacComparision;\n providerName?: string;\n passive: boolean;\n idpIssuer?: string;\n audience?: string;\n scoping?: SamlScopingConfig;\n wantAssertionsSigned?: boolean;\n maxAssertionAgeMs: number;\n\n // InResponseTo Validation\n validateInResponseTo: boolean;\n requestIdExpirationPeriodMs: number;\n cacheProvider: CacheProvider;\n\n // Logout\n logoutUrl: string;\n additionalLogoutParams: Record<string, string>;\n logoutCallbackUrl?: string;\n\n // extras\n disableRequestAcsUrl: boolean;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { SamlSigningOptions } from "./types";
2
+ export declare function assertRequired<T>(value: T | null | undefined, error?: string): T;
3
+ export declare function signXmlResponse(samlMessage: string, options: SamlSigningOptions): string;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signXmlResponse = exports.assertRequired = void 0;
4
+ const xml_1 = require("./xml");
5
+ function assertRequired(value, error) {
6
+ if (value === undefined || value === null || (typeof value === "string" && value.length === 0)) {
7
+ throw new TypeError(error !== null && error !== void 0 ? error : "value does not exist");
8
+ }
9
+ else {
10
+ return value;
11
+ }
12
+ }
13
+ exports.assertRequired = assertRequired;
14
+ function signXmlResponse(samlMessage, options) {
15
+ const responseXpath = '//*[local-name(.)="Response" and namespace-uri(.)="urn:oasis:names:tc:SAML:2.0:protocol"]';
16
+ return (0, xml_1.signXml)(samlMessage, responseXpath, { reference: responseXpath, action: "append" }, options);
17
+ }
18
+ exports.signXmlResponse = signXmlResponse;
19
+ //# sourceMappingURL=utility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/node-saml/utility.ts"],"names":[],"mappings":";;;AACA,+BAAgC;AAEhC,SAAgB,cAAc,CAAI,KAA2B,EAAE,KAAc;IAC3E,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,EAAE;QAC9F,MAAM,IAAI,SAAS,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,sBAAsB,CAAC,CAAC;KACtD;SAAM;QACL,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,wCAMC;AAED,SAAgB,eAAe,CAAC,WAAmB,EAAE,OAA2B;IAC9E,MAAM,aAAa,GACjB,2FAA2F,CAAC;IAE9F,OAAO,IAAA,aAAO,EACZ,WAAW,EACX,aAAa,EACb,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,EAC9C,OAAO,CACR,CAAC;AACJ,CAAC;AAVD,0CAUC","sourcesContent":["import { SamlSigningOptions } from \"./types\";\nimport { signXml } from \"./xml\";\n\nexport function assertRequired<T>(value: T | null | undefined, error?: string): T {\n if (value === undefined || value === null || (typeof value === \"string\" && value.length === 0)) {\n throw new TypeError(error ?? \"value does not exist\");\n } else {\n return value;\n }\n}\n\nexport function signXmlResponse(samlMessage: string, options: SamlSigningOptions): string {\n const responseXpath =\n '//*[local-name(.)=\"Response\" and namespace-uri(.)=\"urn:oasis:names:tc:SAML:2.0:protocol\"]';\n\n return signXml(\n samlMessage,\n responseXpath,\n { reference: responseXpath, action: \"append\" },\n options\n );\n}\n"]}
@@ -0,0 +1,21 @@
1
+ /// <reference types="node" />
2
+ import { SamlSigningOptions } from "./types";
3
+ export declare const xpath: {
4
+ selectAttributes: (node: Node, xpath: string) => Attr[];
5
+ selectElements: (node: Node, xpath: string) => Element[];
6
+ };
7
+ export declare const decryptXml: (xml: string, decryptionKey: string | Buffer) => Promise<string>;
8
+ /**
9
+ * This function checks that the |signature| is signed with a given |cert|.
10
+ */
11
+ export declare const validateXmlSignatureForCert: (signature: Node, certPem: string, fullXml: string, currentNode: Element) => boolean;
12
+ interface XmlSignatureLocation {
13
+ reference: string;
14
+ action: "append" | "prepend" | "before" | "after";
15
+ }
16
+ export declare const signXml: (xml: string, xpath: string, location: XmlSignatureLocation, options: SamlSigningOptions) => string;
17
+ export declare const parseDomFromString: (xml: string) => Document;
18
+ export declare const parseXml2JsFromString: (xml: string | Buffer) => Promise<any>;
19
+ export declare const buildXml2JsObject: (rootName: string, xml: any) => string;
20
+ export declare const buildXmlBuilderObject: (xml: Record<string, any>, pretty: boolean) => string;
21
+ export {};
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildXmlBuilderObject = exports.buildXml2JsObject = exports.parseXml2JsFromString = exports.parseDomFromString = exports.signXml = exports.validateXmlSignatureForCert = exports.decryptXml = exports.xpath = void 0;
4
+ const util = require("util");
5
+ const xmlCrypto = require("xml-crypto");
6
+ const xmlenc = require("xml-encryption");
7
+ const xmldom = require("@xmldom/xmldom");
8
+ const xml2js = require("xml2js");
9
+ const xmlbuilder = require("xmlbuilder");
10
+ const types_1 = require("./types");
11
+ const algorithms = require("./algorithms");
12
+ const selectXPath = (guard, node, xpath) => {
13
+ const result = xmlCrypto.xpath(node, xpath);
14
+ if (!guard(result)) {
15
+ throw new Error("invalid xpath return type");
16
+ }
17
+ return result;
18
+ };
19
+ const attributesXPathTypeGuard = (values) => {
20
+ return values.every((value) => {
21
+ if (typeof value != "object") {
22
+ return false;
23
+ }
24
+ return typeof value.nodeType === "number" && value.nodeType === value.ATTRIBUTE_NODE;
25
+ });
26
+ };
27
+ const elementsXPathTypeGuard = (values) => {
28
+ return values.every((value) => {
29
+ if (typeof value != "object") {
30
+ return false;
31
+ }
32
+ return typeof value.nodeType === "number" && value.nodeType === value.ELEMENT_NODE;
33
+ });
34
+ };
35
+ exports.xpath = {
36
+ selectAttributes: (node, xpath) => selectXPath(attributesXPathTypeGuard, node, xpath),
37
+ selectElements: (node, xpath) => selectXPath(elementsXPathTypeGuard, node, xpath),
38
+ };
39
+ const decryptXml = async (xml, decryptionKey) => util.promisify(xmlenc.decrypt).bind(xmlenc)(xml, { key: decryptionKey });
40
+ exports.decryptXml = decryptXml;
41
+ const normalizeNewlines = (xml) => {
42
+ // we can use this utility before passing XML to `xml-crypto`
43
+ // we are considered the XML processor and are responsible for newline normalization
44
+ // https://github.com/node-saml/passport-saml/issues/431#issuecomment-718132752
45
+ return xml.replace(/\r\n?/g, "\n");
46
+ };
47
+ const normalizeXml = (xml) => {
48
+ // we can use this utility to parse and re-stringify XML
49
+ // `DOMParser` will take care of normalization tasks, like replacing XML-encoded carriage returns with actual carriage returns
50
+ return (0, exports.parseDomFromString)(xml).toString();
51
+ };
52
+ /**
53
+ * This function checks that the |signature| is signed with a given |cert|.
54
+ */
55
+ const validateXmlSignatureForCert = (signature, certPem, fullXml, currentNode) => {
56
+ const sig = new xmlCrypto.SignedXml();
57
+ sig.keyInfoProvider = {
58
+ file: "",
59
+ getKeyInfo: () => "<X509Data></X509Data>",
60
+ getKey: () => Buffer.from(certPem),
61
+ };
62
+ const signatureStr = normalizeNewlines(signature.toString());
63
+ sig.loadSignature(signatureStr);
64
+ // We expect each signature to contain exactly one reference to the top level of the xml we
65
+ // are validating, so if we see anything else, reject.
66
+ if (sig.references.length != 1)
67
+ return false;
68
+ const refUri = sig.references[0].uri;
69
+ const refId = refUri[0] === "#" ? refUri.substring(1) : refUri;
70
+ // If we can't find the reference at the top level, reject
71
+ const idAttribute = currentNode.getAttribute("ID") ? "ID" : "Id";
72
+ if (currentNode.getAttribute(idAttribute) != refId)
73
+ return false;
74
+ // If we find any extra referenced nodes, reject. (xml-crypto only verifies one digest, so
75
+ // multiple candidate references is bad news)
76
+ const totalReferencedNodes = exports.xpath.selectElements(currentNode.ownerDocument, "//*[@" + idAttribute + "='" + refId + "']");
77
+ if (totalReferencedNodes.length > 1) {
78
+ return false;
79
+ }
80
+ // normalize XML to replace XML-encoded carriage returns with actual carriage returns
81
+ fullXml = normalizeXml(fullXml);
82
+ fullXml = normalizeNewlines(fullXml);
83
+ return sig.checkSignature(fullXml);
84
+ };
85
+ exports.validateXmlSignatureForCert = validateXmlSignatureForCert;
86
+ const signXml = (xml, xpath, location, options) => {
87
+ var _a;
88
+ const defaultTransforms = [
89
+ "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
90
+ "http://www.w3.org/2001/10/xml-exc-c14n#",
91
+ ];
92
+ if (!xml)
93
+ throw new Error("samlMessage is required");
94
+ if (!location)
95
+ throw new Error("location is required");
96
+ if (!options)
97
+ throw new Error("options is required");
98
+ if (!(0, types_1.isValidSamlSigningOptions)(options))
99
+ throw new Error("options.privateKey is required");
100
+ const transforms = (_a = options.xmlSignatureTransforms) !== null && _a !== void 0 ? _a : defaultTransforms;
101
+ const sig = new xmlCrypto.SignedXml();
102
+ if (options.signatureAlgorithm != null) {
103
+ sig.signatureAlgorithm = algorithms.getSigningAlgorithm(options.signatureAlgorithm);
104
+ }
105
+ sig.addReference(xpath, transforms, algorithms.getDigestAlgorithm(options.digestAlgorithm));
106
+ sig.signingKey = options.privateKey;
107
+ sig.computeSignature(xml, {
108
+ location,
109
+ });
110
+ return sig.getSignedXml();
111
+ };
112
+ exports.signXml = signXml;
113
+ const parseDomFromString = (xml) => {
114
+ return new xmldom.DOMParser().parseFromString(xml);
115
+ };
116
+ exports.parseDomFromString = parseDomFromString;
117
+ const parseXml2JsFromString = async (xml) => {
118
+ const parserConfig = {
119
+ explicitRoot: true,
120
+ explicitCharkey: true,
121
+ tagNameProcessors: [xml2js.processors.stripPrefix],
122
+ };
123
+ const parser = new xml2js.Parser(parserConfig);
124
+ return parser.parseStringPromise(xml);
125
+ };
126
+ exports.parseXml2JsFromString = parseXml2JsFromString;
127
+ const buildXml2JsObject = (rootName, xml) => {
128
+ const builderOpts = {
129
+ rootName,
130
+ headless: true,
131
+ };
132
+ return new xml2js.Builder(builderOpts).buildObject(xml);
133
+ };
134
+ exports.buildXml2JsObject = buildXml2JsObject;
135
+ const buildXmlBuilderObject = (xml, pretty) => {
136
+ const options = pretty ? { pretty: true, indent: " ", newline: "\n" } : {};
137
+ return xmlbuilder.create(xml).end(options);
138
+ };
139
+ exports.buildXmlBuilderObject = buildXmlBuilderObject;
140
+ //# sourceMappingURL=xml.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xml.js","sourceRoot":"","sources":["../../src/node-saml/xml.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAC7B,wCAAwC;A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C/C,OAAO,MAAM,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC;AACxC,CAAC,CAAC;AARW,QAAA,qBAAqB,yBAQhC;AAEK,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,GAAQ,EAAU,EAAE;IACtE,MAAM,WAAW,GAAG;QAClB,QAAQ;QACR,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC,CAAC;AANW,QAAA,iBAAiB,qBAM5B;AAEK,MAAM,qBAAqB,GAAG,CAAC,GAAwB,EAAE,MAAe,EAAU,EAAE;IACzF,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5E,OAAO,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC7C,CAAC,CAAC;AAHW,QAAA,qBAAqB,yBAGhC","sourcesContent":["import * as util from \"util\";\nimport * as xmlCrypto from \"xml-crypto\";\nimport * as xmlenc from \"xml-encryption\";\nimport * as xmldom from \"@xmldom/xmldom\";\nimport * as xml2js from \"xml2js\";\nimport * as xmlbuilder from \"xmlbuilder\";\nimport { isValidSamlSigningOptions, SamlSigningOptions } from \"./types\";\nimport * as algorithms from \"./algorithms\";\n\ntype SelectedValue = string | number | boolean | Node;\n\nconst selectXPath = <T extends SelectedValue>(\n guard: (values: SelectedValue[]) => values is T[],\n node: Node,\n xpath: string\n): T[] => {\n const result = xmlCrypto.xpath(node, xpath);\n if (!guard(result)) {\n throw new Error(\"invalid xpath return type\");\n }\n return result;\n};\n\nconst attributesXPathTypeGuard = (values: SelectedValue[]): values is Attr[] => {\n return values.every((value) => {\n if (typeof value != \"object\") {\n return false;\n }\n return typeof value.nodeType === \"number\" && value.nodeType === value.ATTRIBUTE_NODE;\n });\n};\n\nconst elementsXPathTypeGuard = (values: SelectedValue[]): values is Element[] => {\n return values.every((value) => {\n if (typeof value != \"object\") {\n return false;\n }\n return typeof value.nodeType === \"number\" && value.nodeType === value.ELEMENT_NODE;\n });\n};\n\nexport const xpath = {\n selectAttributes: (node: Node, xpath: string): Attr[] =>\n selectXPath(attributesXPathTypeGuard, node, xpath),\n selectElements: (node: Node, xpath: string): Element[] =>\n selectXPath(elementsXPathTypeGuard, node, xpath),\n};\n\nexport const decryptXml = async (xml: string, decryptionKey: string | Buffer) =>\n util.promisify(xmlenc.decrypt).bind(xmlenc)(xml, { key: decryptionKey });\n\nconst normalizeNewlines = (xml: string): string => {\n // we can use this utility before passing XML to `xml-crypto`\n // we are considered the XML processor and are responsible for newline normalization\n // https://github.com/node-saml/passport-saml/issues/431#issuecomment-718132752\n return xml.replace(/\\r\\n?/g, \"\\n\");\n};\n\nconst normalizeXml = (xml: string): string => {\n // we can use this utility to parse and re-stringify XML\n // `DOMParser` will take care of normalization tasks, like replacing XML-encoded carriage returns with actual carriage returns\n return parseDomFromString(xml).toString();\n};\n\n/**\n * This function checks that the |signature| is signed with a given |cert|.\n */\nexport const validateXmlSignatureForCert = (\n signature: Node,\n certPem: string,\n fullXml: string,\n currentNode: Element\n): boolean => {\n const sig = new xmlCrypto.SignedXml();\n sig.keyInfoProvider = {\n file: \"\",\n getKeyInfo: () => \"<X509Data></X509Data>\",\n getKey: () => Buffer.from(certPem),\n };\n const signatureStr = normalizeNewlines(signature.toString());\n sig.loadSignature(signatureStr);\n // We expect each signature to contain exactly one reference to the top level of the xml we\n // are validating, so if we see anything else, reject.\n if (sig.references.length != 1) return false;\n const refUri = sig.references[0].uri!;\n const refId = refUri[0] === \"#\" ? refUri.substring(1) : refUri;\n // If we can't find the reference at the top level, reject\n const idAttribute = currentNode.getAttribute(\"ID\") ? \"ID\" : \"Id\";\n if (currentNode.getAttribute(idAttribute) != refId) return false;\n // If we find any extra referenced nodes, reject. (xml-crypto only verifies one digest, so\n // multiple candidate references is bad news)\n const totalReferencedNodes = xpath.selectElements(\n currentNode.ownerDocument,\n \"//*[@\" + idAttribute + \"='\" + refId + \"']\"\n );\n\n if (totalReferencedNodes.length > 1) {\n return false;\n }\n // normalize XML to replace XML-encoded carriage returns with actual carriage returns\n fullXml = normalizeXml(fullXml);\n fullXml = normalizeNewlines(fullXml);\n return sig.checkSignature(fullXml);\n};\n\ninterface XmlSignatureLocation {\n reference: string;\n action: \"append\" | \"prepend\" | \"before\" | \"after\";\n}\n\nexport const signXml = (\n xml: string,\n xpath: string,\n location: XmlSignatureLocation,\n options: SamlSigningOptions\n): string => {\n const defaultTransforms = [\n \"http://www.w3.org/2000/09/xmldsig#enveloped-signature\",\n \"http://www.w3.org/2001/10/xml-exc-c14n#\",\n ];\n\n if (!xml) throw new Error(\"samlMessage is required\");\n if (!location) throw new Error(\"location is required\");\n if (!options) throw new Error(\"options is required\");\n if (!isValidSamlSigningOptions(options)) throw new Error(\"options.privateKey is required\");\n\n const transforms = options.xmlSignatureTransforms ?? defaultTransforms;\n const sig = new xmlCrypto.SignedXml();\n if (options.signatureAlgorithm != null) {\n sig.signatureAlgorithm = algorithms.getSigningAlgorithm(options.signatureAlgorithm);\n }\n sig.addReference(xpath, transforms, algorithms.getDigestAlgorithm(options.digestAlgorithm));\n sig.signingKey = options.privateKey;\n sig.computeSignature(xml, {\n location,\n });\n\n return sig.getSignedXml();\n};\n\nexport const parseDomFromString = (xml: string): Document => {\n return new xmldom.DOMParser().parseFromString(xml);\n};\n\nexport const parseXml2JsFromString = async (xml: string | Buffer): Promise<any> => {\n const parserConfig = {\n explicitRoot: true,\n explicitCharkey: true,\n tagNameProcessors: [xml2js.processors.stripPrefix],\n };\n const parser = new xml2js.Parser(parserConfig);\n return parser.parseStringPromise(xml);\n};\n\nexport const buildXml2JsObject = (rootName: string, xml: any): string => {\n const builderOpts = {\n rootName,\n headless: true,\n };\n return new xml2js.Builder(builderOpts).buildObject(xml);\n};\n\nexport const buildXmlBuilderObject = (xml: Record<string, any>, pretty: boolean): string => {\n const options = pretty ? { pretty: true, indent: \" \", newline: \"\\n\" } : {};\n return xmlbuilder.create(xml).end(options);\n};\n"]}
@@ -0,0 +1,6 @@
1
+ import type { CacheItem, CacheProvider } from "../node-saml/inmemory-cache-provider";
2
+ import { SAML } from "../node-saml";
3
+ import { Strategy, AbstractStrategy } from "./strategy";
4
+ import { MultiSamlStrategy } from "./multiSamlStrategy";
5
+ import type { AuthenticateOptions, Profile, SamlConfig, VerifiedCallback, VerifyWithRequest, VerifyWithoutRequest } from "./types";
6
+ export { SAML, AbstractStrategy, Strategy, MultiSamlStrategy, CacheItem, CacheProvider, AuthenticateOptions, Profile, SamlConfig, VerifiedCallback, VerifyWithRequest, VerifyWithoutRequest, };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MultiSamlStrategy = exports.Strategy = exports.AbstractStrategy = exports.SAML = void 0;
4
+ const node_saml_1 = require("../node-saml");
5
+ Object.defineProperty(exports, "SAML", { enumerable: true, get: function () { return node_saml_1.SAML; } });
6
+ const strategy_1 = require("./strategy");
7
+ Object.defineProperty(exports, "Strategy", { enumerable: true, get: function () { return strategy_1.Strategy; } });
8
+ Object.defineProperty(exports, "AbstractStrategy", { enumerable: true, get: function () { return strategy_1.AbstractStrategy; } });
9
+ const multiSamlStrategy_1 = require("./multiSamlStrategy");
10
+ Object.defineProperty(exports, "MultiSamlStrategy", { enumerable: true, get: function () { return multiSamlStrategy_1.MultiSamlStrategy; } });
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/passport-saml/index.ts"],"names":[],"mappings":";;;AACA,4CAAoC;AAclC,qFAdO,gBAAI,OAcP;AAbN,yCAAwD;AAetD,yFAfO,mBAAQ,OAeP;AADR,iGAdiB,2BAAgB,OAcjB;AAblB,2DAAwD;AAetD,kGAfO,qCAAiB,OAeP","sourcesContent":["import type { CacheItem, CacheProvider } from \"../node-saml/inmemory-cache-provider\";\nimport { SAML } from \"../node-saml\";\nimport { Strategy, AbstractStrategy } from \"./strategy\";\nimport { MultiSamlStrategy } from \"./multiSamlStrategy\";\n\nimport type {\n AuthenticateOptions,\n Profile,\n SamlConfig,\n VerifiedCallback,\n VerifyWithRequest,\n VerifyWithoutRequest,\n} from \"./types\";\n\nexport {\n SAML,\n AbstractStrategy,\n Strategy,\n MultiSamlStrategy,\n CacheItem,\n CacheProvider,\n AuthenticateOptions,\n Profile,\n SamlConfig,\n VerifiedCallback,\n VerifyWithRequest,\n VerifyWithoutRequest,\n};\n"]}
@@ -0,0 +1,13 @@
1
+ import { AbstractStrategy } from "./strategy";
2
+ import type { Request } from "express";
3
+ import { AuthenticateOptions, MultiSamlConfig, RequestWithUser, SamlConfig, VerifyWithoutRequest, VerifyWithRequest } from "./types";
4
+ export declare class MultiSamlStrategy extends AbstractStrategy {
5
+ static readonly newSamlProviderOnConstruct = false;
6
+ _options: SamlConfig & MultiSamlConfig;
7
+ constructor(options: MultiSamlConfig, verify: VerifyWithRequest);
8
+ constructor(options: MultiSamlConfig, verify: VerifyWithoutRequest);
9
+ authenticate(req: RequestWithUser, options: AuthenticateOptions): void;
10
+ logout(req: RequestWithUser, callback: (err: Error | null, url?: string | null | undefined) => void): void;
11
+ generateServiceProviderMetadata(req: Request, decryptionCert: string | null, signingCert: string | null, callback: (err: Error | null, metadata?: string) => void): void;
12
+ error(err: Error): void;
13
+ }