totp-e47c784e.js 284 KB

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