auth-config.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. /*! firebase-admin v12.1.1 */
  2. "use strict";
  3. /*!
  4. * Copyright 2018 Google Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. exports.EmailPrivacyAuthConfig = exports.PasswordPolicyAuthConfig = exports.RecaptchaAuthConfig = exports.SmsRegionsAuthConfig = exports.OIDCConfig = exports.SAMLConfig = exports.EmailSignInConfig = exports.validateTestPhoneNumbers = exports.MultiFactorAuthConfig = exports.MAXIMUM_TEST_PHONE_NUMBERS = void 0;
  20. const validator = require("../utils/validator");
  21. const deep_copy_1 = require("../utils/deep-copy");
  22. const error_1 = require("../utils/error");
  23. /** A maximum of 10 test phone number / code pairs can be configured. */
  24. exports.MAXIMUM_TEST_PHONE_NUMBERS = 10;
  25. /** Client Auth factor type to server auth factor type mapping. */
  26. const AUTH_FACTOR_CLIENT_TO_SERVER_TYPE = {
  27. phone: 'PHONE_SMS',
  28. };
  29. /** Server Auth factor type to client auth factor type mapping. */
  30. const AUTH_FACTOR_SERVER_TO_CLIENT_TYPE = Object.keys(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE)
  31. .reduce((res, key) => {
  32. res[AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[key]] = key;
  33. return res;
  34. }, {});
  35. /**
  36. * Defines the multi-factor config class used to convert client side MultiFactorConfig
  37. * to a format that is understood by the Auth server.
  38. *
  39. * @internal
  40. */
  41. class MultiFactorAuthConfig {
  42. /**
  43. * Static method to convert a client side request to a MultiFactorAuthServerConfig.
  44. * Throws an error if validation fails.
  45. *
  46. * @param options - The options object to convert to a server request.
  47. * @returns The resulting server request.
  48. * @internal
  49. */
  50. static buildServerRequest(options) {
  51. const request = {};
  52. MultiFactorAuthConfig.validate(options);
  53. if (Object.prototype.hasOwnProperty.call(options, 'state')) {
  54. request.state = options.state;
  55. }
  56. if (Object.prototype.hasOwnProperty.call(options, 'factorIds')) {
  57. (options.factorIds || []).forEach((factorId) => {
  58. if (typeof request.enabledProviders === 'undefined') {
  59. request.enabledProviders = [];
  60. }
  61. request.enabledProviders.push(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId]);
  62. });
  63. // In case an empty array is passed. Ensure it gets populated so the array is cleared.
  64. if (options.factorIds && options.factorIds.length === 0) {
  65. request.enabledProviders = [];
  66. }
  67. }
  68. if (Object.prototype.hasOwnProperty.call(options, 'providerConfigs')) {
  69. request.providerConfigs = options.providerConfigs;
  70. }
  71. return request;
  72. }
  73. /**
  74. * Validates the MultiFactorConfig options object. Throws an error on failure.
  75. *
  76. * @param options - The options object to validate.
  77. */
  78. static validate(options) {
  79. const validKeys = {
  80. state: true,
  81. factorIds: true,
  82. providerConfigs: true,
  83. };
  84. if (!validator.isNonNullObject(options)) {
  85. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig" must be a non-null object.');
  86. }
  87. // Check for unsupported top level attributes.
  88. for (const key in options) {
  89. if (!(key in validKeys)) {
  90. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid MultiFactorConfig parameter.`);
  91. }
  92. }
  93. // Validate content.
  94. if (typeof options.state !== 'undefined' &&
  95. options.state !== 'ENABLED' &&
  96. options.state !== 'DISABLED') {
  97. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.state" must be either "ENABLED" or "DISABLED".');
  98. }
  99. if (typeof options.factorIds !== 'undefined') {
  100. if (!validator.isArray(options.factorIds)) {
  101. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.factorIds" must be an array of valid "AuthFactorTypes".');
  102. }
  103. // Validate content of array.
  104. options.factorIds.forEach((factorId) => {
  105. if (typeof AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId] === 'undefined') {
  106. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${factorId}" is not a valid "AuthFactorType".`);
  107. }
  108. });
  109. }
  110. if (typeof options.providerConfigs !== 'undefined') {
  111. if (!validator.isArray(options.providerConfigs)) {
  112. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs" must be an array of valid "MultiFactorProviderConfig."');
  113. }
  114. //Validate content of array.
  115. options.providerConfigs.forEach((multiFactorProviderConfig) => {
  116. if (typeof multiFactorProviderConfig === 'undefined' || !validator.isObject(multiFactorProviderConfig)) {
  117. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${multiFactorProviderConfig}" is not a valid "MultiFactorProviderConfig" type.`);
  118. }
  119. const validProviderConfigKeys = {
  120. state: true,
  121. totpProviderConfig: true,
  122. };
  123. for (const key in multiFactorProviderConfig) {
  124. if (!(key in validProviderConfigKeys)) {
  125. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid ProviderConfig parameter.`);
  126. }
  127. }
  128. if (typeof multiFactorProviderConfig.state === 'undefined' ||
  129. (multiFactorProviderConfig.state !== 'ENABLED' &&
  130. multiFactorProviderConfig.state !== 'DISABLED')) {
  131. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs.state" must be either "ENABLED" or "DISABLED".');
  132. }
  133. // Since TOTP is the only provider config available right now, not defining it will lead into an error
  134. if (typeof multiFactorProviderConfig.totpProviderConfig === 'undefined') {
  135. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs.totpProviderConfig" must be defined.');
  136. }
  137. const validTotpProviderConfigKeys = {
  138. adjacentIntervals: true,
  139. };
  140. for (const key in multiFactorProviderConfig.totpProviderConfig) {
  141. if (!(key in validTotpProviderConfigKeys)) {
  142. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid TotpProviderConfig parameter.`);
  143. }
  144. }
  145. const adjIntervals = multiFactorProviderConfig.totpProviderConfig.adjacentIntervals;
  146. if (typeof adjIntervals !== 'undefined' &&
  147. (!Number.isInteger(adjIntervals) || adjIntervals < 0 || adjIntervals > 10)) {
  148. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"MultiFactorConfig.providerConfigs.totpProviderConfig.adjacentIntervals" must' +
  149. ' be a valid number between 0 and 10 (both inclusive).');
  150. }
  151. });
  152. }
  153. }
  154. /**
  155. * The MultiFactorAuthConfig constructor.
  156. *
  157. * @param response - The server side response used to initialize the
  158. * MultiFactorAuthConfig object.
  159. * @constructor
  160. * @internal
  161. */
  162. constructor(response) {
  163. if (typeof response.state === 'undefined') {
  164. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response');
  165. }
  166. this.state = response.state;
  167. this.factorIds = [];
  168. (response.enabledProviders || []).forEach((enabledProvider) => {
  169. // Ignore unsupported types. It is possible the current admin SDK version is
  170. // not up to date and newer backend types are supported.
  171. if (typeof AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider] !== 'undefined') {
  172. this.factorIds.push(AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider]);
  173. }
  174. });
  175. this.providerConfigs = [];
  176. (response.providerConfigs || []).forEach((providerConfig) => {
  177. if (typeof providerConfig !== 'undefined') {
  178. if (typeof providerConfig.state === 'undefined' ||
  179. typeof providerConfig.totpProviderConfig === 'undefined' ||
  180. (typeof providerConfig.totpProviderConfig.adjacentIntervals !== 'undefined' &&
  181. typeof providerConfig.totpProviderConfig.adjacentIntervals !== 'number')) {
  182. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response');
  183. }
  184. this.providerConfigs.push(providerConfig);
  185. }
  186. });
  187. }
  188. /** Converts MultiFactorConfig to JSON object
  189. * @returns The plain object representation of the multi-factor config instance. */
  190. toJSON() {
  191. return {
  192. state: this.state,
  193. factorIds: this.factorIds,
  194. providerConfigs: this.providerConfigs,
  195. };
  196. }
  197. }
  198. exports.MultiFactorAuthConfig = MultiFactorAuthConfig;
  199. /**
  200. * Validates the provided map of test phone number / code pairs.
  201. * @param testPhoneNumbers - The phone number / code pairs to validate.
  202. */
  203. function validateTestPhoneNumbers(testPhoneNumbers) {
  204. if (!validator.isObject(testPhoneNumbers)) {
  205. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"testPhoneNumbers" must be a map of phone number / code pairs.');
  206. }
  207. if (Object.keys(testPhoneNumbers).length > exports.MAXIMUM_TEST_PHONE_NUMBERS) {
  208. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED);
  209. }
  210. for (const phoneNumber in testPhoneNumbers) {
  211. // Validate phone number.
  212. if (!validator.isPhoneNumber(phoneNumber)) {
  213. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${phoneNumber}" is not a valid E.164 standard compliant phone number.`);
  214. }
  215. // Validate code.
  216. if (!validator.isString(testPhoneNumbers[phoneNumber]) ||
  217. !/^[\d]{6}$/.test(testPhoneNumbers[phoneNumber])) {
  218. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${testPhoneNumbers[phoneNumber]}" is not a valid 6 digit code string.`);
  219. }
  220. }
  221. }
  222. exports.validateTestPhoneNumbers = validateTestPhoneNumbers;
  223. /**
  224. * Defines the email sign-in config class used to convert client side EmailSignInConfig
  225. * to a format that is understood by the Auth server.
  226. *
  227. * @internal
  228. */
  229. class EmailSignInConfig {
  230. /**
  231. * Static method to convert a client side request to a EmailSignInConfigServerRequest.
  232. * Throws an error if validation fails.
  233. *
  234. * @param options - The options object to convert to a server request.
  235. * @returns The resulting server request.
  236. * @internal
  237. */
  238. static buildServerRequest(options) {
  239. const request = {};
  240. EmailSignInConfig.validate(options);
  241. if (Object.prototype.hasOwnProperty.call(options, 'enabled')) {
  242. request.allowPasswordSignup = options.enabled;
  243. }
  244. if (Object.prototype.hasOwnProperty.call(options, 'passwordRequired')) {
  245. request.enableEmailLinkSignin = !options.passwordRequired;
  246. }
  247. return request;
  248. }
  249. /**
  250. * Validates the EmailSignInConfig options object. Throws an error on failure.
  251. *
  252. * @param options - The options object to validate.
  253. */
  254. static validate(options) {
  255. // TODO: Validate the request.
  256. const validKeys = {
  257. enabled: true,
  258. passwordRequired: true,
  259. };
  260. if (!validator.isNonNullObject(options)) {
  261. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig" must be a non-null object.');
  262. }
  263. // Check for unsupported top level attributes.
  264. for (const key in options) {
  265. if (!(key in validKeys)) {
  266. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid EmailSignInConfig parameter.`);
  267. }
  268. }
  269. // Validate content.
  270. if (typeof options.enabled !== 'undefined' &&
  271. !validator.isBoolean(options.enabled)) {
  272. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.enabled" must be a boolean.');
  273. }
  274. if (typeof options.passwordRequired !== 'undefined' &&
  275. !validator.isBoolean(options.passwordRequired)) {
  276. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.passwordRequired" must be a boolean.');
  277. }
  278. }
  279. /**
  280. * The EmailSignInConfig constructor.
  281. *
  282. * @param response - The server side response used to initialize the
  283. * EmailSignInConfig object.
  284. * @constructor
  285. */
  286. constructor(response) {
  287. if (typeof response.allowPasswordSignup === 'undefined') {
  288. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response');
  289. }
  290. this.enabled = response.allowPasswordSignup;
  291. this.passwordRequired = !response.enableEmailLinkSignin;
  292. }
  293. /** @returns The plain object representation of the email sign-in config. */
  294. toJSON() {
  295. return {
  296. enabled: this.enabled,
  297. passwordRequired: this.passwordRequired,
  298. };
  299. }
  300. }
  301. exports.EmailSignInConfig = EmailSignInConfig;
  302. /**
  303. * Defines the SAMLConfig class used to convert a client side configuration to its
  304. * server side representation.
  305. *
  306. * @internal
  307. */
  308. class SAMLConfig {
  309. /**
  310. * Converts a client side request to a SAMLConfigServerRequest which is the format
  311. * accepted by the backend server.
  312. * Throws an error if validation fails. If the request is not a SAMLConfig request,
  313. * returns null.
  314. *
  315. * @param options - The options object to convert to a server request.
  316. * @param ignoreMissingFields - Whether to ignore missing fields.
  317. * @returns The resulting server request or null if not valid.
  318. */
  319. static buildServerRequest(options, ignoreMissingFields = false) {
  320. const makeRequest = validator.isNonNullObject(options) &&
  321. (options.providerId || ignoreMissingFields);
  322. if (!makeRequest) {
  323. return null;
  324. }
  325. const request = {};
  326. // Validate options.
  327. SAMLConfig.validate(options, ignoreMissingFields);
  328. request.enabled = options.enabled;
  329. request.displayName = options.displayName;
  330. // IdP config.
  331. if (options.idpEntityId || options.ssoURL || options.x509Certificates) {
  332. request.idpConfig = {
  333. idpEntityId: options.idpEntityId,
  334. ssoUrl: options.ssoURL,
  335. signRequest: options.enableRequestSigning,
  336. idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [],
  337. };
  338. if (options.x509Certificates) {
  339. for (const cert of (options.x509Certificates || [])) {
  340. request.idpConfig.idpCertificates.push({ x509Certificate: cert });
  341. }
  342. }
  343. }
  344. // RP config.
  345. if (options.callbackURL || options.rpEntityId) {
  346. request.spConfig = {
  347. spEntityId: options.rpEntityId,
  348. callbackUri: options.callbackURL,
  349. };
  350. }
  351. return request;
  352. }
  353. /**
  354. * Returns the provider ID corresponding to the resource name if available.
  355. *
  356. * @param resourceName - The server side resource name.
  357. * @returns The provider ID corresponding to the resource, null otherwise.
  358. */
  359. static getProviderIdFromResourceName(resourceName) {
  360. // name is of form projects/project1/inboundSamlConfigs/providerId1
  361. const matchProviderRes = resourceName.match(/\/inboundSamlConfigs\/(saml\..*)$/);
  362. if (!matchProviderRes || matchProviderRes.length < 2) {
  363. return null;
  364. }
  365. return matchProviderRes[1];
  366. }
  367. /**
  368. * @param providerId - The provider ID to check.
  369. * @returns Whether the provider ID corresponds to a SAML provider.
  370. */
  371. static isProviderId(providerId) {
  372. return validator.isNonEmptyString(providerId) && providerId.indexOf('saml.') === 0;
  373. }
  374. /**
  375. * Validates the SAMLConfig options object. Throws an error on failure.
  376. *
  377. * @param options - The options object to validate.
  378. * @param ignoreMissingFields - Whether to ignore missing fields.
  379. */
  380. static validate(options, ignoreMissingFields = false) {
  381. const validKeys = {
  382. enabled: true,
  383. displayName: true,
  384. providerId: true,
  385. idpEntityId: true,
  386. ssoURL: true,
  387. x509Certificates: true,
  388. rpEntityId: true,
  389. callbackURL: true,
  390. enableRequestSigning: true,
  391. };
  392. if (!validator.isNonNullObject(options)) {
  393. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig" must be a valid non-null object.');
  394. }
  395. // Check for unsupported top level attributes.
  396. for (const key in options) {
  397. if (!(key in validKeys)) {
  398. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SAML config parameter.`);
  399. }
  400. }
  401. // Required fields.
  402. if (validator.isNonEmptyString(options.providerId)) {
  403. if (options.providerId.indexOf('saml.') !== 0) {
  404. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".');
  405. }
  406. }
  407. else if (!ignoreMissingFields) {
  408. // providerId is required and not provided correctly.
  409. throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".');
  410. }
  411. if (!(ignoreMissingFields && typeof options.idpEntityId === 'undefined') &&
  412. !validator.isNonEmptyString(options.idpEntityId)) {
  413. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.idpEntityId" must be a valid non-empty string.');
  414. }
  415. if (!(ignoreMissingFields && typeof options.ssoURL === 'undefined') &&
  416. !validator.isURL(options.ssoURL)) {
  417. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.ssoURL" must be a valid URL string.');
  418. }
  419. if (!(ignoreMissingFields && typeof options.rpEntityId === 'undefined') &&
  420. !validator.isNonEmptyString(options.rpEntityId)) {
  421. throw new error_1.FirebaseAuthError(!options.rpEntityId ? error_1.AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG :
  422. error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.rpEntityId" must be a valid non-empty string.');
  423. }
  424. if (!(ignoreMissingFields && typeof options.callbackURL === 'undefined') &&
  425. !validator.isURL(options.callbackURL)) {
  426. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.callbackURL" must be a valid URL string.');
  427. }
  428. if (!(ignoreMissingFields && typeof options.x509Certificates === 'undefined') &&
  429. !validator.isArray(options.x509Certificates)) {
  430. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.');
  431. }
  432. (options.x509Certificates || []).forEach((cert) => {
  433. if (!validator.isNonEmptyString(cert)) {
  434. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.');
  435. }
  436. });
  437. if (typeof options.enableRequestSigning !== 'undefined' &&
  438. !validator.isBoolean(options.enableRequestSigning)) {
  439. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enableRequestSigning" must be a boolean.');
  440. }
  441. if (typeof options.enabled !== 'undefined' &&
  442. !validator.isBoolean(options.enabled)) {
  443. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enabled" must be a boolean.');
  444. }
  445. if (typeof options.displayName !== 'undefined' &&
  446. !validator.isString(options.displayName)) {
  447. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.displayName" must be a valid string.');
  448. }
  449. }
  450. /**
  451. * The SAMLConfig constructor.
  452. *
  453. * @param response - The server side response used to initialize the SAMLConfig object.
  454. * @constructor
  455. */
  456. constructor(response) {
  457. if (!response ||
  458. !response.idpConfig ||
  459. !response.idpConfig.idpEntityId ||
  460. !response.idpConfig.ssoUrl ||
  461. !response.spConfig ||
  462. !response.spConfig.spEntityId ||
  463. !response.name ||
  464. !(validator.isString(response.name) &&
  465. SAMLConfig.getProviderIdFromResourceName(response.name))) {
  466. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
  467. }
  468. const providerId = SAMLConfig.getProviderIdFromResourceName(response.name);
  469. if (!providerId) {
  470. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
  471. }
  472. this.providerId = providerId;
  473. // RP config.
  474. this.rpEntityId = response.spConfig.spEntityId;
  475. this.callbackURL = response.spConfig.callbackUri;
  476. // IdP config.
  477. this.idpEntityId = response.idpConfig.idpEntityId;
  478. this.ssoURL = response.idpConfig.ssoUrl;
  479. this.enableRequestSigning = !!response.idpConfig.signRequest;
  480. const x509Certificates = [];
  481. for (const cert of (response.idpConfig.idpCertificates || [])) {
  482. if (cert.x509Certificate) {
  483. x509Certificates.push(cert.x509Certificate);
  484. }
  485. }
  486. this.x509Certificates = x509Certificates;
  487. // When enabled is undefined, it takes its default value of false.
  488. this.enabled = !!response.enabled;
  489. this.displayName = response.displayName;
  490. }
  491. /** @returns The plain object representation of the SAMLConfig. */
  492. toJSON() {
  493. return {
  494. enabled: this.enabled,
  495. displayName: this.displayName,
  496. providerId: this.providerId,
  497. idpEntityId: this.idpEntityId,
  498. ssoURL: this.ssoURL,
  499. x509Certificates: (0, deep_copy_1.deepCopy)(this.x509Certificates),
  500. rpEntityId: this.rpEntityId,
  501. callbackURL: this.callbackURL,
  502. enableRequestSigning: this.enableRequestSigning,
  503. };
  504. }
  505. }
  506. exports.SAMLConfig = SAMLConfig;
  507. /**
  508. * Defines the OIDCConfig class used to convert a client side configuration to its
  509. * server side representation.
  510. *
  511. * @internal
  512. */
  513. class OIDCConfig {
  514. /**
  515. * Converts a client side request to a OIDCConfigServerRequest which is the format
  516. * accepted by the backend server.
  517. * Throws an error if validation fails. If the request is not a OIDCConfig request,
  518. * returns null.
  519. *
  520. * @param options - The options object to convert to a server request.
  521. * @param ignoreMissingFields - Whether to ignore missing fields.
  522. * @returns The resulting server request or null if not valid.
  523. */
  524. static buildServerRequest(options, ignoreMissingFields = false) {
  525. const makeRequest = validator.isNonNullObject(options) &&
  526. (options.providerId || ignoreMissingFields);
  527. if (!makeRequest) {
  528. return null;
  529. }
  530. const request = {};
  531. // Validate options.
  532. OIDCConfig.validate(options, ignoreMissingFields);
  533. request.enabled = options.enabled;
  534. request.displayName = options.displayName;
  535. request.issuer = options.issuer;
  536. request.clientId = options.clientId;
  537. if (typeof options.clientSecret !== 'undefined') {
  538. request.clientSecret = options.clientSecret;
  539. }
  540. if (typeof options.responseType !== 'undefined') {
  541. request.responseType = options.responseType;
  542. }
  543. return request;
  544. }
  545. /**
  546. * Returns the provider ID corresponding to the resource name if available.
  547. *
  548. * @param resourceName - The server side resource name
  549. * @returns The provider ID corresponding to the resource, null otherwise.
  550. */
  551. static getProviderIdFromResourceName(resourceName) {
  552. // name is of form projects/project1/oauthIdpConfigs/providerId1
  553. const matchProviderRes = resourceName.match(/\/oauthIdpConfigs\/(oidc\..*)$/);
  554. if (!matchProviderRes || matchProviderRes.length < 2) {
  555. return null;
  556. }
  557. return matchProviderRes[1];
  558. }
  559. /**
  560. * @param providerId - The provider ID to check.
  561. * @returns Whether the provider ID corresponds to an OIDC provider.
  562. */
  563. static isProviderId(providerId) {
  564. return validator.isNonEmptyString(providerId) && providerId.indexOf('oidc.') === 0;
  565. }
  566. /**
  567. * Validates the OIDCConfig options object. Throws an error on failure.
  568. *
  569. * @param options - The options object to validate.
  570. * @param ignoreMissingFields - Whether to ignore missing fields.
  571. */
  572. static validate(options, ignoreMissingFields = false) {
  573. const validKeys = {
  574. enabled: true,
  575. displayName: true,
  576. providerId: true,
  577. clientId: true,
  578. issuer: true,
  579. clientSecret: true,
  580. responseType: true,
  581. };
  582. const validResponseTypes = {
  583. idToken: true,
  584. code: true,
  585. };
  586. if (!validator.isNonNullObject(options)) {
  587. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig" must be a valid non-null object.');
  588. }
  589. // Check for unsupported top level attributes.
  590. for (const key in options) {
  591. if (!(key in validKeys)) {
  592. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OIDC config parameter.`);
  593. }
  594. }
  595. // Required fields.
  596. if (validator.isNonEmptyString(options.providerId)) {
  597. if (options.providerId.indexOf('oidc.') !== 0) {
  598. throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".');
  599. }
  600. }
  601. else if (!ignoreMissingFields) {
  602. throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".');
  603. }
  604. if (!(ignoreMissingFields && typeof options.clientId === 'undefined') &&
  605. !validator.isNonEmptyString(options.clientId)) {
  606. throw new error_1.FirebaseAuthError(!options.clientId ? error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID : error_1.AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID, '"OIDCAuthProviderConfig.clientId" must be a valid non-empty string.');
  607. }
  608. if (!(ignoreMissingFields && typeof options.issuer === 'undefined') &&
  609. !validator.isURL(options.issuer)) {
  610. throw new error_1.FirebaseAuthError(!options.issuer ? error_1.AuthClientErrorCode.MISSING_ISSUER : error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.issuer" must be a valid URL string.');
  611. }
  612. if (typeof options.enabled !== 'undefined' &&
  613. !validator.isBoolean(options.enabled)) {
  614. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.enabled" must be a boolean.');
  615. }
  616. if (typeof options.displayName !== 'undefined' &&
  617. !validator.isString(options.displayName)) {
  618. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.displayName" must be a valid string.');
  619. }
  620. if (typeof options.clientSecret !== 'undefined' &&
  621. !validator.isNonEmptyString(options.clientSecret)) {
  622. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.clientSecret" must be a valid string.');
  623. }
  624. if (validator.isNonNullObject(options.responseType) && typeof options.responseType !== 'undefined') {
  625. Object.keys(options.responseType).forEach((key) => {
  626. if (!(key in validResponseTypes)) {
  627. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OAuthResponseType parameter.`);
  628. }
  629. });
  630. const idToken = options.responseType.idToken;
  631. if (typeof idToken !== 'undefined' && !validator.isBoolean(idToken)) {
  632. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.idToken" must be a boolean.');
  633. }
  634. const code = options.responseType.code;
  635. if (typeof code !== 'undefined') {
  636. if (!validator.isBoolean(code)) {
  637. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.code" must be a boolean.');
  638. }
  639. // If code flow is enabled, client secret must be provided.
  640. if (code && typeof options.clientSecret === 'undefined') {
  641. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET, 'The OAuth configuration client secret is required to enable OIDC code flow.');
  642. }
  643. }
  644. const allKeys = Object.keys(options.responseType).length;
  645. const enabledCount = Object.values(options.responseType).filter(Boolean).length;
  646. // Only one of OAuth response types can be set to true.
  647. if (allKeys > 1 && enabledCount !== 1) {
  648. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE, 'Only exactly one OAuth responseType should be set to true.');
  649. }
  650. }
  651. }
  652. /**
  653. * The OIDCConfig constructor.
  654. *
  655. * @param response - The server side response used to initialize the OIDCConfig object.
  656. * @constructor
  657. */
  658. constructor(response) {
  659. if (!response ||
  660. !response.issuer ||
  661. !response.clientId ||
  662. !response.name ||
  663. !(validator.isString(response.name) &&
  664. OIDCConfig.getProviderIdFromResourceName(response.name))) {
  665. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid OIDC configuration response');
  666. }
  667. const providerId = OIDCConfig.getProviderIdFromResourceName(response.name);
  668. if (!providerId) {
  669. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
  670. }
  671. this.providerId = providerId;
  672. this.clientId = response.clientId;
  673. this.issuer = response.issuer;
  674. // When enabled is undefined, it takes its default value of false.
  675. this.enabled = !!response.enabled;
  676. this.displayName = response.displayName;
  677. if (typeof response.clientSecret !== 'undefined') {
  678. this.clientSecret = response.clientSecret;
  679. }
  680. if (typeof response.responseType !== 'undefined') {
  681. this.responseType = response.responseType;
  682. }
  683. }
  684. /** @returns The plain object representation of the OIDCConfig. */
  685. toJSON() {
  686. return {
  687. enabled: this.enabled,
  688. displayName: this.displayName,
  689. providerId: this.providerId,
  690. issuer: this.issuer,
  691. clientId: this.clientId,
  692. clientSecret: (0, deep_copy_1.deepCopy)(this.clientSecret),
  693. responseType: (0, deep_copy_1.deepCopy)(this.responseType),
  694. };
  695. }
  696. }
  697. exports.OIDCConfig = OIDCConfig;
  698. /**
  699. * Defines the SMSRegionConfig class used for validation.
  700. *
  701. * @internal
  702. */
  703. class SmsRegionsAuthConfig {
  704. static validate(options) {
  705. if (!validator.isNonNullObject(options)) {
  706. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig" must be a non-null object.');
  707. }
  708. const validKeys = {
  709. allowlistOnly: true,
  710. allowByDefault: true,
  711. };
  712. for (const key in options) {
  713. if (!(key in validKeys)) {
  714. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig parameter.`);
  715. }
  716. }
  717. // validate mutual exclusiveness of allowByDefault and allowlistOnly
  718. if (typeof options.allowByDefault !== 'undefined' && typeof options.allowlistOnly !== 'undefined') {
  719. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'SmsRegionConfig cannot have both "allowByDefault" and "allowlistOnly" parameters.');
  720. }
  721. // validation for allowByDefault type
  722. if (typeof options.allowByDefault !== 'undefined') {
  723. const allowByDefaultValidKeys = {
  724. disallowedRegions: true,
  725. };
  726. for (const key in options.allowByDefault) {
  727. if (!(key in allowByDefaultValidKeys)) {
  728. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig.allowByDefault parameter.`);
  729. }
  730. }
  731. // disallowedRegion can be empty.
  732. if (typeof options.allowByDefault.disallowedRegions !== 'undefined'
  733. && !validator.isArray(options.allowByDefault.disallowedRegions)) {
  734. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig.allowByDefault.disallowedRegions" must be a valid string array.');
  735. }
  736. }
  737. if (typeof options.allowlistOnly !== 'undefined') {
  738. const allowListOnlyValidKeys = {
  739. allowedRegions: true,
  740. };
  741. for (const key in options.allowlistOnly) {
  742. if (!(key in allowListOnlyValidKeys)) {
  743. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig.allowlistOnly parameter.`);
  744. }
  745. }
  746. // allowedRegions can be empty
  747. if (typeof options.allowlistOnly.allowedRegions !== 'undefined'
  748. && !validator.isArray(options.allowlistOnly.allowedRegions)) {
  749. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig.allowlistOnly.allowedRegions" must be a valid string array.');
  750. }
  751. }
  752. }
  753. }
  754. exports.SmsRegionsAuthConfig = SmsRegionsAuthConfig;
  755. class RecaptchaAuthConfig {
  756. constructor(recaptchaConfig) {
  757. this.emailPasswordEnforcementState = recaptchaConfig.emailPasswordEnforcementState;
  758. this.managedRules = recaptchaConfig.managedRules;
  759. this.recaptchaKeys = recaptchaConfig.recaptchaKeys;
  760. this.useAccountDefender = recaptchaConfig.useAccountDefender;
  761. }
  762. /**
  763. * Validates the RecaptchaConfig options object. Throws an error on failure.
  764. * @param options - The options object to validate.
  765. */
  766. static validate(options) {
  767. const validKeys = {
  768. emailPasswordEnforcementState: true,
  769. managedRules: true,
  770. recaptchaKeys: true,
  771. useAccountDefender: true,
  772. };
  773. if (!validator.isNonNullObject(options)) {
  774. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig" must be a non-null object.');
  775. }
  776. for (const key in options) {
  777. if (!(key in validKeys)) {
  778. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid RecaptchaConfig parameter.`);
  779. }
  780. }
  781. // Validation
  782. if (typeof options.emailPasswordEnforcementState !== undefined) {
  783. if (!validator.isNonEmptyString(options.emailPasswordEnforcementState)) {
  784. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"RecaptchaConfig.emailPasswordEnforcementState" must be a valid non-empty string.');
  785. }
  786. if (options.emailPasswordEnforcementState !== 'OFF' &&
  787. options.emailPasswordEnforcementState !== 'AUDIT' &&
  788. options.emailPasswordEnforcementState !== 'ENFORCE') {
  789. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.emailPasswordEnforcementState" must be either "OFF", "AUDIT" or "ENFORCE".');
  790. }
  791. }
  792. if (typeof options.managedRules !== 'undefined') {
  793. // Validate array
  794. if (!validator.isArray(options.managedRules)) {
  795. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.managedRules" must be an array of valid "RecaptchaManagedRule".');
  796. }
  797. // Validate each rule of the array
  798. options.managedRules.forEach((managedRule) => {
  799. RecaptchaAuthConfig.validateManagedRule(managedRule);
  800. });
  801. }
  802. if (typeof options.useAccountDefender !== 'undefined') {
  803. if (!validator.isBoolean(options.useAccountDefender)) {
  804. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.useAccountDefender" must be a boolean value".');
  805. }
  806. }
  807. }
  808. /**
  809. * Validate each element in ManagedRule array
  810. * @param options - The options object to validate.
  811. */
  812. static validateManagedRule(options) {
  813. const validKeys = {
  814. endScore: true,
  815. action: true,
  816. };
  817. if (!validator.isNonNullObject(options)) {
  818. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaManagedRule" must be a non-null object.');
  819. }
  820. // Check for unsupported top level attributes.
  821. for (const key in options) {
  822. if (!(key in validKeys)) {
  823. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid RecaptchaManagedRule parameter.`);
  824. }
  825. }
  826. // Validate content.
  827. if (typeof options.action !== 'undefined' &&
  828. options.action !== 'BLOCK') {
  829. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaManagedRule.action" must be "BLOCK".');
  830. }
  831. }
  832. /**
  833. * Returns a JSON-serializable representation of this object.
  834. * @returns The JSON-serializable object representation of the ReCaptcha config instance
  835. */
  836. toJSON() {
  837. const json = {
  838. emailPasswordEnforcementState: this.emailPasswordEnforcementState,
  839. managedRules: (0, deep_copy_1.deepCopy)(this.managedRules),
  840. recaptchaKeys: (0, deep_copy_1.deepCopy)(this.recaptchaKeys),
  841. useAccountDefender: this.useAccountDefender,
  842. };
  843. if (typeof json.emailPasswordEnforcementState === 'undefined') {
  844. delete json.emailPasswordEnforcementState;
  845. }
  846. if (typeof json.managedRules === 'undefined') {
  847. delete json.managedRules;
  848. }
  849. if (typeof json.recaptchaKeys === 'undefined') {
  850. delete json.recaptchaKeys;
  851. }
  852. if (typeof json.useAccountDefender === 'undefined') {
  853. delete json.useAccountDefender;
  854. }
  855. return json;
  856. }
  857. }
  858. exports.RecaptchaAuthConfig = RecaptchaAuthConfig;
  859. /**
  860. * Defines the password policy config class used to convert client side PasswordPolicyConfig
  861. * to a format that is understood by the Auth server.
  862. *
  863. * @internal
  864. */
  865. class PasswordPolicyAuthConfig {
  866. /**
  867. * Static method to convert a client side request to a PasswordPolicyAuthServerConfig.
  868. * Throws an error if validation fails.
  869. *
  870. * @param options - The options object to convert to a server request.
  871. * @returns The resulting server request.
  872. * @internal
  873. */
  874. static buildServerRequest(options) {
  875. const request = {};
  876. PasswordPolicyAuthConfig.validate(options);
  877. if (Object.prototype.hasOwnProperty.call(options, 'enforcementState')) {
  878. request.passwordPolicyEnforcementState = options.enforcementState;
  879. }
  880. request.forceUpgradeOnSignin = false;
  881. if (Object.prototype.hasOwnProperty.call(options, 'forceUpgradeOnSignin')) {
  882. request.forceUpgradeOnSignin = options.forceUpgradeOnSignin;
  883. }
  884. const constraintsRequest = {
  885. containsUppercaseCharacter: false,
  886. containsLowercaseCharacter: false,
  887. containsNonAlphanumericCharacter: false,
  888. containsNumericCharacter: false,
  889. minPasswordLength: 6,
  890. maxPasswordLength: 4096,
  891. };
  892. request.passwordPolicyVersions = [];
  893. if (Object.prototype.hasOwnProperty.call(options, 'constraints')) {
  894. if (options) {
  895. if (options.constraints?.requireUppercase !== undefined) {
  896. constraintsRequest.containsUppercaseCharacter = options.constraints.requireUppercase;
  897. }
  898. if (options.constraints?.requireLowercase !== undefined) {
  899. constraintsRequest.containsLowercaseCharacter = options.constraints.requireLowercase;
  900. }
  901. if (options.constraints?.requireNonAlphanumeric !== undefined) {
  902. constraintsRequest.containsNonAlphanumericCharacter = options.constraints.requireNonAlphanumeric;
  903. }
  904. if (options.constraints?.requireNumeric !== undefined) {
  905. constraintsRequest.containsNumericCharacter = options.constraints.requireNumeric;
  906. }
  907. if (options.constraints?.minLength !== undefined) {
  908. constraintsRequest.minPasswordLength = options.constraints.minLength;
  909. }
  910. if (options.constraints?.maxLength !== undefined) {
  911. constraintsRequest.maxPasswordLength = options.constraints.maxLength;
  912. }
  913. }
  914. }
  915. request.passwordPolicyVersions.push({ customStrengthOptions: constraintsRequest });
  916. return request;
  917. }
  918. /**
  919. * Validates the PasswordPolicyConfig options object. Throws an error on failure.
  920. *
  921. * @param options - The options object to validate.
  922. * @internal
  923. */
  924. static validate(options) {
  925. const validKeys = {
  926. enforcementState: true,
  927. forceUpgradeOnSignin: true,
  928. constraints: true,
  929. };
  930. if (!validator.isNonNullObject(options)) {
  931. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig" must be a non-null object.');
  932. }
  933. // Check for unsupported top level attributes.
  934. for (const key in options) {
  935. if (!(key in validKeys)) {
  936. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid PasswordPolicyConfig parameter.`);
  937. }
  938. }
  939. // Validate content.
  940. if (typeof options.enforcementState === 'undefined' ||
  941. !(options.enforcementState === 'ENFORCE' ||
  942. options.enforcementState === 'OFF')) {
  943. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.enforcementState" must be either "ENFORCE" or "OFF".');
  944. }
  945. if (typeof options.forceUpgradeOnSignin !== 'undefined') {
  946. if (!validator.isBoolean(options.forceUpgradeOnSignin)) {
  947. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.forceUpgradeOnSignin" must be a boolean.');
  948. }
  949. }
  950. if (typeof options.constraints !== 'undefined') {
  951. if (options.enforcementState === 'ENFORCE' && !validator.isNonNullObject(options.constraints)) {
  952. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints" must be a non-empty object.');
  953. }
  954. const validCharKeys = {
  955. requireUppercase: true,
  956. requireLowercase: true,
  957. requireNumeric: true,
  958. requireNonAlphanumeric: true,
  959. minLength: true,
  960. maxLength: true,
  961. };
  962. // Check for unsupported attributes.
  963. for (const key in options.constraints) {
  964. if (!(key in validCharKeys)) {
  965. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid PasswordPolicyConfig.constraints parameter.`);
  966. }
  967. }
  968. if (typeof options.constraints.requireUppercase !== 'undefined' &&
  969. !validator.isBoolean(options.constraints.requireUppercase)) {
  970. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireUppercase" must be a boolean.');
  971. }
  972. if (typeof options.constraints.requireLowercase !== 'undefined' &&
  973. !validator.isBoolean(options.constraints.requireLowercase)) {
  974. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireLowercase" must be a boolean.');
  975. }
  976. if (typeof options.constraints.requireNonAlphanumeric !== 'undefined' &&
  977. !validator.isBoolean(options.constraints.requireNonAlphanumeric)) {
  978. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireNonAlphanumeric"' +
  979. ' must be a boolean.');
  980. }
  981. if (typeof options.constraints.requireNumeric !== 'undefined' &&
  982. !validator.isBoolean(options.constraints.requireNumeric)) {
  983. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireNumeric" must be a boolean.');
  984. }
  985. if (typeof options.constraints.minLength === 'undefined') {
  986. options.constraints.minLength = 6;
  987. }
  988. else if (!validator.isNumber(options.constraints.minLength)) {
  989. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.minLength" must be a number.');
  990. }
  991. else {
  992. if (!(options.constraints.minLength >= 6
  993. && options.constraints.minLength <= 30)) {
  994. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.minLength"' +
  995. ' must be an integer between 6 and 30, inclusive.');
  996. }
  997. }
  998. if (typeof options.constraints.maxLength === 'undefined') {
  999. options.constraints.maxLength = 4096;
  1000. }
  1001. else if (!validator.isNumber(options.constraints.maxLength)) {
  1002. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.maxLength" must be a number.');
  1003. }
  1004. else {
  1005. if (!(options.constraints.maxLength >= options.constraints.minLength &&
  1006. options.constraints.maxLength <= 4096)) {
  1007. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.maxLength"' +
  1008. ' must be greater than or equal to minLength and at max 4096.');
  1009. }
  1010. }
  1011. }
  1012. else {
  1013. if (options.enforcementState === 'ENFORCE') {
  1014. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints" must be defined.');
  1015. }
  1016. }
  1017. }
  1018. /**
  1019. * The PasswordPolicyAuthConfig constructor.
  1020. *
  1021. * @param response - The server side response used to initialize the
  1022. * PasswordPolicyAuthConfig object.
  1023. * @constructor
  1024. * @internal
  1025. */
  1026. constructor(response) {
  1027. if (typeof response.passwordPolicyEnforcementState === 'undefined') {
  1028. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid password policy configuration response');
  1029. }
  1030. this.enforcementState = response.passwordPolicyEnforcementState;
  1031. let constraintsResponse = {};
  1032. if (typeof response.passwordPolicyVersions !== 'undefined') {
  1033. (response.passwordPolicyVersions || []).forEach((policyVersion) => {
  1034. constraintsResponse = {
  1035. requireLowercase: policyVersion.customStrengthOptions?.containsLowercaseCharacter,
  1036. requireUppercase: policyVersion.customStrengthOptions?.containsUppercaseCharacter,
  1037. requireNonAlphanumeric: policyVersion.customStrengthOptions?.containsNonAlphanumericCharacter,
  1038. requireNumeric: policyVersion.customStrengthOptions?.containsNumericCharacter,
  1039. minLength: policyVersion.customStrengthOptions?.minPasswordLength,
  1040. maxLength: policyVersion.customStrengthOptions?.maxPasswordLength,
  1041. };
  1042. });
  1043. }
  1044. this.constraints = constraintsResponse;
  1045. this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ? true : false;
  1046. }
  1047. }
  1048. exports.PasswordPolicyAuthConfig = PasswordPolicyAuthConfig;
  1049. /**
  1050. * Defines the EmailPrivacyAuthConfig class used for validation.
  1051. *
  1052. * @internal
  1053. */
  1054. class EmailPrivacyAuthConfig {
  1055. static validate(options) {
  1056. if (!validator.isNonNullObject(options)) {
  1057. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"EmailPrivacyConfig" must be a non-null object.');
  1058. }
  1059. const validKeys = {
  1060. enableImprovedEmailPrivacy: true,
  1061. };
  1062. for (const key in options) {
  1063. if (!(key in validKeys)) {
  1064. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid "EmailPrivacyConfig" parameter.`);
  1065. }
  1066. }
  1067. if (typeof options.enableImprovedEmailPrivacy !== 'undefined'
  1068. && !validator.isBoolean(options.enableImprovedEmailPrivacy)) {
  1069. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"EmailPrivacyConfig.enableImprovedEmailPrivacy" must be a valid boolean value.');
  1070. }
  1071. }
  1072. }
  1073. exports.EmailPrivacyAuthConfig = EmailPrivacyAuthConfig;