totp-9fcfcaa9.js 364 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188
  1. 'use strict';
  2. var tslib = require('tslib');
  3. var util = require('@firebase/util');
  4. var app = require('@firebase/app');
  5. var component = require('@firebase/component');
  6. var fetchImpl = require('node-fetch');
  7. var logger = require('@firebase/logger');
  8. function _interopNamespace(e) {
  9. if (e && e.__esModule) return e;
  10. var n = Object.create(null);
  11. if (e) {
  12. Object.keys(e).forEach(function (k) {
  13. if (k !== 'default') {
  14. var d = Object.getOwnPropertyDescriptor(e, k);
  15. Object.defineProperty(n, k, d.get ? d : {
  16. enumerable: true,
  17. get: function () { return e[k]; }
  18. });
  19. }
  20. });
  21. }
  22. n["default"] = e;
  23. return Object.freeze(n);
  24. }
  25. var fetchImpl__namespace = /*#__PURE__*/_interopNamespace(fetchImpl);
  26. /**
  27. * @license
  28. * Copyright 2021 Google LLC
  29. *
  30. * Licensed under the Apache License, Version 2.0 (the "License");
  31. * you may not use this file except in compliance with the License.
  32. * You may obtain a copy of the License at
  33. *
  34. * http://www.apache.org/licenses/LICENSE-2.0
  35. *
  36. * Unless required by applicable law or agreed to in writing, software
  37. * distributed under the License is distributed on an "AS IS" BASIS,
  38. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39. * See the License for the specific language governing permissions and
  40. * limitations under the License.
  41. */
  42. /**
  43. * An enum of factors that may be used for multifactor authentication.
  44. *
  45. * @public
  46. */
  47. var FactorId = {
  48. /** Phone as second factor */
  49. PHONE: 'phone',
  50. TOTP: 'totp'
  51. };
  52. /**
  53. * Enumeration of supported providers.
  54. *
  55. * @public
  56. */
  57. var ProviderId = {
  58. /** Facebook provider ID */
  59. FACEBOOK: 'facebook.com',
  60. /** GitHub provider ID */
  61. GITHUB: 'github.com',
  62. /** Google provider ID */
  63. GOOGLE: 'google.com',
  64. /** Password provider */
  65. PASSWORD: 'password',
  66. /** Phone provider */
  67. PHONE: 'phone',
  68. /** Twitter provider ID */
  69. TWITTER: 'twitter.com'
  70. };
  71. /**
  72. * Enumeration of supported sign-in methods.
  73. *
  74. * @public
  75. */
  76. var SignInMethod = {
  77. /** Email link sign in method */
  78. EMAIL_LINK: 'emailLink',
  79. /** Email/password sign in method */
  80. EMAIL_PASSWORD: 'password',
  81. /** Facebook sign in method */
  82. FACEBOOK: 'facebook.com',
  83. /** GitHub sign in method */
  84. GITHUB: 'github.com',
  85. /** Google sign in method */
  86. GOOGLE: 'google.com',
  87. /** Phone sign in method */
  88. PHONE: 'phone',
  89. /** Twitter sign in method */
  90. TWITTER: 'twitter.com'
  91. };
  92. /**
  93. * Enumeration of supported operation types.
  94. *
  95. * @public
  96. */
  97. var OperationType = {
  98. /** Operation involving linking an additional provider to an already signed-in user. */
  99. LINK: 'link',
  100. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  101. REAUTHENTICATE: 'reauthenticate',
  102. /** Operation involving signing in a user. */
  103. SIGN_IN: 'signIn'
  104. };
  105. /**
  106. * An enumeration of the possible email action types.
  107. *
  108. * @public
  109. */
  110. var ActionCodeOperation = {
  111. /** The email link sign-in action. */
  112. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  113. /** The password reset action. */
  114. PASSWORD_RESET: 'PASSWORD_RESET',
  115. /** The email revocation action. */
  116. RECOVER_EMAIL: 'RECOVER_EMAIL',
  117. /** The revert second factor addition email action. */
  118. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  119. /** The revert second factor addition email action. */
  120. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  121. /** The email verification action. */
  122. VERIFY_EMAIL: 'VERIFY_EMAIL'
  123. };
  124. /**
  125. * @license
  126. * Copyright 2020 Google LLC
  127. *
  128. * Licensed under the Apache License, Version 2.0 (the "License");
  129. * you may not use this file except in compliance with the License.
  130. * You may obtain a copy of the License at
  131. *
  132. * http://www.apache.org/licenses/LICENSE-2.0
  133. *
  134. * Unless required by applicable law or agreed to in writing, software
  135. * distributed under the License is distributed on an "AS IS" BASIS,
  136. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  137. * See the License for the specific language governing permissions and
  138. * limitations under the License.
  139. */
  140. function _debugErrorMap() {
  141. var _a;
  142. return _a = {},
  143. _a["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
  144. _a["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */] = '',
  145. _a["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
  146. 'authorized to use Firebase Authentication with the provided API key. ' +
  147. 'Review your key configuration in the Google API console.',
  148. _a["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
  149. 'Android package name or iOS bundle ID) provided is not installed on ' +
  150. 'this device.',
  151. _a["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
  152. 'already used or the domain associated with it does not match the list ' +
  153. 'of whitelisted domains.',
  154. _a["code-expired" /* AuthErrorCode.CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
  155. 'again.',
  156. _a["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
  157. _a["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */] = 'This browser is not supported.',
  158. _a["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
  159. _a["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
  160. _a["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
  161. 'again before retrying this request.',
  162. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  163. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  164. 'starting any other Firebase SDK.',
  165. _a["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  166. 'conditions.',
  167. _a["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
  168. _a["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */] = 'The email address is already in use by another account.',
  169. _a["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
  170. 'no longer be configured to use the emulator. Try calling ' +
  171. '"connectAuthEmulator()" sooner.',
  172. _a["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */] = 'The action code has expired.',
  173. _a["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
  174. _a["internal-error" /* AuthErrorCode.INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
  175. _a["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
  176. ' The reCAPTCHA token response is either invalid or expired.',
  177. _a["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
  178. _a["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
  179. "if the user's token has been tampered with, or if the user isn't for " +
  180. 'the project associated with this API key.',
  181. _a["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  182. _a["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
  183. 'invalid. Please resend the verification code sms and be sure to use the ' +
  184. 'verification code provided by the user.',
  185. _a["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
  186. _a["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  187. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  188. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  189. 'cordova-plugin-customurlscheme.',
  190. _a["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
  191. _a["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
  192. _a["invalid-email" /* AuthErrorCode.INVALID_EMAIL */] = 'The email address is badly formatted.',
  193. _a["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
  194. _a["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
  195. _a["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
  196. _a["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
  197. _a["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
  198. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  199. _a["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
  200. _a["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
  201. 'only supports OAuth providers.',
  202. _a["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
  203. 'specified API key.',
  204. _a["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
  205. 'project. Edit the list of authorized domains from the Firebase console.',
  206. _a["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
  207. 'expired, or has already been used.',
  208. _a["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
  209. _a["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
  210. _a["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
  211. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  212. 'phone numbers are written in the format [+][country code][subscriber ' +
  213. 'number including area code].',
  214. _a["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
  215. _a["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
  216. 'recipient email address is invalid.',
  217. _a["invalid-sender" /* AuthErrorCode.INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
  218. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  219. _a["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
  220. _a["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
  221. _a["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */] = 'Login blocked by user-provided method: {$originalMessage}',
  222. _a["missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
  223. _a["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  224. 'by following the instructions in the Firebase console.',
  225. _a["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
  226. 'assertion. A reCAPTCHA response token needs to be provided.',
  227. _a["missing-verification-code" /* AuthErrorCode.MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
  228. _a["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
  229. _a["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
  230. _a["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  231. _a["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
  232. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  233. 'in the ID token payload.',
  234. _a["missing-password" /* AuthErrorCode.MISSING_PASSWORD */] = 'A non-empty password must be provided',
  235. _a["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
  236. _a["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
  237. _a["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
  238. _a["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
  239. _a["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
  240. _a["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
  241. _a["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
  242. _a["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
  243. 'sign-in credentials. Sign in using a provider associated with this ' +
  244. 'email address.',
  245. _a["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  246. _a["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  247. _a["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
  248. _a["null-user" /* AuthErrorCode.NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
  249. 'requires a non-null user object.',
  250. _a["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
  251. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  252. 'Auth section.',
  253. _a["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
  254. 'running on. "location.protocol" must be http, https or chrome-extension' +
  255. ' and web storage must be enabled.',
  256. _a["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  257. _a["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
  258. _a["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
  259. _a["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
  260. _a["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
  261. _a["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
  262. _a["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
  263. _a["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
  264. _a["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
  265. _a["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
  266. _a["timeout" /* AuthErrorCode.TIMEOUT */] = 'The operation has timed out.',
  267. _a["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
  268. _a["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
  269. 'Try again later.',
  270. _a["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  271. 'the domain in the Firebase console.',
  272. _a["unsupported-first-factor" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
  273. _a["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
  274. _a["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
  275. _a["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
  276. _a["user-cancelled" /* AuthErrorCode.USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
  277. _a["user-not-found" /* AuthErrorCode.USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
  278. 'have been deleted.',
  279. _a["user-disabled" /* AuthErrorCode.USER_DISABLED */] = 'The user account has been disabled by an administrator.',
  280. _a["user-mismatch" /* AuthErrorCode.USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
  281. _a["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */] = '',
  282. _a["weak-password" /* AuthErrorCode.WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
  283. _a["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
  284. _a["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
  285. 'different options. To avoid this error, call initializeAuth() with the ' +
  286. 'same options as when it was originally called, or call getAuth() to return the' +
  287. ' already initialized instance.',
  288. _a["missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is missing when sending request to the backend.',
  289. _a["invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is invalid when sending request to the backend.',
  290. _a["invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */] = 'The reCAPTCHA action is invalid when sending request to the backend.',
  291. _a["recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */] = 'reCAPTCHA Enterprise integration is not enabled for this project.',
  292. _a["missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */] = 'The reCAPTCHA client type is missing when sending request to the backend.',
  293. _a["missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is missing when sending request to the backend.',
  294. _a["invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */] = 'Invalid request parameters.',
  295. _a["invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is invalid when sending request to the backend.',
  296. _a;
  297. }
  298. function _prodErrorMap() {
  299. var _a;
  300. // We will include this one message in the prod error map since by the very
  301. // nature of this error, developers will never be able to see the message
  302. // using the debugErrorMap (which is installed during auth initialization).
  303. return _a = {},
  304. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  305. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  306. 'starting any other Firebase SDK.',
  307. _a;
  308. }
  309. /**
  310. * A verbose error map with detailed descriptions for most error codes.
  311. *
  312. * See discussion at {@link AuthErrorMap}
  313. *
  314. * @public
  315. */
  316. var debugErrorMap = _debugErrorMap;
  317. /**
  318. * A minimal error map with all verbose error messages stripped.
  319. *
  320. * See discussion at {@link AuthErrorMap}
  321. *
  322. * @public
  323. */
  324. var prodErrorMap = _prodErrorMap;
  325. var _DEFAULT_AUTH_ERROR_FACTORY = new util.ErrorFactory('auth', 'Firebase', _prodErrorMap());
  326. /**
  327. * A map of potential `Auth` error codes, for easier comparison with errors
  328. * thrown by the SDK.
  329. *
  330. * @remarks
  331. * Note that you can't tree-shake individual keys
  332. * in the map, so by using the map you might substantially increase your
  333. * bundle size.
  334. *
  335. * @public
  336. */
  337. var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  338. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  339. ARGUMENT_ERROR: 'auth/argument-error',
  340. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  341. APP_NOT_INSTALLED: 'auth/app-not-installed',
  342. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  343. CODE_EXPIRED: 'auth/code-expired',
  344. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  345. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  346. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  347. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  348. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  349. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  350. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  351. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  352. EMAIL_EXISTS: 'auth/email-already-in-use',
  353. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  354. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  355. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  356. INTERNAL_ERROR: 'auth/internal-error',
  357. INVALID_API_KEY: 'auth/invalid-api-key',
  358. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  359. INVALID_APP_ID: 'auth/invalid-app-id',
  360. INVALID_AUTH: 'auth/invalid-user-token',
  361. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  362. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  363. INVALID_CODE: 'auth/invalid-verification-code',
  364. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  365. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  366. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  367. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  368. INVALID_EMAIL: 'auth/invalid-email',
  369. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  370. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  371. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  372. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  373. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  374. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  375. INVALID_OOB_CODE: 'auth/invalid-action-code',
  376. INVALID_ORIGIN: 'auth/unauthorized-domain',
  377. INVALID_PASSWORD: 'auth/wrong-password',
  378. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  379. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  380. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  381. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  382. INVALID_SENDER: 'auth/invalid-sender',
  383. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  384. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  385. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  386. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  387. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  388. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  389. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  390. MISSING_CODE: 'auth/missing-verification-code',
  391. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  392. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  393. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  394. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  395. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  396. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  397. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  398. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  399. MODULE_DESTROYED: 'auth/app-deleted',
  400. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  401. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  402. NULL_USER: 'auth/null-user',
  403. NO_AUTH_EVENT: 'auth/no-auth-event',
  404. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  405. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  406. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  407. POPUP_BLOCKED: 'auth/popup-blocked',
  408. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  409. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  410. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  411. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  412. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  413. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  414. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  415. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  416. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  417. TIMEOUT: 'auth/timeout',
  418. TOKEN_EXPIRED: 'auth/user-token-expired',
  419. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  420. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  421. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  422. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  423. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  424. UNVERIFIED_EMAIL: 'auth/unverified-email',
  425. USER_CANCELLED: 'auth/user-cancelled',
  426. USER_DELETED: 'auth/user-not-found',
  427. USER_DISABLED: 'auth/user-disabled',
  428. USER_MISMATCH: 'auth/user-mismatch',
  429. USER_SIGNED_OUT: 'auth/user-signed-out',
  430. WEAK_PASSWORD: 'auth/weak-password',
  431. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  432. ALREADY_INITIALIZED: 'auth/already-initialized',
  433. RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',
  434. MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',
  435. INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',
  436. INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',
  437. MISSING_CLIENT_TYPE: 'auth/missing-client-type',
  438. MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',
  439. INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',
  440. INVALID_REQ_TYPE: 'auth/invalid-req-type'
  441. };
  442. /**
  443. * @license
  444. * Copyright 2020 Google LLC
  445. *
  446. * Licensed under the Apache License, Version 2.0 (the "License");
  447. * you may not use this file except in compliance with the License.
  448. * You may obtain a copy of the License at
  449. *
  450. * http://www.apache.org/licenses/LICENSE-2.0
  451. *
  452. * Unless required by applicable law or agreed to in writing, software
  453. * distributed under the License is distributed on an "AS IS" BASIS,
  454. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  455. * See the License for the specific language governing permissions and
  456. * limitations under the License.
  457. */
  458. var logClient = new logger.Logger('@firebase/auth');
  459. function _logWarn(msg) {
  460. var args = [];
  461. for (var _i = 1; _i < arguments.length; _i++) {
  462. args[_i - 1] = arguments[_i];
  463. }
  464. if (logClient.logLevel <= logger.LogLevel.WARN) {
  465. logClient.warn.apply(logClient, tslib.__spreadArray(["Auth (".concat(app.SDK_VERSION, "): ").concat(msg)], args, false));
  466. }
  467. }
  468. function _logError(msg) {
  469. var args = [];
  470. for (var _i = 1; _i < arguments.length; _i++) {
  471. args[_i - 1] = arguments[_i];
  472. }
  473. if (logClient.logLevel <= logger.LogLevel.ERROR) {
  474. logClient.error.apply(logClient, tslib.__spreadArray(["Auth (".concat(app.SDK_VERSION, "): ").concat(msg)], args, false));
  475. }
  476. }
  477. /**
  478. * @license
  479. * Copyright 2020 Google LLC
  480. *
  481. * Licensed under the Apache License, Version 2.0 (the "License");
  482. * you may not use this file except in compliance with the License.
  483. * You may obtain a copy of the License at
  484. *
  485. * http://www.apache.org/licenses/LICENSE-2.0
  486. *
  487. * Unless required by applicable law or agreed to in writing, software
  488. * distributed under the License is distributed on an "AS IS" BASIS,
  489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  490. * See the License for the specific language governing permissions and
  491. * limitations under the License.
  492. */
  493. function _fail(authOrCode) {
  494. var rest = [];
  495. for (var _i = 1; _i < arguments.length; _i++) {
  496. rest[_i - 1] = arguments[_i];
  497. }
  498. throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  499. }
  500. function _createError(authOrCode) {
  501. var rest = [];
  502. for (var _i = 1; _i < arguments.length; _i++) {
  503. rest[_i - 1] = arguments[_i];
  504. }
  505. return createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  506. }
  507. function _errorWithCustomMessage(auth, code, message) {
  508. var _a;
  509. var errorMap = tslib.__assign(tslib.__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
  510. var factory = new util.ErrorFactory('auth', 'Firebase', errorMap);
  511. return factory.create(code, {
  512. appName: auth.name
  513. });
  514. }
  515. function createErrorInternal(authOrCode) {
  516. var _a;
  517. var rest = [];
  518. for (var _i = 1; _i < arguments.length; _i++) {
  519. rest[_i - 1] = arguments[_i];
  520. }
  521. if (typeof authOrCode !== 'string') {
  522. var code = rest[0];
  523. var fullParams = tslib.__spreadArray([], rest.slice(1), true);
  524. if (fullParams[0]) {
  525. fullParams[0].appName = authOrCode.name;
  526. }
  527. return (_a = authOrCode._errorFactory).create.apply(_a, tslib.__spreadArray([code], fullParams, false));
  528. }
  529. return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, tslib.__spreadArray([authOrCode], rest, false));
  530. }
  531. function _assert(assertion, authOrCode) {
  532. var rest = [];
  533. for (var _i = 2; _i < arguments.length; _i++) {
  534. rest[_i - 2] = arguments[_i];
  535. }
  536. if (!assertion) {
  537. throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  538. }
  539. }
  540. /**
  541. * Unconditionally fails, throwing an internal error with the given message.
  542. *
  543. * @param failure type of failure encountered
  544. * @throws Error
  545. */
  546. function debugFail(failure) {
  547. // Log the failure in addition to throw an exception, just in case the
  548. // exception is swallowed.
  549. var message = "INTERNAL ASSERTION FAILED: " + failure;
  550. _logError(message);
  551. // NOTE: We don't use FirebaseError here because these are internal failures
  552. // that cannot be handled by the user. (Also it would create a circular
  553. // dependency between the error and assert modules which doesn't work.)
  554. throw new Error(message);
  555. }
  556. /**
  557. * Fails if the given assertion condition is false, throwing an Error with the
  558. * given message if it did.
  559. *
  560. * @param assertion
  561. * @param message
  562. */
  563. function debugAssert(assertion, message) {
  564. if (!assertion) {
  565. debugFail(message);
  566. }
  567. }
  568. /**
  569. * @license
  570. * Copyright 2020 Google LLC
  571. *
  572. * Licensed under the Apache License, Version 2.0 (the "License");
  573. * you may not use this file except in compliance with the License.
  574. * You may obtain a copy of the License at
  575. *
  576. * http://www.apache.org/licenses/LICENSE-2.0
  577. *
  578. * Unless required by applicable law or agreed to in writing, software
  579. * distributed under the License is distributed on an "AS IS" BASIS,
  580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  581. * See the License for the specific language governing permissions and
  582. * limitations under the License.
  583. */
  584. function _getCurrentUrl() {
  585. var _a;
  586. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  587. }
  588. function _isHttpOrHttps() {
  589. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  590. }
  591. function _getCurrentScheme() {
  592. var _a;
  593. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  594. }
  595. /**
  596. * @license
  597. * Copyright 2020 Google LLC
  598. *
  599. * Licensed under the Apache License, Version 2.0 (the "License");
  600. * you may not use this file except in compliance with the License.
  601. * You may obtain a copy of the License at
  602. *
  603. * http://www.apache.org/licenses/LICENSE-2.0
  604. *
  605. * Unless required by applicable law or agreed to in writing, software
  606. * distributed under the License is distributed on an "AS IS" BASIS,
  607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  608. * See the License for the specific language governing permissions and
  609. * limitations under the License.
  610. */
  611. /**
  612. * Determine whether the browser is working online
  613. */
  614. function _isOnline() {
  615. if (typeof navigator !== 'undefined' &&
  616. navigator &&
  617. 'onLine' in navigator &&
  618. typeof navigator.onLine === 'boolean' &&
  619. // Apply only for traditional web apps and Chrome extensions.
  620. // This is especially true for Cordova apps which have unreliable
  621. // navigator.onLine behavior unless cordova-plugin-network-information is
  622. // installed which overwrites the native navigator.onLine value and
  623. // defines navigator.connection.
  624. (_isHttpOrHttps() || util.isBrowserExtension() || 'connection' in navigator)) {
  625. return navigator.onLine;
  626. }
  627. // If we can't determine the state, assume it is online.
  628. return true;
  629. }
  630. function _getUserLanguage() {
  631. if (typeof navigator === 'undefined') {
  632. return null;
  633. }
  634. var navigatorLanguage = navigator;
  635. return (
  636. // Most reliable, but only supported in Chrome/Firefox.
  637. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  638. // Supported in most browsers, but returns the language of the browser
  639. // UI, not the language set in browser settings.
  640. navigatorLanguage.language ||
  641. // Couldn't determine language.
  642. null);
  643. }
  644. /**
  645. * @license
  646. * Copyright 2020 Google LLC
  647. *
  648. * Licensed under the Apache License, Version 2.0 (the "License");
  649. * you may not use this file except in compliance with the License.
  650. * You may obtain a copy of the License at
  651. *
  652. * http://www.apache.org/licenses/LICENSE-2.0
  653. *
  654. * Unless required by applicable law or agreed to in writing, software
  655. * distributed under the License is distributed on an "AS IS" BASIS,
  656. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  657. * See the License for the specific language governing permissions and
  658. * limitations under the License.
  659. */
  660. /**
  661. * A structure to help pick between a range of long and short delay durations
  662. * depending on the current environment. In general, the long delay is used for
  663. * mobile environments whereas short delays are used for desktop environments.
  664. */
  665. var Delay = /** @class */ (function () {
  666. function Delay(shortDelay, longDelay) {
  667. this.shortDelay = shortDelay;
  668. this.longDelay = longDelay;
  669. // Internal error when improperly initialized.
  670. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  671. this.isMobile = util.isMobileCordova() || util.isReactNative();
  672. }
  673. Delay.prototype.get = function () {
  674. if (!_isOnline()) {
  675. // Pick the shorter timeout.
  676. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  677. }
  678. // If running in a mobile environment, return the long delay, otherwise
  679. // return the short delay.
  680. // This could be improved in the future to dynamically change based on other
  681. // variables instead of just reading the current environment.
  682. return this.isMobile ? this.longDelay : this.shortDelay;
  683. };
  684. return Delay;
  685. }());
  686. /**
  687. * @license
  688. * Copyright 2020 Google LLC
  689. *
  690. * Licensed under the Apache License, Version 2.0 (the "License");
  691. * you may not use this file except in compliance with the License.
  692. * You may obtain a copy of the License at
  693. *
  694. * http://www.apache.org/licenses/LICENSE-2.0
  695. *
  696. * Unless required by applicable law or agreed to in writing, software
  697. * distributed under the License is distributed on an "AS IS" BASIS,
  698. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  699. * See the License for the specific language governing permissions and
  700. * limitations under the License.
  701. */
  702. function _emulatorUrl(config, path) {
  703. debugAssert(config.emulator, 'Emulator should always be set here');
  704. var url = config.emulator.url;
  705. if (!path) {
  706. return url;
  707. }
  708. return "".concat(url).concat(path.startsWith('/') ? path.slice(1) : path);
  709. }
  710. /**
  711. * @license
  712. * Copyright 2020 Google LLC
  713. *
  714. * Licensed under the Apache License, Version 2.0 (the "License");
  715. * you may not use this file except in compliance with the License.
  716. * You may obtain a copy of the License at
  717. *
  718. * http://www.apache.org/licenses/LICENSE-2.0
  719. *
  720. * Unless required by applicable law or agreed to in writing, software
  721. * distributed under the License is distributed on an "AS IS" BASIS,
  722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  723. * See the License for the specific language governing permissions and
  724. * limitations under the License.
  725. */
  726. var FetchProvider = /** @class */ (function () {
  727. function FetchProvider() {
  728. }
  729. FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
  730. this.fetchImpl = fetchImpl;
  731. if (headersImpl) {
  732. this.headersImpl = headersImpl;
  733. }
  734. if (responseImpl) {
  735. this.responseImpl = responseImpl;
  736. }
  737. };
  738. FetchProvider.fetch = function () {
  739. if (this.fetchImpl) {
  740. return this.fetchImpl;
  741. }
  742. if (typeof self !== 'undefined' && 'fetch' in self) {
  743. return self.fetch;
  744. }
  745. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  746. };
  747. FetchProvider.headers = function () {
  748. if (this.headersImpl) {
  749. return this.headersImpl;
  750. }
  751. if (typeof self !== 'undefined' && 'Headers' in self) {
  752. return self.Headers;
  753. }
  754. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  755. };
  756. FetchProvider.response = function () {
  757. if (this.responseImpl) {
  758. return this.responseImpl;
  759. }
  760. if (typeof self !== 'undefined' && 'Response' in self) {
  761. return self.Response;
  762. }
  763. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  764. };
  765. return FetchProvider;
  766. }());
  767. /**
  768. * @license
  769. * Copyright 2020 Google LLC
  770. *
  771. * Licensed under the Apache License, Version 2.0 (the "License");
  772. * you may not use this file except in compliance with the License.
  773. * You may obtain a copy of the License at
  774. *
  775. * http://www.apache.org/licenses/LICENSE-2.0
  776. *
  777. * Unless required by applicable law or agreed to in writing, software
  778. * distributed under the License is distributed on an "AS IS" BASIS,
  779. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  780. * See the License for the specific language governing permissions and
  781. * limitations under the License.
  782. */
  783. var _a$1;
  784. /**
  785. * Map from errors returned by the server to errors to developer visible errors
  786. */
  787. var SERVER_ERROR_MAP = (_a$1 = {},
  788. // Custom token errors.
  789. _a$1["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  790. // This can only happen if the SDK sends a bad request.
  791. _a$1["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  792. // Create Auth URI errors.
  793. _a$1["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */] = "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  794. // This can only happen if the SDK sends a bad request.
  795. _a$1["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  796. // Sign in with email and password errors (some apply to sign up too).
  797. _a$1["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */] = "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  798. // This can only happen if the SDK sends a bad request.
  799. _a$1["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */] = "missing-password" /* AuthErrorCode.MISSING_PASSWORD */,
  800. // Sign up with email and password errors.
  801. _a$1["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */] = "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  802. _a$1["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  803. // Verify assertion for sign in with credential errors:
  804. _a$1["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  805. _a$1["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  806. _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  807. // This can only happen if the SDK sends a bad request.
  808. _a$1["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  809. // Send Password reset email errors:
  810. _a$1["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  811. _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  812. _a$1["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */] = "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  813. _a$1["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */] = "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  814. // This can only happen if the SDK sends a bad request.
  815. _a$1["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  816. // Operations that require ID token in request:
  817. _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  818. _a$1["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */] = "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  819. _a$1["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  820. _a$1["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  821. // Other errors.
  822. _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  823. // Phone Auth related errors.
  824. _a$1["INVALID_CODE" /* ServerError.INVALID_CODE */] = "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  825. _a$1["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */] = "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  826. _a$1["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  827. _a$1["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */] = "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  828. _a$1["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */] = "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  829. // Other action code errors when additional settings passed.
  830. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  831. // This is OK as this error will be caught by client side validation.
  832. _a$1["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  833. _a$1["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  834. // getProjectConfig errors when clientId is passed.
  835. _a$1["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  836. // User actions (sign-up or deletion) disabled errors.
  837. _a$1["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  838. // Multi factor related errors.
  839. _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  840. _a$1["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  841. _a$1["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  842. _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  843. _a$1["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  844. _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  845. // Blocking functions related errors.
  846. _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  847. // Recaptcha related errors.
  848. _a$1["RECAPTCHA_NOT_ENABLED" /* ServerError.RECAPTCHA_NOT_ENABLED */] = "recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,
  849. _a$1["MISSING_RECAPTCHA_TOKEN" /* ServerError.MISSING_RECAPTCHA_TOKEN */] = "missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,
  850. _a$1["INVALID_RECAPTCHA_TOKEN" /* ServerError.INVALID_RECAPTCHA_TOKEN */] = "invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,
  851. _a$1["INVALID_RECAPTCHA_ACTION" /* ServerError.INVALID_RECAPTCHA_ACTION */] = "invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,
  852. _a$1["MISSING_CLIENT_TYPE" /* ServerError.MISSING_CLIENT_TYPE */] = "missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */,
  853. _a$1["MISSING_RECAPTCHA_VERSION" /* ServerError.MISSING_RECAPTCHA_VERSION */] = "missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,
  854. _a$1["INVALID_RECAPTCHA_VERSION" /* ServerError.INVALID_RECAPTCHA_VERSION */] = "invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,
  855. _a$1["INVALID_REQ_TYPE" /* ServerError.INVALID_REQ_TYPE */] = "invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */,
  856. _a$1);
  857. /**
  858. * @license
  859. * Copyright 2020 Google LLC
  860. *
  861. * Licensed under the Apache License, Version 2.0 (the "License");
  862. * you may not use this file except in compliance with the License.
  863. * You may obtain a copy of the License at
  864. *
  865. * http://www.apache.org/licenses/LICENSE-2.0
  866. *
  867. * Unless required by applicable law or agreed to in writing, software
  868. * distributed under the License is distributed on an "AS IS" BASIS,
  869. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  870. * See the License for the specific language governing permissions and
  871. * limitations under the License.
  872. */
  873. var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  874. function _addTidIfNecessary(auth, request) {
  875. if (auth.tenantId && !request.tenantId) {
  876. return tslib.__assign(tslib.__assign({}, request), { tenantId: auth.tenantId });
  877. }
  878. return request;
  879. }
  880. function _performApiRequest(auth, method, path, request, customErrorMap) {
  881. if (customErrorMap === void 0) { customErrorMap = {}; }
  882. return tslib.__awaiter(this, void 0, void 0, function () {
  883. var _this = this;
  884. return tslib.__generator(this, function (_a) {
  885. return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  886. var body, params, query, headers;
  887. return tslib.__generator(this, function (_a) {
  888. switch (_a.label) {
  889. case 0:
  890. body = {};
  891. params = {};
  892. if (request) {
  893. if (method === "GET" /* HttpMethod.GET */) {
  894. params = request;
  895. }
  896. else {
  897. body = {
  898. body: JSON.stringify(request)
  899. };
  900. }
  901. }
  902. query = util.querystring(tslib.__assign({ key: auth.config.apiKey }, params)).slice(1);
  903. return [4 /*yield*/, auth._getAdditionalHeaders()];
  904. case 1:
  905. headers = _a.sent();
  906. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  907. if (auth.languageCode) {
  908. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  909. }
  910. return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), tslib.__assign({ method: method, headers: headers, referrerPolicy: 'no-referrer' }, body))];
  911. }
  912. });
  913. }); })];
  914. });
  915. });
  916. }
  917. function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  918. return tslib.__awaiter(this, void 0, void 0, function () {
  919. var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
  920. return tslib.__generator(this, function (_b) {
  921. switch (_b.label) {
  922. case 0:
  923. auth._canInitEmulator = false;
  924. errorMap = tslib.__assign(tslib.__assign({}, SERVER_ERROR_MAP), customErrorMap);
  925. _b.label = 1;
  926. case 1:
  927. _b.trys.push([1, 4, , 5]);
  928. networkTimeout = new NetworkTimeout(auth);
  929. return [4 /*yield*/, Promise.race([
  930. fetchFn(),
  931. networkTimeout.promise
  932. ])];
  933. case 2:
  934. response = _b.sent();
  935. // If we've reached this point, the fetch succeeded and the networkTimeout
  936. // didn't throw; clear the network timeout delay so that Node won't hang
  937. networkTimeout.clearNetworkTimeout();
  938. return [4 /*yield*/, response.json()];
  939. case 3:
  940. json = _b.sent();
  941. if ('needConfirmation' in json) {
  942. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  943. }
  944. if (response.ok && !('errorMessage' in json)) {
  945. return [2 /*return*/, json];
  946. }
  947. else {
  948. errorMessage = response.ok ? json.errorMessage : json.error.message;
  949. _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
  950. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  951. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  952. }
  953. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  954. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  955. }
  956. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  957. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  958. }
  959. authError = errorMap[serverErrorCode] ||
  960. serverErrorCode
  961. .toLowerCase()
  962. .replace(/[_\s]+/g, '-');
  963. if (serverErrorMessage) {
  964. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  965. }
  966. else {
  967. _fail(auth, authError);
  968. }
  969. }
  970. return [3 /*break*/, 5];
  971. case 4:
  972. e_1 = _b.sent();
  973. if (e_1 instanceof util.FirebaseError) {
  974. throw e_1;
  975. }
  976. // Changing this to a different error code will log user out when there is a network error
  977. // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.
  978. // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316
  979. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e_1) });
  980. return [3 /*break*/, 5];
  981. case 5: return [2 /*return*/];
  982. }
  983. });
  984. });
  985. }
  986. function _performSignInRequest(auth, method, path, request, customErrorMap) {
  987. if (customErrorMap === void 0) { customErrorMap = {}; }
  988. return tslib.__awaiter(this, void 0, void 0, function () {
  989. var serverResponse;
  990. return tslib.__generator(this, function (_a) {
  991. switch (_a.label) {
  992. case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
  993. case 1:
  994. serverResponse = (_a.sent());
  995. if ('mfaPendingCredential' in serverResponse) {
  996. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  997. _serverResponse: serverResponse
  998. });
  999. }
  1000. return [2 /*return*/, serverResponse];
  1001. }
  1002. });
  1003. });
  1004. }
  1005. function _getFinalTarget(auth, host, path, query) {
  1006. var base = "".concat(host).concat(path, "?").concat(query);
  1007. if (!auth.config.emulator) {
  1008. return "".concat(auth.config.apiScheme, "://").concat(base);
  1009. }
  1010. return _emulatorUrl(auth.config, base);
  1011. }
  1012. var NetworkTimeout = /** @class */ (function () {
  1013. function NetworkTimeout(auth) {
  1014. var _this = this;
  1015. this.auth = auth;
  1016. // Node timers and browser timers are fundamentally incompatible, but we
  1017. // don't care about the value here
  1018. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1019. this.timer = null;
  1020. this.promise = new Promise(function (_, reject) {
  1021. _this.timer = setTimeout(function () {
  1022. return reject(_createError(_this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1023. }, DEFAULT_API_TIMEOUT_MS.get());
  1024. });
  1025. }
  1026. NetworkTimeout.prototype.clearNetworkTimeout = function () {
  1027. clearTimeout(this.timer);
  1028. };
  1029. return NetworkTimeout;
  1030. }());
  1031. function _makeTaggedError(auth, code, response) {
  1032. var errorParams = {
  1033. appName: auth.name
  1034. };
  1035. if (response.email) {
  1036. errorParams.email = response.email;
  1037. }
  1038. if (response.phoneNumber) {
  1039. errorParams.phoneNumber = response.phoneNumber;
  1040. }
  1041. var error = _createError(auth, code, errorParams);
  1042. // We know customData is defined on error because errorParams is defined
  1043. error.customData._tokenResponse = response;
  1044. return error;
  1045. }
  1046. /**
  1047. * @license
  1048. * Copyright 2020 Google LLC
  1049. *
  1050. * Licensed under the Apache License, Version 2.0 (the "License");
  1051. * you may not use this file except in compliance with the License.
  1052. * You may obtain a copy of the License at
  1053. *
  1054. * http://www.apache.org/licenses/LICENSE-2.0
  1055. *
  1056. * Unless required by applicable law or agreed to in writing, software
  1057. * distributed under the License is distributed on an "AS IS" BASIS,
  1058. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1059. * See the License for the specific language governing permissions and
  1060. * limitations under the License.
  1061. */
  1062. function deleteAccount(auth, request) {
  1063. return tslib.__awaiter(this, void 0, void 0, function () {
  1064. return tslib.__generator(this, function (_a) {
  1065. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request)];
  1066. });
  1067. });
  1068. }
  1069. function deleteLinkedAccounts(auth, request) {
  1070. return tslib.__awaiter(this, void 0, void 0, function () {
  1071. return tslib.__generator(this, function (_a) {
  1072. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  1073. });
  1074. });
  1075. }
  1076. function getAccountInfo(auth, request) {
  1077. return tslib.__awaiter(this, void 0, void 0, function () {
  1078. return tslib.__generator(this, function (_a) {
  1079. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request)];
  1080. });
  1081. });
  1082. }
  1083. /**
  1084. * @license
  1085. * Copyright 2020 Google LLC
  1086. *
  1087. * Licensed under the Apache License, Version 2.0 (the "License");
  1088. * you may not use this file except in compliance with the License.
  1089. * You may obtain a copy of the License at
  1090. *
  1091. * http://www.apache.org/licenses/LICENSE-2.0
  1092. *
  1093. * Unless required by applicable law or agreed to in writing, software
  1094. * distributed under the License is distributed on an "AS IS" BASIS,
  1095. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1096. * See the License for the specific language governing permissions and
  1097. * limitations under the License.
  1098. */
  1099. function utcTimestampToDateString(utcTimestamp) {
  1100. if (!utcTimestamp) {
  1101. return undefined;
  1102. }
  1103. try {
  1104. // Convert to date object.
  1105. var date = new Date(Number(utcTimestamp));
  1106. // Test date is valid.
  1107. if (!isNaN(date.getTime())) {
  1108. // Convert to UTC date string.
  1109. return date.toUTCString();
  1110. }
  1111. }
  1112. catch (e) {
  1113. // Do nothing. undefined will be returned.
  1114. }
  1115. return undefined;
  1116. }
  1117. /**
  1118. * @license
  1119. * Copyright 2020 Google LLC
  1120. *
  1121. * Licensed under the Apache License, Version 2.0 (the "License");
  1122. * you may not use this file except in compliance with the License.
  1123. * You may obtain a copy of the License at
  1124. *
  1125. * http://www.apache.org/licenses/LICENSE-2.0
  1126. *
  1127. * Unless required by applicable law or agreed to in writing, software
  1128. * distributed under the License is distributed on an "AS IS" BASIS,
  1129. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1130. * See the License for the specific language governing permissions and
  1131. * limitations under the License.
  1132. */
  1133. /**
  1134. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1135. *
  1136. * @remarks
  1137. * Returns the current token if it has not expired or if it will not expire in the next five
  1138. * minutes. Otherwise, this will refresh the token and return a new one.
  1139. *
  1140. * @param user - The user.
  1141. * @param forceRefresh - Force refresh regardless of token expiration.
  1142. *
  1143. * @public
  1144. */
  1145. function getIdToken(user, forceRefresh) {
  1146. if (forceRefresh === void 0) { forceRefresh = false; }
  1147. return util.getModularInstance(user).getIdToken(forceRefresh);
  1148. }
  1149. /**
  1150. * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
  1151. *
  1152. * @remarks
  1153. * Returns the current token if it has not expired or if it will not expire in the next five
  1154. * minutes. Otherwise, this will refresh the token and return a new one.
  1155. *
  1156. * @param user - The user.
  1157. * @param forceRefresh - Force refresh regardless of token expiration.
  1158. *
  1159. * @public
  1160. */
  1161. function getIdTokenResult(user, forceRefresh) {
  1162. if (forceRefresh === void 0) { forceRefresh = false; }
  1163. return tslib.__awaiter(this, void 0, void 0, function () {
  1164. var userInternal, token, claims, firebase, signInProvider;
  1165. return tslib.__generator(this, function (_a) {
  1166. switch (_a.label) {
  1167. case 0:
  1168. userInternal = util.getModularInstance(user);
  1169. return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
  1170. case 1:
  1171. token = _a.sent();
  1172. claims = _parseToken(token);
  1173. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1174. firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1175. signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1176. return [2 /*return*/, {
  1177. claims: claims,
  1178. token: token,
  1179. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1180. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1181. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1182. signInProvider: signInProvider || null,
  1183. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1184. }];
  1185. }
  1186. });
  1187. });
  1188. }
  1189. function secondsStringToMilliseconds(seconds) {
  1190. return Number(seconds) * 1000;
  1191. }
  1192. function _parseToken(token) {
  1193. var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
  1194. if (algorithm === undefined ||
  1195. payload === undefined ||
  1196. signature === undefined) {
  1197. _logError('JWT malformed, contained fewer than 3 sections');
  1198. return null;
  1199. }
  1200. try {
  1201. var decoded = util.base64Decode(payload);
  1202. if (!decoded) {
  1203. _logError('Failed to decode base64 JWT payload');
  1204. return null;
  1205. }
  1206. return JSON.parse(decoded);
  1207. }
  1208. catch (e) {
  1209. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1210. return null;
  1211. }
  1212. }
  1213. /**
  1214. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1215. */
  1216. function _tokenExpiresIn(token) {
  1217. var parsedToken = _parseToken(token);
  1218. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1219. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1220. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1221. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1222. }
  1223. /**
  1224. * @license
  1225. * Copyright 2020 Google LLC
  1226. *
  1227. * Licensed under the Apache License, Version 2.0 (the "License");
  1228. * you may not use this file except in compliance with the License.
  1229. * You may obtain a copy of the License at
  1230. *
  1231. * http://www.apache.org/licenses/LICENSE-2.0
  1232. *
  1233. * Unless required by applicable law or agreed to in writing, software
  1234. * distributed under the License is distributed on an "AS IS" BASIS,
  1235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1236. * See the License for the specific language governing permissions and
  1237. * limitations under the License.
  1238. */
  1239. function _logoutIfInvalidated(user, promise, bypassAuthState) {
  1240. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1241. return tslib.__awaiter(this, void 0, void 0, function () {
  1242. var e_1;
  1243. return tslib.__generator(this, function (_a) {
  1244. switch (_a.label) {
  1245. case 0:
  1246. if (bypassAuthState) {
  1247. return [2 /*return*/, promise];
  1248. }
  1249. _a.label = 1;
  1250. case 1:
  1251. _a.trys.push([1, 3, , 6]);
  1252. return [4 /*yield*/, promise];
  1253. case 2: return [2 /*return*/, _a.sent()];
  1254. case 3:
  1255. e_1 = _a.sent();
  1256. if (!(e_1 instanceof util.FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
  1257. if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
  1258. return [4 /*yield*/, user.auth.signOut()];
  1259. case 4:
  1260. _a.sent();
  1261. _a.label = 5;
  1262. case 5: throw e_1;
  1263. case 6: return [2 /*return*/];
  1264. }
  1265. });
  1266. });
  1267. }
  1268. function isUserInvalidated(_a) {
  1269. var code = _a.code;
  1270. return (code === "auth/".concat("user-disabled" /* AuthErrorCode.USER_DISABLED */) ||
  1271. code === "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */));
  1272. }
  1273. /**
  1274. * @license
  1275. * Copyright 2020 Google LLC
  1276. *
  1277. * Licensed under the Apache License, Version 2.0 (the "License");
  1278. * you may not use this file except in compliance with the License.
  1279. * You may obtain a copy of the License at
  1280. *
  1281. * http://www.apache.org/licenses/LICENSE-2.0
  1282. *
  1283. * Unless required by applicable law or agreed to in writing, software
  1284. * distributed under the License is distributed on an "AS IS" BASIS,
  1285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1286. * See the License for the specific language governing permissions and
  1287. * limitations under the License.
  1288. */
  1289. var ProactiveRefresh = /** @class */ (function () {
  1290. function ProactiveRefresh(user) {
  1291. this.user = user;
  1292. this.isRunning = false;
  1293. // Node timers and browser timers return fundamentally different types.
  1294. // We don't actually care what the value is but TS won't accept unknown and
  1295. // we can't cast properly in both environments.
  1296. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1297. this.timerId = null;
  1298. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1299. }
  1300. ProactiveRefresh.prototype._start = function () {
  1301. if (this.isRunning) {
  1302. return;
  1303. }
  1304. this.isRunning = true;
  1305. this.schedule();
  1306. };
  1307. ProactiveRefresh.prototype._stop = function () {
  1308. if (!this.isRunning) {
  1309. return;
  1310. }
  1311. this.isRunning = false;
  1312. if (this.timerId !== null) {
  1313. clearTimeout(this.timerId);
  1314. }
  1315. };
  1316. ProactiveRefresh.prototype.getInterval = function (wasError) {
  1317. var _a;
  1318. if (wasError) {
  1319. var interval = this.errorBackoff;
  1320. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1321. return interval;
  1322. }
  1323. else {
  1324. // Reset the error backoff
  1325. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1326. var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1327. var interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1328. return Math.max(0, interval);
  1329. }
  1330. };
  1331. ProactiveRefresh.prototype.schedule = function (wasError) {
  1332. var _this = this;
  1333. if (wasError === void 0) { wasError = false; }
  1334. if (!this.isRunning) {
  1335. // Just in case...
  1336. return;
  1337. }
  1338. var interval = this.getInterval(wasError);
  1339. this.timerId = setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1340. return tslib.__generator(this, function (_a) {
  1341. switch (_a.label) {
  1342. case 0: return [4 /*yield*/, this.iteration()];
  1343. case 1:
  1344. _a.sent();
  1345. return [2 /*return*/];
  1346. }
  1347. });
  1348. }); }, interval);
  1349. };
  1350. ProactiveRefresh.prototype.iteration = function () {
  1351. return tslib.__awaiter(this, void 0, void 0, function () {
  1352. var e_1;
  1353. return tslib.__generator(this, function (_a) {
  1354. switch (_a.label) {
  1355. case 0:
  1356. _a.trys.push([0, 2, , 3]);
  1357. return [4 /*yield*/, this.user.getIdToken(true)];
  1358. case 1:
  1359. _a.sent();
  1360. return [3 /*break*/, 3];
  1361. case 2:
  1362. e_1 = _a.sent();
  1363. // Only retry on network errors
  1364. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) ===
  1365. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  1366. this.schedule(/* wasError */ true);
  1367. }
  1368. return [2 /*return*/];
  1369. case 3:
  1370. this.schedule();
  1371. return [2 /*return*/];
  1372. }
  1373. });
  1374. });
  1375. };
  1376. return ProactiveRefresh;
  1377. }());
  1378. /**
  1379. * @license
  1380. * Copyright 2020 Google LLC
  1381. *
  1382. * Licensed under the Apache License, Version 2.0 (the "License");
  1383. * you may not use this file except in compliance with the License.
  1384. * You may obtain a copy of the License at
  1385. *
  1386. * http://www.apache.org/licenses/LICENSE-2.0
  1387. *
  1388. * Unless required by applicable law or agreed to in writing, software
  1389. * distributed under the License is distributed on an "AS IS" BASIS,
  1390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1391. * See the License for the specific language governing permissions and
  1392. * limitations under the License.
  1393. */
  1394. var UserMetadata = /** @class */ (function () {
  1395. function UserMetadata(createdAt, lastLoginAt) {
  1396. this.createdAt = createdAt;
  1397. this.lastLoginAt = lastLoginAt;
  1398. this._initializeTime();
  1399. }
  1400. UserMetadata.prototype._initializeTime = function () {
  1401. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1402. this.creationTime = utcTimestampToDateString(this.createdAt);
  1403. };
  1404. UserMetadata.prototype._copy = function (metadata) {
  1405. this.createdAt = metadata.createdAt;
  1406. this.lastLoginAt = metadata.lastLoginAt;
  1407. this._initializeTime();
  1408. };
  1409. UserMetadata.prototype.toJSON = function () {
  1410. return {
  1411. createdAt: this.createdAt,
  1412. lastLoginAt: this.lastLoginAt
  1413. };
  1414. };
  1415. return UserMetadata;
  1416. }());
  1417. /**
  1418. * @license
  1419. * Copyright 2019 Google LLC
  1420. *
  1421. * Licensed under the Apache License, Version 2.0 (the "License");
  1422. * you may not use this file except in compliance with the License.
  1423. * You may obtain a copy of the License at
  1424. *
  1425. * http://www.apache.org/licenses/LICENSE-2.0
  1426. *
  1427. * Unless required by applicable law or agreed to in writing, software
  1428. * distributed under the License is distributed on an "AS IS" BASIS,
  1429. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1430. * See the License for the specific language governing permissions and
  1431. * limitations under the License.
  1432. */
  1433. function _reloadWithoutSaving(user) {
  1434. var _a;
  1435. return tslib.__awaiter(this, void 0, void 0, function () {
  1436. var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
  1437. return tslib.__generator(this, function (_b) {
  1438. switch (_b.label) {
  1439. case 0:
  1440. auth = user.auth;
  1441. return [4 /*yield*/, user.getIdToken()];
  1442. case 1:
  1443. idToken = _b.sent();
  1444. return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
  1445. case 2:
  1446. response = _b.sent();
  1447. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1448. coreAccount = response.users[0];
  1449. user._notifyReloadListener(coreAccount);
  1450. newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1451. ? extractProviderData(coreAccount.providerUserInfo)
  1452. : [];
  1453. providerData = mergeProviderData(user.providerData, newProviderData);
  1454. oldIsAnonymous = user.isAnonymous;
  1455. newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1456. isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1457. updates = {
  1458. uid: coreAccount.localId,
  1459. displayName: coreAccount.displayName || null,
  1460. photoURL: coreAccount.photoUrl || null,
  1461. email: coreAccount.email || null,
  1462. emailVerified: coreAccount.emailVerified || false,
  1463. phoneNumber: coreAccount.phoneNumber || null,
  1464. tenantId: coreAccount.tenantId || null,
  1465. providerData: providerData,
  1466. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1467. isAnonymous: isAnonymous
  1468. };
  1469. Object.assign(user, updates);
  1470. return [2 /*return*/];
  1471. }
  1472. });
  1473. });
  1474. }
  1475. /**
  1476. * Reloads user account data, if signed in.
  1477. *
  1478. * @param user - The user.
  1479. *
  1480. * @public
  1481. */
  1482. function reload(user) {
  1483. return tslib.__awaiter(this, void 0, void 0, function () {
  1484. var userInternal;
  1485. return tslib.__generator(this, function (_a) {
  1486. switch (_a.label) {
  1487. case 0:
  1488. userInternal = util.getModularInstance(user);
  1489. return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
  1490. case 1:
  1491. _a.sent();
  1492. // Even though the current user hasn't changed, update
  1493. // current user will trigger a persistence update w/ the
  1494. // new info.
  1495. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  1496. case 2:
  1497. // Even though the current user hasn't changed, update
  1498. // current user will trigger a persistence update w/ the
  1499. // new info.
  1500. _a.sent();
  1501. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1502. return [2 /*return*/];
  1503. }
  1504. });
  1505. });
  1506. }
  1507. function mergeProviderData(original, newData) {
  1508. var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
  1509. return tslib.__spreadArray(tslib.__spreadArray([], deduped, true), newData, true);
  1510. }
  1511. function extractProviderData(providers) {
  1512. return providers.map(function (_a) {
  1513. var providerId = _a.providerId, provider = tslib.__rest(_a, ["providerId"]);
  1514. return {
  1515. providerId: providerId,
  1516. uid: provider.rawId || '',
  1517. displayName: provider.displayName || null,
  1518. email: provider.email || null,
  1519. phoneNumber: provider.phoneNumber || null,
  1520. photoURL: provider.photoUrl || null
  1521. };
  1522. });
  1523. }
  1524. /**
  1525. * @license
  1526. * Copyright 2020 Google LLC
  1527. *
  1528. * Licensed under the Apache License, Version 2.0 (the "License");
  1529. * you may not use this file except in compliance with the License.
  1530. * You may obtain a copy of the License at
  1531. *
  1532. * http://www.apache.org/licenses/LICENSE-2.0
  1533. *
  1534. * Unless required by applicable law or agreed to in writing, software
  1535. * distributed under the License is distributed on an "AS IS" BASIS,
  1536. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1537. * See the License for the specific language governing permissions and
  1538. * limitations under the License.
  1539. */
  1540. function requestStsToken(auth, refreshToken) {
  1541. return tslib.__awaiter(this, void 0, void 0, function () {
  1542. var response;
  1543. var _this = this;
  1544. return tslib.__generator(this, function (_a) {
  1545. switch (_a.label) {
  1546. case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1547. var body, _a, tokenApiHost, apiKey, url, headers;
  1548. return tslib.__generator(this, function (_b) {
  1549. switch (_b.label) {
  1550. case 0:
  1551. body = util.querystring({
  1552. 'grant_type': 'refresh_token',
  1553. 'refresh_token': refreshToken
  1554. }).slice(1);
  1555. _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
  1556. url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, "key=".concat(apiKey));
  1557. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1558. case 1:
  1559. headers = _b.sent();
  1560. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1561. return [2 /*return*/, FetchProvider.fetch()(url, {
  1562. method: "POST" /* HttpMethod.POST */,
  1563. headers: headers,
  1564. body: body
  1565. })];
  1566. }
  1567. });
  1568. }); })];
  1569. case 1:
  1570. response = _a.sent();
  1571. // The response comes back in snake_case. Convert to camel:
  1572. return [2 /*return*/, {
  1573. accessToken: response.access_token,
  1574. expiresIn: response.expires_in,
  1575. refreshToken: response.refresh_token
  1576. }];
  1577. }
  1578. });
  1579. });
  1580. }
  1581. /**
  1582. * @license
  1583. * Copyright 2020 Google LLC
  1584. *
  1585. * Licensed under the Apache License, Version 2.0 (the "License");
  1586. * you may not use this file except in compliance with the License.
  1587. * You may obtain a copy of the License at
  1588. *
  1589. * http://www.apache.org/licenses/LICENSE-2.0
  1590. *
  1591. * Unless required by applicable law or agreed to in writing, software
  1592. * distributed under the License is distributed on an "AS IS" BASIS,
  1593. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1594. * See the License for the specific language governing permissions and
  1595. * limitations under the License.
  1596. */
  1597. /**
  1598. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1599. * it references AuthInternal which has a circular dependency with UserInternal.
  1600. *
  1601. * @internal
  1602. */
  1603. var StsTokenManager = /** @class */ (function () {
  1604. function StsTokenManager() {
  1605. this.refreshToken = null;
  1606. this.accessToken = null;
  1607. this.expirationTime = null;
  1608. }
  1609. Object.defineProperty(StsTokenManager.prototype, "isExpired", {
  1610. get: function () {
  1611. return (!this.expirationTime ||
  1612. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1613. },
  1614. enumerable: false,
  1615. configurable: true
  1616. });
  1617. StsTokenManager.prototype.updateFromServerResponse = function (response) {
  1618. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1619. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1620. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1621. var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1622. ? Number(response.expiresIn)
  1623. : _tokenExpiresIn(response.idToken);
  1624. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1625. };
  1626. StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
  1627. if (forceRefresh === void 0) { forceRefresh = false; }
  1628. return tslib.__awaiter(this, void 0, void 0, function () {
  1629. return tslib.__generator(this, function (_a) {
  1630. switch (_a.label) {
  1631. case 0:
  1632. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1633. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1634. return [2 /*return*/, this.accessToken];
  1635. }
  1636. if (!this.refreshToken) return [3 /*break*/, 2];
  1637. return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
  1638. case 1:
  1639. _a.sent();
  1640. return [2 /*return*/, this.accessToken];
  1641. case 2: return [2 /*return*/, null];
  1642. }
  1643. });
  1644. });
  1645. };
  1646. StsTokenManager.prototype.clearRefreshToken = function () {
  1647. this.refreshToken = null;
  1648. };
  1649. StsTokenManager.prototype.refresh = function (auth, oldToken) {
  1650. return tslib.__awaiter(this, void 0, void 0, function () {
  1651. var _a, accessToken, refreshToken, expiresIn;
  1652. return tslib.__generator(this, function (_b) {
  1653. switch (_b.label) {
  1654. case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
  1655. case 1:
  1656. _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
  1657. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1658. return [2 /*return*/];
  1659. }
  1660. });
  1661. });
  1662. };
  1663. StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
  1664. this.refreshToken = refreshToken || null;
  1665. this.accessToken = accessToken || null;
  1666. this.expirationTime = Date.now() + expiresInSec * 1000;
  1667. };
  1668. StsTokenManager.fromJSON = function (appName, object) {
  1669. var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
  1670. var manager = new StsTokenManager();
  1671. if (refreshToken) {
  1672. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1673. appName: appName
  1674. });
  1675. manager.refreshToken = refreshToken;
  1676. }
  1677. if (accessToken) {
  1678. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1679. appName: appName
  1680. });
  1681. manager.accessToken = accessToken;
  1682. }
  1683. if (expirationTime) {
  1684. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1685. appName: appName
  1686. });
  1687. manager.expirationTime = expirationTime;
  1688. }
  1689. return manager;
  1690. };
  1691. StsTokenManager.prototype.toJSON = function () {
  1692. return {
  1693. refreshToken: this.refreshToken,
  1694. accessToken: this.accessToken,
  1695. expirationTime: this.expirationTime
  1696. };
  1697. };
  1698. StsTokenManager.prototype._assign = function (stsTokenManager) {
  1699. this.accessToken = stsTokenManager.accessToken;
  1700. this.refreshToken = stsTokenManager.refreshToken;
  1701. this.expirationTime = stsTokenManager.expirationTime;
  1702. };
  1703. StsTokenManager.prototype._clone = function () {
  1704. return Object.assign(new StsTokenManager(), this.toJSON());
  1705. };
  1706. StsTokenManager.prototype._performRefresh = function () {
  1707. return debugFail('not implemented');
  1708. };
  1709. return StsTokenManager;
  1710. }());
  1711. /**
  1712. * @license
  1713. * Copyright 2020 Google LLC
  1714. *
  1715. * Licensed under the Apache License, Version 2.0 (the "License");
  1716. * you may not use this file except in compliance with the License.
  1717. * You may obtain a copy of the License at
  1718. *
  1719. * http://www.apache.org/licenses/LICENSE-2.0
  1720. *
  1721. * Unless required by applicable law or agreed to in writing, software
  1722. * distributed under the License is distributed on an "AS IS" BASIS,
  1723. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1724. * See the License for the specific language governing permissions and
  1725. * limitations under the License.
  1726. */
  1727. function assertStringOrUndefined(assertion, appName) {
  1728. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName: appName });
  1729. }
  1730. var UserImpl = /** @class */ (function () {
  1731. function UserImpl(_a) {
  1732. var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = tslib.__rest(_a, ["uid", "auth", "stsTokenManager"]);
  1733. // For the user object, provider is always Firebase.
  1734. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1735. this.proactiveRefresh = new ProactiveRefresh(this);
  1736. this.reloadUserInfo = null;
  1737. this.reloadListener = null;
  1738. this.uid = uid;
  1739. this.auth = auth;
  1740. this.stsTokenManager = stsTokenManager;
  1741. this.accessToken = stsTokenManager.accessToken;
  1742. this.displayName = opt.displayName || null;
  1743. this.email = opt.email || null;
  1744. this.emailVerified = opt.emailVerified || false;
  1745. this.phoneNumber = opt.phoneNumber || null;
  1746. this.photoURL = opt.photoURL || null;
  1747. this.isAnonymous = opt.isAnonymous || false;
  1748. this.tenantId = opt.tenantId || null;
  1749. this.providerData = opt.providerData ? tslib.__spreadArray([], opt.providerData, true) : [];
  1750. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1751. }
  1752. UserImpl.prototype.getIdToken = function (forceRefresh) {
  1753. return tslib.__awaiter(this, void 0, void 0, function () {
  1754. var accessToken;
  1755. return tslib.__generator(this, function (_a) {
  1756. switch (_a.label) {
  1757. case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
  1758. case 1:
  1759. accessToken = _a.sent();
  1760. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1761. if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
  1762. this.accessToken = accessToken;
  1763. return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1764. case 2:
  1765. _a.sent();
  1766. this.auth._notifyListenersIfCurrent(this);
  1767. _a.label = 3;
  1768. case 3: return [2 /*return*/, accessToken];
  1769. }
  1770. });
  1771. });
  1772. };
  1773. UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
  1774. return getIdTokenResult(this, forceRefresh);
  1775. };
  1776. UserImpl.prototype.reload = function () {
  1777. return reload(this);
  1778. };
  1779. UserImpl.prototype._assign = function (user) {
  1780. if (this === user) {
  1781. return;
  1782. }
  1783. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1784. this.displayName = user.displayName;
  1785. this.photoURL = user.photoURL;
  1786. this.email = user.email;
  1787. this.emailVerified = user.emailVerified;
  1788. this.phoneNumber = user.phoneNumber;
  1789. this.isAnonymous = user.isAnonymous;
  1790. this.tenantId = user.tenantId;
  1791. this.providerData = user.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
  1792. this.metadata._copy(user.metadata);
  1793. this.stsTokenManager._assign(user.stsTokenManager);
  1794. };
  1795. UserImpl.prototype._clone = function (auth) {
  1796. var newUser = new UserImpl(tslib.__assign(tslib.__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
  1797. newUser.metadata._copy(this.metadata);
  1798. return newUser;
  1799. };
  1800. UserImpl.prototype._onReload = function (callback) {
  1801. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1802. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1803. this.reloadListener = callback;
  1804. if (this.reloadUserInfo) {
  1805. this._notifyReloadListener(this.reloadUserInfo);
  1806. this.reloadUserInfo = null;
  1807. }
  1808. };
  1809. UserImpl.prototype._notifyReloadListener = function (userInfo) {
  1810. if (this.reloadListener) {
  1811. this.reloadListener(userInfo);
  1812. }
  1813. else {
  1814. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1815. this.reloadUserInfo = userInfo;
  1816. }
  1817. };
  1818. UserImpl.prototype._startProactiveRefresh = function () {
  1819. this.proactiveRefresh._start();
  1820. };
  1821. UserImpl.prototype._stopProactiveRefresh = function () {
  1822. this.proactiveRefresh._stop();
  1823. };
  1824. UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
  1825. if (reload === void 0) { reload = false; }
  1826. return tslib.__awaiter(this, void 0, void 0, function () {
  1827. var tokensRefreshed;
  1828. return tslib.__generator(this, function (_a) {
  1829. switch (_a.label) {
  1830. case 0:
  1831. tokensRefreshed = false;
  1832. if (response.idToken &&
  1833. response.idToken !== this.stsTokenManager.accessToken) {
  1834. this.stsTokenManager.updateFromServerResponse(response);
  1835. tokensRefreshed = true;
  1836. }
  1837. if (!reload) return [3 /*break*/, 2];
  1838. return [4 /*yield*/, _reloadWithoutSaving(this)];
  1839. case 1:
  1840. _a.sent();
  1841. _a.label = 2;
  1842. case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1843. case 3:
  1844. _a.sent();
  1845. if (tokensRefreshed) {
  1846. this.auth._notifyListenersIfCurrent(this);
  1847. }
  1848. return [2 /*return*/];
  1849. }
  1850. });
  1851. });
  1852. };
  1853. UserImpl.prototype.delete = function () {
  1854. return tslib.__awaiter(this, void 0, void 0, function () {
  1855. var idToken;
  1856. return tslib.__generator(this, function (_a) {
  1857. switch (_a.label) {
  1858. case 0: return [4 /*yield*/, this.getIdToken()];
  1859. case 1:
  1860. idToken = _a.sent();
  1861. return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
  1862. case 2:
  1863. _a.sent();
  1864. this.stsTokenManager.clearRefreshToken();
  1865. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1866. // cancels pending actions...
  1867. return [2 /*return*/, this.auth.signOut()];
  1868. }
  1869. });
  1870. });
  1871. };
  1872. UserImpl.prototype.toJSON = function () {
  1873. return tslib.__assign(tslib.__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
  1874. // Redirect event ID must be maintained in case there is a pending
  1875. // redirect event.
  1876. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1877. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1878. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1879. };
  1880. Object.defineProperty(UserImpl.prototype, "refreshToken", {
  1881. get: function () {
  1882. return this.stsTokenManager.refreshToken || '';
  1883. },
  1884. enumerable: false,
  1885. configurable: true
  1886. });
  1887. UserImpl._fromJSON = function (auth, object) {
  1888. var _a, _b, _c, _d, _e, _f, _g, _h;
  1889. var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1890. var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1891. var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1892. var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1893. var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1894. var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1895. var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1896. var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1897. var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
  1898. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1899. var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1900. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1901. assertStringOrUndefined(displayName, auth.name);
  1902. assertStringOrUndefined(email, auth.name);
  1903. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1904. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1905. assertStringOrUndefined(phoneNumber, auth.name);
  1906. assertStringOrUndefined(photoURL, auth.name);
  1907. assertStringOrUndefined(tenantId, auth.name);
  1908. assertStringOrUndefined(_redirectEventId, auth.name);
  1909. assertStringOrUndefined(createdAt, auth.name);
  1910. assertStringOrUndefined(lastLoginAt, auth.name);
  1911. var user = new UserImpl({
  1912. uid: uid,
  1913. auth: auth,
  1914. email: email,
  1915. emailVerified: emailVerified,
  1916. displayName: displayName,
  1917. isAnonymous: isAnonymous,
  1918. photoURL: photoURL,
  1919. phoneNumber: phoneNumber,
  1920. tenantId: tenantId,
  1921. stsTokenManager: stsTokenManager,
  1922. createdAt: createdAt,
  1923. lastLoginAt: lastLoginAt
  1924. });
  1925. if (providerData && Array.isArray(providerData)) {
  1926. user.providerData = providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
  1927. }
  1928. if (_redirectEventId) {
  1929. user._redirectEventId = _redirectEventId;
  1930. }
  1931. return user;
  1932. };
  1933. /**
  1934. * Initialize a User from an idToken server response
  1935. * @param auth
  1936. * @param idTokenResponse
  1937. */
  1938. UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
  1939. if (isAnonymous === void 0) { isAnonymous = false; }
  1940. return tslib.__awaiter(this, void 0, void 0, function () {
  1941. var stsTokenManager, user;
  1942. return tslib.__generator(this, function (_a) {
  1943. switch (_a.label) {
  1944. case 0:
  1945. stsTokenManager = new StsTokenManager();
  1946. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1947. user = new UserImpl({
  1948. uid: idTokenResponse.localId,
  1949. auth: auth,
  1950. stsTokenManager: stsTokenManager,
  1951. isAnonymous: isAnonymous
  1952. });
  1953. // Updates the user info and data and resolves with a user instance.
  1954. return [4 /*yield*/, _reloadWithoutSaving(user)];
  1955. case 1:
  1956. // Updates the user info and data and resolves with a user instance.
  1957. _a.sent();
  1958. return [2 /*return*/, user];
  1959. }
  1960. });
  1961. });
  1962. };
  1963. return UserImpl;
  1964. }());
  1965. /**
  1966. * @license
  1967. * Copyright 2020 Google LLC
  1968. *
  1969. * Licensed under the Apache License, Version 2.0 (the "License");
  1970. * you may not use this file except in compliance with the License.
  1971. * You may obtain a copy of the License at
  1972. *
  1973. * http://www.apache.org/licenses/LICENSE-2.0
  1974. *
  1975. * Unless required by applicable law or agreed to in writing, software
  1976. * distributed under the License is distributed on an "AS IS" BASIS,
  1977. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1978. * See the License for the specific language governing permissions and
  1979. * limitations under the License.
  1980. */
  1981. var instanceCache = new Map();
  1982. function _getInstance(cls) {
  1983. debugAssert(cls instanceof Function, 'Expected a class definition');
  1984. var instance = instanceCache.get(cls);
  1985. if (instance) {
  1986. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  1987. return instance;
  1988. }
  1989. instance = new cls();
  1990. instanceCache.set(cls, instance);
  1991. return instance;
  1992. }
  1993. /**
  1994. * @license
  1995. * Copyright 2019 Google LLC
  1996. *
  1997. * Licensed under the Apache License, Version 2.0 (the "License");
  1998. * you may not use this file except in compliance with the License.
  1999. * You may obtain a copy of the License at
  2000. *
  2001. * http://www.apache.org/licenses/LICENSE-2.0
  2002. *
  2003. * Unless required by applicable law or agreed to in writing, software
  2004. * distributed under the License is distributed on an "AS IS" BASIS,
  2005. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2006. * See the License for the specific language governing permissions and
  2007. * limitations under the License.
  2008. */
  2009. var InMemoryPersistence = /** @class */ (function () {
  2010. function InMemoryPersistence() {
  2011. this.type = "NONE" /* PersistenceType.NONE */;
  2012. this.storage = {};
  2013. }
  2014. InMemoryPersistence.prototype._isAvailable = function () {
  2015. return tslib.__awaiter(this, void 0, void 0, function () {
  2016. return tslib.__generator(this, function (_a) {
  2017. return [2 /*return*/, true];
  2018. });
  2019. });
  2020. };
  2021. InMemoryPersistence.prototype._set = function (key, value) {
  2022. return tslib.__awaiter(this, void 0, void 0, function () {
  2023. return tslib.__generator(this, function (_a) {
  2024. this.storage[key] = value;
  2025. return [2 /*return*/];
  2026. });
  2027. });
  2028. };
  2029. InMemoryPersistence.prototype._get = function (key) {
  2030. return tslib.__awaiter(this, void 0, void 0, function () {
  2031. var value;
  2032. return tslib.__generator(this, function (_a) {
  2033. value = this.storage[key];
  2034. return [2 /*return*/, value === undefined ? null : value];
  2035. });
  2036. });
  2037. };
  2038. InMemoryPersistence.prototype._remove = function (key) {
  2039. return tslib.__awaiter(this, void 0, void 0, function () {
  2040. return tslib.__generator(this, function (_a) {
  2041. delete this.storage[key];
  2042. return [2 /*return*/];
  2043. });
  2044. });
  2045. };
  2046. InMemoryPersistence.prototype._addListener = function (_key, _listener) {
  2047. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2048. return;
  2049. };
  2050. InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
  2051. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2052. return;
  2053. };
  2054. InMemoryPersistence.type = 'NONE';
  2055. return InMemoryPersistence;
  2056. }());
  2057. /**
  2058. * An implementation of {@link Persistence} of type 'NONE'.
  2059. *
  2060. * @public
  2061. */
  2062. var inMemoryPersistence = InMemoryPersistence;
  2063. /**
  2064. * @license
  2065. * Copyright 2019 Google LLC
  2066. *
  2067. * Licensed under the Apache License, Version 2.0 (the "License");
  2068. * you may not use this file except in compliance with the License.
  2069. * You may obtain a copy of the License at
  2070. *
  2071. * http://www.apache.org/licenses/LICENSE-2.0
  2072. *
  2073. * Unless required by applicable law or agreed to in writing, software
  2074. * distributed under the License is distributed on an "AS IS" BASIS,
  2075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2076. * See the License for the specific language governing permissions and
  2077. * limitations under the License.
  2078. */
  2079. function _persistenceKeyName(key, apiKey, appName) {
  2080. return "".concat("firebase" /* Namespace.PERSISTENCE */, ":").concat(key, ":").concat(apiKey, ":").concat(appName);
  2081. }
  2082. var PersistenceUserManager = /** @class */ (function () {
  2083. function PersistenceUserManager(persistence, auth, userKey) {
  2084. this.persistence = persistence;
  2085. this.auth = auth;
  2086. this.userKey = userKey;
  2087. var _a = this.auth, config = _a.config, name = _a.name;
  2088. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  2089. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  2090. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  2091. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  2092. }
  2093. PersistenceUserManager.prototype.setCurrentUser = function (user) {
  2094. return this.persistence._set(this.fullUserKey, user.toJSON());
  2095. };
  2096. PersistenceUserManager.prototype.getCurrentUser = function () {
  2097. return tslib.__awaiter(this, void 0, void 0, function () {
  2098. var blob;
  2099. return tslib.__generator(this, function (_a) {
  2100. switch (_a.label) {
  2101. case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
  2102. case 1:
  2103. blob = _a.sent();
  2104. return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
  2105. }
  2106. });
  2107. });
  2108. };
  2109. PersistenceUserManager.prototype.removeCurrentUser = function () {
  2110. return this.persistence._remove(this.fullUserKey);
  2111. };
  2112. PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
  2113. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  2114. };
  2115. PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
  2116. return tslib.__awaiter(this, void 0, void 0, function () {
  2117. var currentUser;
  2118. return tslib.__generator(this, function (_a) {
  2119. switch (_a.label) {
  2120. case 0:
  2121. if (this.persistence === newPersistence) {
  2122. return [2 /*return*/];
  2123. }
  2124. return [4 /*yield*/, this.getCurrentUser()];
  2125. case 1:
  2126. currentUser = _a.sent();
  2127. return [4 /*yield*/, this.removeCurrentUser()];
  2128. case 2:
  2129. _a.sent();
  2130. this.persistence = newPersistence;
  2131. if (currentUser) {
  2132. return [2 /*return*/, this.setCurrentUser(currentUser)];
  2133. }
  2134. return [2 /*return*/];
  2135. }
  2136. });
  2137. });
  2138. };
  2139. PersistenceUserManager.prototype.delete = function () {
  2140. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  2141. };
  2142. PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
  2143. if (userKey === void 0) { userKey = "authUser" /* KeyName.AUTH_USER */; }
  2144. return tslib.__awaiter(this, void 0, void 0, function () {
  2145. var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
  2146. var _this = this;
  2147. return tslib.__generator(this, function (_b) {
  2148. switch (_b.label) {
  2149. case 0:
  2150. if (!persistenceHierarchy.length) {
  2151. return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
  2152. }
  2153. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2154. return tslib.__generator(this, function (_a) {
  2155. switch (_a.label) {
  2156. case 0: return [4 /*yield*/, persistence._isAvailable()];
  2157. case 1:
  2158. if (_a.sent()) {
  2159. return [2 /*return*/, persistence];
  2160. }
  2161. return [2 /*return*/, undefined];
  2162. }
  2163. });
  2164. }); }))];
  2165. case 1:
  2166. availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
  2167. selectedPersistence = availablePersistences[0] ||
  2168. _getInstance(inMemoryPersistence);
  2169. key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  2170. userToMigrate = null;
  2171. _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
  2172. _b.label = 2;
  2173. case 2:
  2174. if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
  2175. persistence = persistenceHierarchy_1[_i];
  2176. _b.label = 3;
  2177. case 3:
  2178. _b.trys.push([3, 5, , 6]);
  2179. return [4 /*yield*/, persistence._get(key)];
  2180. case 4:
  2181. blob = _b.sent();
  2182. if (blob) {
  2183. user = UserImpl._fromJSON(auth, blob);
  2184. if (persistence !== selectedPersistence) {
  2185. userToMigrate = user;
  2186. }
  2187. selectedPersistence = persistence;
  2188. return [3 /*break*/, 7];
  2189. }
  2190. return [3 /*break*/, 6];
  2191. case 5:
  2192. _b.sent();
  2193. return [3 /*break*/, 6];
  2194. case 6:
  2195. _i++;
  2196. return [3 /*break*/, 2];
  2197. case 7:
  2198. migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
  2199. // If the persistence does _not_ allow migration, just finish off here
  2200. if (!selectedPersistence._shouldAllowMigration ||
  2201. !migrationHierarchy.length) {
  2202. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2203. }
  2204. selectedPersistence = migrationHierarchy[0];
  2205. if (!userToMigrate) return [3 /*break*/, 9];
  2206. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2207. // we'll just let it bubble to surface the error.
  2208. return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
  2209. case 8:
  2210. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2211. // we'll just let it bubble to surface the error.
  2212. _b.sent();
  2213. _b.label = 9;
  2214. case 9:
  2215. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2216. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2217. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2218. return tslib.__generator(this, function (_b) {
  2219. switch (_b.label) {
  2220. case 0:
  2221. if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
  2222. _b.label = 1;
  2223. case 1:
  2224. _b.trys.push([1, 3, , 4]);
  2225. return [4 /*yield*/, persistence._remove(key)];
  2226. case 2:
  2227. _b.sent();
  2228. return [3 /*break*/, 4];
  2229. case 3:
  2230. _b.sent();
  2231. return [3 /*break*/, 4];
  2232. case 4: return [2 /*return*/];
  2233. }
  2234. });
  2235. }); }))];
  2236. case 10:
  2237. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2238. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2239. _b.sent();
  2240. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2241. }
  2242. });
  2243. });
  2244. };
  2245. return PersistenceUserManager;
  2246. }());
  2247. /**
  2248. * @license
  2249. * Copyright 2020 Google LLC
  2250. *
  2251. * Licensed under the Apache License, Version 2.0 (the "License");
  2252. * you may not use this file except in compliance with the License.
  2253. * You may obtain a copy of the License at
  2254. *
  2255. * http://www.apache.org/licenses/LICENSE-2.0
  2256. *
  2257. * Unless required by applicable law or agreed to in writing, software
  2258. * distributed under the License is distributed on an "AS IS" BASIS,
  2259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2260. * See the License for the specific language governing permissions and
  2261. * limitations under the License.
  2262. */
  2263. /**
  2264. * Determine the browser for the purposes of reporting usage to the API
  2265. */
  2266. function _getBrowserName(userAgent) {
  2267. var ua = userAgent.toLowerCase();
  2268. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  2269. return "Opera" /* BrowserName.OPERA */;
  2270. }
  2271. else if (_isIEMobile(ua)) {
  2272. // Windows phone IEMobile browser.
  2273. return "IEMobile" /* BrowserName.IEMOBILE */;
  2274. }
  2275. else if (ua.includes('msie') || ua.includes('trident/')) {
  2276. return "IE" /* BrowserName.IE */;
  2277. }
  2278. else if (ua.includes('edge/')) {
  2279. return "Edge" /* BrowserName.EDGE */;
  2280. }
  2281. else if (_isFirefox(ua)) {
  2282. return "Firefox" /* BrowserName.FIREFOX */;
  2283. }
  2284. else if (ua.includes('silk/')) {
  2285. return "Silk" /* BrowserName.SILK */;
  2286. }
  2287. else if (_isBlackBerry(ua)) {
  2288. // Blackberry browser.
  2289. return "Blackberry" /* BrowserName.BLACKBERRY */;
  2290. }
  2291. else if (_isWebOS(ua)) {
  2292. // WebOS default browser.
  2293. return "Webos" /* BrowserName.WEBOS */;
  2294. }
  2295. else if (_isSafari(ua)) {
  2296. return "Safari" /* BrowserName.SAFARI */;
  2297. }
  2298. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  2299. !ua.includes('edge/')) {
  2300. return "Chrome" /* BrowserName.CHROME */;
  2301. }
  2302. else if (_isAndroid(ua)) {
  2303. // Android stock browser.
  2304. return "Android" /* BrowserName.ANDROID */;
  2305. }
  2306. else {
  2307. // Most modern browsers have name/version at end of user agent string.
  2308. var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  2309. var matches = userAgent.match(re);
  2310. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  2311. return matches[1];
  2312. }
  2313. }
  2314. return "Other" /* BrowserName.OTHER */;
  2315. }
  2316. function _isFirefox(ua) {
  2317. if (ua === void 0) { ua = util.getUA(); }
  2318. return /firefox\//i.test(ua);
  2319. }
  2320. function _isSafari(userAgent) {
  2321. if (userAgent === void 0) { userAgent = util.getUA(); }
  2322. var ua = userAgent.toLowerCase();
  2323. return (ua.includes('safari/') &&
  2324. !ua.includes('chrome/') &&
  2325. !ua.includes('crios/') &&
  2326. !ua.includes('android'));
  2327. }
  2328. function _isChromeIOS(ua) {
  2329. if (ua === void 0) { ua = util.getUA(); }
  2330. return /crios\//i.test(ua);
  2331. }
  2332. function _isIEMobile(ua) {
  2333. if (ua === void 0) { ua = util.getUA(); }
  2334. return /iemobile/i.test(ua);
  2335. }
  2336. function _isAndroid(ua) {
  2337. if (ua === void 0) { ua = util.getUA(); }
  2338. return /android/i.test(ua);
  2339. }
  2340. function _isBlackBerry(ua) {
  2341. if (ua === void 0) { ua = util.getUA(); }
  2342. return /blackberry/i.test(ua);
  2343. }
  2344. function _isWebOS(ua) {
  2345. if (ua === void 0) { ua = util.getUA(); }
  2346. return /webos/i.test(ua);
  2347. }
  2348. function _isIOS(ua) {
  2349. if (ua === void 0) { ua = util.getUA(); }
  2350. return (/iphone|ipad|ipod/i.test(ua) ||
  2351. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2352. }
  2353. function _isIOS7Or8(ua) {
  2354. if (ua === void 0) { ua = util.getUA(); }
  2355. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2356. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2357. }
  2358. function _isIE10() {
  2359. return util.isIE() && document.documentMode === 10;
  2360. }
  2361. function _isMobileBrowser(ua) {
  2362. if (ua === void 0) { ua = util.getUA(); }
  2363. // TODO: implement getBrowserName equivalent for OS.
  2364. return (_isIOS(ua) ||
  2365. _isAndroid(ua) ||
  2366. _isWebOS(ua) ||
  2367. _isBlackBerry(ua) ||
  2368. /windows phone/i.test(ua) ||
  2369. _isIEMobile(ua));
  2370. }
  2371. function _isIframe() {
  2372. try {
  2373. // Check that the current window is not the top window.
  2374. // If so, return true.
  2375. return !!(window && window !== window.top);
  2376. }
  2377. catch (e) {
  2378. return false;
  2379. }
  2380. }
  2381. /**
  2382. * @license
  2383. * Copyright 2020 Google LLC
  2384. *
  2385. * Licensed under the Apache License, Version 2.0 (the "License");
  2386. * you may not use this file except in compliance with the License.
  2387. * You may obtain a copy of the License at
  2388. *
  2389. * http://www.apache.org/licenses/LICENSE-2.0
  2390. *
  2391. * Unless required by applicable law or agreed to in writing, software
  2392. * distributed under the License is distributed on an "AS IS" BASIS,
  2393. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2394. * See the License for the specific language governing permissions and
  2395. * limitations under the License.
  2396. */
  2397. /*
  2398. * Determine the SDK version string
  2399. */
  2400. function _getClientVersion(clientPlatform, frameworks) {
  2401. if (frameworks === void 0) { frameworks = []; }
  2402. var reportedPlatform;
  2403. switch (clientPlatform) {
  2404. case "Browser" /* ClientPlatform.BROWSER */:
  2405. // In a browser environment, report the browser name.
  2406. reportedPlatform = _getBrowserName(util.getUA());
  2407. break;
  2408. case "Worker" /* ClientPlatform.WORKER */:
  2409. // Technically a worker runs from a browser but we need to differentiate a
  2410. // worker from a browser.
  2411. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2412. reportedPlatform = "".concat(_getBrowserName(util.getUA()), "-").concat(clientPlatform);
  2413. break;
  2414. default:
  2415. reportedPlatform = clientPlatform;
  2416. }
  2417. var reportedFrameworks = frameworks.length
  2418. ? frameworks.join(',')
  2419. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2420. return "".concat(reportedPlatform, "/").concat("JsCore" /* ClientImplementation.CORE */, "/").concat(app.SDK_VERSION, "/").concat(reportedFrameworks);
  2421. }
  2422. /**
  2423. * @license
  2424. * Copyright 2020 Google LLC
  2425. *
  2426. * Licensed under the Apache License, Version 2.0 (the "License");
  2427. * you may not use this file except in compliance with the License.
  2428. * You may obtain a copy of the License at
  2429. *
  2430. * http://www.apache.org/licenses/LICENSE-2.0
  2431. *
  2432. * Unless required by applicable law or agreed to in writing, software
  2433. * distributed under the License is distributed on an "AS IS" BASIS,
  2434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2435. * See the License for the specific language governing permissions and
  2436. * limitations under the License.
  2437. */
  2438. function getRecaptchaConfig(auth, request) {
  2439. return tslib.__awaiter(this, void 0, void 0, function () {
  2440. return tslib.__generator(this, function (_a) {
  2441. return [2 /*return*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v2/recaptchaConfig" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request))];
  2442. });
  2443. });
  2444. }
  2445. /**
  2446. * @license
  2447. * Copyright 2020 Google LLC
  2448. *
  2449. * Licensed under the Apache License, Version 2.0 (the "License");
  2450. * you may not use this file except in compliance with the License.
  2451. * You may obtain a copy of the License at
  2452. *
  2453. * http://www.apache.org/licenses/LICENSE-2.0
  2454. *
  2455. * Unless required by applicable law or agreed to in writing, software
  2456. * distributed under the License is distributed on an "AS IS" BASIS,
  2457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2458. * See the License for the specific language governing permissions and
  2459. * limitations under the License.
  2460. */
  2461. function isEnterprise(grecaptcha) {
  2462. return (grecaptcha !== undefined &&
  2463. grecaptcha.enterprise !== undefined);
  2464. }
  2465. var RecaptchaConfig = /** @class */ (function () {
  2466. function RecaptchaConfig(response) {
  2467. /**
  2468. * The reCAPTCHA site key.
  2469. */
  2470. this.siteKey = '';
  2471. /**
  2472. * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.
  2473. */
  2474. this.emailPasswordEnabled = false;
  2475. if (response.recaptchaKey === undefined) {
  2476. throw new Error('recaptchaKey undefined');
  2477. }
  2478. // Example response.recaptchaKey: "projects/proj123/keys/sitekey123"
  2479. this.siteKey = response.recaptchaKey.split('/')[3];
  2480. this.emailPasswordEnabled = response.recaptchaEnforcementState.some(function (enforcementState) {
  2481. return enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&
  2482. enforcementState.enforcementState !== 'OFF';
  2483. });
  2484. }
  2485. return RecaptchaConfig;
  2486. }());
  2487. /**
  2488. * @license
  2489. * Copyright 2020 Google LLC
  2490. *
  2491. * Licensed under the Apache License, Version 2.0 (the "License");
  2492. * you may not use this file except in compliance with the License.
  2493. * You may obtain a copy of the License at
  2494. *
  2495. * http://www.apache.org/licenses/LICENSE-2.0
  2496. *
  2497. * Unless required by applicable law or agreed to in writing, software
  2498. * distributed under the License is distributed on an "AS IS" BASIS,
  2499. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2500. * See the License for the specific language governing permissions and
  2501. * limitations under the License.
  2502. */
  2503. function getScriptParentElement() {
  2504. var _a, _b;
  2505. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  2506. }
  2507. function _loadJS(url) {
  2508. // TODO: consider adding timeout support & cancellation
  2509. return new Promise(function (resolve, reject) {
  2510. var el = document.createElement('script');
  2511. el.setAttribute('src', url);
  2512. el.onload = resolve;
  2513. el.onerror = function (e) {
  2514. var error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2515. error.customData = e;
  2516. reject(error);
  2517. };
  2518. el.type = 'text/javascript';
  2519. el.charset = 'UTF-8';
  2520. getScriptParentElement().appendChild(el);
  2521. });
  2522. }
  2523. /* eslint-disable @typescript-eslint/no-require-imports */
  2524. var RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';
  2525. var RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';
  2526. var FAKE_TOKEN = 'NO_RECAPTCHA';
  2527. var RecaptchaEnterpriseVerifier = /** @class */ (function () {
  2528. /**
  2529. *
  2530. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  2531. *
  2532. */
  2533. function RecaptchaEnterpriseVerifier(authExtern) {
  2534. /**
  2535. * Identifies the type of application verifier (e.g. "recaptcha-enterprise").
  2536. */
  2537. this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
  2538. this.auth = _castAuth(authExtern);
  2539. }
  2540. /**
  2541. * Executes the verification process.
  2542. *
  2543. * @returns A Promise for a token that can be used to assert the validity of a request.
  2544. */
  2545. RecaptchaEnterpriseVerifier.prototype.verify = function (action, forceRefresh) {
  2546. if (action === void 0) { action = 'verify'; }
  2547. if (forceRefresh === void 0) { forceRefresh = false; }
  2548. return tslib.__awaiter(this, void 0, void 0, function () {
  2549. function retrieveSiteKey(auth) {
  2550. return tslib.__awaiter(this, void 0, void 0, function () {
  2551. var _this = this;
  2552. return tslib.__generator(this, function (_a) {
  2553. if (!forceRefresh) {
  2554. if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {
  2555. return [2 /*return*/, auth._agentRecaptchaConfig.siteKey];
  2556. }
  2557. if (auth.tenantId != null &&
  2558. auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {
  2559. return [2 /*return*/, auth._tenantRecaptchaConfigs[auth.tenantId].siteKey];
  2560. }
  2561. }
  2562. return [2 /*return*/, new Promise(function (resolve, reject) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2563. return tslib.__generator(this, function (_a) {
  2564. getRecaptchaConfig(auth, {
  2565. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  2566. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2567. })
  2568. .then(function (response) {
  2569. if (response.recaptchaKey === undefined) {
  2570. reject(new Error('recaptcha Enterprise site key undefined'));
  2571. }
  2572. else {
  2573. var config = new RecaptchaConfig(response);
  2574. if (auth.tenantId == null) {
  2575. auth._agentRecaptchaConfig = config;
  2576. }
  2577. else {
  2578. auth._tenantRecaptchaConfigs[auth.tenantId] = config;
  2579. }
  2580. return resolve(config.siteKey);
  2581. }
  2582. })
  2583. .catch(function (error) {
  2584. reject(error);
  2585. });
  2586. return [2 /*return*/];
  2587. });
  2588. }); })];
  2589. });
  2590. });
  2591. }
  2592. function retrieveRecaptchaToken(siteKey, resolve, reject) {
  2593. var grecaptcha = window.grecaptcha;
  2594. if (isEnterprise(grecaptcha)) {
  2595. grecaptcha.enterprise.ready(function () {
  2596. grecaptcha.enterprise
  2597. .execute(siteKey, { action: action })
  2598. .then(function (token) {
  2599. resolve(token);
  2600. })
  2601. .catch(function () {
  2602. resolve(FAKE_TOKEN);
  2603. });
  2604. });
  2605. }
  2606. else {
  2607. reject(Error('No reCAPTCHA enterprise script loaded.'));
  2608. }
  2609. }
  2610. var _this = this;
  2611. return tslib.__generator(this, function (_a) {
  2612. return [2 /*return*/, new Promise(function (resolve, reject) {
  2613. retrieveSiteKey(_this.auth)
  2614. .then(function (siteKey) {
  2615. if (!forceRefresh && isEnterprise(window.grecaptcha)) {
  2616. retrieveRecaptchaToken(siteKey, resolve, reject);
  2617. }
  2618. else {
  2619. if (typeof window === 'undefined') {
  2620. reject(new Error('RecaptchaVerifier is only supported in browser'));
  2621. return;
  2622. }
  2623. _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)
  2624. .then(function () {
  2625. retrieveRecaptchaToken(siteKey, resolve, reject);
  2626. })
  2627. .catch(function (error) {
  2628. reject(error);
  2629. });
  2630. }
  2631. })
  2632. .catch(function (error) {
  2633. reject(error);
  2634. });
  2635. })];
  2636. });
  2637. });
  2638. };
  2639. return RecaptchaEnterpriseVerifier;
  2640. }());
  2641. function injectRecaptchaFields(auth, request, action, captchaResp) {
  2642. if (captchaResp === void 0) { captchaResp = false; }
  2643. return tslib.__awaiter(this, void 0, void 0, function () {
  2644. var verifier, captchaResponse, newRequest;
  2645. return tslib.__generator(this, function (_a) {
  2646. switch (_a.label) {
  2647. case 0:
  2648. verifier = new RecaptchaEnterpriseVerifier(auth);
  2649. _a.label = 1;
  2650. case 1:
  2651. _a.trys.push([1, 3, , 5]);
  2652. return [4 /*yield*/, verifier.verify(action)];
  2653. case 2:
  2654. captchaResponse = _a.sent();
  2655. return [3 /*break*/, 5];
  2656. case 3:
  2657. _a.sent();
  2658. return [4 /*yield*/, verifier.verify(action, true)];
  2659. case 4:
  2660. captchaResponse = _a.sent();
  2661. return [3 /*break*/, 5];
  2662. case 5:
  2663. newRequest = tslib.__assign({}, request);
  2664. if (!captchaResp) {
  2665. Object.assign(newRequest, { captchaResponse: captchaResponse });
  2666. }
  2667. else {
  2668. Object.assign(newRequest, { 'captchaResp': captchaResponse });
  2669. }
  2670. Object.assign(newRequest, { 'clientType': "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */ });
  2671. Object.assign(newRequest, {
  2672. 'recaptchaVersion': "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2673. });
  2674. return [2 /*return*/, newRequest];
  2675. }
  2676. });
  2677. });
  2678. }
  2679. /**
  2680. * @license
  2681. * Copyright 2022 Google LLC
  2682. *
  2683. * Licensed under the Apache License, Version 2.0 (the "License");
  2684. * you may not use this file except in compliance with the License.
  2685. * You may obtain a copy of the License at
  2686. *
  2687. * http://www.apache.org/licenses/LICENSE-2.0
  2688. *
  2689. * Unless required by applicable law or agreed to in writing, software
  2690. * distributed under the License is distributed on an "AS IS" BASIS,
  2691. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2692. * See the License for the specific language governing permissions and
  2693. * limitations under the License.
  2694. */
  2695. var AuthMiddlewareQueue = /** @class */ (function () {
  2696. function AuthMiddlewareQueue(auth) {
  2697. this.auth = auth;
  2698. this.queue = [];
  2699. }
  2700. AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
  2701. var _this = this;
  2702. // The callback could be sync or async. Wrap it into a
  2703. // function that is always async.
  2704. var wrappedCallback = function (user) {
  2705. return new Promise(function (resolve, reject) {
  2706. try {
  2707. var result = callback(user);
  2708. // Either resolve with existing promise or wrap a non-promise
  2709. // return value into a promise.
  2710. resolve(result);
  2711. }
  2712. catch (e) {
  2713. // Sync callback throws.
  2714. reject(e);
  2715. }
  2716. });
  2717. };
  2718. // Attach the onAbort if present
  2719. wrappedCallback.onAbort = onAbort;
  2720. this.queue.push(wrappedCallback);
  2721. var index = this.queue.length - 1;
  2722. return function () {
  2723. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2724. // indexing of other elements.
  2725. _this.queue[index] = function () { return Promise.resolve(); };
  2726. };
  2727. };
  2728. AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
  2729. return tslib.__awaiter(this, void 0, void 0, function () {
  2730. var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
  2731. return tslib.__generator(this, function (_c) {
  2732. switch (_c.label) {
  2733. case 0:
  2734. if (this.auth.currentUser === nextUser) {
  2735. return [2 /*return*/];
  2736. }
  2737. onAbortStack = [];
  2738. _c.label = 1;
  2739. case 1:
  2740. _c.trys.push([1, 6, , 7]);
  2741. _i = 0, _a = this.queue;
  2742. _c.label = 2;
  2743. case 2:
  2744. if (!(_i < _a.length)) return [3 /*break*/, 5];
  2745. beforeStateCallback = _a[_i];
  2746. return [4 /*yield*/, beforeStateCallback(nextUser)];
  2747. case 3:
  2748. _c.sent();
  2749. // Only push the onAbort if the callback succeeds
  2750. if (beforeStateCallback.onAbort) {
  2751. onAbortStack.push(beforeStateCallback.onAbort);
  2752. }
  2753. _c.label = 4;
  2754. case 4:
  2755. _i++;
  2756. return [3 /*break*/, 2];
  2757. case 5: return [3 /*break*/, 7];
  2758. case 6:
  2759. e_1 = _c.sent();
  2760. // Run all onAbort, with separate try/catch to ignore any errors and
  2761. // continue
  2762. onAbortStack.reverse();
  2763. for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
  2764. onAbort = onAbortStack_1[_b];
  2765. try {
  2766. onAbort();
  2767. }
  2768. catch (_) {
  2769. /* swallow error */
  2770. }
  2771. }
  2772. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2773. originalMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  2774. });
  2775. case 7: return [2 /*return*/];
  2776. }
  2777. });
  2778. });
  2779. };
  2780. return AuthMiddlewareQueue;
  2781. }());
  2782. /**
  2783. * @license
  2784. * Copyright 2020 Google LLC
  2785. *
  2786. * Licensed under the Apache License, Version 2.0 (the "License");
  2787. * you may not use this file except in compliance with the License.
  2788. * You may obtain a copy of the License at
  2789. *
  2790. * http://www.apache.org/licenses/LICENSE-2.0
  2791. *
  2792. * Unless required by applicable law or agreed to in writing, software
  2793. * distributed under the License is distributed on an "AS IS" BASIS,
  2794. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2795. * See the License for the specific language governing permissions and
  2796. * limitations under the License.
  2797. */
  2798. var AuthImpl = /** @class */ (function () {
  2799. function AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config) {
  2800. this.app = app;
  2801. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2802. this.appCheckServiceProvider = appCheckServiceProvider;
  2803. this.config = config;
  2804. this.currentUser = null;
  2805. this.emulatorConfig = null;
  2806. this.operations = Promise.resolve();
  2807. this.authStateSubscription = new Subscription(this);
  2808. this.idTokenSubscription = new Subscription(this);
  2809. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2810. this.redirectUser = null;
  2811. this.isProactiveRefreshEnabled = false;
  2812. // Any network calls will set this to true and prevent subsequent emulator
  2813. // initialization
  2814. this._canInitEmulator = true;
  2815. this._isInitialized = false;
  2816. this._deleted = false;
  2817. this._initializationPromise = null;
  2818. this._popupRedirectResolver = null;
  2819. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2820. this._agentRecaptchaConfig = null;
  2821. this._tenantRecaptchaConfigs = {};
  2822. // Tracks the last notified UID for state change listeners to prevent
  2823. // repeated calls to the callbacks. Undefined means it's never been
  2824. // called, whereas null means it's been called with a signed out user
  2825. this.lastNotifiedUid = undefined;
  2826. this.languageCode = null;
  2827. this.tenantId = null;
  2828. this.settings = { appVerificationDisabledForTesting: false };
  2829. this.frameworks = [];
  2830. this.name = app.name;
  2831. this.clientVersion = config.sdkClientVersion;
  2832. }
  2833. AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
  2834. var _this = this;
  2835. if (popupRedirectResolver) {
  2836. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2837. }
  2838. // Have to check for app deletion throughout initialization (after each
  2839. // promise resolution)
  2840. this._initializationPromise = this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  2841. var _a;
  2842. var _b, _c;
  2843. return tslib.__generator(this, function (_d) {
  2844. switch (_d.label) {
  2845. case 0:
  2846. if (this._deleted) {
  2847. return [2 /*return*/];
  2848. }
  2849. _a = this;
  2850. return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
  2851. case 1:
  2852. _a.persistenceManager = _d.sent();
  2853. if (this._deleted) {
  2854. return [2 /*return*/];
  2855. }
  2856. if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
  2857. _d.label = 2;
  2858. case 2:
  2859. _d.trys.push([2, 4, , 5]);
  2860. return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
  2861. case 3:
  2862. _d.sent();
  2863. return [3 /*break*/, 5];
  2864. case 4:
  2865. _d.sent();
  2866. return [3 /*break*/, 5];
  2867. case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
  2868. case 6:
  2869. _d.sent();
  2870. this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
  2871. if (this._deleted) {
  2872. return [2 /*return*/];
  2873. }
  2874. this._isInitialized = true;
  2875. return [2 /*return*/];
  2876. }
  2877. });
  2878. }); });
  2879. return this._initializationPromise;
  2880. };
  2881. /**
  2882. * If the persistence is changed in another window, the user manager will let us know
  2883. */
  2884. AuthImpl.prototype._onStorageEvent = function () {
  2885. return tslib.__awaiter(this, void 0, void 0, function () {
  2886. var user;
  2887. return tslib.__generator(this, function (_a) {
  2888. switch (_a.label) {
  2889. case 0:
  2890. if (this._deleted) {
  2891. return [2 /*return*/];
  2892. }
  2893. return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2894. case 1:
  2895. user = _a.sent();
  2896. if (!this.currentUser && !user) {
  2897. // No change, do nothing (was signed out and remained signed out).
  2898. return [2 /*return*/];
  2899. }
  2900. if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
  2901. // Data update, simply copy data changes.
  2902. this._currentUser._assign(user);
  2903. // If tokens changed from previous user tokens, this will trigger
  2904. // notifyAuthListeners_.
  2905. return [4 /*yield*/, this.currentUser.getIdToken()];
  2906. case 2:
  2907. // If tokens changed from previous user tokens, this will trigger
  2908. // notifyAuthListeners_.
  2909. _a.sent();
  2910. return [2 /*return*/];
  2911. case 3:
  2912. // Update current Auth state. Either a new login or logout.
  2913. // Skip blocking callbacks, they should not apply to a change in another tab.
  2914. return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
  2915. case 4:
  2916. // Update current Auth state. Either a new login or logout.
  2917. // Skip blocking callbacks, they should not apply to a change in another tab.
  2918. _a.sent();
  2919. return [2 /*return*/];
  2920. }
  2921. });
  2922. });
  2923. };
  2924. AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
  2925. var _a;
  2926. return tslib.__awaiter(this, void 0, void 0, function () {
  2927. var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
  2928. return tslib.__generator(this, function (_b) {
  2929. switch (_b.label) {
  2930. case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2931. case 1:
  2932. previouslyStoredUser = (_b.sent());
  2933. futureCurrentUser = previouslyStoredUser;
  2934. needsTocheckMiddleware = false;
  2935. if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
  2936. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2937. case 2:
  2938. _b.sent();
  2939. redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2940. storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2941. return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
  2942. case 3:
  2943. result = _b.sent();
  2944. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2945. // matches the redirect user, then we want to initially sign in with the
  2946. // new user object from result.
  2947. // TODO(samgho): More thoroughly test all of this
  2948. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2949. (result === null || result === void 0 ? void 0 : result.user)) {
  2950. futureCurrentUser = result.user;
  2951. needsTocheckMiddleware = true;
  2952. }
  2953. _b.label = 4;
  2954. case 4:
  2955. // If no user in persistence, there is no current user. Set to null.
  2956. if (!futureCurrentUser) {
  2957. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2958. }
  2959. if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
  2960. if (!needsTocheckMiddleware) return [3 /*break*/, 8];
  2961. _b.label = 5;
  2962. case 5:
  2963. _b.trys.push([5, 7, , 8]);
  2964. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
  2965. case 6:
  2966. _b.sent();
  2967. return [3 /*break*/, 8];
  2968. case 7:
  2969. e_2 = _b.sent();
  2970. futureCurrentUser = previouslyStoredUser;
  2971. // We know this is available since the bit is only set when the
  2972. // resolver is available
  2973. this._popupRedirectResolver._overrideRedirectResult(this, function () {
  2974. return Promise.reject(e_2);
  2975. });
  2976. return [3 /*break*/, 8];
  2977. case 8:
  2978. if (futureCurrentUser) {
  2979. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2980. }
  2981. else {
  2982. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2983. }
  2984. case 9:
  2985. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2986. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2987. case 10:
  2988. _b.sent();
  2989. // If the redirect user's event ID matches the current user's event ID,
  2990. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2991. // This is important for the reauthenticateWithRedirect() flow.
  2992. if (this.redirectUser &&
  2993. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2994. return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
  2995. }
  2996. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2997. }
  2998. });
  2999. });
  3000. };
  3001. AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
  3002. return tslib.__awaiter(this, void 0, void 0, function () {
  3003. var result;
  3004. return tslib.__generator(this, function (_a) {
  3005. switch (_a.label) {
  3006. case 0:
  3007. result = null;
  3008. _a.label = 1;
  3009. case 1:
  3010. _a.trys.push([1, 3, , 5]);
  3011. return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
  3012. case 2:
  3013. // We know this._popupRedirectResolver is set since redirectResolver
  3014. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  3015. result = _a.sent();
  3016. return [3 /*break*/, 5];
  3017. case 3:
  3018. _a.sent();
  3019. // Swallow any errors here; the code can retrieve them in
  3020. // getRedirectResult().
  3021. return [4 /*yield*/, this._setRedirectUser(null)];
  3022. case 4:
  3023. // Swallow any errors here; the code can retrieve them in
  3024. // getRedirectResult().
  3025. _a.sent();
  3026. return [3 /*break*/, 5];
  3027. case 5: return [2 /*return*/, result];
  3028. }
  3029. });
  3030. });
  3031. };
  3032. AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
  3033. return tslib.__awaiter(this, void 0, void 0, function () {
  3034. var e_4;
  3035. return tslib.__generator(this, function (_a) {
  3036. switch (_a.label) {
  3037. case 0:
  3038. _a.trys.push([0, 2, , 3]);
  3039. return [4 /*yield*/, _reloadWithoutSaving(user)];
  3040. case 1:
  3041. _a.sent();
  3042. return [3 /*break*/, 3];
  3043. case 2:
  3044. e_4 = _a.sent();
  3045. if ((e_4 === null || e_4 === void 0 ? void 0 : e_4.code) !==
  3046. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  3047. // Something's wrong with the user's token. Log them out and remove
  3048. // them from storage
  3049. return [2 /*return*/, this.directlySetCurrentUser(null)];
  3050. }
  3051. return [3 /*break*/, 3];
  3052. case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
  3053. }
  3054. });
  3055. });
  3056. };
  3057. AuthImpl.prototype.useDeviceLanguage = function () {
  3058. this.languageCode = _getUserLanguage();
  3059. };
  3060. AuthImpl.prototype._delete = function () {
  3061. return tslib.__awaiter(this, void 0, void 0, function () {
  3062. return tslib.__generator(this, function (_a) {
  3063. this._deleted = true;
  3064. return [2 /*return*/];
  3065. });
  3066. });
  3067. };
  3068. AuthImpl.prototype.updateCurrentUser = function (userExtern) {
  3069. return tslib.__awaiter(this, void 0, void 0, function () {
  3070. var user;
  3071. return tslib.__generator(this, function (_a) {
  3072. user = userExtern
  3073. ? util.getModularInstance(userExtern)
  3074. : null;
  3075. if (user) {
  3076. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  3077. }
  3078. return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
  3079. });
  3080. });
  3081. };
  3082. AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
  3083. if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
  3084. return tslib.__awaiter(this, void 0, void 0, function () {
  3085. var _this = this;
  3086. return tslib.__generator(this, function (_a) {
  3087. switch (_a.label) {
  3088. case 0:
  3089. if (this._deleted) {
  3090. return [2 /*return*/];
  3091. }
  3092. if (user) {
  3093. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  3094. }
  3095. if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
  3096. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
  3097. case 1:
  3098. _a.sent();
  3099. _a.label = 2;
  3100. case 2: return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  3101. return tslib.__generator(this, function (_a) {
  3102. switch (_a.label) {
  3103. case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
  3104. case 1:
  3105. _a.sent();
  3106. this.notifyAuthListeners();
  3107. return [2 /*return*/];
  3108. }
  3109. });
  3110. }); })];
  3111. }
  3112. });
  3113. });
  3114. };
  3115. AuthImpl.prototype.signOut = function () {
  3116. return tslib.__awaiter(this, void 0, void 0, function () {
  3117. return tslib.__generator(this, function (_a) {
  3118. switch (_a.label) {
  3119. case 0:
  3120. // Run first, to block _setRedirectUser() if any callbacks fail.
  3121. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
  3122. case 1:
  3123. // Run first, to block _setRedirectUser() if any callbacks fail.
  3124. _a.sent();
  3125. if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
  3126. return [4 /*yield*/, this._setRedirectUser(null)];
  3127. case 2:
  3128. _a.sent();
  3129. _a.label = 3;
  3130. case 3:
  3131. // Prevent callbacks from being called again in _updateCurrentUser, as
  3132. // they were already called in the first line.
  3133. return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
  3134. }
  3135. });
  3136. });
  3137. };
  3138. AuthImpl.prototype.setPersistence = function (persistence) {
  3139. var _this = this;
  3140. return this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  3141. return tslib.__generator(this, function (_a) {
  3142. switch (_a.label) {
  3143. case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
  3144. case 1:
  3145. _a.sent();
  3146. return [2 /*return*/];
  3147. }
  3148. });
  3149. }); });
  3150. };
  3151. AuthImpl.prototype.initializeRecaptchaConfig = function () {
  3152. return tslib.__awaiter(this, void 0, void 0, function () {
  3153. var response, config, verifier;
  3154. return tslib.__generator(this, function (_a) {
  3155. switch (_a.label) {
  3156. case 0: return [4 /*yield*/, getRecaptchaConfig(this, {
  3157. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  3158. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  3159. })];
  3160. case 1:
  3161. response = _a.sent();
  3162. config = new RecaptchaConfig(response);
  3163. if (this.tenantId == null) {
  3164. this._agentRecaptchaConfig = config;
  3165. }
  3166. else {
  3167. this._tenantRecaptchaConfigs[this.tenantId] = config;
  3168. }
  3169. if (config.emailPasswordEnabled) {
  3170. verifier = new RecaptchaEnterpriseVerifier(this);
  3171. void verifier.verify();
  3172. }
  3173. return [2 /*return*/];
  3174. }
  3175. });
  3176. });
  3177. };
  3178. AuthImpl.prototype._getRecaptchaConfig = function () {
  3179. if (this.tenantId == null) {
  3180. return this._agentRecaptchaConfig;
  3181. }
  3182. else {
  3183. return this._tenantRecaptchaConfigs[this.tenantId];
  3184. }
  3185. };
  3186. AuthImpl.prototype._getPersistence = function () {
  3187. return this.assertedPersistence.persistence.type;
  3188. };
  3189. AuthImpl.prototype._updateErrorMap = function (errorMap) {
  3190. this._errorFactory = new util.ErrorFactory('auth', 'Firebase', errorMap());
  3191. };
  3192. AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
  3193. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  3194. };
  3195. AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
  3196. return this.beforeStateQueue.pushCallback(callback, onAbort);
  3197. };
  3198. AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
  3199. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  3200. };
  3201. AuthImpl.prototype.toJSON = function () {
  3202. var _a;
  3203. return {
  3204. apiKey: this.config.apiKey,
  3205. authDomain: this.config.authDomain,
  3206. appName: this.name,
  3207. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  3208. };
  3209. };
  3210. AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
  3211. return tslib.__awaiter(this, void 0, void 0, function () {
  3212. var redirectManager;
  3213. return tslib.__generator(this, function (_a) {
  3214. switch (_a.label) {
  3215. case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
  3216. case 1:
  3217. redirectManager = _a.sent();
  3218. return [2 /*return*/, user === null
  3219. ? redirectManager.removeCurrentUser()
  3220. : redirectManager.setCurrentUser(user)];
  3221. }
  3222. });
  3223. });
  3224. };
  3225. AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
  3226. return tslib.__awaiter(this, void 0, void 0, function () {
  3227. var resolver, _a, _b;
  3228. return tslib.__generator(this, function (_c) {
  3229. switch (_c.label) {
  3230. case 0:
  3231. if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
  3232. resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  3233. this._popupRedirectResolver;
  3234. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3235. _a = this;
  3236. return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */)];
  3237. case 1:
  3238. _a.redirectPersistenceManager = _c.sent();
  3239. _b = this;
  3240. return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
  3241. case 2:
  3242. _b.redirectUser =
  3243. _c.sent();
  3244. _c.label = 3;
  3245. case 3: return [2 /*return*/, this.redirectPersistenceManager];
  3246. }
  3247. });
  3248. });
  3249. };
  3250. AuthImpl.prototype._redirectUserForId = function (id) {
  3251. var _a, _b;
  3252. return tslib.__awaiter(this, void 0, void 0, function () {
  3253. var _this = this;
  3254. return tslib.__generator(this, function (_c) {
  3255. switch (_c.label) {
  3256. case 0:
  3257. if (!this._isInitialized) return [3 /*break*/, 2];
  3258. return [4 /*yield*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  3259. return [2 /*return*/];
  3260. }); }); })];
  3261. case 1:
  3262. _c.sent();
  3263. _c.label = 2;
  3264. case 2:
  3265. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  3266. return [2 /*return*/, this._currentUser];
  3267. }
  3268. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  3269. return [2 /*return*/, this.redirectUser];
  3270. }
  3271. return [2 /*return*/, null];
  3272. }
  3273. });
  3274. });
  3275. };
  3276. AuthImpl.prototype._persistUserIfCurrent = function (user) {
  3277. return tslib.__awaiter(this, void 0, void 0, function () {
  3278. var _this = this;
  3279. return tslib.__generator(this, function (_a) {
  3280. if (user === this.currentUser) {
  3281. return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  3282. return [2 /*return*/, this.directlySetCurrentUser(user)];
  3283. }); }); })];
  3284. }
  3285. return [2 /*return*/];
  3286. });
  3287. });
  3288. };
  3289. /** Notifies listeners only if the user is current */
  3290. AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
  3291. if (user === this.currentUser) {
  3292. this.notifyAuthListeners();
  3293. }
  3294. };
  3295. AuthImpl.prototype._key = function () {
  3296. return "".concat(this.config.authDomain, ":").concat(this.config.apiKey, ":").concat(this.name);
  3297. };
  3298. AuthImpl.prototype._startProactiveRefresh = function () {
  3299. this.isProactiveRefreshEnabled = true;
  3300. if (this.currentUser) {
  3301. this._currentUser._startProactiveRefresh();
  3302. }
  3303. };
  3304. AuthImpl.prototype._stopProactiveRefresh = function () {
  3305. this.isProactiveRefreshEnabled = false;
  3306. if (this.currentUser) {
  3307. this._currentUser._stopProactiveRefresh();
  3308. }
  3309. };
  3310. Object.defineProperty(AuthImpl.prototype, "_currentUser", {
  3311. /** Returns the current user cast as the internal type */
  3312. get: function () {
  3313. return this.currentUser;
  3314. },
  3315. enumerable: false,
  3316. configurable: true
  3317. });
  3318. AuthImpl.prototype.notifyAuthListeners = function () {
  3319. var _a, _b;
  3320. if (!this._isInitialized) {
  3321. return;
  3322. }
  3323. this.idTokenSubscription.next(this.currentUser);
  3324. var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  3325. if (this.lastNotifiedUid !== currentUid) {
  3326. this.lastNotifiedUid = currentUid;
  3327. this.authStateSubscription.next(this.currentUser);
  3328. }
  3329. };
  3330. AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
  3331. var _this = this;
  3332. if (this._deleted) {
  3333. return function () { };
  3334. }
  3335. var cb = typeof nextOrObserver === 'function'
  3336. ? nextOrObserver
  3337. : nextOrObserver.next.bind(nextOrObserver);
  3338. var promise = this._isInitialized
  3339. ? Promise.resolve()
  3340. : this._initializationPromise;
  3341. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3342. // The callback needs to be called asynchronously per the spec.
  3343. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3344. promise.then(function () { return cb(_this.currentUser); });
  3345. if (typeof nextOrObserver === 'function') {
  3346. return subscription.addObserver(nextOrObserver, error, completed);
  3347. }
  3348. else {
  3349. return subscription.addObserver(nextOrObserver);
  3350. }
  3351. };
  3352. /**
  3353. * Unprotected (from race conditions) method to set the current user. This
  3354. * should only be called from within a queued callback. This is necessary
  3355. * because the queue shouldn't rely on another queued callback.
  3356. */
  3357. AuthImpl.prototype.directlySetCurrentUser = function (user) {
  3358. return tslib.__awaiter(this, void 0, void 0, function () {
  3359. return tslib.__generator(this, function (_a) {
  3360. switch (_a.label) {
  3361. case 0:
  3362. if (this.currentUser && this.currentUser !== user) {
  3363. this._currentUser._stopProactiveRefresh();
  3364. }
  3365. if (user && this.isProactiveRefreshEnabled) {
  3366. user._startProactiveRefresh();
  3367. }
  3368. this.currentUser = user;
  3369. if (!user) return [3 /*break*/, 2];
  3370. return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
  3371. case 1:
  3372. _a.sent();
  3373. return [3 /*break*/, 4];
  3374. case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
  3375. case 3:
  3376. _a.sent();
  3377. _a.label = 4;
  3378. case 4: return [2 /*return*/];
  3379. }
  3380. });
  3381. });
  3382. };
  3383. AuthImpl.prototype.queue = function (action) {
  3384. // In case something errors, the callback still should be called in order
  3385. // to keep the promise chain alive
  3386. this.operations = this.operations.then(action, action);
  3387. return this.operations;
  3388. };
  3389. Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
  3390. get: function () {
  3391. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3392. return this.persistenceManager;
  3393. },
  3394. enumerable: false,
  3395. configurable: true
  3396. });
  3397. AuthImpl.prototype._logFramework = function (framework) {
  3398. if (!framework || this.frameworks.includes(framework)) {
  3399. return;
  3400. }
  3401. this.frameworks.push(framework);
  3402. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  3403. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  3404. this.frameworks.sort();
  3405. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  3406. };
  3407. AuthImpl.prototype._getFrameworks = function () {
  3408. return this.frameworks;
  3409. };
  3410. AuthImpl.prototype._getAdditionalHeaders = function () {
  3411. var _a;
  3412. return tslib.__awaiter(this, void 0, void 0, function () {
  3413. var headers, heartbeatsHeader, appCheckToken;
  3414. var _b;
  3415. return tslib.__generator(this, function (_c) {
  3416. switch (_c.label) {
  3417. case 0:
  3418. headers = (_b = {},
  3419. _b["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */] = this.clientVersion,
  3420. _b);
  3421. if (this.app.options.appId) {
  3422. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  3423. }
  3424. return [4 /*yield*/, ((_a = this.heartbeatServiceProvider
  3425. .getImmediate({
  3426. optional: true
  3427. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
  3428. case 1:
  3429. heartbeatsHeader = _c.sent();
  3430. if (heartbeatsHeader) {
  3431. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  3432. }
  3433. return [4 /*yield*/, this._getAppCheckToken()];
  3434. case 2:
  3435. appCheckToken = _c.sent();
  3436. if (appCheckToken) {
  3437. headers["X-Firebase-AppCheck" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;
  3438. }
  3439. return [2 /*return*/, headers];
  3440. }
  3441. });
  3442. });
  3443. };
  3444. AuthImpl.prototype._getAppCheckToken = function () {
  3445. var _a;
  3446. return tslib.__awaiter(this, void 0, void 0, function () {
  3447. var appCheckTokenResult;
  3448. return tslib.__generator(this, function (_b) {
  3449. switch (_b.label) {
  3450. case 0: return [4 /*yield*/, ((_a = this.appCheckServiceProvider
  3451. .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken())];
  3452. case 1:
  3453. appCheckTokenResult = _b.sent();
  3454. if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
  3455. // Context: appCheck.getToken() will never throw even if an error happened.
  3456. // In the error case, a dummy token will be returned along with an error field describing
  3457. // the error. In general, we shouldn't care about the error condition and just use
  3458. // the token (actual or dummy) to send requests.
  3459. _logWarn("Error while retrieving App Check token: ".concat(appCheckTokenResult.error));
  3460. }
  3461. return [2 /*return*/, appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token];
  3462. }
  3463. });
  3464. });
  3465. };
  3466. return AuthImpl;
  3467. }());
  3468. /**
  3469. * Method to be used to cast down to our private implmentation of Auth.
  3470. * It will also handle unwrapping from the compat type if necessary
  3471. *
  3472. * @param auth Auth object passed in from developer
  3473. */
  3474. function _castAuth(auth) {
  3475. return util.getModularInstance(auth);
  3476. }
  3477. /** Helper class to wrap subscriber logic */
  3478. var Subscription = /** @class */ (function () {
  3479. function Subscription(auth) {
  3480. var _this = this;
  3481. this.auth = auth;
  3482. this.observer = null;
  3483. this.addObserver = util.createSubscribe(function (observer) { return (_this.observer = observer); });
  3484. }
  3485. Object.defineProperty(Subscription.prototype, "next", {
  3486. get: function () {
  3487. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3488. return this.observer.next.bind(this.observer);
  3489. },
  3490. enumerable: false,
  3491. configurable: true
  3492. });
  3493. return Subscription;
  3494. }());
  3495. /**
  3496. * @license
  3497. * Copyright 2020 Google LLC
  3498. *
  3499. * Licensed under the Apache License, Version 2.0 (the "License");
  3500. * you may not use this file except in compliance with the License.
  3501. * You may obtain a copy of the License at
  3502. *
  3503. * http://www.apache.org/licenses/LICENSE-2.0
  3504. *
  3505. * Unless required by applicable law or agreed to in writing, software
  3506. * distributed under the License is distributed on an "AS IS" BASIS,
  3507. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3508. * See the License for the specific language governing permissions and
  3509. * limitations under the License.
  3510. */
  3511. /**
  3512. * Initializes an {@link Auth} instance with fine-grained control over
  3513. * {@link Dependencies}.
  3514. *
  3515. * @remarks
  3516. *
  3517. * This function allows more control over the {@link Auth} instance than
  3518. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  3519. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  3520. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  3521. * need control over which persistence layer is used, or to minimize bundle
  3522. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  3523. *
  3524. * For example, if your app only uses anonymous accounts and you only want
  3525. * accounts saved for the current session, initialize `Auth` with:
  3526. *
  3527. * ```js
  3528. * const auth = initializeAuth(app, {
  3529. * persistence: browserSessionPersistence,
  3530. * popupRedirectResolver: undefined,
  3531. * });
  3532. * ```
  3533. *
  3534. * @public
  3535. */
  3536. function initializeAuth(app$1, deps) {
  3537. var provider = app._getProvider(app$1, 'auth');
  3538. if (provider.isInitialized()) {
  3539. var auth_1 = provider.getImmediate();
  3540. var initialOptions = provider.getOptions();
  3541. if (util.deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  3542. return auth_1;
  3543. }
  3544. else {
  3545. _fail(auth_1, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  3546. }
  3547. }
  3548. var auth = provider.initialize({ options: deps });
  3549. return auth;
  3550. }
  3551. function _initializeAuthInstance(auth, deps) {
  3552. var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  3553. var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  3554. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  3555. auth._updateErrorMap(deps.errorMap);
  3556. }
  3557. // This promise is intended to float; auth initialization happens in the
  3558. // background, meanwhile the auth object may be used by the app.
  3559. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3560. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  3561. }
  3562. /**
  3563. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  3564. * Firebase Auth services.
  3565. *
  3566. * @remarks
  3567. * This must be called synchronously immediately following the first call to
  3568. * {@link initializeAuth}. Do not use with production credentials as emulator
  3569. * traffic is not encrypted.
  3570. *
  3571. *
  3572. * @example
  3573. * ```javascript
  3574. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  3575. * ```
  3576. *
  3577. * @param auth - The {@link Auth} instance.
  3578. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  3579. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  3580. * `true` to disable the warning banner attached to the DOM.
  3581. *
  3582. * @public
  3583. */
  3584. function connectAuthEmulator(auth, url, options) {
  3585. var authInternal = _castAuth(auth);
  3586. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  3587. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  3588. var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  3589. var protocol = extractProtocol(url);
  3590. var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
  3591. var portStr = port === null ? '' : ":".concat(port);
  3592. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  3593. authInternal.config.emulator = { url: "".concat(protocol, "//").concat(host).concat(portStr, "/") };
  3594. authInternal.settings.appVerificationDisabledForTesting = true;
  3595. authInternal.emulatorConfig = Object.freeze({
  3596. host: host,
  3597. port: port,
  3598. protocol: protocol.replace(':', ''),
  3599. options: Object.freeze({ disableWarnings: disableWarnings })
  3600. });
  3601. if (!disableWarnings) {
  3602. emitEmulatorWarning();
  3603. }
  3604. }
  3605. function extractProtocol(url) {
  3606. var protocolEnd = url.indexOf(':');
  3607. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  3608. }
  3609. function extractHostAndPort(url) {
  3610. var protocol = extractProtocol(url);
  3611. var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  3612. if (!authority) {
  3613. return { host: '', port: null };
  3614. }
  3615. var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  3616. var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  3617. if (bracketedIPv6) {
  3618. var host = bracketedIPv6[1];
  3619. return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  3620. }
  3621. else {
  3622. var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
  3623. return { host: host, port: parsePort(port) };
  3624. }
  3625. }
  3626. function parsePort(portStr) {
  3627. if (!portStr) {
  3628. return null;
  3629. }
  3630. var port = Number(portStr);
  3631. if (isNaN(port)) {
  3632. return null;
  3633. }
  3634. return port;
  3635. }
  3636. function emitEmulatorWarning() {
  3637. function attachBanner() {
  3638. var el = document.createElement('p');
  3639. var sty = el.style;
  3640. el.innerText =
  3641. 'Running in emulator mode. Do not use with production credentials.';
  3642. sty.position = 'fixed';
  3643. sty.width = '100%';
  3644. sty.backgroundColor = '#ffffff';
  3645. sty.border = '.1em solid #000000';
  3646. sty.color = '#b50000';
  3647. sty.bottom = '0px';
  3648. sty.left = '0px';
  3649. sty.margin = '0px';
  3650. sty.zIndex = '10000';
  3651. sty.textAlign = 'center';
  3652. el.classList.add('firebase-emulator-warning');
  3653. document.body.appendChild(el);
  3654. }
  3655. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  3656. console.info('WARNING: You are using the Auth Emulator,' +
  3657. ' which is intended for local testing only. Do not use with' +
  3658. ' production credentials.');
  3659. }
  3660. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  3661. if (document.readyState === 'loading') {
  3662. window.addEventListener('DOMContentLoaded', attachBanner);
  3663. }
  3664. else {
  3665. attachBanner();
  3666. }
  3667. }
  3668. }
  3669. /**
  3670. * @license
  3671. * Copyright 2020 Google LLC
  3672. *
  3673. * Licensed under the Apache License, Version 2.0 (the "License");
  3674. * you may not use this file except in compliance with the License.
  3675. * You may obtain a copy of the License at
  3676. *
  3677. * http://www.apache.org/licenses/LICENSE-2.0
  3678. *
  3679. * Unless required by applicable law or agreed to in writing, software
  3680. * distributed under the License is distributed on an "AS IS" BASIS,
  3681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3682. * See the License for the specific language governing permissions and
  3683. * limitations under the License.
  3684. */
  3685. /**
  3686. * Interface that represents the credentials returned by an {@link AuthProvider}.
  3687. *
  3688. * @remarks
  3689. * Implementations specify the details about each auth provider's credential requirements.
  3690. *
  3691. * @public
  3692. */
  3693. var AuthCredential = /** @class */ (function () {
  3694. /** @internal */
  3695. function AuthCredential(
  3696. /**
  3697. * The authentication provider ID for the credential.
  3698. *
  3699. * @remarks
  3700. * For example, 'facebook.com', or 'google.com'.
  3701. */
  3702. providerId,
  3703. /**
  3704. * The authentication sign in method for the credential.
  3705. *
  3706. * @remarks
  3707. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  3708. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  3709. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  3710. */
  3711. signInMethod) {
  3712. this.providerId = providerId;
  3713. this.signInMethod = signInMethod;
  3714. }
  3715. /**
  3716. * Returns a JSON-serializable representation of this object.
  3717. *
  3718. * @returns a JSON-serializable representation of this object.
  3719. */
  3720. AuthCredential.prototype.toJSON = function () {
  3721. return debugFail('not implemented');
  3722. };
  3723. /** @internal */
  3724. AuthCredential.prototype._getIdTokenResponse = function (_auth) {
  3725. return debugFail('not implemented');
  3726. };
  3727. /** @internal */
  3728. AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
  3729. return debugFail('not implemented');
  3730. };
  3731. /** @internal */
  3732. AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
  3733. return debugFail('not implemented');
  3734. };
  3735. return AuthCredential;
  3736. }());
  3737. /**
  3738. * @license
  3739. * Copyright 2020 Google LLC
  3740. *
  3741. * Licensed under the Apache License, Version 2.0 (the "License");
  3742. * you may not use this file except in compliance with the License.
  3743. * You may obtain a copy of the License at
  3744. *
  3745. * http://www.apache.org/licenses/LICENSE-2.0
  3746. *
  3747. * Unless required by applicable law or agreed to in writing, software
  3748. * distributed under the License is distributed on an "AS IS" BASIS,
  3749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3750. * See the License for the specific language governing permissions and
  3751. * limitations under the License.
  3752. */
  3753. function resetPassword(auth, request) {
  3754. return tslib.__awaiter(this, void 0, void 0, function () {
  3755. return tslib.__generator(this, function (_a) {
  3756. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
  3757. });
  3758. });
  3759. }
  3760. function updateEmailPassword(auth, request) {
  3761. return tslib.__awaiter(this, void 0, void 0, function () {
  3762. return tslib.__generator(this, function (_a) {
  3763. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  3764. });
  3765. });
  3766. }
  3767. function applyActionCode$1(auth, request) {
  3768. return tslib.__awaiter(this, void 0, void 0, function () {
  3769. return tslib.__generator(this, function (_a) {
  3770. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
  3771. });
  3772. });
  3773. }
  3774. /**
  3775. * @license
  3776. * Copyright 2020 Google LLC
  3777. *
  3778. * Licensed under the Apache License, Version 2.0 (the "License");
  3779. * you may not use this file except in compliance with the License.
  3780. * You may obtain a copy of the License at
  3781. *
  3782. * http://www.apache.org/licenses/LICENSE-2.0
  3783. *
  3784. * Unless required by applicable law or agreed to in writing, software
  3785. * distributed under the License is distributed on an "AS IS" BASIS,
  3786. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3787. * See the License for the specific language governing permissions and
  3788. * limitations under the License.
  3789. */
  3790. function signInWithPassword(auth, request) {
  3791. return tslib.__awaiter(this, void 0, void 0, function () {
  3792. return tslib.__generator(this, function (_a) {
  3793. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
  3794. });
  3795. });
  3796. }
  3797. function sendOobCode(auth, request) {
  3798. return tslib.__awaiter(this, void 0, void 0, function () {
  3799. return tslib.__generator(this, function (_a) {
  3800. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
  3801. });
  3802. });
  3803. }
  3804. function sendEmailVerification$1(auth, request) {
  3805. return tslib.__awaiter(this, void 0, void 0, function () {
  3806. return tslib.__generator(this, function (_a) {
  3807. return [2 /*return*/, sendOobCode(auth, request)];
  3808. });
  3809. });
  3810. }
  3811. function sendPasswordResetEmail$1(auth, request) {
  3812. return tslib.__awaiter(this, void 0, void 0, function () {
  3813. return tslib.__generator(this, function (_a) {
  3814. return [2 /*return*/, sendOobCode(auth, request)];
  3815. });
  3816. });
  3817. }
  3818. function sendSignInLinkToEmail$1(auth, request) {
  3819. return tslib.__awaiter(this, void 0, void 0, function () {
  3820. return tslib.__generator(this, function (_a) {
  3821. return [2 /*return*/, sendOobCode(auth, request)];
  3822. });
  3823. });
  3824. }
  3825. function verifyAndChangeEmail(auth, request) {
  3826. return tslib.__awaiter(this, void 0, void 0, function () {
  3827. return tslib.__generator(this, function (_a) {
  3828. return [2 /*return*/, sendOobCode(auth, request)];
  3829. });
  3830. });
  3831. }
  3832. /**
  3833. * @license
  3834. * Copyright 2020 Google LLC
  3835. *
  3836. * Licensed under the Apache License, Version 2.0 (the "License");
  3837. * you may not use this file except in compliance with the License.
  3838. * You may obtain a copy of the License at
  3839. *
  3840. * http://www.apache.org/licenses/LICENSE-2.0
  3841. *
  3842. * Unless required by applicable law or agreed to in writing, software
  3843. * distributed under the License is distributed on an "AS IS" BASIS,
  3844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3845. * See the License for the specific language governing permissions and
  3846. * limitations under the License.
  3847. */
  3848. function signInWithEmailLink$1(auth, request) {
  3849. return tslib.__awaiter(this, void 0, void 0, function () {
  3850. return tslib.__generator(this, function (_a) {
  3851. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3852. });
  3853. });
  3854. }
  3855. function signInWithEmailLinkForLinking(auth, request) {
  3856. return tslib.__awaiter(this, void 0, void 0, function () {
  3857. return tslib.__generator(this, function (_a) {
  3858. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3859. });
  3860. });
  3861. }
  3862. /**
  3863. * @license
  3864. * Copyright 2020 Google LLC
  3865. *
  3866. * Licensed under the Apache License, Version 2.0 (the "License");
  3867. * you may not use this file except in compliance with the License.
  3868. * You may obtain a copy of the License at
  3869. *
  3870. * http://www.apache.org/licenses/LICENSE-2.0
  3871. *
  3872. * Unless required by applicable law or agreed to in writing, software
  3873. * distributed under the License is distributed on an "AS IS" BASIS,
  3874. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3875. * See the License for the specific language governing permissions and
  3876. * limitations under the License.
  3877. */
  3878. /**
  3879. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  3880. * {@link ProviderId}.PASSWORD
  3881. *
  3882. * @remarks
  3883. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  3884. * {@link SignInMethod}.EMAIL_LINK.
  3885. *
  3886. * @public
  3887. */
  3888. var EmailAuthCredential = /** @class */ (function (_super) {
  3889. tslib.__extends(EmailAuthCredential, _super);
  3890. /** @internal */
  3891. function EmailAuthCredential(
  3892. /** @internal */
  3893. _email,
  3894. /** @internal */
  3895. _password, signInMethod,
  3896. /** @internal */
  3897. _tenantId) {
  3898. if (_tenantId === void 0) { _tenantId = null; }
  3899. var _this = _super.call(this, "password" /* ProviderId.PASSWORD */, signInMethod) || this;
  3900. _this._email = _email;
  3901. _this._password = _password;
  3902. _this._tenantId = _tenantId;
  3903. return _this;
  3904. }
  3905. /** @internal */
  3906. EmailAuthCredential._fromEmailAndPassword = function (email, password) {
  3907. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  3908. };
  3909. /** @internal */
  3910. EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
  3911. if (tenantId === void 0) { tenantId = null; }
  3912. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  3913. };
  3914. /** {@inheritdoc AuthCredential.toJSON} */
  3915. EmailAuthCredential.prototype.toJSON = function () {
  3916. return {
  3917. email: this._email,
  3918. password: this._password,
  3919. signInMethod: this.signInMethod,
  3920. tenantId: this._tenantId
  3921. };
  3922. };
  3923. /**
  3924. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  3925. *
  3926. * @param json - Either `object` or the stringified representation of the object. When string is
  3927. * provided, `JSON.parse` would be called first.
  3928. *
  3929. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3930. */
  3931. EmailAuthCredential.fromJSON = function (json) {
  3932. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3933. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  3934. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  3935. return this._fromEmailAndPassword(obj.email, obj.password);
  3936. }
  3937. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  3938. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  3939. }
  3940. }
  3941. return null;
  3942. };
  3943. /** @internal */
  3944. EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3945. var _a;
  3946. return tslib.__awaiter(this, void 0, void 0, function () {
  3947. var _b, request_1, requestWithRecaptcha;
  3948. var _this = this;
  3949. return tslib.__generator(this, function (_c) {
  3950. switch (_c.label) {
  3951. case 0:
  3952. _b = this.signInMethod;
  3953. switch (_b) {
  3954. case "password" /* SignInMethod.EMAIL_PASSWORD */: return [3 /*break*/, 1];
  3955. case "emailLink" /* SignInMethod.EMAIL_LINK */: return [3 /*break*/, 4];
  3956. }
  3957. return [3 /*break*/, 5];
  3958. case 1:
  3959. request_1 = {
  3960. returnSecureToken: true,
  3961. email: this._email,
  3962. password: this._password,
  3963. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  3964. };
  3965. if (!((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  3966. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  3967. case 2:
  3968. requestWithRecaptcha = _c.sent();
  3969. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  3970. case 3: return [2 /*return*/, signInWithPassword(auth, request_1).catch(function (error) { return tslib.__awaiter(_this, void 0, void 0, function () {
  3971. var requestWithRecaptcha;
  3972. return tslib.__generator(this, function (_a) {
  3973. switch (_a.label) {
  3974. case 0:
  3975. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  3976. console.log('Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  3977. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  3978. case 1:
  3979. requestWithRecaptcha = _a.sent();
  3980. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  3981. case 2: return [2 /*return*/, Promise.reject(error)];
  3982. }
  3983. });
  3984. }); })];
  3985. case 4: return [2 /*return*/, signInWithEmailLink$1(auth, {
  3986. email: this._email,
  3987. oobCode: this._password
  3988. })];
  3989. case 5:
  3990. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3991. _c.label = 6;
  3992. case 6: return [2 /*return*/];
  3993. }
  3994. });
  3995. });
  3996. };
  3997. /** @internal */
  3998. EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3999. return tslib.__awaiter(this, void 0, void 0, function () {
  4000. return tslib.__generator(this, function (_a) {
  4001. switch (this.signInMethod) {
  4002. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  4003. return [2 /*return*/, updateEmailPassword(auth, {
  4004. idToken: idToken,
  4005. returnSecureToken: true,
  4006. email: this._email,
  4007. password: this._password
  4008. })];
  4009. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  4010. return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
  4011. idToken: idToken,
  4012. email: this._email,
  4013. oobCode: this._password
  4014. })];
  4015. default:
  4016. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4017. }
  4018. return [2 /*return*/];
  4019. });
  4020. });
  4021. };
  4022. /** @internal */
  4023. EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4024. return this._getIdTokenResponse(auth);
  4025. };
  4026. return EmailAuthCredential;
  4027. }(AuthCredential));
  4028. /**
  4029. * @license
  4030. * Copyright 2020 Google LLC
  4031. *
  4032. * Licensed under the Apache License, Version 2.0 (the "License");
  4033. * you may not use this file except in compliance with the License.
  4034. * You may obtain a copy of the License at
  4035. *
  4036. * http://www.apache.org/licenses/LICENSE-2.0
  4037. *
  4038. * Unless required by applicable law or agreed to in writing, software
  4039. * distributed under the License is distributed on an "AS IS" BASIS,
  4040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4041. * See the License for the specific language governing permissions and
  4042. * limitations under the License.
  4043. */
  4044. function signInWithIdp(auth, request) {
  4045. return tslib.__awaiter(this, void 0, void 0, function () {
  4046. return tslib.__generator(this, function (_a) {
  4047. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
  4048. });
  4049. });
  4050. }
  4051. /**
  4052. * @license
  4053. * Copyright 2020 Google LLC
  4054. *
  4055. * Licensed under the Apache License, Version 2.0 (the "License");
  4056. * you may not use this file except in compliance with the License.
  4057. * You may obtain a copy of the License at
  4058. *
  4059. * http://www.apache.org/licenses/LICENSE-2.0
  4060. *
  4061. * Unless required by applicable law or agreed to in writing, software
  4062. * distributed under the License is distributed on an "AS IS" BASIS,
  4063. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4064. * See the License for the specific language governing permissions and
  4065. * limitations under the License.
  4066. */
  4067. var IDP_REQUEST_URI$1 = 'http://localhost';
  4068. /**
  4069. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  4070. *
  4071. * @remarks
  4072. * Implementations specify the details about each auth provider's credential requirements.
  4073. *
  4074. * @public
  4075. */
  4076. var OAuthCredential = /** @class */ (function (_super) {
  4077. tslib.__extends(OAuthCredential, _super);
  4078. function OAuthCredential() {
  4079. var _this = _super !== null && _super.apply(this, arguments) || this;
  4080. _this.pendingToken = null;
  4081. return _this;
  4082. }
  4083. /** @internal */
  4084. OAuthCredential._fromParams = function (params) {
  4085. var cred = new OAuthCredential(params.providerId, params.signInMethod);
  4086. if (params.idToken || params.accessToken) {
  4087. // OAuth 2 and either ID token or access token.
  4088. if (params.idToken) {
  4089. cred.idToken = params.idToken;
  4090. }
  4091. if (params.accessToken) {
  4092. cred.accessToken = params.accessToken;
  4093. }
  4094. // Add nonce if available and no pendingToken is present.
  4095. if (params.nonce && !params.pendingToken) {
  4096. cred.nonce = params.nonce;
  4097. }
  4098. if (params.pendingToken) {
  4099. cred.pendingToken = params.pendingToken;
  4100. }
  4101. }
  4102. else if (params.oauthToken && params.oauthTokenSecret) {
  4103. // OAuth 1 and OAuth token with token secret
  4104. cred.accessToken = params.oauthToken;
  4105. cred.secret = params.oauthTokenSecret;
  4106. }
  4107. else {
  4108. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4109. }
  4110. return cred;
  4111. };
  4112. /** {@inheritdoc AuthCredential.toJSON} */
  4113. OAuthCredential.prototype.toJSON = function () {
  4114. return {
  4115. idToken: this.idToken,
  4116. accessToken: this.accessToken,
  4117. secret: this.secret,
  4118. nonce: this.nonce,
  4119. pendingToken: this.pendingToken,
  4120. providerId: this.providerId,
  4121. signInMethod: this.signInMethod
  4122. };
  4123. };
  4124. /**
  4125. * Static method to deserialize a JSON representation of an object into an
  4126. * {@link AuthCredential}.
  4127. *
  4128. * @param json - Input can be either Object or the stringified representation of the object.
  4129. * When string is provided, JSON.parse would be called first.
  4130. *
  4131. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4132. */
  4133. OAuthCredential.fromJSON = function (json) {
  4134. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4135. var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = tslib.__rest(obj, ["providerId", "signInMethod"]);
  4136. if (!providerId || !signInMethod) {
  4137. return null;
  4138. }
  4139. var cred = new OAuthCredential(providerId, signInMethod);
  4140. cred.idToken = rest.idToken || undefined;
  4141. cred.accessToken = rest.accessToken || undefined;
  4142. cred.secret = rest.secret;
  4143. cred.nonce = rest.nonce;
  4144. cred.pendingToken = rest.pendingToken || null;
  4145. return cred;
  4146. };
  4147. /** @internal */
  4148. OAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4149. var request = this.buildRequest();
  4150. return signInWithIdp(auth, request);
  4151. };
  4152. /** @internal */
  4153. OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4154. var request = this.buildRequest();
  4155. request.idToken = idToken;
  4156. return signInWithIdp(auth, request);
  4157. };
  4158. /** @internal */
  4159. OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4160. var request = this.buildRequest();
  4161. request.autoCreate = false;
  4162. return signInWithIdp(auth, request);
  4163. };
  4164. OAuthCredential.prototype.buildRequest = function () {
  4165. var request = {
  4166. requestUri: IDP_REQUEST_URI$1,
  4167. returnSecureToken: true
  4168. };
  4169. if (this.pendingToken) {
  4170. request.pendingToken = this.pendingToken;
  4171. }
  4172. else {
  4173. var postBody = {};
  4174. if (this.idToken) {
  4175. postBody['id_token'] = this.idToken;
  4176. }
  4177. if (this.accessToken) {
  4178. postBody['access_token'] = this.accessToken;
  4179. }
  4180. if (this.secret) {
  4181. postBody['oauth_token_secret'] = this.secret;
  4182. }
  4183. postBody['providerId'] = this.providerId;
  4184. if (this.nonce && !this.pendingToken) {
  4185. postBody['nonce'] = this.nonce;
  4186. }
  4187. request.postBody = util.querystring(postBody);
  4188. }
  4189. return request;
  4190. };
  4191. return OAuthCredential;
  4192. }(AuthCredential));
  4193. /**
  4194. * @license
  4195. * Copyright 2020 Google LLC
  4196. *
  4197. * Licensed under the Apache License, Version 2.0 (the "License");
  4198. * you may not use this file except in compliance with the License.
  4199. * You may obtain a copy of the License at
  4200. *
  4201. * http://www.apache.org/licenses/LICENSE-2.0
  4202. *
  4203. * Unless required by applicable law or agreed to in writing, software
  4204. * distributed under the License is distributed on an "AS IS" BASIS,
  4205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4206. * See the License for the specific language governing permissions and
  4207. * limitations under the License.
  4208. */
  4209. var _a;
  4210. function signInWithPhoneNumber$1(auth, request) {
  4211. return tslib.__awaiter(this, void 0, void 0, function () {
  4212. return tslib.__generator(this, function (_a) {
  4213. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  4214. });
  4215. });
  4216. }
  4217. function linkWithPhoneNumber$1(auth, request) {
  4218. return tslib.__awaiter(this, void 0, void 0, function () {
  4219. var response;
  4220. return tslib.__generator(this, function (_a) {
  4221. switch (_a.label) {
  4222. case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  4223. case 1:
  4224. response = _a.sent();
  4225. if (response.temporaryProof) {
  4226. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  4227. }
  4228. return [2 /*return*/, response];
  4229. }
  4230. });
  4231. });
  4232. }
  4233. var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
  4234. _a["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  4235. _a);
  4236. function verifyPhoneNumberForExisting(auth, request) {
  4237. return tslib.__awaiter(this, void 0, void 0, function () {
  4238. var apiRequest;
  4239. return tslib.__generator(this, function (_a) {
  4240. apiRequest = tslib.__assign(tslib.__assign({}, request), { operation: 'REAUTH' });
  4241. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
  4242. });
  4243. });
  4244. }
  4245. /**
  4246. * @license
  4247. * Copyright 2020 Google LLC
  4248. *
  4249. * Licensed under the Apache License, Version 2.0 (the "License");
  4250. * you may not use this file except in compliance with the License.
  4251. * You may obtain a copy of the License at
  4252. *
  4253. * http://www.apache.org/licenses/LICENSE-2.0
  4254. *
  4255. * Unless required by applicable law or agreed to in writing, software
  4256. * distributed under the License is distributed on an "AS IS" BASIS,
  4257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4258. * See the License for the specific language governing permissions and
  4259. * limitations under the License.
  4260. */
  4261. /**
  4262. * Represents the credentials returned by {@link PhoneAuthProvider}.
  4263. *
  4264. * @public
  4265. */
  4266. var PhoneAuthCredential = /** @class */ (function (_super) {
  4267. tslib.__extends(PhoneAuthCredential, _super);
  4268. function PhoneAuthCredential(params) {
  4269. var _this = _super.call(this, "phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */) || this;
  4270. _this.params = params;
  4271. return _this;
  4272. }
  4273. /** @internal */
  4274. PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
  4275. return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
  4276. };
  4277. /** @internal */
  4278. PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
  4279. return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
  4280. };
  4281. /** @internal */
  4282. PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4283. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  4284. };
  4285. /** @internal */
  4286. PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4287. return linkWithPhoneNumber$1(auth, tslib.__assign({ idToken: idToken }, this._makeVerificationRequest()));
  4288. };
  4289. /** @internal */
  4290. PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4291. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  4292. };
  4293. /** @internal */
  4294. PhoneAuthCredential.prototype._makeVerificationRequest = function () {
  4295. var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
  4296. if (temporaryProof && phoneNumber) {
  4297. return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
  4298. }
  4299. return {
  4300. sessionInfo: verificationId,
  4301. code: verificationCode
  4302. };
  4303. };
  4304. /** {@inheritdoc AuthCredential.toJSON} */
  4305. PhoneAuthCredential.prototype.toJSON = function () {
  4306. var obj = {
  4307. providerId: this.providerId
  4308. };
  4309. if (this.params.phoneNumber) {
  4310. obj.phoneNumber = this.params.phoneNumber;
  4311. }
  4312. if (this.params.temporaryProof) {
  4313. obj.temporaryProof = this.params.temporaryProof;
  4314. }
  4315. if (this.params.verificationCode) {
  4316. obj.verificationCode = this.params.verificationCode;
  4317. }
  4318. if (this.params.verificationId) {
  4319. obj.verificationId = this.params.verificationId;
  4320. }
  4321. return obj;
  4322. };
  4323. /** Generates a phone credential based on a plain object or a JSON string. */
  4324. PhoneAuthCredential.fromJSON = function (json) {
  4325. if (typeof json === 'string') {
  4326. json = JSON.parse(json);
  4327. }
  4328. var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
  4329. if (!verificationCode &&
  4330. !verificationId &&
  4331. !phoneNumber &&
  4332. !temporaryProof) {
  4333. return null;
  4334. }
  4335. return new PhoneAuthCredential({
  4336. verificationId: verificationId,
  4337. verificationCode: verificationCode,
  4338. phoneNumber: phoneNumber,
  4339. temporaryProof: temporaryProof
  4340. });
  4341. };
  4342. return PhoneAuthCredential;
  4343. }(AuthCredential));
  4344. /**
  4345. * @license
  4346. * Copyright 2020 Google LLC
  4347. *
  4348. * Licensed under the Apache License, Version 2.0 (the "License");
  4349. * you may not use this file except in compliance with the License.
  4350. * You may obtain a copy of the License at
  4351. *
  4352. * http://www.apache.org/licenses/LICENSE-2.0
  4353. *
  4354. * Unless required by applicable law or agreed to in writing, software
  4355. * distributed under the License is distributed on an "AS IS" BASIS,
  4356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4357. * See the License for the specific language governing permissions and
  4358. * limitations under the License.
  4359. */
  4360. /**
  4361. * Maps the mode string in action code URL to Action Code Info operation.
  4362. *
  4363. * @param mode
  4364. */
  4365. function parseMode(mode) {
  4366. switch (mode) {
  4367. case 'recoverEmail':
  4368. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  4369. case 'resetPassword':
  4370. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  4371. case 'signIn':
  4372. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  4373. case 'verifyEmail':
  4374. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  4375. case 'verifyAndChangeEmail':
  4376. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  4377. case 'revertSecondFactorAddition':
  4378. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  4379. default:
  4380. return null;
  4381. }
  4382. }
  4383. /**
  4384. * Helper to parse FDL links
  4385. *
  4386. * @param url
  4387. */
  4388. function parseDeepLink(url) {
  4389. var link = util.querystringDecode(util.extractQuerystring(url))['link'];
  4390. // Double link case (automatic redirect).
  4391. var doubleDeepLink = link
  4392. ? util.querystringDecode(util.extractQuerystring(link))['deep_link_id']
  4393. : null;
  4394. // iOS custom scheme links.
  4395. var iOSDeepLink = util.querystringDecode(util.extractQuerystring(url))['deep_link_id'];
  4396. var iOSDoubleDeepLink = iOSDeepLink
  4397. ? util.querystringDecode(util.extractQuerystring(iOSDeepLink))['link']
  4398. : null;
  4399. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  4400. }
  4401. /**
  4402. * A utility class to parse email action URLs such as password reset, email verification,
  4403. * email link sign in, etc.
  4404. *
  4405. * @public
  4406. */
  4407. var ActionCodeURL = /** @class */ (function () {
  4408. /**
  4409. * @param actionLink - The link from which to extract the URL.
  4410. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4411. *
  4412. * @internal
  4413. */
  4414. function ActionCodeURL(actionLink) {
  4415. var _a, _b, _c, _d, _e, _f;
  4416. var searchParams = util.querystringDecode(util.extractQuerystring(actionLink));
  4417. var apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  4418. var code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  4419. var operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  4420. // Validate API key, code and mode.
  4421. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4422. this.apiKey = apiKey;
  4423. this.operation = operation;
  4424. this.code = code;
  4425. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  4426. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  4427. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  4428. }
  4429. /**
  4430. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  4431. * otherwise returns null.
  4432. *
  4433. * @param link - The email action link string.
  4434. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4435. *
  4436. * @public
  4437. */
  4438. ActionCodeURL.parseLink = function (link) {
  4439. var actionLink = parseDeepLink(link);
  4440. try {
  4441. return new ActionCodeURL(actionLink);
  4442. }
  4443. catch (_a) {
  4444. return null;
  4445. }
  4446. };
  4447. return ActionCodeURL;
  4448. }());
  4449. /**
  4450. * Parses the email action link string and returns an {@link ActionCodeURL} if
  4451. * the link is valid, otherwise returns null.
  4452. *
  4453. * @public
  4454. */
  4455. function parseActionCodeURL(link) {
  4456. return ActionCodeURL.parseLink(link);
  4457. }
  4458. /**
  4459. * @license
  4460. * Copyright 2020 Google LLC
  4461. *
  4462. * Licensed under the Apache License, Version 2.0 (the "License");
  4463. * you may not use this file except in compliance with the License.
  4464. * You may obtain a copy of the License at
  4465. *
  4466. * http://www.apache.org/licenses/LICENSE-2.0
  4467. *
  4468. * Unless required by applicable law or agreed to in writing, software
  4469. * distributed under the License is distributed on an "AS IS" BASIS,
  4470. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4471. * See the License for the specific language governing permissions and
  4472. * limitations under the License.
  4473. */
  4474. /**
  4475. * Provider for generating {@link EmailAuthCredential}.
  4476. *
  4477. * @public
  4478. */
  4479. var EmailAuthProvider = /** @class */ (function () {
  4480. function EmailAuthProvider() {
  4481. /**
  4482. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4483. */
  4484. this.providerId = EmailAuthProvider.PROVIDER_ID;
  4485. }
  4486. /**
  4487. * Initialize an {@link AuthCredential} using an email and password.
  4488. *
  4489. * @example
  4490. * ```javascript
  4491. * const authCredential = EmailAuthProvider.credential(email, password);
  4492. * const userCredential = await signInWithCredential(auth, authCredential);
  4493. * ```
  4494. *
  4495. * @example
  4496. * ```javascript
  4497. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  4498. * ```
  4499. *
  4500. * @param email - Email address.
  4501. * @param password - User account password.
  4502. * @returns The auth provider credential.
  4503. */
  4504. EmailAuthProvider.credential = function (email, password) {
  4505. return EmailAuthCredential._fromEmailAndPassword(email, password);
  4506. };
  4507. /**
  4508. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  4509. * email link operation.
  4510. *
  4511. * @example
  4512. * ```javascript
  4513. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  4514. * const userCredential = await signInWithCredential(auth, authCredential);
  4515. * ```
  4516. *
  4517. * @example
  4518. * ```javascript
  4519. * await sendSignInLinkToEmail(auth, email);
  4520. * // Obtain emailLink from user.
  4521. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  4522. * ```
  4523. *
  4524. * @param auth - The {@link Auth} instance used to verify the link.
  4525. * @param email - Email address.
  4526. * @param emailLink - Sign-in email link.
  4527. * @returns - The auth provider credential.
  4528. */
  4529. EmailAuthProvider.credentialWithLink = function (email, emailLink) {
  4530. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  4531. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4532. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  4533. };
  4534. /**
  4535. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4536. */
  4537. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  4538. /**
  4539. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  4540. */
  4541. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  4542. /**
  4543. * Always set to {@link SignInMethod}.EMAIL_LINK.
  4544. */
  4545. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  4546. return EmailAuthProvider;
  4547. }());
  4548. /**
  4549. * @license
  4550. * Copyright 2020 Google LLC
  4551. *
  4552. * Licensed under the Apache License, Version 2.0 (the "License");
  4553. * you may not use this file except in compliance with the License.
  4554. * You may obtain a copy of the License at
  4555. *
  4556. * http://www.apache.org/licenses/LICENSE-2.0
  4557. *
  4558. * Unless required by applicable law or agreed to in writing, software
  4559. * distributed under the License is distributed on an "AS IS" BASIS,
  4560. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4561. * See the License for the specific language governing permissions and
  4562. * limitations under the License.
  4563. */
  4564. /**
  4565. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  4566. *
  4567. * This class is not meant to be instantiated directly.
  4568. *
  4569. * @public
  4570. */
  4571. var FederatedAuthProvider = /** @class */ (function () {
  4572. /**
  4573. * Constructor for generic OAuth providers.
  4574. *
  4575. * @param providerId - Provider for which credentials should be generated.
  4576. */
  4577. function FederatedAuthProvider(providerId) {
  4578. this.providerId = providerId;
  4579. /** @internal */
  4580. this.defaultLanguageCode = null;
  4581. /** @internal */
  4582. this.customParameters = {};
  4583. }
  4584. /**
  4585. * Set the language gode.
  4586. *
  4587. * @param languageCode - language code
  4588. */
  4589. FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
  4590. this.defaultLanguageCode = languageCode;
  4591. };
  4592. /**
  4593. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  4594. * operations.
  4595. *
  4596. * @remarks
  4597. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  4598. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  4599. *
  4600. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  4601. */
  4602. FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
  4603. this.customParameters = customOAuthParameters;
  4604. return this;
  4605. };
  4606. /**
  4607. * Retrieve the current list of {@link CustomParameters}.
  4608. */
  4609. FederatedAuthProvider.prototype.getCustomParameters = function () {
  4610. return this.customParameters;
  4611. };
  4612. return FederatedAuthProvider;
  4613. }());
  4614. /**
  4615. * @license
  4616. * Copyright 2019 Google LLC
  4617. *
  4618. * Licensed under the Apache License, Version 2.0 (the "License");
  4619. * you may not use this file except in compliance with the License.
  4620. * You may obtain a copy of the License at
  4621. *
  4622. * http://www.apache.org/licenses/LICENSE-2.0
  4623. *
  4624. * Unless required by applicable law or agreed to in writing, software
  4625. * distributed under the License is distributed on an "AS IS" BASIS,
  4626. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4627. * See the License for the specific language governing permissions and
  4628. * limitations under the License.
  4629. */
  4630. /**
  4631. * Common code to all OAuth providers. This is separate from the
  4632. * {@link OAuthProvider} so that child providers (like
  4633. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  4634. * Instead, they rely on a static `credential` method.
  4635. */
  4636. var BaseOAuthProvider = /** @class */ (function (_super) {
  4637. tslib.__extends(BaseOAuthProvider, _super);
  4638. function BaseOAuthProvider() {
  4639. var _this = _super !== null && _super.apply(this, arguments) || this;
  4640. /** @internal */
  4641. _this.scopes = [];
  4642. return _this;
  4643. }
  4644. /**
  4645. * Add an OAuth scope to the credential.
  4646. *
  4647. * @param scope - Provider OAuth scope to add.
  4648. */
  4649. BaseOAuthProvider.prototype.addScope = function (scope) {
  4650. // If not already added, add scope to list.
  4651. if (!this.scopes.includes(scope)) {
  4652. this.scopes.push(scope);
  4653. }
  4654. return this;
  4655. };
  4656. /**
  4657. * Retrieve the current list of OAuth scopes.
  4658. */
  4659. BaseOAuthProvider.prototype.getScopes = function () {
  4660. return tslib.__spreadArray([], this.scopes, true);
  4661. };
  4662. return BaseOAuthProvider;
  4663. }(FederatedAuthProvider));
  4664. /**
  4665. * Provider for generating generic {@link OAuthCredential}.
  4666. *
  4667. * @example
  4668. * ```javascript
  4669. * // Sign in using a redirect.
  4670. * const provider = new OAuthProvider('google.com');
  4671. * // Start a sign in process for an unauthenticated user.
  4672. * provider.addScope('profile');
  4673. * provider.addScope('email');
  4674. * await signInWithRedirect(auth, provider);
  4675. * // This will trigger a full page redirect away from your app
  4676. *
  4677. * // After returning from the redirect when your app initializes you can obtain the result
  4678. * const result = await getRedirectResult(auth);
  4679. * if (result) {
  4680. * // This is the signed-in user
  4681. * const user = result.user;
  4682. * // This gives you a OAuth Access Token for the provider.
  4683. * const credential = provider.credentialFromResult(auth, result);
  4684. * const token = credential.accessToken;
  4685. * }
  4686. * ```
  4687. *
  4688. * @example
  4689. * ```javascript
  4690. * // Sign in using a popup.
  4691. * const provider = new OAuthProvider('google.com');
  4692. * provider.addScope('profile');
  4693. * provider.addScope('email');
  4694. * const result = await signInWithPopup(auth, provider);
  4695. *
  4696. * // The signed-in user info.
  4697. * const user = result.user;
  4698. * // This gives you a OAuth Access Token for the provider.
  4699. * const credential = provider.credentialFromResult(auth, result);
  4700. * const token = credential.accessToken;
  4701. * ```
  4702. * @public
  4703. */
  4704. var OAuthProvider = /** @class */ (function (_super) {
  4705. tslib.__extends(OAuthProvider, _super);
  4706. function OAuthProvider() {
  4707. return _super !== null && _super.apply(this, arguments) || this;
  4708. }
  4709. /**
  4710. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  4711. * @param json - A plain object or a JSON string
  4712. */
  4713. OAuthProvider.credentialFromJSON = function (json) {
  4714. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4715. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4716. return OAuthCredential._fromParams(obj);
  4717. };
  4718. /**
  4719. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  4720. *
  4721. * @remarks
  4722. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  4723. * the raw nonce must match the nonce field in the ID token.
  4724. *
  4725. * @example
  4726. * ```javascript
  4727. * // `googleUser` from the onsuccess Google Sign In callback.
  4728. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4729. * const provider = new OAuthProvider('google.com');
  4730. * const credential = provider.credential({
  4731. * idToken: googleUser.getAuthResponse().id_token,
  4732. * });
  4733. * const result = await signInWithCredential(credential);
  4734. * ```
  4735. *
  4736. * @param params - Either the options object containing the ID token, access token and raw nonce
  4737. * or the ID token string.
  4738. */
  4739. OAuthProvider.prototype.credential = function (params) {
  4740. return this._credential(tslib.__assign(tslib.__assign({}, params), { nonce: params.rawNonce }));
  4741. };
  4742. /** An internal credential method that accepts more permissive options */
  4743. OAuthProvider.prototype._credential = function (params) {
  4744. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4745. // For OAuthCredential, sign in method is same as providerId.
  4746. return OAuthCredential._fromParams(tslib.__assign(tslib.__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  4747. };
  4748. /**
  4749. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4750. *
  4751. * @param userCredential - The user credential.
  4752. */
  4753. OAuthProvider.credentialFromResult = function (userCredential) {
  4754. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  4755. };
  4756. /**
  4757. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4758. * thrown during a sign-in, link, or reauthenticate operation.
  4759. *
  4760. * @param userCredential - The user credential.
  4761. */
  4762. OAuthProvider.credentialFromError = function (error) {
  4763. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  4764. };
  4765. OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
  4766. var tokenResponse = _a._tokenResponse;
  4767. if (!tokenResponse) {
  4768. return null;
  4769. }
  4770. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
  4771. if (!oauthAccessToken &&
  4772. !oauthTokenSecret &&
  4773. !oauthIdToken &&
  4774. !pendingToken) {
  4775. return null;
  4776. }
  4777. if (!providerId) {
  4778. return null;
  4779. }
  4780. try {
  4781. return new OAuthProvider(providerId)._credential({
  4782. idToken: oauthIdToken,
  4783. accessToken: oauthAccessToken,
  4784. nonce: nonce,
  4785. pendingToken: pendingToken
  4786. });
  4787. }
  4788. catch (e) {
  4789. return null;
  4790. }
  4791. };
  4792. return OAuthProvider;
  4793. }(BaseOAuthProvider));
  4794. /**
  4795. * @license
  4796. * Copyright 2020 Google LLC
  4797. *
  4798. * Licensed under the Apache License, Version 2.0 (the "License");
  4799. * you may not use this file except in compliance with the License.
  4800. * You may obtain a copy of the License at
  4801. *
  4802. * http://www.apache.org/licenses/LICENSE-2.0
  4803. *
  4804. * Unless required by applicable law or agreed to in writing, software
  4805. * distributed under the License is distributed on an "AS IS" BASIS,
  4806. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4807. * See the License for the specific language governing permissions and
  4808. * limitations under the License.
  4809. */
  4810. /**
  4811. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  4812. *
  4813. * @example
  4814. * ```javascript
  4815. * // Sign in using a redirect.
  4816. * const provider = new FacebookAuthProvider();
  4817. * // Start a sign in process for an unauthenticated user.
  4818. * provider.addScope('user_birthday');
  4819. * await signInWithRedirect(auth, provider);
  4820. * // This will trigger a full page redirect away from your app
  4821. *
  4822. * // After returning from the redirect when your app initializes you can obtain the result
  4823. * const result = await getRedirectResult(auth);
  4824. * if (result) {
  4825. * // This is the signed-in user
  4826. * const user = result.user;
  4827. * // This gives you a Facebook Access Token.
  4828. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4829. * const token = credential.accessToken;
  4830. * }
  4831. * ```
  4832. *
  4833. * @example
  4834. * ```javascript
  4835. * // Sign in using a popup.
  4836. * const provider = new FacebookAuthProvider();
  4837. * provider.addScope('user_birthday');
  4838. * const result = await signInWithPopup(auth, provider);
  4839. *
  4840. * // The signed-in user info.
  4841. * const user = result.user;
  4842. * // This gives you a Facebook Access Token.
  4843. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4844. * const token = credential.accessToken;
  4845. * ```
  4846. *
  4847. * @public
  4848. */
  4849. var FacebookAuthProvider = /** @class */ (function (_super) {
  4850. tslib.__extends(FacebookAuthProvider, _super);
  4851. function FacebookAuthProvider() {
  4852. return _super.call(this, "facebook.com" /* ProviderId.FACEBOOK */) || this;
  4853. }
  4854. /**
  4855. * Creates a credential for Facebook.
  4856. *
  4857. * @example
  4858. * ```javascript
  4859. * // `event` from the Facebook auth.authResponseChange callback.
  4860. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  4861. * const result = await signInWithCredential(credential);
  4862. * ```
  4863. *
  4864. * @param accessToken - Facebook access token.
  4865. */
  4866. FacebookAuthProvider.credential = function (accessToken) {
  4867. return OAuthCredential._fromParams({
  4868. providerId: FacebookAuthProvider.PROVIDER_ID,
  4869. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  4870. accessToken: accessToken
  4871. });
  4872. };
  4873. /**
  4874. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4875. *
  4876. * @param userCredential - The user credential.
  4877. */
  4878. FacebookAuthProvider.credentialFromResult = function (userCredential) {
  4879. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  4880. };
  4881. /**
  4882. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4883. * thrown during a sign-in, link, or reauthenticate operation.
  4884. *
  4885. * @param userCredential - The user credential.
  4886. */
  4887. FacebookAuthProvider.credentialFromError = function (error) {
  4888. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4889. };
  4890. FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
  4891. var tokenResponse = _a._tokenResponse;
  4892. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4893. return null;
  4894. }
  4895. if (!tokenResponse.oauthAccessToken) {
  4896. return null;
  4897. }
  4898. try {
  4899. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  4900. }
  4901. catch (_b) {
  4902. return null;
  4903. }
  4904. };
  4905. /** Always set to {@link SignInMethod}.FACEBOOK. */
  4906. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  4907. /** Always set to {@link ProviderId}.FACEBOOK. */
  4908. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  4909. return FacebookAuthProvider;
  4910. }(BaseOAuthProvider));
  4911. /**
  4912. * @license
  4913. * Copyright 2020 Google LLC
  4914. *
  4915. * Licensed under the Apache License, Version 2.0 (the "License");
  4916. * you may not use this file except in compliance with the License.
  4917. * You may obtain a copy of the License at
  4918. *
  4919. * http://www.apache.org/licenses/LICENSE-2.0
  4920. *
  4921. * Unless required by applicable law or agreed to in writing, software
  4922. * distributed under the License is distributed on an "AS IS" BASIS,
  4923. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4924. * See the License for the specific language governing permissions and
  4925. * limitations under the License.
  4926. */
  4927. /**
  4928. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  4929. *
  4930. * @example
  4931. * ```javascript
  4932. * // Sign in using a redirect.
  4933. * const provider = new GoogleAuthProvider();
  4934. * // Start a sign in process for an unauthenticated user.
  4935. * provider.addScope('profile');
  4936. * provider.addScope('email');
  4937. * await signInWithRedirect(auth, provider);
  4938. * // This will trigger a full page redirect away from your app
  4939. *
  4940. * // After returning from the redirect when your app initializes you can obtain the result
  4941. * const result = await getRedirectResult(auth);
  4942. * if (result) {
  4943. * // This is the signed-in user
  4944. * const user = result.user;
  4945. * // This gives you a Google Access Token.
  4946. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4947. * const token = credential.accessToken;
  4948. * }
  4949. * ```
  4950. *
  4951. * @example
  4952. * ```javascript
  4953. * // Sign in using a popup.
  4954. * const provider = new GoogleAuthProvider();
  4955. * provider.addScope('profile');
  4956. * provider.addScope('email');
  4957. * const result = await signInWithPopup(auth, provider);
  4958. *
  4959. * // The signed-in user info.
  4960. * const user = result.user;
  4961. * // This gives you a Google Access Token.
  4962. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4963. * const token = credential.accessToken;
  4964. * ```
  4965. *
  4966. * @public
  4967. */
  4968. var GoogleAuthProvider = /** @class */ (function (_super) {
  4969. tslib.__extends(GoogleAuthProvider, _super);
  4970. function GoogleAuthProvider() {
  4971. var _this = _super.call(this, "google.com" /* ProviderId.GOOGLE */) || this;
  4972. _this.addScope('profile');
  4973. return _this;
  4974. }
  4975. /**
  4976. * Creates a credential for Google. At least one of ID token and access token is required.
  4977. *
  4978. * @example
  4979. * ```javascript
  4980. * // \`googleUser\` from the onsuccess Google Sign In callback.
  4981. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  4982. * const result = await signInWithCredential(credential);
  4983. * ```
  4984. *
  4985. * @param idToken - Google ID token.
  4986. * @param accessToken - Google access token.
  4987. */
  4988. GoogleAuthProvider.credential = function (idToken, accessToken) {
  4989. return OAuthCredential._fromParams({
  4990. providerId: GoogleAuthProvider.PROVIDER_ID,
  4991. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  4992. idToken: idToken,
  4993. accessToken: accessToken
  4994. });
  4995. };
  4996. /**
  4997. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4998. *
  4999. * @param userCredential - The user credential.
  5000. */
  5001. GoogleAuthProvider.credentialFromResult = function (userCredential) {
  5002. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  5003. };
  5004. /**
  5005. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5006. * thrown during a sign-in, link, or reauthenticate operation.
  5007. *
  5008. * @param userCredential - The user credential.
  5009. */
  5010. GoogleAuthProvider.credentialFromError = function (error) {
  5011. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5012. };
  5013. GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
  5014. var tokenResponse = _a._tokenResponse;
  5015. if (!tokenResponse) {
  5016. return null;
  5017. }
  5018. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
  5019. if (!oauthIdToken && !oauthAccessToken) {
  5020. // This could be an oauth 1 credential or a phone credential
  5021. return null;
  5022. }
  5023. try {
  5024. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  5025. }
  5026. catch (_c) {
  5027. return null;
  5028. }
  5029. };
  5030. /** Always set to {@link SignInMethod}.GOOGLE. */
  5031. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  5032. /** Always set to {@link ProviderId}.GOOGLE. */
  5033. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  5034. return GoogleAuthProvider;
  5035. }(BaseOAuthProvider));
  5036. /**
  5037. * @license
  5038. * Copyright 2020 Google LLC
  5039. *
  5040. * Licensed under the Apache License, Version 2.0 (the "License");
  5041. * you may not use this file except in compliance with the License.
  5042. * You may obtain a copy of the License at
  5043. *
  5044. * http://www.apache.org/licenses/LICENSE-2.0
  5045. *
  5046. * Unless required by applicable law or agreed to in writing, software
  5047. * distributed under the License is distributed on an "AS IS" BASIS,
  5048. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5049. * See the License for the specific language governing permissions and
  5050. * limitations under the License.
  5051. */
  5052. /**
  5053. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  5054. *
  5055. * @remarks
  5056. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  5057. * the {@link signInWithPopup} handler:
  5058. *
  5059. * @example
  5060. * ```javascript
  5061. * // Sign in using a redirect.
  5062. * const provider = new GithubAuthProvider();
  5063. * // Start a sign in process for an unauthenticated user.
  5064. * provider.addScope('repo');
  5065. * await signInWithRedirect(auth, provider);
  5066. * // This will trigger a full page redirect away from your app
  5067. *
  5068. * // After returning from the redirect when your app initializes you can obtain the result
  5069. * const result = await getRedirectResult(auth);
  5070. * if (result) {
  5071. * // This is the signed-in user
  5072. * const user = result.user;
  5073. * // This gives you a Github Access Token.
  5074. * const credential = GithubAuthProvider.credentialFromResult(result);
  5075. * const token = credential.accessToken;
  5076. * }
  5077. * ```
  5078. *
  5079. * @example
  5080. * ```javascript
  5081. * // Sign in using a popup.
  5082. * const provider = new GithubAuthProvider();
  5083. * provider.addScope('repo');
  5084. * const result = await signInWithPopup(auth, provider);
  5085. *
  5086. * // The signed-in user info.
  5087. * const user = result.user;
  5088. * // This gives you a Github Access Token.
  5089. * const credential = GithubAuthProvider.credentialFromResult(result);
  5090. * const token = credential.accessToken;
  5091. * ```
  5092. * @public
  5093. */
  5094. var GithubAuthProvider = /** @class */ (function (_super) {
  5095. tslib.__extends(GithubAuthProvider, _super);
  5096. function GithubAuthProvider() {
  5097. return _super.call(this, "github.com" /* ProviderId.GITHUB */) || this;
  5098. }
  5099. /**
  5100. * Creates a credential for Github.
  5101. *
  5102. * @param accessToken - Github access token.
  5103. */
  5104. GithubAuthProvider.credential = function (accessToken) {
  5105. return OAuthCredential._fromParams({
  5106. providerId: GithubAuthProvider.PROVIDER_ID,
  5107. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  5108. accessToken: accessToken
  5109. });
  5110. };
  5111. /**
  5112. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5113. *
  5114. * @param userCredential - The user credential.
  5115. */
  5116. GithubAuthProvider.credentialFromResult = function (userCredential) {
  5117. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  5118. };
  5119. /**
  5120. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5121. * thrown during a sign-in, link, or reauthenticate operation.
  5122. *
  5123. * @param userCredential - The user credential.
  5124. */
  5125. GithubAuthProvider.credentialFromError = function (error) {
  5126. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5127. };
  5128. GithubAuthProvider.credentialFromTaggedObject = function (_a) {
  5129. var tokenResponse = _a._tokenResponse;
  5130. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  5131. return null;
  5132. }
  5133. if (!tokenResponse.oauthAccessToken) {
  5134. return null;
  5135. }
  5136. try {
  5137. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  5138. }
  5139. catch (_b) {
  5140. return null;
  5141. }
  5142. };
  5143. /** Always set to {@link SignInMethod}.GITHUB. */
  5144. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  5145. /** Always set to {@link ProviderId}.GITHUB. */
  5146. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  5147. return GithubAuthProvider;
  5148. }(BaseOAuthProvider));
  5149. /**
  5150. * @license
  5151. * Copyright 2020 Google LLC
  5152. *
  5153. * Licensed under the Apache License, Version 2.0 (the "License");
  5154. * you may not use this file except in compliance with the License.
  5155. * You may obtain a copy of the License at
  5156. *
  5157. * http://www.apache.org/licenses/LICENSE-2.0
  5158. *
  5159. * Unless required by applicable law or agreed to in writing, software
  5160. * distributed under the License is distributed on an "AS IS" BASIS,
  5161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5162. * See the License for the specific language governing permissions and
  5163. * limitations under the License.
  5164. */
  5165. var IDP_REQUEST_URI = 'http://localhost';
  5166. /**
  5167. * @public
  5168. */
  5169. var SAMLAuthCredential = /** @class */ (function (_super) {
  5170. tslib.__extends(SAMLAuthCredential, _super);
  5171. /** @internal */
  5172. function SAMLAuthCredential(providerId, pendingToken) {
  5173. var _this = _super.call(this, providerId, providerId) || this;
  5174. _this.pendingToken = pendingToken;
  5175. return _this;
  5176. }
  5177. /** @internal */
  5178. SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
  5179. var request = this.buildRequest();
  5180. return signInWithIdp(auth, request);
  5181. };
  5182. /** @internal */
  5183. SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  5184. var request = this.buildRequest();
  5185. request.idToken = idToken;
  5186. return signInWithIdp(auth, request);
  5187. };
  5188. /** @internal */
  5189. SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  5190. var request = this.buildRequest();
  5191. request.autoCreate = false;
  5192. return signInWithIdp(auth, request);
  5193. };
  5194. /** {@inheritdoc AuthCredential.toJSON} */
  5195. SAMLAuthCredential.prototype.toJSON = function () {
  5196. return {
  5197. signInMethod: this.signInMethod,
  5198. providerId: this.providerId,
  5199. pendingToken: this.pendingToken
  5200. };
  5201. };
  5202. /**
  5203. * Static method to deserialize a JSON representation of an object into an
  5204. * {@link AuthCredential}.
  5205. *
  5206. * @param json - Input can be either Object or the stringified representation of the object.
  5207. * When string is provided, JSON.parse would be called first.
  5208. *
  5209. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  5210. */
  5211. SAMLAuthCredential.fromJSON = function (json) {
  5212. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  5213. var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
  5214. if (!providerId ||
  5215. !signInMethod ||
  5216. !pendingToken ||
  5217. providerId !== signInMethod) {
  5218. return null;
  5219. }
  5220. return new SAMLAuthCredential(providerId, pendingToken);
  5221. };
  5222. /**
  5223. * Helper static method to avoid exposing the constructor to end users.
  5224. *
  5225. * @internal
  5226. */
  5227. SAMLAuthCredential._create = function (providerId, pendingToken) {
  5228. return new SAMLAuthCredential(providerId, pendingToken);
  5229. };
  5230. SAMLAuthCredential.prototype.buildRequest = function () {
  5231. return {
  5232. requestUri: IDP_REQUEST_URI,
  5233. returnSecureToken: true,
  5234. pendingToken: this.pendingToken
  5235. };
  5236. };
  5237. return SAMLAuthCredential;
  5238. }(AuthCredential));
  5239. /**
  5240. * @license
  5241. * Copyright 2020 Google LLC
  5242. *
  5243. * Licensed under the Apache License, Version 2.0 (the "License");
  5244. * you may not use this file except in compliance with the License.
  5245. * You may obtain a copy of the License at
  5246. *
  5247. * http://www.apache.org/licenses/LICENSE-2.0
  5248. *
  5249. * Unless required by applicable law or agreed to in writing, software
  5250. * distributed under the License is distributed on an "AS IS" BASIS,
  5251. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5252. * See the License for the specific language governing permissions and
  5253. * limitations under the License.
  5254. */
  5255. var SAML_PROVIDER_PREFIX = 'saml.';
  5256. /**
  5257. * An {@link AuthProvider} for SAML.
  5258. *
  5259. * @public
  5260. */
  5261. var SAMLAuthProvider = /** @class */ (function (_super) {
  5262. tslib.__extends(SAMLAuthProvider, _super);
  5263. /**
  5264. * Constructor. The providerId must start with "saml."
  5265. * @param providerId - SAML provider ID.
  5266. */
  5267. function SAMLAuthProvider(providerId) {
  5268. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5269. return _super.call(this, providerId) || this;
  5270. }
  5271. /**
  5272. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  5273. * successful SAML flow completes.
  5274. *
  5275. * @remarks
  5276. *
  5277. * For example, to get an {@link AuthCredential}, you could write the
  5278. * following code:
  5279. *
  5280. * ```js
  5281. * const userCredential = await signInWithPopup(auth, samlProvider);
  5282. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  5283. * ```
  5284. *
  5285. * @param userCredential - The user credential.
  5286. */
  5287. SAMLAuthProvider.credentialFromResult = function (userCredential) {
  5288. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  5289. };
  5290. /**
  5291. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5292. * thrown during a sign-in, link, or reauthenticate operation.
  5293. *
  5294. * @param userCredential - The user credential.
  5295. */
  5296. SAMLAuthProvider.credentialFromError = function (error) {
  5297. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  5298. };
  5299. /**
  5300. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  5301. * @param json - A plain object or a JSON string
  5302. */
  5303. SAMLAuthProvider.credentialFromJSON = function (json) {
  5304. var credential = SAMLAuthCredential.fromJSON(json);
  5305. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5306. return credential;
  5307. };
  5308. SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
  5309. var tokenResponse = _a._tokenResponse;
  5310. if (!tokenResponse) {
  5311. return null;
  5312. }
  5313. var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
  5314. if (!pendingToken || !providerId) {
  5315. return null;
  5316. }
  5317. try {
  5318. return SAMLAuthCredential._create(providerId, pendingToken);
  5319. }
  5320. catch (e) {
  5321. return null;
  5322. }
  5323. };
  5324. return SAMLAuthProvider;
  5325. }(FederatedAuthProvider));
  5326. /**
  5327. * @license
  5328. * Copyright 2020 Google LLC
  5329. *
  5330. * Licensed under the Apache License, Version 2.0 (the "License");
  5331. * you may not use this file except in compliance with the License.
  5332. * You may obtain a copy of the License at
  5333. *
  5334. * http://www.apache.org/licenses/LICENSE-2.0
  5335. *
  5336. * Unless required by applicable law or agreed to in writing, software
  5337. * distributed under the License is distributed on an "AS IS" BASIS,
  5338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5339. * See the License for the specific language governing permissions and
  5340. * limitations under the License.
  5341. */
  5342. /**
  5343. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  5344. *
  5345. * @example
  5346. * ```javascript
  5347. * // Sign in using a redirect.
  5348. * const provider = new TwitterAuthProvider();
  5349. * // Start a sign in process for an unauthenticated user.
  5350. * await signInWithRedirect(auth, provider);
  5351. * // This will trigger a full page redirect away from your app
  5352. *
  5353. * // After returning from the redirect when your app initializes you can obtain the result
  5354. * const result = await getRedirectResult(auth);
  5355. * if (result) {
  5356. * // This is the signed-in user
  5357. * const user = result.user;
  5358. * // This gives you a Twitter Access Token and Secret.
  5359. * const credential = TwitterAuthProvider.credentialFromResult(result);
  5360. * const token = credential.accessToken;
  5361. * const secret = credential.secret;
  5362. * }
  5363. * ```
  5364. *
  5365. * @example
  5366. * ```javascript
  5367. * // Sign in using a popup.
  5368. * const provider = new TwitterAuthProvider();
  5369. * const result = await signInWithPopup(auth, provider);
  5370. *
  5371. * // The signed-in user info.
  5372. * const user = result.user;
  5373. * // This gives you a Twitter Access Token and Secret.
  5374. * const credential = TwitterAuthProvider.credentialFromResult(result);
  5375. * const token = credential.accessToken;
  5376. * const secret = credential.secret;
  5377. * ```
  5378. *
  5379. * @public
  5380. */
  5381. var TwitterAuthProvider = /** @class */ (function (_super) {
  5382. tslib.__extends(TwitterAuthProvider, _super);
  5383. function TwitterAuthProvider() {
  5384. return _super.call(this, "twitter.com" /* ProviderId.TWITTER */) || this;
  5385. }
  5386. /**
  5387. * Creates a credential for Twitter.
  5388. *
  5389. * @param token - Twitter access token.
  5390. * @param secret - Twitter secret.
  5391. */
  5392. TwitterAuthProvider.credential = function (token, secret) {
  5393. return OAuthCredential._fromParams({
  5394. providerId: TwitterAuthProvider.PROVIDER_ID,
  5395. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  5396. oauthToken: token,
  5397. oauthTokenSecret: secret
  5398. });
  5399. };
  5400. /**
  5401. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5402. *
  5403. * @param userCredential - The user credential.
  5404. */
  5405. TwitterAuthProvider.credentialFromResult = function (userCredential) {
  5406. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  5407. };
  5408. /**
  5409. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5410. * thrown during a sign-in, link, or reauthenticate operation.
  5411. *
  5412. * @param userCredential - The user credential.
  5413. */
  5414. TwitterAuthProvider.credentialFromError = function (error) {
  5415. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5416. };
  5417. TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
  5418. var tokenResponse = _a._tokenResponse;
  5419. if (!tokenResponse) {
  5420. return null;
  5421. }
  5422. var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
  5423. if (!oauthAccessToken || !oauthTokenSecret) {
  5424. return null;
  5425. }
  5426. try {
  5427. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  5428. }
  5429. catch (_c) {
  5430. return null;
  5431. }
  5432. };
  5433. /** Always set to {@link SignInMethod}.TWITTER. */
  5434. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  5435. /** Always set to {@link ProviderId}.TWITTER. */
  5436. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  5437. return TwitterAuthProvider;
  5438. }(BaseOAuthProvider));
  5439. /**
  5440. * @license
  5441. * Copyright 2020 Google LLC
  5442. *
  5443. * Licensed under the Apache License, Version 2.0 (the "License");
  5444. * you may not use this file except in compliance with the License.
  5445. * You may obtain a copy of the License at
  5446. *
  5447. * http://www.apache.org/licenses/LICENSE-2.0
  5448. *
  5449. * Unless required by applicable law or agreed to in writing, software
  5450. * distributed under the License is distributed on an "AS IS" BASIS,
  5451. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5452. * See the License for the specific language governing permissions and
  5453. * limitations under the License.
  5454. */
  5455. function signUp(auth, request) {
  5456. return tslib.__awaiter(this, void 0, void 0, function () {
  5457. return tslib.__generator(this, function (_a) {
  5458. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request))];
  5459. });
  5460. });
  5461. }
  5462. /**
  5463. * @license
  5464. * Copyright 2020 Google LLC
  5465. *
  5466. * Licensed under the Apache License, Version 2.0 (the "License");
  5467. * you may not use this file except in compliance with the License.
  5468. * You may obtain a copy of the License at
  5469. *
  5470. * http://www.apache.org/licenses/LICENSE-2.0
  5471. *
  5472. * Unless required by applicable law or agreed to in writing, software
  5473. * distributed under the License is distributed on an "AS IS" BASIS,
  5474. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5475. * See the License for the specific language governing permissions and
  5476. * limitations under the License.
  5477. */
  5478. var UserCredentialImpl = /** @class */ (function () {
  5479. function UserCredentialImpl(params) {
  5480. this.user = params.user;
  5481. this.providerId = params.providerId;
  5482. this._tokenResponse = params._tokenResponse;
  5483. this.operationType = params.operationType;
  5484. }
  5485. UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
  5486. if (isAnonymous === void 0) { isAnonymous = false; }
  5487. return tslib.__awaiter(this, void 0, void 0, function () {
  5488. var user, providerId, userCred;
  5489. return tslib.__generator(this, function (_a) {
  5490. switch (_a.label) {
  5491. case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
  5492. case 1:
  5493. user = _a.sent();
  5494. providerId = providerIdForResponse(idTokenResponse);
  5495. userCred = new UserCredentialImpl({
  5496. user: user,
  5497. providerId: providerId,
  5498. _tokenResponse: idTokenResponse,
  5499. operationType: operationType
  5500. });
  5501. return [2 /*return*/, userCred];
  5502. }
  5503. });
  5504. });
  5505. };
  5506. UserCredentialImpl._forOperation = function (user, operationType, response) {
  5507. return tslib.__awaiter(this, void 0, void 0, function () {
  5508. var providerId;
  5509. return tslib.__generator(this, function (_a) {
  5510. switch (_a.label) {
  5511. case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  5512. case 1:
  5513. _a.sent();
  5514. providerId = providerIdForResponse(response);
  5515. return [2 /*return*/, new UserCredentialImpl({
  5516. user: user,
  5517. providerId: providerId,
  5518. _tokenResponse: response,
  5519. operationType: operationType
  5520. })];
  5521. }
  5522. });
  5523. });
  5524. };
  5525. return UserCredentialImpl;
  5526. }());
  5527. function providerIdForResponse(response) {
  5528. if (response.providerId) {
  5529. return response.providerId;
  5530. }
  5531. if ('phoneNumber' in response) {
  5532. return "phone" /* ProviderId.PHONE */;
  5533. }
  5534. return null;
  5535. }
  5536. /**
  5537. * @license
  5538. * Copyright 2020 Google LLC
  5539. *
  5540. * Licensed under the Apache License, Version 2.0 (the "License");
  5541. * you may not use this file except in compliance with the License.
  5542. * You may obtain a copy of the License at
  5543. *
  5544. * http://www.apache.org/licenses/LICENSE-2.0
  5545. *
  5546. * Unless required by applicable law or agreed to in writing, software
  5547. * distributed under the License is distributed on an "AS IS" BASIS,
  5548. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5549. * See the License for the specific language governing permissions and
  5550. * limitations under the License.
  5551. */
  5552. /**
  5553. * Asynchronously signs in as an anonymous user.
  5554. *
  5555. * @remarks
  5556. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  5557. * new anonymous user identity will be created and returned.
  5558. *
  5559. * @param auth - The {@link Auth} instance.
  5560. *
  5561. * @public
  5562. */
  5563. function signInAnonymously(auth) {
  5564. var _a;
  5565. return tslib.__awaiter(this, void 0, void 0, function () {
  5566. var authInternal, response, userCredential;
  5567. return tslib.__generator(this, function (_b) {
  5568. switch (_b.label) {
  5569. case 0:
  5570. authInternal = _castAuth(auth);
  5571. return [4 /*yield*/, authInternal._initializationPromise];
  5572. case 1:
  5573. _b.sent();
  5574. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  5575. // If an anonymous user is already signed in, no need to sign them in again.
  5576. return [2 /*return*/, new UserCredentialImpl({
  5577. user: authInternal.currentUser,
  5578. providerId: null,
  5579. operationType: "signIn" /* OperationType.SIGN_IN */
  5580. })];
  5581. }
  5582. return [4 /*yield*/, signUp(authInternal, {
  5583. returnSecureToken: true
  5584. })];
  5585. case 2:
  5586. response = _b.sent();
  5587. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true)];
  5588. case 3:
  5589. userCredential = _b.sent();
  5590. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5591. case 4:
  5592. _b.sent();
  5593. return [2 /*return*/, userCredential];
  5594. }
  5595. });
  5596. });
  5597. }
  5598. /**
  5599. * @license
  5600. * Copyright 2020 Google LLC
  5601. *
  5602. * Licensed under the Apache License, Version 2.0 (the "License");
  5603. * you may not use this file except in compliance with the License.
  5604. * You may obtain a copy of the License at
  5605. *
  5606. * http://www.apache.org/licenses/LICENSE-2.0
  5607. *
  5608. * Unless required by applicable law or agreed to in writing, software
  5609. * distributed under the License is distributed on an "AS IS" BASIS,
  5610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5611. * See the License for the specific language governing permissions and
  5612. * limitations under the License.
  5613. */
  5614. var MultiFactorError = /** @class */ (function (_super) {
  5615. tslib.__extends(MultiFactorError, _super);
  5616. function MultiFactorError(auth, error, operationType, user) {
  5617. var _this = this;
  5618. var _a;
  5619. _this = _super.call(this, error.code, error.message) || this;
  5620. _this.operationType = operationType;
  5621. _this.user = user;
  5622. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5623. Object.setPrototypeOf(_this, MultiFactorError.prototype);
  5624. _this.customData = {
  5625. appName: auth.name,
  5626. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  5627. _serverResponse: error.customData._serverResponse,
  5628. operationType: operationType
  5629. };
  5630. return _this;
  5631. }
  5632. MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
  5633. return new MultiFactorError(auth, error, operationType, user);
  5634. };
  5635. return MultiFactorError;
  5636. }(util.FirebaseError));
  5637. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  5638. var idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  5639. ? credential._getReauthenticationResolver(auth)
  5640. : credential._getIdTokenResponse(auth);
  5641. return idTokenProvider.catch(function (error) {
  5642. if (error.code === "auth/".concat("multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */)) {
  5643. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  5644. }
  5645. throw error;
  5646. });
  5647. }
  5648. /**
  5649. * @license
  5650. * Copyright 2020 Google LLC
  5651. *
  5652. * Licensed under the Apache License, Version 2.0 (the "License");
  5653. * you may not use this file except in compliance with the License.
  5654. * You may obtain a copy of the License at
  5655. *
  5656. * http://www.apache.org/licenses/LICENSE-2.0
  5657. *
  5658. * Unless required by applicable law or agreed to in writing, software
  5659. * distributed under the License is distributed on an "AS IS" BASIS,
  5660. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5661. * See the License for the specific language governing permissions and
  5662. * limitations under the License.
  5663. */
  5664. /**
  5665. * Takes a set of UserInfo provider data and converts it to a set of names
  5666. */
  5667. function providerDataAsNames(providerData) {
  5668. return new Set(providerData
  5669. .map(function (_a) {
  5670. var providerId = _a.providerId;
  5671. return providerId;
  5672. })
  5673. .filter(function (pid) { return !!pid; }));
  5674. }
  5675. /**
  5676. * @license
  5677. * Copyright 2019 Google LLC
  5678. *
  5679. * Licensed under the Apache License, Version 2.0 (the "License");
  5680. * you may not use this file except in compliance with the License.
  5681. * You may obtain a copy of the License at
  5682. *
  5683. * http://www.apache.org/licenses/LICENSE-2.0
  5684. *
  5685. * Unless required by applicable law or agreed to in writing, software
  5686. * distributed under the License is distributed on an "AS IS" BASIS,
  5687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5688. * See the License for the specific language governing permissions and
  5689. * limitations under the License.
  5690. */
  5691. /**
  5692. * Unlinks a provider from a user account.
  5693. *
  5694. * @param user - The user.
  5695. * @param providerId - The provider to unlink.
  5696. *
  5697. * @public
  5698. */
  5699. function unlink(user, providerId) {
  5700. return tslib.__awaiter(this, void 0, void 0, function () {
  5701. var userInternal, providerUserInfo, _a, _b, providersLeft;
  5702. var _c;
  5703. return tslib.__generator(this, function (_d) {
  5704. switch (_d.label) {
  5705. case 0:
  5706. userInternal = util.getModularInstance(user);
  5707. return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
  5708. case 1:
  5709. _d.sent();
  5710. _a = deleteLinkedAccounts;
  5711. _b = [userInternal.auth];
  5712. _c = {};
  5713. return [4 /*yield*/, userInternal.getIdToken()];
  5714. case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
  5715. _c.deleteProvider = [providerId],
  5716. _c)]))];
  5717. case 3:
  5718. providerUserInfo = (_d.sent()).providerUserInfo;
  5719. providersLeft = providerDataAsNames(providerUserInfo || []);
  5720. userInternal.providerData = userInternal.providerData.filter(function (pd) {
  5721. return providersLeft.has(pd.providerId);
  5722. });
  5723. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  5724. userInternal.phoneNumber = null;
  5725. }
  5726. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  5727. case 4:
  5728. _d.sent();
  5729. return [2 /*return*/, userInternal];
  5730. }
  5731. });
  5732. });
  5733. }
  5734. function _link(user, credential, bypassAuthState) {
  5735. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5736. return tslib.__awaiter(this, void 0, void 0, function () {
  5737. var response, _a, _b, _c, _d, _e;
  5738. return tslib.__generator(this, function (_f) {
  5739. switch (_f.label) {
  5740. case 0:
  5741. _a = _logoutIfInvalidated;
  5742. _b = [user];
  5743. _d = (_c = credential)._linkToIdToken;
  5744. _e = [user.auth];
  5745. return [4 /*yield*/, user.getIdToken()];
  5746. case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])),
  5747. bypassAuthState]))];
  5748. case 2:
  5749. response = _f.sent();
  5750. return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response)];
  5751. }
  5752. });
  5753. });
  5754. }
  5755. function _assertLinkedStatus(expected, user, provider) {
  5756. return tslib.__awaiter(this, void 0, void 0, function () {
  5757. var providerIds, code;
  5758. return tslib.__generator(this, function (_a) {
  5759. switch (_a.label) {
  5760. case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
  5761. case 1:
  5762. _a.sent();
  5763. providerIds = providerDataAsNames(user.providerData);
  5764. code = expected === false
  5765. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  5766. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  5767. _assert(providerIds.has(provider) === expected, user.auth, code);
  5768. return [2 /*return*/];
  5769. }
  5770. });
  5771. });
  5772. }
  5773. /**
  5774. * @license
  5775. * Copyright 2019 Google LLC
  5776. *
  5777. * Licensed under the Apache License, Version 2.0 (the "License");
  5778. * you may not use this file except in compliance with the License.
  5779. * You may obtain a copy of the License at
  5780. *
  5781. * http://www.apache.org/licenses/LICENSE-2.0
  5782. *
  5783. * Unless required by applicable law or agreed to in writing, software
  5784. * distributed under the License is distributed on an "AS IS" BASIS,
  5785. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5786. * See the License for the specific language governing permissions and
  5787. * limitations under the License.
  5788. */
  5789. function _reauthenticate(user, credential, bypassAuthState) {
  5790. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5791. return tslib.__awaiter(this, void 0, void 0, function () {
  5792. var auth, operationType, response, parsed, localId, e_1;
  5793. return tslib.__generator(this, function (_a) {
  5794. switch (_a.label) {
  5795. case 0:
  5796. auth = user.auth;
  5797. operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  5798. _a.label = 1;
  5799. case 1:
  5800. _a.trys.push([1, 3, , 4]);
  5801. return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
  5802. case 2:
  5803. response = _a.sent();
  5804. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5805. parsed = _parseToken(response.idToken);
  5806. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5807. localId = parsed.sub;
  5808. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5809. return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
  5810. case 3:
  5811. e_1 = _a.sent();
  5812. // Convert user deleted error into user mismatch
  5813. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/".concat("user-not-found" /* AuthErrorCode.USER_DELETED */)) {
  5814. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5815. }
  5816. throw e_1;
  5817. case 4: return [2 /*return*/];
  5818. }
  5819. });
  5820. });
  5821. }
  5822. /**
  5823. * @license
  5824. * Copyright 2020 Google LLC
  5825. *
  5826. * Licensed under the Apache License, Version 2.0 (the "License");
  5827. * you may not use this file except in compliance with the License.
  5828. * You may obtain a copy of the License at
  5829. *
  5830. * http://www.apache.org/licenses/LICENSE-2.0
  5831. *
  5832. * Unless required by applicable law or agreed to in writing, software
  5833. * distributed under the License is distributed on an "AS IS" BASIS,
  5834. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5835. * See the License for the specific language governing permissions and
  5836. * limitations under the License.
  5837. */
  5838. function _signInWithCredential(auth, credential, bypassAuthState) {
  5839. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5840. return tslib.__awaiter(this, void 0, void 0, function () {
  5841. var operationType, response, userCredential;
  5842. return tslib.__generator(this, function (_a) {
  5843. switch (_a.label) {
  5844. case 0:
  5845. operationType = "signIn" /* OperationType.SIGN_IN */;
  5846. return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
  5847. case 1:
  5848. response = _a.sent();
  5849. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
  5850. case 2:
  5851. userCredential = _a.sent();
  5852. if (!!bypassAuthState) return [3 /*break*/, 4];
  5853. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  5854. case 3:
  5855. _a.sent();
  5856. _a.label = 4;
  5857. case 4: return [2 /*return*/, userCredential];
  5858. }
  5859. });
  5860. });
  5861. }
  5862. /**
  5863. * Asynchronously signs in with the given credentials.
  5864. *
  5865. * @remarks
  5866. * An {@link AuthProvider} can be used to generate the credential.
  5867. *
  5868. * @param auth - The {@link Auth} instance.
  5869. * @param credential - The auth credential.
  5870. *
  5871. * @public
  5872. */
  5873. function signInWithCredential(auth, credential) {
  5874. return tslib.__awaiter(this, void 0, void 0, function () {
  5875. return tslib.__generator(this, function (_a) {
  5876. return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
  5877. });
  5878. });
  5879. }
  5880. /**
  5881. * Links the user account with the given credentials.
  5882. *
  5883. * @remarks
  5884. * An {@link AuthProvider} can be used to generate the credential.
  5885. *
  5886. * @param user - The user.
  5887. * @param credential - The auth credential.
  5888. *
  5889. * @public
  5890. */
  5891. function linkWithCredential(user, credential) {
  5892. return tslib.__awaiter(this, void 0, void 0, function () {
  5893. var userInternal;
  5894. return tslib.__generator(this, function (_a) {
  5895. switch (_a.label) {
  5896. case 0:
  5897. userInternal = util.getModularInstance(user);
  5898. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
  5899. case 1:
  5900. _a.sent();
  5901. return [2 /*return*/, _link(userInternal, credential)];
  5902. }
  5903. });
  5904. });
  5905. }
  5906. /**
  5907. * Re-authenticates a user using a fresh credential.
  5908. *
  5909. * @remarks
  5910. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  5911. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error
  5912. * or a `TOKEN_EXPIRED` error.
  5913. *
  5914. * @param user - The user.
  5915. * @param credential - The auth credential.
  5916. *
  5917. * @public
  5918. */
  5919. function reauthenticateWithCredential(user, credential) {
  5920. return tslib.__awaiter(this, void 0, void 0, function () {
  5921. return tslib.__generator(this, function (_a) {
  5922. return [2 /*return*/, _reauthenticate(util.getModularInstance(user), credential)];
  5923. });
  5924. });
  5925. }
  5926. /**
  5927. * @license
  5928. * Copyright 2020 Google LLC
  5929. *
  5930. * Licensed under the Apache License, Version 2.0 (the "License");
  5931. * you may not use this file except in compliance with the License.
  5932. * You may obtain a copy of the License at
  5933. *
  5934. * http://www.apache.org/licenses/LICENSE-2.0
  5935. *
  5936. * Unless required by applicable law or agreed to in writing, software
  5937. * distributed under the License is distributed on an "AS IS" BASIS,
  5938. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5939. * See the License for the specific language governing permissions and
  5940. * limitations under the License.
  5941. */
  5942. function signInWithCustomToken$1(auth, request) {
  5943. return tslib.__awaiter(this, void 0, void 0, function () {
  5944. return tslib.__generator(this, function (_a) {
  5945. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
  5946. });
  5947. });
  5948. }
  5949. /**
  5950. * @license
  5951. * Copyright 2020 Google LLC
  5952. *
  5953. * Licensed under the Apache License, Version 2.0 (the "License");
  5954. * you may not use this file except in compliance with the License.
  5955. * You may obtain a copy of the License at
  5956. *
  5957. * http://www.apache.org/licenses/LICENSE-2.0
  5958. *
  5959. * Unless required by applicable law or agreed to in writing, software
  5960. * distributed under the License is distributed on an "AS IS" BASIS,
  5961. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5962. * See the License for the specific language governing permissions and
  5963. * limitations under the License.
  5964. */
  5965. /**
  5966. * Asynchronously signs in using a custom token.
  5967. *
  5968. * @remarks
  5969. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  5970. * be generated by an auth backend using the
  5971. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  5972. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  5973. *
  5974. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  5975. *
  5976. * @param auth - The {@link Auth} instance.
  5977. * @param customToken - The custom token to sign in with.
  5978. *
  5979. * @public
  5980. */
  5981. function signInWithCustomToken(auth, customToken) {
  5982. return tslib.__awaiter(this, void 0, void 0, function () {
  5983. var authInternal, response, cred;
  5984. return tslib.__generator(this, function (_a) {
  5985. switch (_a.label) {
  5986. case 0:
  5987. authInternal = _castAuth(auth);
  5988. return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
  5989. token: customToken,
  5990. returnSecureToken: true
  5991. })];
  5992. case 1:
  5993. response = _a.sent();
  5994. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  5995. case 2:
  5996. cred = _a.sent();
  5997. return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
  5998. case 3:
  5999. _a.sent();
  6000. return [2 /*return*/, cred];
  6001. }
  6002. });
  6003. });
  6004. }
  6005. /**
  6006. * @license
  6007. * Copyright 2020 Google LLC
  6008. *
  6009. * Licensed under the Apache License, Version 2.0 (the "License");
  6010. * you may not use this file except in compliance with the License.
  6011. * You may obtain a copy of the License at
  6012. *
  6013. * http://www.apache.org/licenses/LICENSE-2.0
  6014. *
  6015. * Unless required by applicable law or agreed to in writing, software
  6016. * distributed under the License is distributed on an "AS IS" BASIS,
  6017. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6018. * See the License for the specific language governing permissions and
  6019. * limitations under the License.
  6020. */
  6021. var MultiFactorInfoImpl = /** @class */ (function () {
  6022. function MultiFactorInfoImpl(factorId, response) {
  6023. this.factorId = factorId;
  6024. this.uid = response.mfaEnrollmentId;
  6025. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  6026. this.displayName = response.displayName;
  6027. }
  6028. MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
  6029. if ('phoneInfo' in enrollment) {
  6030. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6031. }
  6032. else if ('totpInfo' in enrollment) {
  6033. return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6034. }
  6035. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6036. };
  6037. return MultiFactorInfoImpl;
  6038. }());
  6039. var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
  6040. tslib.__extends(PhoneMultiFactorInfoImpl, _super);
  6041. function PhoneMultiFactorInfoImpl(response) {
  6042. var _this = _super.call(this, "phone" /* FactorId.PHONE */, response) || this;
  6043. _this.phoneNumber = response.phoneInfo;
  6044. return _this;
  6045. }
  6046. PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  6047. return new PhoneMultiFactorInfoImpl(enrollment);
  6048. };
  6049. return PhoneMultiFactorInfoImpl;
  6050. }(MultiFactorInfoImpl));
  6051. var TotpMultiFactorInfoImpl = /** @class */ (function (_super) {
  6052. tslib.__extends(TotpMultiFactorInfoImpl, _super);
  6053. function TotpMultiFactorInfoImpl(response) {
  6054. return _super.call(this, "totp" /* FactorId.TOTP */, response) || this;
  6055. }
  6056. TotpMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  6057. return new TotpMultiFactorInfoImpl(enrollment);
  6058. };
  6059. return TotpMultiFactorInfoImpl;
  6060. }(MultiFactorInfoImpl));
  6061. /**
  6062. * @license
  6063. * Copyright 2020 Google LLC
  6064. *
  6065. * Licensed under the Apache License, Version 2.0 (the "License");
  6066. * you may not use this file except in compliance with the License.
  6067. * You may obtain a copy of the License at
  6068. *
  6069. * http://www.apache.org/licenses/LICENSE-2.0
  6070. *
  6071. * Unless required by applicable law or agreed to in writing, software
  6072. * distributed under the License is distributed on an "AS IS" BASIS,
  6073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6074. * See the License for the specific language governing permissions and
  6075. * limitations under the License.
  6076. */
  6077. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  6078. var _a;
  6079. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  6080. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  6081. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  6082. request.continueUrl = actionCodeSettings.url;
  6083. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  6084. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  6085. if (actionCodeSettings.iOS) {
  6086. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  6087. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  6088. }
  6089. if (actionCodeSettings.android) {
  6090. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  6091. request.androidInstallApp = actionCodeSettings.android.installApp;
  6092. request.androidMinimumVersionCode =
  6093. actionCodeSettings.android.minimumVersion;
  6094. request.androidPackageName = actionCodeSettings.android.packageName;
  6095. }
  6096. }
  6097. /**
  6098. * @license
  6099. * Copyright 2020 Google LLC
  6100. *
  6101. * Licensed under the Apache License, Version 2.0 (the "License");
  6102. * you may not use this file except in compliance with the License.
  6103. * You may obtain a copy of the License at
  6104. *
  6105. * http://www.apache.org/licenses/LICENSE-2.0
  6106. *
  6107. * Unless required by applicable law or agreed to in writing, software
  6108. * distributed under the License is distributed on an "AS IS" BASIS,
  6109. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6110. * See the License for the specific language governing permissions and
  6111. * limitations under the License.
  6112. */
  6113. /**
  6114. * Sends a password reset email to the given email address.
  6115. *
  6116. * @remarks
  6117. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  6118. * the email sent to the user, along with the new password specified by the user.
  6119. *
  6120. * @example
  6121. * ```javascript
  6122. * const actionCodeSettings = {
  6123. * url: 'https://www.example.com/?email=user@example.com',
  6124. * iOS: {
  6125. * bundleId: 'com.example.ios'
  6126. * },
  6127. * android: {
  6128. * packageName: 'com.example.android',
  6129. * installApp: true,
  6130. * minimumVersion: '12'
  6131. * },
  6132. * handleCodeInApp: true
  6133. * };
  6134. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  6135. * // Obtain code from user.
  6136. * await confirmPasswordReset('user@example.com', code);
  6137. * ```
  6138. *
  6139. * @param auth - The {@link Auth} instance.
  6140. * @param email - The user's email address.
  6141. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6142. *
  6143. * @public
  6144. */
  6145. function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  6146. var _a;
  6147. return tslib.__awaiter(this, void 0, void 0, function () {
  6148. var authInternal, request, requestWithRecaptcha;
  6149. var _this = this;
  6150. return tslib.__generator(this, function (_b) {
  6151. switch (_b.label) {
  6152. case 0:
  6153. authInternal = _castAuth(auth);
  6154. request = {
  6155. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  6156. email: email,
  6157. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6158. };
  6159. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  6160. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6161. case 1:
  6162. requestWithRecaptcha = _b.sent();
  6163. if (actionCodeSettings) {
  6164. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  6165. }
  6166. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  6167. case 2:
  6168. _b.sent();
  6169. return [3 /*break*/, 5];
  6170. case 3:
  6171. if (actionCodeSettings) {
  6172. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  6173. }
  6174. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, request)
  6175. .catch(function (error) { return tslib.__awaiter(_this, void 0, void 0, function () {
  6176. var requestWithRecaptcha;
  6177. return tslib.__generator(this, function (_a) {
  6178. switch (_a.label) {
  6179. case 0:
  6180. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  6181. console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');
  6182. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6183. case 1:
  6184. requestWithRecaptcha = _a.sent();
  6185. if (actionCodeSettings) {
  6186. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  6187. }
  6188. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  6189. case 2:
  6190. _a.sent();
  6191. return [3 /*break*/, 4];
  6192. case 3: return [2 /*return*/, Promise.reject(error)];
  6193. case 4: return [2 /*return*/];
  6194. }
  6195. });
  6196. }); })];
  6197. case 4:
  6198. _b.sent();
  6199. _b.label = 5;
  6200. case 5: return [2 /*return*/];
  6201. }
  6202. });
  6203. });
  6204. }
  6205. /**
  6206. * Completes the password reset process, given a confirmation code and new password.
  6207. *
  6208. * @param auth - The {@link Auth} instance.
  6209. * @param oobCode - A confirmation code sent to the user.
  6210. * @param newPassword - The new password.
  6211. *
  6212. * @public
  6213. */
  6214. function confirmPasswordReset(auth, oobCode, newPassword) {
  6215. return tslib.__awaiter(this, void 0, void 0, function () {
  6216. return tslib.__generator(this, function (_a) {
  6217. switch (_a.label) {
  6218. case 0: return [4 /*yield*/, resetPassword(util.getModularInstance(auth), {
  6219. oobCode: oobCode,
  6220. newPassword: newPassword
  6221. })];
  6222. case 1:
  6223. _a.sent();
  6224. return [2 /*return*/];
  6225. }
  6226. });
  6227. });
  6228. }
  6229. /**
  6230. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  6231. *
  6232. * @param auth - The {@link Auth} instance.
  6233. * @param oobCode - A verification code sent to the user.
  6234. *
  6235. * @public
  6236. */
  6237. function applyActionCode(auth, oobCode) {
  6238. return tslib.__awaiter(this, void 0, void 0, function () {
  6239. return tslib.__generator(this, function (_a) {
  6240. switch (_a.label) {
  6241. case 0: return [4 /*yield*/, applyActionCode$1(util.getModularInstance(auth), { oobCode: oobCode })];
  6242. case 1:
  6243. _a.sent();
  6244. return [2 /*return*/];
  6245. }
  6246. });
  6247. });
  6248. }
  6249. /**
  6250. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  6251. *
  6252. * @returns metadata about the code.
  6253. *
  6254. * @param auth - The {@link Auth} instance.
  6255. * @param oobCode - A verification code sent to the user.
  6256. *
  6257. * @public
  6258. */
  6259. function checkActionCode(auth, oobCode) {
  6260. return tslib.__awaiter(this, void 0, void 0, function () {
  6261. var authModular, response, operation, multiFactorInfo;
  6262. return tslib.__generator(this, function (_a) {
  6263. switch (_a.label) {
  6264. case 0:
  6265. authModular = util.getModularInstance(auth);
  6266. return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
  6267. case 1:
  6268. response = _a.sent();
  6269. operation = response.requestType;
  6270. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6271. switch (operation) {
  6272. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  6273. break;
  6274. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  6275. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6276. break;
  6277. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  6278. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6279. // fall through
  6280. default:
  6281. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6282. }
  6283. multiFactorInfo = null;
  6284. if (response.mfaInfo) {
  6285. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  6286. }
  6287. return [2 /*return*/, {
  6288. data: {
  6289. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  6290. ? response.newEmail
  6291. : response.email) || null,
  6292. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  6293. ? response.email
  6294. : response.newEmail) || null,
  6295. multiFactorInfo: multiFactorInfo
  6296. },
  6297. operation: operation
  6298. }];
  6299. }
  6300. });
  6301. });
  6302. }
  6303. /**
  6304. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  6305. *
  6306. * @returns the user's email address if valid.
  6307. *
  6308. * @param auth - The {@link Auth} instance.
  6309. * @param code - A verification code sent to the user.
  6310. *
  6311. * @public
  6312. */
  6313. function verifyPasswordResetCode(auth, code) {
  6314. return tslib.__awaiter(this, void 0, void 0, function () {
  6315. var data;
  6316. return tslib.__generator(this, function (_a) {
  6317. switch (_a.label) {
  6318. case 0: return [4 /*yield*/, checkActionCode(util.getModularInstance(auth), code)];
  6319. case 1:
  6320. data = (_a.sent()).data;
  6321. // Email should always be present since a code was sent to it
  6322. return [2 /*return*/, data.email];
  6323. }
  6324. });
  6325. });
  6326. }
  6327. /**
  6328. * Creates a new user account associated with the specified email address and password.
  6329. *
  6330. * @remarks
  6331. * On successful creation of the user account, this user will also be signed in to your application.
  6332. *
  6333. * User account creation can fail if the account already exists or the password is invalid.
  6334. *
  6335. * Note: The email address acts as a unique identifier for the user and enables an email-based
  6336. * password reset. This function will create a new user account and set the initial user password.
  6337. *
  6338. * @param auth - The {@link Auth} instance.
  6339. * @param email - The user's email address.
  6340. * @param password - The user's chosen password.
  6341. *
  6342. * @public
  6343. */
  6344. function createUserWithEmailAndPassword(auth, email, password) {
  6345. var _a;
  6346. return tslib.__awaiter(this, void 0, void 0, function () {
  6347. var authInternal, request, signUpResponse, requestWithRecaptcha, response, userCredential;
  6348. var _this = this;
  6349. return tslib.__generator(this, function (_b) {
  6350. switch (_b.label) {
  6351. case 0:
  6352. authInternal = _castAuth(auth);
  6353. request = {
  6354. returnSecureToken: true,
  6355. email: email,
  6356. password: password,
  6357. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6358. };
  6359. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 2];
  6360. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  6361. case 1:
  6362. requestWithRecaptcha = _b.sent();
  6363. signUpResponse = signUp(authInternal, requestWithRecaptcha);
  6364. return [3 /*break*/, 3];
  6365. case 2:
  6366. signUpResponse = signUp(authInternal, request).catch(function (error) { return tslib.__awaiter(_this, void 0, void 0, function () {
  6367. var requestWithRecaptcha;
  6368. return tslib.__generator(this, function (_a) {
  6369. switch (_a.label) {
  6370. case 0:
  6371. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  6372. console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');
  6373. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  6374. case 1:
  6375. requestWithRecaptcha = _a.sent();
  6376. return [2 /*return*/, signUp(authInternal, requestWithRecaptcha)];
  6377. case 2: return [2 /*return*/, Promise.reject(error)];
  6378. }
  6379. });
  6380. }); });
  6381. _b.label = 3;
  6382. case 3: return [4 /*yield*/, signUpResponse.catch(function (error) {
  6383. return Promise.reject(error);
  6384. })];
  6385. case 4:
  6386. response = _b.sent();
  6387. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  6388. case 5:
  6389. userCredential = _b.sent();
  6390. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  6391. case 6:
  6392. _b.sent();
  6393. return [2 /*return*/, userCredential];
  6394. }
  6395. });
  6396. });
  6397. }
  6398. /**
  6399. * Asynchronously signs in using an email and password.
  6400. *
  6401. * @remarks
  6402. * Fails with an error if the email address and password do not match.
  6403. *
  6404. * Note: The user's password is NOT the password used to access the user's email account. The
  6405. * email address serves as a unique identifier for the user, and the password is used to access
  6406. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  6407. *
  6408. * @param auth - The {@link Auth} instance.
  6409. * @param email - The users email address.
  6410. * @param password - The users password.
  6411. *
  6412. * @public
  6413. */
  6414. function signInWithEmailAndPassword(auth, email, password) {
  6415. return signInWithCredential(util.getModularInstance(auth), EmailAuthProvider.credential(email, password));
  6416. }
  6417. /**
  6418. * @license
  6419. * Copyright 2020 Google LLC
  6420. *
  6421. * Licensed under the Apache License, Version 2.0 (the "License");
  6422. * you may not use this file except in compliance with the License.
  6423. * You may obtain a copy of the License at
  6424. *
  6425. * http://www.apache.org/licenses/LICENSE-2.0
  6426. *
  6427. * Unless required by applicable law or agreed to in writing, software
  6428. * distributed under the License is distributed on an "AS IS" BASIS,
  6429. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6430. * See the License for the specific language governing permissions and
  6431. * limitations under the License.
  6432. */
  6433. /**
  6434. * Sends a sign-in email link to the user with the specified email.
  6435. *
  6436. * @remarks
  6437. * The sign-in operation has to always be completed in the app unlike other out of band email
  6438. * actions (password reset and email verifications). This is because, at the end of the flow,
  6439. * the user is expected to be signed in and their Auth state persisted within the app.
  6440. *
  6441. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  6442. * address and the email link supplied in the email sent to the user.
  6443. *
  6444. * @example
  6445. * ```javascript
  6446. * const actionCodeSettings = {
  6447. * url: 'https://www.example.com/?email=user@example.com',
  6448. * iOS: {
  6449. * bundleId: 'com.example.ios'
  6450. * },
  6451. * android: {
  6452. * packageName: 'com.example.android',
  6453. * installApp: true,
  6454. * minimumVersion: '12'
  6455. * },
  6456. * handleCodeInApp: true
  6457. * };
  6458. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  6459. * // Obtain emailLink from the user.
  6460. * if(isSignInWithEmailLink(auth, emailLink)) {
  6461. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  6462. * }
  6463. * ```
  6464. *
  6465. * @param authInternal - The {@link Auth} instance.
  6466. * @param email - The user's email address.
  6467. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6468. *
  6469. * @public
  6470. */
  6471. function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  6472. var _a;
  6473. return tslib.__awaiter(this, void 0, void 0, function () {
  6474. function setActionCodeSettings(request, actionCodeSettings) {
  6475. _assert(actionCodeSettings.handleCodeInApp, authInternal, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6476. if (actionCodeSettings) {
  6477. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  6478. }
  6479. }
  6480. var authInternal, request, requestWithRecaptcha;
  6481. var _this = this;
  6482. return tslib.__generator(this, function (_b) {
  6483. switch (_b.label) {
  6484. case 0:
  6485. authInternal = _castAuth(auth);
  6486. request = {
  6487. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  6488. email: email,
  6489. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6490. };
  6491. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  6492. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6493. case 1:
  6494. requestWithRecaptcha = _b.sent();
  6495. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  6496. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  6497. case 2:
  6498. _b.sent();
  6499. return [3 /*break*/, 5];
  6500. case 3:
  6501. setActionCodeSettings(request, actionCodeSettings);
  6502. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, request)
  6503. .catch(function (error) { return tslib.__awaiter(_this, void 0, void 0, function () {
  6504. var requestWithRecaptcha;
  6505. return tslib.__generator(this, function (_a) {
  6506. switch (_a.label) {
  6507. case 0:
  6508. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  6509. console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  6510. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6511. case 1:
  6512. requestWithRecaptcha = _a.sent();
  6513. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  6514. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  6515. case 2:
  6516. _a.sent();
  6517. return [3 /*break*/, 4];
  6518. case 3: return [2 /*return*/, Promise.reject(error)];
  6519. case 4: return [2 /*return*/];
  6520. }
  6521. });
  6522. }); })];
  6523. case 4:
  6524. _b.sent();
  6525. _b.label = 5;
  6526. case 5: return [2 /*return*/];
  6527. }
  6528. });
  6529. });
  6530. }
  6531. /**
  6532. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  6533. *
  6534. * @param auth - The {@link Auth} instance.
  6535. * @param emailLink - The link sent to the user's email address.
  6536. *
  6537. * @public
  6538. */
  6539. function isSignInWithEmailLink(auth, emailLink) {
  6540. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  6541. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  6542. }
  6543. /**
  6544. * Asynchronously signs in using an email and sign-in email link.
  6545. *
  6546. * @remarks
  6547. * If no link is passed, the link is inferred from the current URL.
  6548. *
  6549. * Fails with an error if the email address is invalid or OTP in email link expires.
  6550. *
  6551. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  6552. *
  6553. * @example
  6554. * ```javascript
  6555. * const actionCodeSettings = {
  6556. * url: 'https://www.example.com/?email=user@example.com',
  6557. * iOS: {
  6558. * bundleId: 'com.example.ios'
  6559. * },
  6560. * android: {
  6561. * packageName: 'com.example.android',
  6562. * installApp: true,
  6563. * minimumVersion: '12'
  6564. * },
  6565. * handleCodeInApp: true
  6566. * };
  6567. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  6568. * // Obtain emailLink from the user.
  6569. * if(isSignInWithEmailLink(auth, emailLink)) {
  6570. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  6571. * }
  6572. * ```
  6573. *
  6574. * @param auth - The {@link Auth} instance.
  6575. * @param email - The user's email address.
  6576. * @param emailLink - The link sent to the user's email address.
  6577. *
  6578. * @public
  6579. */
  6580. function signInWithEmailLink(auth, email, emailLink) {
  6581. return tslib.__awaiter(this, void 0, void 0, function () {
  6582. var authModular, credential;
  6583. return tslib.__generator(this, function (_a) {
  6584. authModular = util.getModularInstance(auth);
  6585. credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  6586. // Check if the tenant ID in the email link matches the tenant ID on Auth
  6587. // instance.
  6588. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  6589. return [2 /*return*/, signInWithCredential(authModular, credential)];
  6590. });
  6591. });
  6592. }
  6593. /**
  6594. * @license
  6595. * Copyright 2020 Google LLC
  6596. *
  6597. * Licensed under the Apache License, Version 2.0 (the "License");
  6598. * you may not use this file except in compliance with the License.
  6599. * You may obtain a copy of the License at
  6600. *
  6601. * http://www.apache.org/licenses/LICENSE-2.0
  6602. *
  6603. * Unless required by applicable law or agreed to in writing, software
  6604. * distributed under the License is distributed on an "AS IS" BASIS,
  6605. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6606. * See the License for the specific language governing permissions and
  6607. * limitations under the License.
  6608. */
  6609. function createAuthUri(auth, request) {
  6610. return tslib.__awaiter(this, void 0, void 0, function () {
  6611. return tslib.__generator(this, function (_a) {
  6612. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
  6613. });
  6614. });
  6615. }
  6616. /**
  6617. * @license
  6618. * Copyright 2020 Google LLC
  6619. *
  6620. * Licensed under the Apache License, Version 2.0 (the "License");
  6621. * you may not use this file except in compliance with the License.
  6622. * You may obtain a copy of the License at
  6623. *
  6624. * http://www.apache.org/licenses/LICENSE-2.0
  6625. *
  6626. * Unless required by applicable law or agreed to in writing, software
  6627. * distributed under the License is distributed on an "AS IS" BASIS,
  6628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6629. * See the License for the specific language governing permissions and
  6630. * limitations under the License.
  6631. */
  6632. /**
  6633. * Gets the list of possible sign in methods for the given email address.
  6634. *
  6635. * @remarks
  6636. * This is useful to differentiate methods of sign-in for the same provider, eg.
  6637. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  6638. * {@link SignInMethod}.EMAIL_PASSWORD and
  6639. * {@link SignInMethod}.EMAIL_LINK.
  6640. *
  6641. * @param auth - The {@link Auth} instance.
  6642. * @param email - The user's email address.
  6643. *
  6644. * @public
  6645. */
  6646. function fetchSignInMethodsForEmail(auth, email) {
  6647. return tslib.__awaiter(this, void 0, void 0, function () {
  6648. var continueUri, request, signinMethods;
  6649. return tslib.__generator(this, function (_a) {
  6650. switch (_a.label) {
  6651. case 0:
  6652. continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  6653. request = {
  6654. identifier: email,
  6655. continueUri: continueUri
  6656. };
  6657. return [4 /*yield*/, createAuthUri(util.getModularInstance(auth), request)];
  6658. case 1:
  6659. signinMethods = (_a.sent()).signinMethods;
  6660. return [2 /*return*/, signinMethods || []];
  6661. }
  6662. });
  6663. });
  6664. }
  6665. /**
  6666. * Sends a verification email to a user.
  6667. *
  6668. * @remarks
  6669. * The verification process is completed by calling {@link applyActionCode}.
  6670. *
  6671. * @example
  6672. * ```javascript
  6673. * const actionCodeSettings = {
  6674. * url: 'https://www.example.com/?email=user@example.com',
  6675. * iOS: {
  6676. * bundleId: 'com.example.ios'
  6677. * },
  6678. * android: {
  6679. * packageName: 'com.example.android',
  6680. * installApp: true,
  6681. * minimumVersion: '12'
  6682. * },
  6683. * handleCodeInApp: true
  6684. * };
  6685. * await sendEmailVerification(user, actionCodeSettings);
  6686. * // Obtain code from the user.
  6687. * await applyActionCode(auth, code);
  6688. * ```
  6689. *
  6690. * @param user - The user.
  6691. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6692. *
  6693. * @public
  6694. */
  6695. function sendEmailVerification(user, actionCodeSettings) {
  6696. return tslib.__awaiter(this, void 0, void 0, function () {
  6697. var userInternal, idToken, request, email;
  6698. return tslib.__generator(this, function (_a) {
  6699. switch (_a.label) {
  6700. case 0:
  6701. userInternal = util.getModularInstance(user);
  6702. return [4 /*yield*/, user.getIdToken()];
  6703. case 1:
  6704. idToken = _a.sent();
  6705. request = {
  6706. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  6707. idToken: idToken
  6708. };
  6709. if (actionCodeSettings) {
  6710. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6711. }
  6712. return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
  6713. case 2:
  6714. email = (_a.sent()).email;
  6715. if (!(email !== user.email)) return [3 /*break*/, 4];
  6716. return [4 /*yield*/, user.reload()];
  6717. case 3:
  6718. _a.sent();
  6719. _a.label = 4;
  6720. case 4: return [2 /*return*/];
  6721. }
  6722. });
  6723. });
  6724. }
  6725. /**
  6726. * Sends a verification email to a new email address.
  6727. *
  6728. * @remarks
  6729. * The user's email will be updated to the new one after being verified.
  6730. *
  6731. * If you have a custom email action handler, you can complete the verification process by calling
  6732. * {@link applyActionCode}.
  6733. *
  6734. * @example
  6735. * ```javascript
  6736. * const actionCodeSettings = {
  6737. * url: 'https://www.example.com/?email=user@example.com',
  6738. * iOS: {
  6739. * bundleId: 'com.example.ios'
  6740. * },
  6741. * android: {
  6742. * packageName: 'com.example.android',
  6743. * installApp: true,
  6744. * minimumVersion: '12'
  6745. * },
  6746. * handleCodeInApp: true
  6747. * };
  6748. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  6749. * // Obtain code from the user.
  6750. * await applyActionCode(auth, code);
  6751. * ```
  6752. *
  6753. * @param user - The user.
  6754. * @param newEmail - The new email address to be verified before update.
  6755. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6756. *
  6757. * @public
  6758. */
  6759. function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  6760. return tslib.__awaiter(this, void 0, void 0, function () {
  6761. var userInternal, idToken, request, email;
  6762. return tslib.__generator(this, function (_a) {
  6763. switch (_a.label) {
  6764. case 0:
  6765. userInternal = util.getModularInstance(user);
  6766. return [4 /*yield*/, user.getIdToken()];
  6767. case 1:
  6768. idToken = _a.sent();
  6769. request = {
  6770. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  6771. idToken: idToken,
  6772. newEmail: newEmail
  6773. };
  6774. if (actionCodeSettings) {
  6775. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6776. }
  6777. return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
  6778. case 2:
  6779. email = (_a.sent()).email;
  6780. if (!(email !== user.email)) return [3 /*break*/, 4];
  6781. // If the local copy of the email on user is outdated, reload the
  6782. // user.
  6783. return [4 /*yield*/, user.reload()];
  6784. case 3:
  6785. // If the local copy of the email on user is outdated, reload the
  6786. // user.
  6787. _a.sent();
  6788. _a.label = 4;
  6789. case 4: return [2 /*return*/];
  6790. }
  6791. });
  6792. });
  6793. }
  6794. /**
  6795. * @license
  6796. * Copyright 2020 Google LLC
  6797. *
  6798. * Licensed under the Apache License, Version 2.0 (the "License");
  6799. * you may not use this file except in compliance with the License.
  6800. * You may obtain a copy of the License at
  6801. *
  6802. * http://www.apache.org/licenses/LICENSE-2.0
  6803. *
  6804. * Unless required by applicable law or agreed to in writing, software
  6805. * distributed under the License is distributed on an "AS IS" BASIS,
  6806. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6807. * See the License for the specific language governing permissions and
  6808. * limitations under the License.
  6809. */
  6810. function updateProfile$1(auth, request) {
  6811. return tslib.__awaiter(this, void 0, void 0, function () {
  6812. return tslib.__generator(this, function (_a) {
  6813. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  6814. });
  6815. });
  6816. }
  6817. /**
  6818. * @license
  6819. * Copyright 2020 Google LLC
  6820. *
  6821. * Licensed under the Apache License, Version 2.0 (the "License");
  6822. * you may not use this file except in compliance with the License.
  6823. * You may obtain a copy of the License at
  6824. *
  6825. * http://www.apache.org/licenses/LICENSE-2.0
  6826. *
  6827. * Unless required by applicable law or agreed to in writing, software
  6828. * distributed under the License is distributed on an "AS IS" BASIS,
  6829. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6830. * See the License for the specific language governing permissions and
  6831. * limitations under the License.
  6832. */
  6833. /**
  6834. * Updates a user's profile data.
  6835. *
  6836. * @param user - The user.
  6837. * @param profile - The profile's `displayName` and `photoURL` to update.
  6838. *
  6839. * @public
  6840. */
  6841. function updateProfile(user, _a) {
  6842. var displayName = _a.displayName, photoUrl = _a.photoURL;
  6843. return tslib.__awaiter(this, void 0, void 0, function () {
  6844. var userInternal, idToken, profileRequest, response, passwordProvider;
  6845. return tslib.__generator(this, function (_b) {
  6846. switch (_b.label) {
  6847. case 0:
  6848. if (displayName === undefined && photoUrl === undefined) {
  6849. return [2 /*return*/];
  6850. }
  6851. userInternal = util.getModularInstance(user);
  6852. return [4 /*yield*/, userInternal.getIdToken()];
  6853. case 1:
  6854. idToken = _b.sent();
  6855. profileRequest = {
  6856. idToken: idToken,
  6857. displayName: displayName,
  6858. photoUrl: photoUrl,
  6859. returnSecureToken: true
  6860. };
  6861. return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
  6862. case 2:
  6863. response = _b.sent();
  6864. userInternal.displayName = response.displayName || null;
  6865. userInternal.photoURL = response.photoUrl || null;
  6866. passwordProvider = userInternal.providerData.find(function (_a) {
  6867. var providerId = _a.providerId;
  6868. return providerId === "password" /* ProviderId.PASSWORD */;
  6869. });
  6870. if (passwordProvider) {
  6871. passwordProvider.displayName = userInternal.displayName;
  6872. passwordProvider.photoURL = userInternal.photoURL;
  6873. }
  6874. return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
  6875. case 3:
  6876. _b.sent();
  6877. return [2 /*return*/];
  6878. }
  6879. });
  6880. });
  6881. }
  6882. /**
  6883. * Updates the user's email address.
  6884. *
  6885. * @remarks
  6886. * An email will be sent to the original email address (if it was set) that allows to revoke the
  6887. * email address change, in order to protect them from account hijacking.
  6888. *
  6889. * Important: this is a security sensitive operation that requires the user to have recently signed
  6890. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6891. * {@link reauthenticateWithCredential}.
  6892. *
  6893. * @param user - The user.
  6894. * @param newEmail - The new email address.
  6895. *
  6896. * @public
  6897. */
  6898. function updateEmail(user, newEmail) {
  6899. return updateEmailOrPassword(util.getModularInstance(user), newEmail, null);
  6900. }
  6901. /**
  6902. * Updates the user's password.
  6903. *
  6904. * @remarks
  6905. * Important: this is a security sensitive operation that requires the user to have recently signed
  6906. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6907. * {@link reauthenticateWithCredential}.
  6908. *
  6909. * @param user - The user.
  6910. * @param newPassword - The new password.
  6911. *
  6912. * @public
  6913. */
  6914. function updatePassword(user, newPassword) {
  6915. return updateEmailOrPassword(util.getModularInstance(user), null, newPassword);
  6916. }
  6917. function updateEmailOrPassword(user, email, password) {
  6918. return tslib.__awaiter(this, void 0, void 0, function () {
  6919. var auth, idToken, request, response;
  6920. return tslib.__generator(this, function (_a) {
  6921. switch (_a.label) {
  6922. case 0:
  6923. auth = user.auth;
  6924. return [4 /*yield*/, user.getIdToken()];
  6925. case 1:
  6926. idToken = _a.sent();
  6927. request = {
  6928. idToken: idToken,
  6929. returnSecureToken: true
  6930. };
  6931. if (email) {
  6932. request.email = email;
  6933. }
  6934. if (password) {
  6935. request.password = password;
  6936. }
  6937. return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
  6938. case 2:
  6939. response = _a.sent();
  6940. return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  6941. case 3:
  6942. _a.sent();
  6943. return [2 /*return*/];
  6944. }
  6945. });
  6946. });
  6947. }
  6948. /**
  6949. * @license
  6950. * Copyright 2019 Google LLC
  6951. *
  6952. * Licensed under the Apache License, Version 2.0 (the "License");
  6953. * you may not use this file except in compliance with the License.
  6954. * You may obtain a copy of the License at
  6955. *
  6956. * http://www.apache.org/licenses/LICENSE-2.0
  6957. *
  6958. * Unless required by applicable law or agreed to in writing, software
  6959. * distributed under the License is distributed on an "AS IS" BASIS,
  6960. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6961. * See the License for the specific language governing permissions and
  6962. * limitations under the License.
  6963. */
  6964. /**
  6965. * Parse the `AdditionalUserInfo` from the ID token response.
  6966. *
  6967. */
  6968. function _fromIdTokenResponse(idTokenResponse) {
  6969. var _a, _b;
  6970. if (!idTokenResponse) {
  6971. return null;
  6972. }
  6973. var providerId = idTokenResponse.providerId;
  6974. var profile = idTokenResponse.rawUserInfo
  6975. ? JSON.parse(idTokenResponse.rawUserInfo)
  6976. : {};
  6977. var isNewUser = idTokenResponse.isNewUser ||
  6978. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  6979. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  6980. var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  6981. if (signInProvider) {
  6982. var filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  6983. signInProvider !== "custom" /* ProviderId.CUSTOM */
  6984. ? signInProvider
  6985. : null;
  6986. // Uses generic class in accordance with the legacy SDK.
  6987. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  6988. }
  6989. }
  6990. if (!providerId) {
  6991. return null;
  6992. }
  6993. switch (providerId) {
  6994. case "facebook.com" /* ProviderId.FACEBOOK */:
  6995. return new FacebookAdditionalUserInfo(isNewUser, profile);
  6996. case "github.com" /* ProviderId.GITHUB */:
  6997. return new GithubAdditionalUserInfo(isNewUser, profile);
  6998. case "google.com" /* ProviderId.GOOGLE */:
  6999. return new GoogleAdditionalUserInfo(isNewUser, profile);
  7000. case "twitter.com" /* ProviderId.TWITTER */:
  7001. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  7002. case "custom" /* ProviderId.CUSTOM */:
  7003. case "anonymous" /* ProviderId.ANONYMOUS */:
  7004. return new GenericAdditionalUserInfo(isNewUser, null);
  7005. default:
  7006. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  7007. }
  7008. }
  7009. var GenericAdditionalUserInfo = /** @class */ (function () {
  7010. function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
  7011. if (profile === void 0) { profile = {}; }
  7012. this.isNewUser = isNewUser;
  7013. this.providerId = providerId;
  7014. this.profile = profile;
  7015. }
  7016. return GenericAdditionalUserInfo;
  7017. }());
  7018. var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
  7019. tslib.__extends(FederatedAdditionalUserInfoWithUsername, _super);
  7020. function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
  7021. var _this = _super.call(this, isNewUser, providerId, profile) || this;
  7022. _this.username = username;
  7023. return _this;
  7024. }
  7025. return FederatedAdditionalUserInfoWithUsername;
  7026. }(GenericAdditionalUserInfo));
  7027. var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
  7028. tslib.__extends(FacebookAdditionalUserInfo, _super);
  7029. function FacebookAdditionalUserInfo(isNewUser, profile) {
  7030. return _super.call(this, isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile) || this;
  7031. }
  7032. return FacebookAdditionalUserInfo;
  7033. }(GenericAdditionalUserInfo));
  7034. var GithubAdditionalUserInfo = /** @class */ (function (_super) {
  7035. tslib.__extends(GithubAdditionalUserInfo, _super);
  7036. function GithubAdditionalUserInfo(isNewUser, profile) {
  7037. return _super.call(this, isNewUser, "github.com" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
  7038. }
  7039. return GithubAdditionalUserInfo;
  7040. }(FederatedAdditionalUserInfoWithUsername));
  7041. var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
  7042. tslib.__extends(GoogleAdditionalUserInfo, _super);
  7043. function GoogleAdditionalUserInfo(isNewUser, profile) {
  7044. return _super.call(this, isNewUser, "google.com" /* ProviderId.GOOGLE */, profile) || this;
  7045. }
  7046. return GoogleAdditionalUserInfo;
  7047. }(GenericAdditionalUserInfo));
  7048. var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
  7049. tslib.__extends(TwitterAdditionalUserInfo, _super);
  7050. function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
  7051. return _super.call(this, isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName) || this;
  7052. }
  7053. return TwitterAdditionalUserInfo;
  7054. }(FederatedAdditionalUserInfoWithUsername));
  7055. /**
  7056. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  7057. *
  7058. * @param userCredential - The user credential.
  7059. *
  7060. * @public
  7061. */
  7062. function getAdditionalUserInfo(userCredential) {
  7063. var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
  7064. if (user.isAnonymous && !_tokenResponse) {
  7065. // Handle the special case where signInAnonymously() gets called twice.
  7066. // No network call is made so there's nothing to actually fill this in
  7067. return {
  7068. providerId: null,
  7069. isNewUser: false,
  7070. profile: null
  7071. };
  7072. }
  7073. return _fromIdTokenResponse(_tokenResponse);
  7074. }
  7075. /**
  7076. * @license
  7077. * Copyright 2020 Google LLC
  7078. *
  7079. * Licensed under the Apache License, Version 2.0 (the "License");
  7080. * you may not use this file except in compliance with the License.
  7081. * You may obtain a copy of the License at
  7082. *
  7083. * http://www.apache.org/licenses/LICENSE-2.0
  7084. *
  7085. * Unless required by applicable law or agreed to in writing, software
  7086. * distributed under the License is distributed on an "AS IS" BASIS,
  7087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7088. * See the License for the specific language governing permissions and
  7089. * limitations under the License.
  7090. */
  7091. // Non-optional auth methods.
  7092. /**
  7093. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  7094. * `Auth` session and applies this type of persistence for future sign-in requests, including
  7095. * sign-in with redirect requests.
  7096. *
  7097. * @remarks
  7098. * This makes it easy for a user signing in to specify whether their session should be
  7099. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  7100. * that are shared by other users or have sensitive data.
  7101. *
  7102. * @example
  7103. * ```javascript
  7104. * setPersistence(auth, browserSessionPersistence);
  7105. * ```
  7106. *
  7107. * @param auth - The {@link Auth} instance.
  7108. * @param persistence - The {@link Persistence} to use.
  7109. * @returns A `Promise` that resolves once the persistence change has completed
  7110. *
  7111. * @public
  7112. */
  7113. function setPersistence(auth, persistence) {
  7114. return util.getModularInstance(auth).setPersistence(persistence);
  7115. }
  7116. /**
  7117. * Loads the reCAPTCHA configuration into the `Auth` instance.
  7118. *
  7119. * @remarks
  7120. * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA
  7121. * verification flow should be triggered for each auth provider, into the
  7122. * current Auth session.
  7123. *
  7124. * If initializeRecaptchaConfig() is not invoked, the auth flow will always start
  7125. * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA
  7126. * verification, the SDK will transparently load the reCAPTCHA config and restart the
  7127. * auth flows.
  7128. *
  7129. * Thus, by calling this optional method, you will reduce the latency of future auth flows.
  7130. * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.
  7131. *
  7132. * @example
  7133. * ```javascript
  7134. * initializeRecaptchaConfig(auth);
  7135. * ```
  7136. *
  7137. * @param auth - The {@link Auth} instance.
  7138. *
  7139. * @public
  7140. */
  7141. function initializeRecaptchaConfig(auth) {
  7142. var authInternal = _castAuth(auth);
  7143. return authInternal.initializeRecaptchaConfig();
  7144. }
  7145. /**
  7146. * Adds an observer for changes to the signed-in user's ID token.
  7147. *
  7148. * @remarks
  7149. * This includes sign-in, sign-out, and token refresh events.
  7150. * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.
  7151. *
  7152. * @param auth - The {@link Auth} instance.
  7153. * @param nextOrObserver - callback triggered on change.
  7154. * @param error - Deprecated. This callback is never triggered. Errors
  7155. * on signing in/out can be caught in promises returned from
  7156. * sign-in/sign-out functions.
  7157. * @param completed - Deprecated. This callback is never triggered.
  7158. *
  7159. * @public
  7160. */
  7161. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  7162. return util.getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  7163. }
  7164. /**
  7165. * Adds a blocking callback that runs before an auth state change
  7166. * sets a new user.
  7167. *
  7168. * @param auth - The {@link Auth} instance.
  7169. * @param callback - callback triggered before new user value is set.
  7170. * If this throws, it blocks the user from being set.
  7171. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  7172. * callback throws, allowing you to undo any side effects.
  7173. */
  7174. function beforeAuthStateChanged(auth, callback, onAbort) {
  7175. return util.getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  7176. }
  7177. /**
  7178. * Adds an observer for changes to the user's sign-in state.
  7179. *
  7180. * @remarks
  7181. * To keep the old behavior, see {@link onIdTokenChanged}.
  7182. *
  7183. * @param auth - The {@link Auth} instance.
  7184. * @param nextOrObserver - callback triggered on change.
  7185. * @param error - Deprecated. This callback is never triggered. Errors
  7186. * on signing in/out can be caught in promises returned from
  7187. * sign-in/sign-out functions.
  7188. * @param completed - Deprecated. This callback is never triggered.
  7189. *
  7190. * @public
  7191. */
  7192. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  7193. return util.getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  7194. }
  7195. /**
  7196. * Sets the current language to the default device/browser preference.
  7197. *
  7198. * @param auth - The {@link Auth} instance.
  7199. *
  7200. * @public
  7201. */
  7202. function useDeviceLanguage(auth) {
  7203. util.getModularInstance(auth).useDeviceLanguage();
  7204. }
  7205. /**
  7206. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  7207. * {@link Auth} instance.
  7208. *
  7209. * @remarks
  7210. * A new instance copy of the user provided will be made and set as currentUser.
  7211. *
  7212. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  7213. * like other sign in methods.
  7214. *
  7215. * The operation fails with an error if the user to be updated belongs to a different Firebase
  7216. * project.
  7217. *
  7218. * @param auth - The {@link Auth} instance.
  7219. * @param user - The new {@link User}.
  7220. *
  7221. * @public
  7222. */
  7223. function updateCurrentUser(auth, user) {
  7224. return util.getModularInstance(auth).updateCurrentUser(user);
  7225. }
  7226. /**
  7227. * Signs out the current user.
  7228. *
  7229. * @param auth - The {@link Auth} instance.
  7230. *
  7231. * @public
  7232. */
  7233. function signOut(auth) {
  7234. return util.getModularInstance(auth).signOut();
  7235. }
  7236. /**
  7237. * Deletes and signs out the user.
  7238. *
  7239. * @remarks
  7240. * Important: this is a security-sensitive operation that requires the user to have recently
  7241. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  7242. * {@link reauthenticateWithCredential}.
  7243. *
  7244. * @param user - The user.
  7245. *
  7246. * @public
  7247. */
  7248. function deleteUser(user) {
  7249. return tslib.__awaiter(this, void 0, void 0, function () {
  7250. return tslib.__generator(this, function (_a) {
  7251. return [2 /*return*/, util.getModularInstance(user).delete()];
  7252. });
  7253. });
  7254. }
  7255. var MultiFactorSessionImpl = /** @class */ (function () {
  7256. function MultiFactorSessionImpl(type, credential, auth) {
  7257. this.type = type;
  7258. this.credential = credential;
  7259. this.auth = auth;
  7260. }
  7261. MultiFactorSessionImpl._fromIdtoken = function (idToken, auth) {
  7262. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  7263. };
  7264. MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
  7265. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  7266. };
  7267. MultiFactorSessionImpl.prototype.toJSON = function () {
  7268. var _a;
  7269. var key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  7270. ? 'idToken'
  7271. : 'pendingCredential';
  7272. return {
  7273. multiFactorSession: (_a = {},
  7274. _a[key] = this.credential,
  7275. _a)
  7276. };
  7277. };
  7278. MultiFactorSessionImpl.fromJSON = function (obj) {
  7279. var _a, _b;
  7280. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  7281. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  7282. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  7283. }
  7284. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  7285. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  7286. }
  7287. }
  7288. return null;
  7289. };
  7290. return MultiFactorSessionImpl;
  7291. }());
  7292. /**
  7293. * @license
  7294. * Copyright 2020 Google LLC
  7295. *
  7296. * Licensed under the Apache License, Version 2.0 (the "License");
  7297. * you may not use this file except in compliance with the License.
  7298. * You may obtain a copy of the License at
  7299. *
  7300. * http://www.apache.org/licenses/LICENSE-2.0
  7301. *
  7302. * Unless required by applicable law or agreed to in writing, software
  7303. * distributed under the License is distributed on an "AS IS" BASIS,
  7304. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7305. * See the License for the specific language governing permissions and
  7306. * limitations under the License.
  7307. */
  7308. var MultiFactorResolverImpl = /** @class */ (function () {
  7309. function MultiFactorResolverImpl(session, hints, signInResolver) {
  7310. this.session = session;
  7311. this.hints = hints;
  7312. this.signInResolver = signInResolver;
  7313. }
  7314. /** @internal */
  7315. MultiFactorResolverImpl._fromError = function (authExtern, error) {
  7316. var _this = this;
  7317. var auth = _castAuth(authExtern);
  7318. var serverResponse = error.customData._serverResponse;
  7319. var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
  7320. return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  7321. });
  7322. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7323. var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  7324. return new MultiFactorResolverImpl(session, hints, function (assertion) { return tslib.__awaiter(_this, void 0, void 0, function () {
  7325. var mfaResponse, idTokenResponse, _a, userCredential;
  7326. return tslib.__generator(this, function (_b) {
  7327. switch (_b.label) {
  7328. case 0: return [4 /*yield*/, assertion._process(auth, session)];
  7329. case 1:
  7330. mfaResponse = _b.sent();
  7331. // Clear out the unneeded fields from the old login response
  7332. delete serverResponse.mfaInfo;
  7333. delete serverResponse.mfaPendingCredential;
  7334. idTokenResponse = tslib.__assign(tslib.__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  7335. _a = error.operationType;
  7336. switch (_a) {
  7337. case "signIn" /* OperationType.SIGN_IN */: return [3 /*break*/, 2];
  7338. case "reauthenticate" /* OperationType.REAUTHENTICATE */: return [3 /*break*/, 5];
  7339. }
  7340. return [3 /*break*/, 6];
  7341. case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
  7342. case 3:
  7343. userCredential = _b.sent();
  7344. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  7345. case 4:
  7346. _b.sent();
  7347. return [2 /*return*/, userCredential];
  7348. case 5:
  7349. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7350. return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
  7351. case 6:
  7352. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7353. _b.label = 7;
  7354. case 7: return [2 /*return*/];
  7355. }
  7356. });
  7357. }); });
  7358. };
  7359. MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
  7360. return tslib.__awaiter(this, void 0, void 0, function () {
  7361. var assertion;
  7362. return tslib.__generator(this, function (_a) {
  7363. assertion = assertionExtern;
  7364. return [2 /*return*/, this.signInResolver(assertion)];
  7365. });
  7366. });
  7367. };
  7368. return MultiFactorResolverImpl;
  7369. }());
  7370. /**
  7371. * Provides a {@link MultiFactorResolver} suitable for completion of a
  7372. * multi-factor flow.
  7373. *
  7374. * @param auth - The {@link Auth} instance.
  7375. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  7376. * reauthentication operation.
  7377. *
  7378. * @public
  7379. */
  7380. function getMultiFactorResolver(auth, error) {
  7381. var _a;
  7382. var authModular = util.getModularInstance(auth);
  7383. var errorInternal = error;
  7384. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7385. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7386. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  7387. }
  7388. /**
  7389. * @license
  7390. * Copyright 2020 Google LLC
  7391. *
  7392. * Licensed under the Apache License, Version 2.0 (the "License");
  7393. * you may not use this file except in compliance with the License.
  7394. * You may obtain a copy of the License at
  7395. *
  7396. * http://www.apache.org/licenses/LICENSE-2.0
  7397. *
  7398. * Unless required by applicable law or agreed to in writing, software
  7399. * distributed under the License is distributed on an "AS IS" BASIS,
  7400. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7401. * See the License for the specific language governing permissions and
  7402. * limitations under the License.
  7403. */
  7404. function startEnrollTotpMfa(auth, request) {
  7405. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7406. }
  7407. function finalizeEnrollTotpMfa(auth, request) {
  7408. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7409. }
  7410. function withdrawMfa(auth, request) {
  7411. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  7412. }
  7413. var MultiFactorUserImpl = /** @class */ (function () {
  7414. function MultiFactorUserImpl(user) {
  7415. var _this = this;
  7416. this.user = user;
  7417. this.enrolledFactors = [];
  7418. user._onReload(function (userInfo) {
  7419. if (userInfo.mfaInfo) {
  7420. _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
  7421. return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
  7422. });
  7423. }
  7424. });
  7425. }
  7426. MultiFactorUserImpl._fromUser = function (user) {
  7427. return new MultiFactorUserImpl(user);
  7428. };
  7429. MultiFactorUserImpl.prototype.getSession = function () {
  7430. return tslib.__awaiter(this, void 0, void 0, function () {
  7431. var _a, _b;
  7432. return tslib.__generator(this, function (_c) {
  7433. switch (_c.label) {
  7434. case 0:
  7435. _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
  7436. return [4 /*yield*/, this.user.getIdToken()];
  7437. case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(), this.user.auth])];
  7438. }
  7439. });
  7440. });
  7441. };
  7442. MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
  7443. return tslib.__awaiter(this, void 0, void 0, function () {
  7444. var assertion, session, finalizeMfaResponse;
  7445. return tslib.__generator(this, function (_a) {
  7446. switch (_a.label) {
  7447. case 0:
  7448. assertion = assertionExtern;
  7449. return [4 /*yield*/, this.getSession()];
  7450. case 1:
  7451. session = (_a.sent());
  7452. return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
  7453. case 2:
  7454. finalizeMfaResponse = _a.sent();
  7455. // New tokens will be issued after enrollment of the new second factors.
  7456. // They need to be updated on the user.
  7457. return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
  7458. case 3:
  7459. // New tokens will be issued after enrollment of the new second factors.
  7460. // They need to be updated on the user.
  7461. _a.sent();
  7462. // The user needs to be reloaded to get the new multi-factor information
  7463. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  7464. // will be updated.
  7465. return [2 /*return*/, this.user.reload()];
  7466. }
  7467. });
  7468. });
  7469. };
  7470. MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
  7471. return tslib.__awaiter(this, void 0, void 0, function () {
  7472. var mfaEnrollmentId, idToken, idTokenResponse, e_1;
  7473. return tslib.__generator(this, function (_a) {
  7474. switch (_a.label) {
  7475. case 0:
  7476. mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  7477. return [4 /*yield*/, this.user.getIdToken()];
  7478. case 1:
  7479. idToken = _a.sent();
  7480. _a.label = 2;
  7481. case 2:
  7482. _a.trys.push([2, 6, , 7]);
  7483. return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  7484. idToken: idToken,
  7485. mfaEnrollmentId: mfaEnrollmentId
  7486. }))];
  7487. case 3:
  7488. idTokenResponse = _a.sent();
  7489. // Remove the second factor from the user's list.
  7490. this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
  7491. var uid = _a.uid;
  7492. return uid !== mfaEnrollmentId;
  7493. });
  7494. // Depending on whether the backend decided to revoke the user's session,
  7495. // the tokenResponse may be empty. If the tokens were not updated (and they
  7496. // are now invalid), reloading the user will discover this and invalidate
  7497. // the user's state accordingly.
  7498. return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
  7499. case 4:
  7500. // Depending on whether the backend decided to revoke the user's session,
  7501. // the tokenResponse may be empty. If the tokens were not updated (and they
  7502. // are now invalid), reloading the user will discover this and invalidate
  7503. // the user's state accordingly.
  7504. _a.sent();
  7505. return [4 /*yield*/, this.user.reload()];
  7506. case 5:
  7507. _a.sent();
  7508. return [3 /*break*/, 7];
  7509. case 6:
  7510. e_1 = _a.sent();
  7511. throw e_1;
  7512. case 7: return [2 /*return*/];
  7513. }
  7514. });
  7515. });
  7516. };
  7517. return MultiFactorUserImpl;
  7518. }());
  7519. var multiFactorUserCache = new WeakMap();
  7520. /**
  7521. * The {@link MultiFactorUser} corresponding to the user.
  7522. *
  7523. * @remarks
  7524. * This is used to access all multi-factor properties and operations related to the user.
  7525. *
  7526. * @param user - The user.
  7527. *
  7528. * @public
  7529. */
  7530. function multiFactor(user) {
  7531. var userModular = util.getModularInstance(user);
  7532. if (!multiFactorUserCache.has(userModular)) {
  7533. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  7534. }
  7535. return multiFactorUserCache.get(userModular);
  7536. }
  7537. var name = "@firebase/auth";
  7538. var version = "0.23.2";
  7539. /**
  7540. * @license
  7541. * Copyright 2020 Google LLC
  7542. *
  7543. * Licensed under the Apache License, Version 2.0 (the "License");
  7544. * you may not use this file except in compliance with the License.
  7545. * You may obtain a copy of the License at
  7546. *
  7547. * http://www.apache.org/licenses/LICENSE-2.0
  7548. *
  7549. * Unless required by applicable law or agreed to in writing, software
  7550. * distributed under the License is distributed on an "AS IS" BASIS,
  7551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7552. * See the License for the specific language governing permissions and
  7553. * limitations under the License.
  7554. */
  7555. var AuthInterop = /** @class */ (function () {
  7556. function AuthInterop(auth) {
  7557. this.auth = auth;
  7558. this.internalListeners = new Map();
  7559. }
  7560. AuthInterop.prototype.getUid = function () {
  7561. var _a;
  7562. this.assertAuthConfigured();
  7563. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  7564. };
  7565. AuthInterop.prototype.getToken = function (forceRefresh) {
  7566. return tslib.__awaiter(this, void 0, void 0, function () {
  7567. var accessToken;
  7568. return tslib.__generator(this, function (_a) {
  7569. switch (_a.label) {
  7570. case 0:
  7571. this.assertAuthConfigured();
  7572. return [4 /*yield*/, this.auth._initializationPromise];
  7573. case 1:
  7574. _a.sent();
  7575. if (!this.auth.currentUser) {
  7576. return [2 /*return*/, null];
  7577. }
  7578. return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
  7579. case 2:
  7580. accessToken = _a.sent();
  7581. return [2 /*return*/, { accessToken: accessToken }];
  7582. }
  7583. });
  7584. });
  7585. };
  7586. AuthInterop.prototype.addAuthTokenListener = function (listener) {
  7587. this.assertAuthConfigured();
  7588. if (this.internalListeners.has(listener)) {
  7589. return;
  7590. }
  7591. var unsubscribe = this.auth.onIdTokenChanged(function (user) {
  7592. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  7593. });
  7594. this.internalListeners.set(listener, unsubscribe);
  7595. this.updateProactiveRefresh();
  7596. };
  7597. AuthInterop.prototype.removeAuthTokenListener = function (listener) {
  7598. this.assertAuthConfigured();
  7599. var unsubscribe = this.internalListeners.get(listener);
  7600. if (!unsubscribe) {
  7601. return;
  7602. }
  7603. this.internalListeners.delete(listener);
  7604. unsubscribe();
  7605. this.updateProactiveRefresh();
  7606. };
  7607. AuthInterop.prototype.assertAuthConfigured = function () {
  7608. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  7609. };
  7610. AuthInterop.prototype.updateProactiveRefresh = function () {
  7611. if (this.internalListeners.size > 0) {
  7612. this.auth._startProactiveRefresh();
  7613. }
  7614. else {
  7615. this.auth._stopProactiveRefresh();
  7616. }
  7617. };
  7618. return AuthInterop;
  7619. }());
  7620. /**
  7621. * @license
  7622. * Copyright 2020 Google LLC
  7623. *
  7624. * Licensed under the Apache License, Version 2.0 (the "License");
  7625. * you may not use this file except in compliance with the License.
  7626. * You may obtain a copy of the License at
  7627. *
  7628. * http://www.apache.org/licenses/LICENSE-2.0
  7629. *
  7630. * Unless required by applicable law or agreed to in writing, software
  7631. * distributed under the License is distributed on an "AS IS" BASIS,
  7632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7633. * See the License for the specific language governing permissions and
  7634. * limitations under the License.
  7635. */
  7636. function getVersionForPlatform(clientPlatform) {
  7637. switch (clientPlatform) {
  7638. case "Node" /* ClientPlatform.NODE */:
  7639. return 'node';
  7640. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  7641. return 'rn';
  7642. case "Worker" /* ClientPlatform.WORKER */:
  7643. return 'webworker';
  7644. case "Cordova" /* ClientPlatform.CORDOVA */:
  7645. return 'cordova';
  7646. default:
  7647. return undefined;
  7648. }
  7649. }
  7650. /** @internal */
  7651. function registerAuth(clientPlatform) {
  7652. app._registerComponent(new component.Component("auth" /* _ComponentName.AUTH */, function (container, _a) {
  7653. var deps = _a.options;
  7654. var app = container.getProvider('app').getImmediate();
  7655. var heartbeatServiceProvider = container.getProvider('heartbeat');
  7656. var appCheckServiceProvider = container.getProvider('app-check-internal');
  7657. var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
  7658. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  7659. var config = {
  7660. apiKey: apiKey,
  7661. authDomain: authDomain,
  7662. clientPlatform: clientPlatform,
  7663. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  7664. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  7665. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  7666. sdkClientVersion: _getClientVersion(clientPlatform)
  7667. };
  7668. var authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);
  7669. _initializeAuthInstance(authInstance, deps);
  7670. return authInstance;
  7671. }, "PUBLIC" /* ComponentType.PUBLIC */)
  7672. /**
  7673. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  7674. * For why we do this, See go/firebase-next-auth-init
  7675. */
  7676. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  7677. /**
  7678. * Because all firebase products that depend on auth depend on auth-internal directly,
  7679. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  7680. */
  7681. .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
  7682. var authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  7683. authInternalProvider.initialize();
  7684. }));
  7685. app._registerComponent(new component.Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, function (container) {
  7686. var auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  7687. return (function (auth) { return new AuthInterop(auth); })(auth);
  7688. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  7689. app.registerVersion(name, version, getVersionForPlatform(clientPlatform));
  7690. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  7691. app.registerVersion(name, version, 'cjs5');
  7692. }
  7693. /**
  7694. * @license
  7695. * Copyright 2021 Google LLC
  7696. *
  7697. * Licensed under the Apache License, Version 2.0 (the "License");
  7698. * you may not use this file except in compliance with the License.
  7699. * You may obtain a copy of the License at
  7700. *
  7701. * http://www.apache.org/licenses/LICENSE-2.0
  7702. *
  7703. * Unless required by applicable law or agreed to in writing, software
  7704. * distributed under the License is distributed on an "AS IS" BASIS,
  7705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7706. * See the License for the specific language governing permissions and
  7707. * limitations under the License.
  7708. */
  7709. // Initialize the fetch polyfill, the types are slightly off so just cast and hope for the best
  7710. FetchProvider.initialize(fetchImpl__namespace.default, fetchImpl__namespace.Headers, fetchImpl__namespace.Response);
  7711. // First, we set up the various platform-specific features for Node (register
  7712. // the version and declare the Node getAuth function)
  7713. function getAuth(app$1) {
  7714. if (app$1 === void 0) { app$1 = app.getApp(); }
  7715. var provider = app._getProvider(app$1, 'auth');
  7716. if (provider.isInitialized()) {
  7717. return provider.getImmediate();
  7718. }
  7719. var auth = initializeAuth(app$1);
  7720. var authEmulatorHost = util.getDefaultEmulatorHost('auth');
  7721. if (authEmulatorHost) {
  7722. connectAuthEmulator(auth, "http://".concat(authEmulatorHost));
  7723. }
  7724. return auth;
  7725. }
  7726. registerAuth("Node" /* ClientPlatform.NODE */);
  7727. // The rest of this file contains no-ops and errors for browser-specific
  7728. // methods. We keep the browser and Node entry points the same, but features
  7729. // that only work in browsers are set to either do nothing (setPersistence) or
  7730. // to reject with an auth/operation-not-supported-in-this-environment error.
  7731. // The below exports are pulled into the main entry point by a rollup alias
  7732. // plugin (overwriting the default browser imports).
  7733. /** auth/operation-not-supported-in-this-environment */
  7734. var NOT_AVAILABLE_ERROR = _createError("operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7735. /** Reject with auth/operation-not-supported-in-this-environment */
  7736. function fail() {
  7737. return tslib.__awaiter(this, void 0, void 0, function () {
  7738. return tslib.__generator(this, function (_a) {
  7739. throw NOT_AVAILABLE_ERROR;
  7740. });
  7741. });
  7742. }
  7743. /**
  7744. * A class which will throw with
  7745. * auth/operation-not-supported-in-this-environment if instantiated
  7746. */
  7747. var FailClass = /** @class */ (function () {
  7748. function FailClass() {
  7749. throw NOT_AVAILABLE_ERROR;
  7750. }
  7751. return FailClass;
  7752. }());
  7753. var browserLocalPersistence = inMemoryPersistence;
  7754. var browserSessionPersistence = inMemoryPersistence;
  7755. var indexedDBLocalPersistence = inMemoryPersistence;
  7756. var browserPopupRedirectResolver = NOT_AVAILABLE_ERROR;
  7757. var PhoneAuthProvider = FailClass;
  7758. var signInWithPhoneNumber = fail;
  7759. var linkWithPhoneNumber = fail;
  7760. var reauthenticateWithPhoneNumber = fail;
  7761. var updatePhoneNumber = fail;
  7762. var signInWithPopup = fail;
  7763. var linkWithPopup = fail;
  7764. var reauthenticateWithPopup = fail;
  7765. var signInWithRedirect = fail;
  7766. var linkWithRedirect = fail;
  7767. var reauthenticateWithRedirect = fail;
  7768. var getRedirectResult = fail;
  7769. var RecaptchaVerifier = FailClass;
  7770. var PhoneMultiFactorGenerator = /** @class */ (function () {
  7771. function PhoneMultiFactorGenerator() {
  7772. }
  7773. PhoneMultiFactorGenerator.assertion = function () {
  7774. throw NOT_AVAILABLE_ERROR;
  7775. };
  7776. return PhoneMultiFactorGenerator;
  7777. }());
  7778. // Set persistence should no-op instead of fail. Changing the prototype will
  7779. // make sure both setPersistence(auth, persistence) and
  7780. // auth.setPersistence(persistence) are covered.
  7781. AuthImpl.prototype.setPersistence = function () { return tslib.__awaiter(void 0, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  7782. return [2 /*return*/];
  7783. }); }); };
  7784. /**
  7785. * @license
  7786. * Copyright 2020 Google LLC
  7787. *
  7788. * Licensed under the Apache License, Version 2.0 (the "License");
  7789. * you may not use this file except in compliance with the License.
  7790. * You may obtain a copy of the License at
  7791. *
  7792. * http://www.apache.org/licenses/LICENSE-2.0
  7793. *
  7794. * Unless required by applicable law or agreed to in writing, software
  7795. * distributed under the License is distributed on an "AS IS" BASIS,
  7796. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7797. * See the License for the specific language governing permissions and
  7798. * limitations under the License.
  7799. */
  7800. function finalizeSignInTotpMfa(auth, request) {
  7801. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7802. }
  7803. var MultiFactorAssertionImpl = /** @class */ (function () {
  7804. function MultiFactorAssertionImpl(factorId) {
  7805. this.factorId = factorId;
  7806. }
  7807. MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
  7808. switch (session.type) {
  7809. case "enroll" /* MultiFactorSessionType.ENROLL */:
  7810. return this._finalizeEnroll(auth, session.credential, displayName);
  7811. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  7812. return this._finalizeSignIn(auth, session.credential);
  7813. default:
  7814. return debugFail('unexpected MultiFactorSessionType');
  7815. }
  7816. };
  7817. return MultiFactorAssertionImpl;
  7818. }());
  7819. /**
  7820. * Provider for generating a {@link TotpMultiFactorAssertion}.
  7821. *
  7822. * @public
  7823. */
  7824. var TotpMultiFactorGenerator = /** @class */ (function () {
  7825. function TotpMultiFactorGenerator() {
  7826. }
  7827. /**
  7828. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of
  7829. * the TOTP (time-based one-time password) second factor.
  7830. * This assertion is used to complete enrollment in TOTP second factor.
  7831. *
  7832. * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.
  7833. * @param oneTimePassword One-time password from TOTP App.
  7834. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  7835. * {@link MultiFactorUser.enroll}.
  7836. */
  7837. TotpMultiFactorGenerator.assertionForEnrollment = function (secret, oneTimePassword) {
  7838. return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);
  7839. };
  7840. /**
  7841. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.
  7842. * This assertion is used to complete signIn with TOTP as the second factor.
  7843. *
  7844. * @param enrollmentId identifies the enrolled TOTP second factor.
  7845. * @param oneTimePassword One-time password from TOTP App.
  7846. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  7847. * {@link MultiFactorResolver.resolveSignIn}.
  7848. */
  7849. TotpMultiFactorGenerator.assertionForSignIn = function (enrollmentId, oneTimePassword) {
  7850. return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);
  7851. };
  7852. /**
  7853. * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.
  7854. * Creates a TOTP secret as part of enrolling a TOTP second factor.
  7855. * Used for generating a QR code URL or inputting into a TOTP app.
  7856. * This method uses the auth instance corresponding to the user in the multiFactorSession.
  7857. *
  7858. * @param session The {@link MultiFactorSession} that the user is part of.
  7859. * @returns A promise to {@link TotpSecret}.
  7860. */
  7861. TotpMultiFactorGenerator.generateSecret = function (session) {
  7862. return tslib.__awaiter(this, void 0, void 0, function () {
  7863. var mfaSession, response;
  7864. return tslib.__generator(this, function (_a) {
  7865. switch (_a.label) {
  7866. case 0:
  7867. mfaSession = session;
  7868. _assert(typeof mfaSession.auth !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7869. return [4 /*yield*/, startEnrollTotpMfa(mfaSession.auth, {
  7870. idToken: mfaSession.credential,
  7871. totpEnrollmentInfo: {}
  7872. })];
  7873. case 1:
  7874. response = _a.sent();
  7875. return [2 /*return*/, TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.auth)];
  7876. }
  7877. });
  7878. });
  7879. };
  7880. /**
  7881. * The identifier of the TOTP second factor: `totp`.
  7882. */
  7883. TotpMultiFactorGenerator.FACTOR_ID = "totp" /* FactorId.TOTP */;
  7884. return TotpMultiFactorGenerator;
  7885. }());
  7886. var TotpMultiFactorAssertionImpl = /** @class */ (function (_super) {
  7887. tslib.__extends(TotpMultiFactorAssertionImpl, _super);
  7888. function TotpMultiFactorAssertionImpl(otp, enrollmentId, secret) {
  7889. var _this = _super.call(this, "totp" /* FactorId.TOTP */) || this;
  7890. _this.otp = otp;
  7891. _this.enrollmentId = enrollmentId;
  7892. _this.secret = secret;
  7893. return _this;
  7894. }
  7895. /** @internal */
  7896. TotpMultiFactorAssertionImpl._fromSecret = function (secret, otp) {
  7897. return new TotpMultiFactorAssertionImpl(otp, undefined, secret);
  7898. };
  7899. /** @internal */
  7900. TotpMultiFactorAssertionImpl._fromEnrollmentId = function (enrollmentId, otp) {
  7901. return new TotpMultiFactorAssertionImpl(otp, enrollmentId);
  7902. };
  7903. /** @internal */
  7904. TotpMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  7905. return tslib.__awaiter(this, void 0, void 0, function () {
  7906. return tslib.__generator(this, function (_a) {
  7907. _assert(typeof this.secret !== 'undefined', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7908. return [2 /*return*/, finalizeEnrollTotpMfa(auth, {
  7909. idToken: idToken,
  7910. displayName: displayName,
  7911. totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)
  7912. })];
  7913. });
  7914. });
  7915. };
  7916. /** @internal */
  7917. TotpMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  7918. return tslib.__awaiter(this, void 0, void 0, function () {
  7919. var totpVerificationInfo;
  7920. return tslib.__generator(this, function (_a) {
  7921. _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7922. totpVerificationInfo = { verificationCode: this.otp };
  7923. return [2 /*return*/, finalizeSignInTotpMfa(auth, {
  7924. mfaPendingCredential: mfaPendingCredential,
  7925. mfaEnrollmentId: this.enrollmentId,
  7926. totpVerificationInfo: totpVerificationInfo
  7927. })];
  7928. });
  7929. });
  7930. };
  7931. return TotpMultiFactorAssertionImpl;
  7932. }(MultiFactorAssertionImpl));
  7933. /**
  7934. * Provider for generating a {@link TotpMultiFactorAssertion}.
  7935. *
  7936. * Stores the shared secret key and other parameters to generate time-based OTPs.
  7937. * Implements methods to retrieve the shared secret key and generate a QR code URL.
  7938. * @public
  7939. */
  7940. var TotpSecret = /** @class */ (function () {
  7941. // The public members are declared outside the constructor so the docs can be generated.
  7942. function TotpSecret(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {
  7943. this.sessionInfo = sessionInfo;
  7944. this.auth = auth;
  7945. this.secretKey = secretKey;
  7946. this.hashingAlgorithm = hashingAlgorithm;
  7947. this.codeLength = codeLength;
  7948. this.codeIntervalSeconds = codeIntervalSeconds;
  7949. this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;
  7950. }
  7951. /** @internal */
  7952. TotpSecret._fromStartTotpMfaEnrollmentResponse = function (response, auth) {
  7953. return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);
  7954. };
  7955. /** @internal */
  7956. TotpSecret.prototype._makeTotpVerificationInfo = function (otp) {
  7957. return { sessionInfo: this.sessionInfo, verificationCode: otp };
  7958. };
  7959. /**
  7960. * Returns a QR code URL as described in
  7961. * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
  7962. * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.
  7963. * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.
  7964. *
  7965. * @param accountName the name of the account/app along with a user identifier.
  7966. * @param issuer issuer of the TOTP (likely the app name).
  7967. * @returns A QR code URL string.
  7968. */
  7969. TotpSecret.prototype.generateQrCodeUrl = function (accountName, issuer) {
  7970. var _a;
  7971. var useDefaults = false;
  7972. if (_isEmptyString(accountName) || _isEmptyString(issuer)) {
  7973. useDefaults = true;
  7974. }
  7975. if (useDefaults) {
  7976. if (_isEmptyString(accountName)) {
  7977. accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';
  7978. }
  7979. if (_isEmptyString(issuer)) {
  7980. issuer = this.auth.name;
  7981. }
  7982. }
  7983. return "otpauth://totp/".concat(issuer, ":").concat(accountName, "?secret=").concat(this.secretKey, "&issuer=").concat(issuer, "&algorithm=").concat(this.hashingAlgorithm, "&digits=").concat(this.codeLength);
  7984. };
  7985. return TotpSecret;
  7986. }());
  7987. /** @internal */
  7988. function _isEmptyString(input) {
  7989. return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;
  7990. }
  7991. exports.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;
  7992. exports.ActionCodeOperation = ActionCodeOperation;
  7993. exports.ActionCodeURL = ActionCodeURL;
  7994. exports.AuthCredential = AuthCredential;
  7995. exports.AuthImpl = AuthImpl;
  7996. exports.BaseOAuthProvider = BaseOAuthProvider;
  7997. exports.EmailAuthCredential = EmailAuthCredential;
  7998. exports.EmailAuthProvider = EmailAuthProvider;
  7999. exports.FacebookAuthProvider = FacebookAuthProvider;
  8000. exports.FactorId = FactorId;
  8001. exports.FederatedAuthProvider = FederatedAuthProvider;
  8002. exports.FetchProvider = FetchProvider;
  8003. exports.GithubAuthProvider = GithubAuthProvider;
  8004. exports.GoogleAuthProvider = GoogleAuthProvider;
  8005. exports.OAuthCredential = OAuthCredential;
  8006. exports.OAuthProvider = OAuthProvider;
  8007. exports.OperationType = OperationType;
  8008. exports.PhoneAuthCredential = PhoneAuthCredential;
  8009. exports.PhoneAuthProvider = PhoneAuthProvider;
  8010. exports.PhoneMultiFactorGenerator = PhoneMultiFactorGenerator;
  8011. exports.ProviderId = ProviderId;
  8012. exports.RecaptchaVerifier = RecaptchaVerifier;
  8013. exports.SAMLAuthCredential = SAMLAuthCredential;
  8014. exports.SAMLAuthProvider = SAMLAuthProvider;
  8015. exports.SignInMethod = SignInMethod;
  8016. exports.TotpMultiFactorGenerator = TotpMultiFactorGenerator;
  8017. exports.TotpSecret = TotpSecret;
  8018. exports.TwitterAuthProvider = TwitterAuthProvider;
  8019. exports.UserImpl = UserImpl;
  8020. exports._assert = _assert;
  8021. exports._castAuth = _castAuth;
  8022. exports._createError = _createError;
  8023. exports._emulatorUrl = _emulatorUrl;
  8024. exports._fail = _fail;
  8025. exports._getClientVersion = _getClientVersion;
  8026. exports._getInstance = _getInstance;
  8027. exports._isAndroid = _isAndroid;
  8028. exports._isIE10 = _isIE10;
  8029. exports._isIOS = _isIOS;
  8030. exports._isIOS7Or8 = _isIOS7Or8;
  8031. exports._isIframe = _isIframe;
  8032. exports._isMobileBrowser = _isMobileBrowser;
  8033. exports._isSafari = _isSafari;
  8034. exports._link = _link;
  8035. exports._performApiRequest = _performApiRequest;
  8036. exports._persistenceKeyName = _persistenceKeyName;
  8037. exports._reauthenticate = _reauthenticate;
  8038. exports._signInWithCredential = _signInWithCredential;
  8039. exports.applyActionCode = applyActionCode;
  8040. exports.beforeAuthStateChanged = beforeAuthStateChanged;
  8041. exports.browserLocalPersistence = browserLocalPersistence;
  8042. exports.browserPopupRedirectResolver = browserPopupRedirectResolver;
  8043. exports.browserSessionPersistence = browserSessionPersistence;
  8044. exports.checkActionCode = checkActionCode;
  8045. exports.confirmPasswordReset = confirmPasswordReset;
  8046. exports.connectAuthEmulator = connectAuthEmulator;
  8047. exports.createUserWithEmailAndPassword = createUserWithEmailAndPassword;
  8048. exports.debugAssert = debugAssert;
  8049. exports.debugErrorMap = debugErrorMap;
  8050. exports.deleteUser = deleteUser;
  8051. exports.fetchSignInMethodsForEmail = fetchSignInMethodsForEmail;
  8052. exports.getAdditionalUserInfo = getAdditionalUserInfo;
  8053. exports.getAuth = getAuth;
  8054. exports.getIdToken = getIdToken;
  8055. exports.getIdTokenResult = getIdTokenResult;
  8056. exports.getMultiFactorResolver = getMultiFactorResolver;
  8057. exports.getRedirectResult = getRedirectResult;
  8058. exports.inMemoryPersistence = inMemoryPersistence;
  8059. exports.indexedDBLocalPersistence = indexedDBLocalPersistence;
  8060. exports.initializeAuth = initializeAuth;
  8061. exports.initializeRecaptchaConfig = initializeRecaptchaConfig;
  8062. exports.isSignInWithEmailLink = isSignInWithEmailLink;
  8063. exports.linkWithCredential = linkWithCredential;
  8064. exports.linkWithPhoneNumber = linkWithPhoneNumber;
  8065. exports.linkWithPopup = linkWithPopup;
  8066. exports.linkWithRedirect = linkWithRedirect;
  8067. exports.multiFactor = multiFactor;
  8068. exports.onAuthStateChanged = onAuthStateChanged;
  8069. exports.onIdTokenChanged = onIdTokenChanged;
  8070. exports.parseActionCodeURL = parseActionCodeURL;
  8071. exports.prodErrorMap = prodErrorMap;
  8072. exports.reauthenticateWithCredential = reauthenticateWithCredential;
  8073. exports.reauthenticateWithPhoneNumber = reauthenticateWithPhoneNumber;
  8074. exports.reauthenticateWithPopup = reauthenticateWithPopup;
  8075. exports.reauthenticateWithRedirect = reauthenticateWithRedirect;
  8076. exports.reload = reload;
  8077. exports.sendEmailVerification = sendEmailVerification;
  8078. exports.sendPasswordResetEmail = sendPasswordResetEmail;
  8079. exports.sendSignInLinkToEmail = sendSignInLinkToEmail;
  8080. exports.setPersistence = setPersistence;
  8081. exports.signInAnonymously = signInAnonymously;
  8082. exports.signInWithCredential = signInWithCredential;
  8083. exports.signInWithCustomToken = signInWithCustomToken;
  8084. exports.signInWithEmailAndPassword = signInWithEmailAndPassword;
  8085. exports.signInWithEmailLink = signInWithEmailLink;
  8086. exports.signInWithIdp = signInWithIdp;
  8087. exports.signInWithPhoneNumber = signInWithPhoneNumber;
  8088. exports.signInWithPopup = signInWithPopup;
  8089. exports.signInWithRedirect = signInWithRedirect;
  8090. exports.signOut = signOut;
  8091. exports.unlink = unlink;
  8092. exports.updateCurrentUser = updateCurrentUser;
  8093. exports.updateEmail = updateEmail;
  8094. exports.updatePassword = updatePassword;
  8095. exports.updatePhoneNumber = updatePhoneNumber;
  8096. exports.updateProfile = updateProfile;
  8097. exports.useDeviceLanguage = useDeviceLanguage;
  8098. exports.verifyBeforeUpdateEmail = verifyBeforeUpdateEmail;
  8099. exports.verifyPasswordResetCode = verifyPasswordResetCode;
  8100. //# sourceMappingURL=totp-9fcfcaa9.js.map