phone-fdde6958.js 397 KB

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