index-cb0c5deb.js 530 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064
  1. import { __spreadArray, __assign, __awaiter, __generator, __rest, __extends } from 'tslib';
  2. import { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, isIE, getUA, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';
  3. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. import { Component } from '@firebase/component';
  6. /**
  7. * @license
  8. * Copyright 2021 Google LLC
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. /**
  23. * An enum of factors that may be used for multifactor authentication.
  24. *
  25. * @public
  26. */
  27. var FactorId = {
  28. /** Phone as second factor */
  29. PHONE: 'phone',
  30. TOTP: 'totp'
  31. };
  32. /**
  33. * Enumeration of supported providers.
  34. *
  35. * @public
  36. */
  37. var ProviderId = {
  38. /** Facebook provider ID */
  39. FACEBOOK: 'facebook.com',
  40. /** GitHub provider ID */
  41. GITHUB: 'github.com',
  42. /** Google provider ID */
  43. GOOGLE: 'google.com',
  44. /** Password provider */
  45. PASSWORD: 'password',
  46. /** Phone provider */
  47. PHONE: 'phone',
  48. /** Twitter provider ID */
  49. TWITTER: 'twitter.com'
  50. };
  51. /**
  52. * Enumeration of supported sign-in methods.
  53. *
  54. * @public
  55. */
  56. var SignInMethod = {
  57. /** Email link sign in method */
  58. EMAIL_LINK: 'emailLink',
  59. /** Email/password sign in method */
  60. EMAIL_PASSWORD: 'password',
  61. /** Facebook sign in method */
  62. FACEBOOK: 'facebook.com',
  63. /** GitHub sign in method */
  64. GITHUB: 'github.com',
  65. /** Google sign in method */
  66. GOOGLE: 'google.com',
  67. /** Phone sign in method */
  68. PHONE: 'phone',
  69. /** Twitter sign in method */
  70. TWITTER: 'twitter.com'
  71. };
  72. /**
  73. * Enumeration of supported operation types.
  74. *
  75. * @public
  76. */
  77. var OperationType = {
  78. /** Operation involving linking an additional provider to an already signed-in user. */
  79. LINK: 'link',
  80. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  81. REAUTHENTICATE: 'reauthenticate',
  82. /** Operation involving signing in a user. */
  83. SIGN_IN: 'signIn'
  84. };
  85. /**
  86. * An enumeration of the possible email action types.
  87. *
  88. * @public
  89. */
  90. var ActionCodeOperation = {
  91. /** The email link sign-in action. */
  92. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  93. /** The password reset action. */
  94. PASSWORD_RESET: 'PASSWORD_RESET',
  95. /** The email revocation action. */
  96. RECOVER_EMAIL: 'RECOVER_EMAIL',
  97. /** The revert second factor addition email action. */
  98. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  99. /** The revert second factor addition email action. */
  100. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  101. /** The email verification action. */
  102. VERIFY_EMAIL: 'VERIFY_EMAIL'
  103. };
  104. /**
  105. * @license
  106. * Copyright 2020 Google LLC
  107. *
  108. * Licensed under the Apache License, Version 2.0 (the "License");
  109. * you may not use this file except in compliance with the License.
  110. * You may obtain a copy of the License at
  111. *
  112. * http://www.apache.org/licenses/LICENSE-2.0
  113. *
  114. * Unless required by applicable law or agreed to in writing, software
  115. * distributed under the License is distributed on an "AS IS" BASIS,
  116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  117. * See the License for the specific language governing permissions and
  118. * limitations under the License.
  119. */
  120. function _debugErrorMap() {
  121. var _a;
  122. return _a = {},
  123. _a["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
  124. _a["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */] = '',
  125. _a["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
  126. 'authorized to use Firebase Authentication with the provided API key. ' +
  127. 'Review your key configuration in the Google API console.',
  128. _a["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
  129. 'Android package name or iOS bundle ID) provided is not installed on ' +
  130. 'this device.',
  131. _a["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
  132. 'already used or the domain associated with it does not match the list ' +
  133. 'of whitelisted domains.',
  134. _a["code-expired" /* AuthErrorCode.CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
  135. 'again.',
  136. _a["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
  137. _a["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */] = 'This browser is not supported.',
  138. _a["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
  139. _a["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
  140. _a["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
  141. 'again before retrying this request.',
  142. _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 ' +
  143. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  144. 'starting any other Firebase SDK.',
  145. _a["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  146. 'conditions.',
  147. _a["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
  148. _a["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */] = 'The email address is already in use by another account.',
  149. _a["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
  150. 'no longer be configured to use the emulator. Try calling ' +
  151. '"connectAuthEmulator()" sooner.',
  152. _a["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */] = 'The action code has expired.',
  153. _a["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
  154. _a["internal-error" /* AuthErrorCode.INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
  155. _a["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
  156. ' The reCAPTCHA token response is either invalid or expired.',
  157. _a["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
  158. _a["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
  159. "if the user's token has been tampered with, or if the user isn't for " +
  160. 'the project associated with this API key.',
  161. _a["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  162. _a["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
  163. 'invalid. Please resend the verification code sms and be sure to use the ' +
  164. 'verification code provided by the user.',
  165. _a["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
  166. _a["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  167. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  168. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  169. 'cordova-plugin-customurlscheme.',
  170. _a["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
  171. _a["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
  172. _a["invalid-email" /* AuthErrorCode.INVALID_EMAIL */] = 'The email address is badly formatted.',
  173. _a["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
  174. _a["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
  175. _a["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
  176. _a["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
  177. _a["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
  178. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  179. _a["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
  180. _a["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
  181. 'only supports OAuth providers.',
  182. _a["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
  183. 'specified API key.',
  184. _a["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
  185. 'project. Edit the list of authorized domains from the Firebase console.',
  186. _a["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
  187. 'expired, or has already been used.',
  188. _a["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
  189. _a["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
  190. _a["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
  191. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  192. 'phone numbers are written in the format [+][country code][subscriber ' +
  193. 'number including area code].',
  194. _a["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
  195. _a["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
  196. 'recipient email address is invalid.',
  197. _a["invalid-sender" /* AuthErrorCode.INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
  198. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  199. _a["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
  200. _a["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
  201. _a["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */] = 'Login blocked by user-provided method: {$originalMessage}',
  202. _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.',
  203. _a["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  204. 'by following the instructions in the Firebase console.',
  205. _a["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
  206. 'assertion. A reCAPTCHA response token needs to be provided.',
  207. _a["missing-verification-code" /* AuthErrorCode.MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
  208. _a["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
  209. _a["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
  210. _a["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  211. _a["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
  212. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  213. 'in the ID token payload.',
  214. _a["missing-password" /* AuthErrorCode.MISSING_PASSWORD */] = 'A non-empty password must be provided',
  215. _a["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
  216. _a["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
  217. _a["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
  218. _a["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
  219. _a["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
  220. _a["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
  221. _a["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
  222. _a["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
  223. 'sign-in credentials. Sign in using a provider associated with this ' +
  224. 'email address.',
  225. _a["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  226. _a["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  227. _a["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
  228. _a["null-user" /* AuthErrorCode.NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
  229. 'requires a non-null user object.',
  230. _a["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
  231. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  232. 'Auth section.',
  233. _a["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
  234. 'running on. "location.protocol" must be http, https or chrome-extension' +
  235. ' and web storage must be enabled.',
  236. _a["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  237. _a["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
  238. _a["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
  239. _a["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
  240. _a["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
  241. _a["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
  242. _a["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
  243. _a["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
  244. _a["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
  245. _a["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
  246. _a["timeout" /* AuthErrorCode.TIMEOUT */] = 'The operation has timed out.',
  247. _a["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
  248. _a["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
  249. 'Try again later.',
  250. _a["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  251. 'the domain in the Firebase console.',
  252. _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.',
  253. _a["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
  254. _a["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
  255. _a["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
  256. _a["user-cancelled" /* AuthErrorCode.USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
  257. _a["user-not-found" /* AuthErrorCode.USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
  258. 'have been deleted.',
  259. _a["user-disabled" /* AuthErrorCode.USER_DISABLED */] = 'The user account has been disabled by an administrator.',
  260. _a["user-mismatch" /* AuthErrorCode.USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
  261. _a["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */] = '',
  262. _a["weak-password" /* AuthErrorCode.WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
  263. _a["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
  264. _a["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
  265. 'different options. To avoid this error, call initializeAuth() with the ' +
  266. 'same options as when it was originally called, or call getAuth() to return the' +
  267. ' already initialized instance.',
  268. _a["missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is missing when sending request to the backend.',
  269. _a["invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */] = 'The reCAPTCHA token is invalid when sending request to the backend.',
  270. _a["invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */] = 'The reCAPTCHA action is invalid when sending request to the backend.',
  271. _a["recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */] = 'reCAPTCHA Enterprise integration is not enabled for this project.',
  272. _a["missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */] = 'The reCAPTCHA client type is missing when sending request to the backend.',
  273. _a["missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is missing when sending request to the backend.',
  274. _a["invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */] = 'Invalid request parameters.',
  275. _a["invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */] = 'The reCAPTCHA version is invalid when sending request to the backend.',
  276. _a;
  277. }
  278. function _prodErrorMap() {
  279. var _a;
  280. // We will include this one message in the prod error map since by the very
  281. // nature of this error, developers will never be able to see the message
  282. // using the debugErrorMap (which is installed during auth initialization).
  283. return _a = {},
  284. _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 ' +
  285. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  286. 'starting any other Firebase SDK.',
  287. _a;
  288. }
  289. /**
  290. * A verbose error map with detailed descriptions for most error codes.
  291. *
  292. * See discussion at {@link AuthErrorMap}
  293. *
  294. * @public
  295. */
  296. var debugErrorMap = _debugErrorMap;
  297. /**
  298. * A minimal error map with all verbose error messages stripped.
  299. *
  300. * See discussion at {@link AuthErrorMap}
  301. *
  302. * @public
  303. */
  304. var prodErrorMap = _prodErrorMap;
  305. var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  306. /**
  307. * A map of potential `Auth` error codes, for easier comparison with errors
  308. * thrown by the SDK.
  309. *
  310. * @remarks
  311. * Note that you can't tree-shake individual keys
  312. * in the map, so by using the map you might substantially increase your
  313. * bundle size.
  314. *
  315. * @public
  316. */
  317. var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  318. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  319. ARGUMENT_ERROR: 'auth/argument-error',
  320. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  321. APP_NOT_INSTALLED: 'auth/app-not-installed',
  322. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  323. CODE_EXPIRED: 'auth/code-expired',
  324. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  325. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  326. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  327. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  328. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  329. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  330. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  331. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  332. EMAIL_EXISTS: 'auth/email-already-in-use',
  333. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  334. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  335. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  336. INTERNAL_ERROR: 'auth/internal-error',
  337. INVALID_API_KEY: 'auth/invalid-api-key',
  338. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  339. INVALID_APP_ID: 'auth/invalid-app-id',
  340. INVALID_AUTH: 'auth/invalid-user-token',
  341. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  342. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  343. INVALID_CODE: 'auth/invalid-verification-code',
  344. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  345. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  346. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  347. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  348. INVALID_EMAIL: 'auth/invalid-email',
  349. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  350. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  351. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  352. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  353. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  354. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  355. INVALID_OOB_CODE: 'auth/invalid-action-code',
  356. INVALID_ORIGIN: 'auth/unauthorized-domain',
  357. INVALID_PASSWORD: 'auth/wrong-password',
  358. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  359. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  360. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  361. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  362. INVALID_SENDER: 'auth/invalid-sender',
  363. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  364. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  365. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  366. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  367. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  368. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  369. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  370. MISSING_CODE: 'auth/missing-verification-code',
  371. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  372. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  373. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  374. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  375. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  376. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  377. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  378. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  379. MODULE_DESTROYED: 'auth/app-deleted',
  380. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  381. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  382. NULL_USER: 'auth/null-user',
  383. NO_AUTH_EVENT: 'auth/no-auth-event',
  384. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  385. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  386. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  387. POPUP_BLOCKED: 'auth/popup-blocked',
  388. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  389. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  390. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  391. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  392. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  393. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  394. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  395. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  396. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  397. TIMEOUT: 'auth/timeout',
  398. TOKEN_EXPIRED: 'auth/user-token-expired',
  399. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  400. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  401. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  402. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  403. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  404. UNVERIFIED_EMAIL: 'auth/unverified-email',
  405. USER_CANCELLED: 'auth/user-cancelled',
  406. USER_DELETED: 'auth/user-not-found',
  407. USER_DISABLED: 'auth/user-disabled',
  408. USER_MISMATCH: 'auth/user-mismatch',
  409. USER_SIGNED_OUT: 'auth/user-signed-out',
  410. WEAK_PASSWORD: 'auth/weak-password',
  411. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  412. ALREADY_INITIALIZED: 'auth/already-initialized',
  413. RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',
  414. MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',
  415. INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',
  416. INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',
  417. MISSING_CLIENT_TYPE: 'auth/missing-client-type',
  418. MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',
  419. INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',
  420. INVALID_REQ_TYPE: 'auth/invalid-req-type'
  421. };
  422. /**
  423. * @license
  424. * Copyright 2020 Google LLC
  425. *
  426. * Licensed under the Apache License, Version 2.0 (the "License");
  427. * you may not use this file except in compliance with the License.
  428. * You may obtain a copy of the License at
  429. *
  430. * http://www.apache.org/licenses/LICENSE-2.0
  431. *
  432. * Unless required by applicable law or agreed to in writing, software
  433. * distributed under the License is distributed on an "AS IS" BASIS,
  434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  435. * See the License for the specific language governing permissions and
  436. * limitations under the License.
  437. */
  438. var logClient = new Logger('@firebase/auth');
  439. function _logWarn(msg) {
  440. var args = [];
  441. for (var _i = 1; _i < arguments.length; _i++) {
  442. args[_i - 1] = arguments[_i];
  443. }
  444. if (logClient.logLevel <= LogLevel.WARN) {
  445. logClient.warn.apply(logClient, __spreadArray(["Auth (".concat(SDK_VERSION, "): ").concat(msg)], args, false));
  446. }
  447. }
  448. function _logError(msg) {
  449. var args = [];
  450. for (var _i = 1; _i < arguments.length; _i++) {
  451. args[_i - 1] = arguments[_i];
  452. }
  453. if (logClient.logLevel <= LogLevel.ERROR) {
  454. logClient.error.apply(logClient, __spreadArray(["Auth (".concat(SDK_VERSION, "): ").concat(msg)], args, false));
  455. }
  456. }
  457. /**
  458. * @license
  459. * Copyright 2020 Google LLC
  460. *
  461. * Licensed under the Apache License, Version 2.0 (the "License");
  462. * you may not use this file except in compliance with the License.
  463. * You may obtain a copy of the License at
  464. *
  465. * http://www.apache.org/licenses/LICENSE-2.0
  466. *
  467. * Unless required by applicable law or agreed to in writing, software
  468. * distributed under the License is distributed on an "AS IS" BASIS,
  469. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  470. * See the License for the specific language governing permissions and
  471. * limitations under the License.
  472. */
  473. function _fail(authOrCode) {
  474. var rest = [];
  475. for (var _i = 1; _i < arguments.length; _i++) {
  476. rest[_i - 1] = arguments[_i];
  477. }
  478. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  479. }
  480. function _createError(authOrCode) {
  481. var rest = [];
  482. for (var _i = 1; _i < arguments.length; _i++) {
  483. rest[_i - 1] = arguments[_i];
  484. }
  485. return createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  486. }
  487. function _errorWithCustomMessage(auth, code, message) {
  488. var _a;
  489. var errorMap = __assign(__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
  490. var factory = new ErrorFactory('auth', 'Firebase', errorMap);
  491. return factory.create(code, {
  492. appName: auth.name
  493. });
  494. }
  495. function _assertInstanceOf(auth, object, instance) {
  496. var constructorInstance = instance;
  497. if (!(object instanceof constructorInstance)) {
  498. if (constructorInstance.name !== object.constructor.name) {
  499. _fail(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  500. }
  501. throw _errorWithCustomMessage(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, "Type of ".concat(object.constructor.name, " does not match expected instance.") +
  502. "Did you pass a reference from a different Auth SDK?");
  503. }
  504. }
  505. function createErrorInternal(authOrCode) {
  506. var _a;
  507. var rest = [];
  508. for (var _i = 1; _i < arguments.length; _i++) {
  509. rest[_i - 1] = arguments[_i];
  510. }
  511. if (typeof authOrCode !== 'string') {
  512. var code = rest[0];
  513. var fullParams = __spreadArray([], rest.slice(1), true);
  514. if (fullParams[0]) {
  515. fullParams[0].appName = authOrCode.name;
  516. }
  517. return (_a = authOrCode._errorFactory).create.apply(_a, __spreadArray([code], fullParams, false));
  518. }
  519. return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, __spreadArray([authOrCode], rest, false));
  520. }
  521. function _assert(assertion, authOrCode) {
  522. var rest = [];
  523. for (var _i = 2; _i < arguments.length; _i++) {
  524. rest[_i - 2] = arguments[_i];
  525. }
  526. if (!assertion) {
  527. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  528. }
  529. }
  530. /**
  531. * Unconditionally fails, throwing an internal error with the given message.
  532. *
  533. * @param failure type of failure encountered
  534. * @throws Error
  535. */
  536. function debugFail(failure) {
  537. // Log the failure in addition to throw an exception, just in case the
  538. // exception is swallowed.
  539. var message = "INTERNAL ASSERTION FAILED: " + failure;
  540. _logError(message);
  541. // NOTE: We don't use FirebaseError here because these are internal failures
  542. // that cannot be handled by the user. (Also it would create a circular
  543. // dependency between the error and assert modules which doesn't work.)
  544. throw new Error(message);
  545. }
  546. /**
  547. * Fails if the given assertion condition is false, throwing an Error with the
  548. * given message if it did.
  549. *
  550. * @param assertion
  551. * @param message
  552. */
  553. function debugAssert(assertion, message) {
  554. if (!assertion) {
  555. debugFail(message);
  556. }
  557. }
  558. /**
  559. * @license
  560. * Copyright 2020 Google LLC
  561. *
  562. * Licensed under the Apache License, Version 2.0 (the "License");
  563. * you may not use this file except in compliance with the License.
  564. * You may obtain a copy of the License at
  565. *
  566. * http://www.apache.org/licenses/LICENSE-2.0
  567. *
  568. * Unless required by applicable law or agreed to in writing, software
  569. * distributed under the License is distributed on an "AS IS" BASIS,
  570. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  571. * See the License for the specific language governing permissions and
  572. * limitations under the License.
  573. */
  574. function _getCurrentUrl() {
  575. var _a;
  576. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  577. }
  578. function _isHttpOrHttps() {
  579. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  580. }
  581. function _getCurrentScheme() {
  582. var _a;
  583. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  584. }
  585. /**
  586. * @license
  587. * Copyright 2020 Google LLC
  588. *
  589. * Licensed under the Apache License, Version 2.0 (the "License");
  590. * you may not use this file except in compliance with the License.
  591. * You may obtain a copy of the License at
  592. *
  593. * http://www.apache.org/licenses/LICENSE-2.0
  594. *
  595. * Unless required by applicable law or agreed to in writing, software
  596. * distributed under the License is distributed on an "AS IS" BASIS,
  597. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  598. * See the License for the specific language governing permissions and
  599. * limitations under the License.
  600. */
  601. /**
  602. * Determine whether the browser is working online
  603. */
  604. function _isOnline() {
  605. if (typeof navigator !== 'undefined' &&
  606. navigator &&
  607. 'onLine' in navigator &&
  608. typeof navigator.onLine === 'boolean' &&
  609. // Apply only for traditional web apps and Chrome extensions.
  610. // This is especially true for Cordova apps which have unreliable
  611. // navigator.onLine behavior unless cordova-plugin-network-information is
  612. // installed which overwrites the native navigator.onLine value and
  613. // defines navigator.connection.
  614. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  615. return navigator.onLine;
  616. }
  617. // If we can't determine the state, assume it is online.
  618. return true;
  619. }
  620. function _getUserLanguage() {
  621. if (typeof navigator === 'undefined') {
  622. return null;
  623. }
  624. var navigatorLanguage = navigator;
  625. return (
  626. // Most reliable, but only supported in Chrome/Firefox.
  627. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  628. // Supported in most browsers, but returns the language of the browser
  629. // UI, not the language set in browser settings.
  630. navigatorLanguage.language ||
  631. // Couldn't determine language.
  632. null);
  633. }
  634. /**
  635. * @license
  636. * Copyright 2020 Google LLC
  637. *
  638. * Licensed under the Apache License, Version 2.0 (the "License");
  639. * you may not use this file except in compliance with the License.
  640. * You may obtain a copy of the License at
  641. *
  642. * http://www.apache.org/licenses/LICENSE-2.0
  643. *
  644. * Unless required by applicable law or agreed to in writing, software
  645. * distributed under the License is distributed on an "AS IS" BASIS,
  646. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  647. * See the License for the specific language governing permissions and
  648. * limitations under the License.
  649. */
  650. /**
  651. * A structure to help pick between a range of long and short delay durations
  652. * depending on the current environment. In general, the long delay is used for
  653. * mobile environments whereas short delays are used for desktop environments.
  654. */
  655. var Delay = /** @class */ (function () {
  656. function Delay(shortDelay, longDelay) {
  657. this.shortDelay = shortDelay;
  658. this.longDelay = longDelay;
  659. // Internal error when improperly initialized.
  660. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  661. this.isMobile = isMobileCordova() || isReactNative();
  662. }
  663. Delay.prototype.get = function () {
  664. if (!_isOnline()) {
  665. // Pick the shorter timeout.
  666. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  667. }
  668. // If running in a mobile environment, return the long delay, otherwise
  669. // return the short delay.
  670. // This could be improved in the future to dynamically change based on other
  671. // variables instead of just reading the current environment.
  672. return this.isMobile ? this.longDelay : this.shortDelay;
  673. };
  674. return Delay;
  675. }());
  676. /**
  677. * @license
  678. * Copyright 2020 Google LLC
  679. *
  680. * Licensed under the Apache License, Version 2.0 (the "License");
  681. * you may not use this file except in compliance with the License.
  682. * You may obtain a copy of the License at
  683. *
  684. * http://www.apache.org/licenses/LICENSE-2.0
  685. *
  686. * Unless required by applicable law or agreed to in writing, software
  687. * distributed under the License is distributed on an "AS IS" BASIS,
  688. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  689. * See the License for the specific language governing permissions and
  690. * limitations under the License.
  691. */
  692. function _emulatorUrl(config, path) {
  693. debugAssert(config.emulator, 'Emulator should always be set here');
  694. var url = config.emulator.url;
  695. if (!path) {
  696. return url;
  697. }
  698. return "".concat(url).concat(path.startsWith('/') ? path.slice(1) : path);
  699. }
  700. /**
  701. * @license
  702. * Copyright 2020 Google LLC
  703. *
  704. * Licensed under the Apache License, Version 2.0 (the "License");
  705. * you may not use this file except in compliance with the License.
  706. * You may obtain a copy of the License at
  707. *
  708. * http://www.apache.org/licenses/LICENSE-2.0
  709. *
  710. * Unless required by applicable law or agreed to in writing, software
  711. * distributed under the License is distributed on an "AS IS" BASIS,
  712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  713. * See the License for the specific language governing permissions and
  714. * limitations under the License.
  715. */
  716. var FetchProvider = /** @class */ (function () {
  717. function FetchProvider() {
  718. }
  719. FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
  720. this.fetchImpl = fetchImpl;
  721. if (headersImpl) {
  722. this.headersImpl = headersImpl;
  723. }
  724. if (responseImpl) {
  725. this.responseImpl = responseImpl;
  726. }
  727. };
  728. FetchProvider.fetch = function () {
  729. if (this.fetchImpl) {
  730. return this.fetchImpl;
  731. }
  732. if (typeof self !== 'undefined' && 'fetch' in self) {
  733. return self.fetch;
  734. }
  735. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  736. };
  737. FetchProvider.headers = function () {
  738. if (this.headersImpl) {
  739. return this.headersImpl;
  740. }
  741. if (typeof self !== 'undefined' && 'Headers' in self) {
  742. return self.Headers;
  743. }
  744. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  745. };
  746. FetchProvider.response = function () {
  747. if (this.responseImpl) {
  748. return this.responseImpl;
  749. }
  750. if (typeof self !== 'undefined' && 'Response' in self) {
  751. return self.Response;
  752. }
  753. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  754. };
  755. return FetchProvider;
  756. }());
  757. /**
  758. * @license
  759. * Copyright 2020 Google LLC
  760. *
  761. * Licensed under the Apache License, Version 2.0 (the "License");
  762. * you may not use this file except in compliance with the License.
  763. * You may obtain a copy of the License at
  764. *
  765. * http://www.apache.org/licenses/LICENSE-2.0
  766. *
  767. * Unless required by applicable law or agreed to in writing, software
  768. * distributed under the License is distributed on an "AS IS" BASIS,
  769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  770. * See the License for the specific language governing permissions and
  771. * limitations under the License.
  772. */
  773. var _a$1;
  774. /**
  775. * Map from errors returned by the server to errors to developer visible errors
  776. */
  777. var SERVER_ERROR_MAP = (_a$1 = {},
  778. // Custom token errors.
  779. _a$1["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  780. // This can only happen if the SDK sends a bad request.
  781. _a$1["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  782. // Create Auth URI errors.
  783. _a$1["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */] = "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  784. // This can only happen if the SDK sends a bad request.
  785. _a$1["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  786. // Sign in with email and password errors (some apply to sign up too).
  787. _a$1["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */] = "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  788. // This can only happen if the SDK sends a bad request.
  789. _a$1["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */] = "missing-password" /* AuthErrorCode.MISSING_PASSWORD */,
  790. // Sign up with email and password errors.
  791. _a$1["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */] = "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  792. _a$1["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  793. // Verify assertion for sign in with credential errors:
  794. _a$1["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  795. _a$1["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  796. _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  797. // This can only happen if the SDK sends a bad request.
  798. _a$1["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  799. // Send Password reset email errors:
  800. _a$1["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  801. _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  802. _a$1["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */] = "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  803. _a$1["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */] = "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  804. // This can only happen if the SDK sends a bad request.
  805. _a$1["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  806. // Operations that require ID token in request:
  807. _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  808. _a$1["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */] = "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  809. _a$1["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  810. _a$1["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  811. // Other errors.
  812. _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  813. // Phone Auth related errors.
  814. _a$1["INVALID_CODE" /* ServerError.INVALID_CODE */] = "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  815. _a$1["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */] = "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  816. _a$1["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  817. _a$1["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */] = "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  818. _a$1["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */] = "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  819. // Other action code errors when additional settings passed.
  820. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  821. // This is OK as this error will be caught by client side validation.
  822. _a$1["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  823. _a$1["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  824. // getProjectConfig errors when clientId is passed.
  825. _a$1["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  826. // User actions (sign-up or deletion) disabled errors.
  827. _a$1["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  828. // Multi factor related errors.
  829. _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  830. _a$1["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  831. _a$1["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  832. _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  833. _a$1["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  834. _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  835. // Blocking functions related errors.
  836. _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  837. // Recaptcha related errors.
  838. _a$1["RECAPTCHA_NOT_ENABLED" /* ServerError.RECAPTCHA_NOT_ENABLED */] = "recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,
  839. _a$1["MISSING_RECAPTCHA_TOKEN" /* ServerError.MISSING_RECAPTCHA_TOKEN */] = "missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,
  840. _a$1["INVALID_RECAPTCHA_TOKEN" /* ServerError.INVALID_RECAPTCHA_TOKEN */] = "invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,
  841. _a$1["INVALID_RECAPTCHA_ACTION" /* ServerError.INVALID_RECAPTCHA_ACTION */] = "invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,
  842. _a$1["MISSING_CLIENT_TYPE" /* ServerError.MISSING_CLIENT_TYPE */] = "missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */,
  843. _a$1["MISSING_RECAPTCHA_VERSION" /* ServerError.MISSING_RECAPTCHA_VERSION */] = "missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,
  844. _a$1["INVALID_RECAPTCHA_VERSION" /* ServerError.INVALID_RECAPTCHA_VERSION */] = "invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,
  845. _a$1["INVALID_REQ_TYPE" /* ServerError.INVALID_REQ_TYPE */] = "invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */,
  846. _a$1);
  847. /**
  848. * @license
  849. * Copyright 2020 Google LLC
  850. *
  851. * Licensed under the Apache License, Version 2.0 (the "License");
  852. * you may not use this file except in compliance with the License.
  853. * You may obtain a copy of the License at
  854. *
  855. * http://www.apache.org/licenses/LICENSE-2.0
  856. *
  857. * Unless required by applicable law or agreed to in writing, software
  858. * distributed under the License is distributed on an "AS IS" BASIS,
  859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  860. * See the License for the specific language governing permissions and
  861. * limitations under the License.
  862. */
  863. var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  864. function _addTidIfNecessary(auth, request) {
  865. if (auth.tenantId && !request.tenantId) {
  866. return __assign(__assign({}, request), { tenantId: auth.tenantId });
  867. }
  868. return request;
  869. }
  870. function _performApiRequest(auth, method, path, request, customErrorMap) {
  871. if (customErrorMap === void 0) { customErrorMap = {}; }
  872. return __awaiter(this, void 0, void 0, function () {
  873. var _this = this;
  874. return __generator(this, function (_a) {
  875. return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return __awaiter(_this, void 0, void 0, function () {
  876. var body, params, query, headers;
  877. return __generator(this, function (_a) {
  878. switch (_a.label) {
  879. case 0:
  880. body = {};
  881. params = {};
  882. if (request) {
  883. if (method === "GET" /* HttpMethod.GET */) {
  884. params = request;
  885. }
  886. else {
  887. body = {
  888. body: JSON.stringify(request)
  889. };
  890. }
  891. }
  892. query = querystring(__assign({ key: auth.config.apiKey }, params)).slice(1);
  893. return [4 /*yield*/, auth._getAdditionalHeaders()];
  894. case 1:
  895. headers = _a.sent();
  896. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  897. if (auth.languageCode) {
  898. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  899. }
  900. return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), __assign({ method: method, headers: headers, referrerPolicy: 'no-referrer' }, body))];
  901. }
  902. });
  903. }); })];
  904. });
  905. });
  906. }
  907. function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  908. return __awaiter(this, void 0, void 0, function () {
  909. var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
  910. return __generator(this, function (_b) {
  911. switch (_b.label) {
  912. case 0:
  913. auth._canInitEmulator = false;
  914. errorMap = __assign(__assign({}, SERVER_ERROR_MAP), customErrorMap);
  915. _b.label = 1;
  916. case 1:
  917. _b.trys.push([1, 4, , 5]);
  918. networkTimeout = new NetworkTimeout(auth);
  919. return [4 /*yield*/, Promise.race([
  920. fetchFn(),
  921. networkTimeout.promise
  922. ])];
  923. case 2:
  924. response = _b.sent();
  925. // If we've reached this point, the fetch succeeded and the networkTimeout
  926. // didn't throw; clear the network timeout delay so that Node won't hang
  927. networkTimeout.clearNetworkTimeout();
  928. return [4 /*yield*/, response.json()];
  929. case 3:
  930. json = _b.sent();
  931. if ('needConfirmation' in json) {
  932. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  933. }
  934. if (response.ok && !('errorMessage' in json)) {
  935. return [2 /*return*/, json];
  936. }
  937. else {
  938. errorMessage = response.ok ? json.errorMessage : json.error.message;
  939. _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
  940. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  941. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  942. }
  943. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  944. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  945. }
  946. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  947. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  948. }
  949. authError = errorMap[serverErrorCode] ||
  950. serverErrorCode
  951. .toLowerCase()
  952. .replace(/[_\s]+/g, '-');
  953. if (serverErrorMessage) {
  954. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  955. }
  956. else {
  957. _fail(auth, authError);
  958. }
  959. }
  960. return [3 /*break*/, 5];
  961. case 4:
  962. e_1 = _b.sent();
  963. if (e_1 instanceof FirebaseError) {
  964. throw e_1;
  965. }
  966. // Changing this to a different error code will log user out when there is a network error
  967. // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.
  968. // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316
  969. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e_1) });
  970. return [3 /*break*/, 5];
  971. case 5: return [2 /*return*/];
  972. }
  973. });
  974. });
  975. }
  976. function _performSignInRequest(auth, method, path, request, customErrorMap) {
  977. if (customErrorMap === void 0) { customErrorMap = {}; }
  978. return __awaiter(this, void 0, void 0, function () {
  979. var serverResponse;
  980. return __generator(this, function (_a) {
  981. switch (_a.label) {
  982. case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
  983. case 1:
  984. serverResponse = (_a.sent());
  985. if ('mfaPendingCredential' in serverResponse) {
  986. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  987. _serverResponse: serverResponse
  988. });
  989. }
  990. return [2 /*return*/, serverResponse];
  991. }
  992. });
  993. });
  994. }
  995. function _getFinalTarget(auth, host, path, query) {
  996. var base = "".concat(host).concat(path, "?").concat(query);
  997. if (!auth.config.emulator) {
  998. return "".concat(auth.config.apiScheme, "://").concat(base);
  999. }
  1000. return _emulatorUrl(auth.config, base);
  1001. }
  1002. var NetworkTimeout = /** @class */ (function () {
  1003. function NetworkTimeout(auth) {
  1004. var _this = this;
  1005. this.auth = auth;
  1006. // Node timers and browser timers are fundamentally incompatible, but we
  1007. // don't care about the value here
  1008. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1009. this.timer = null;
  1010. this.promise = new Promise(function (_, reject) {
  1011. _this.timer = setTimeout(function () {
  1012. return reject(_createError(_this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1013. }, DEFAULT_API_TIMEOUT_MS.get());
  1014. });
  1015. }
  1016. NetworkTimeout.prototype.clearNetworkTimeout = function () {
  1017. clearTimeout(this.timer);
  1018. };
  1019. return NetworkTimeout;
  1020. }());
  1021. function _makeTaggedError(auth, code, response) {
  1022. var errorParams = {
  1023. appName: auth.name
  1024. };
  1025. if (response.email) {
  1026. errorParams.email = response.email;
  1027. }
  1028. if (response.phoneNumber) {
  1029. errorParams.phoneNumber = response.phoneNumber;
  1030. }
  1031. var error = _createError(auth, code, errorParams);
  1032. // We know customData is defined on error because errorParams is defined
  1033. error.customData._tokenResponse = response;
  1034. return error;
  1035. }
  1036. /**
  1037. * @license
  1038. * Copyright 2020 Google LLC
  1039. *
  1040. * Licensed under the Apache License, Version 2.0 (the "License");
  1041. * you may not use this file except in compliance with the License.
  1042. * You may obtain a copy of the License at
  1043. *
  1044. * http://www.apache.org/licenses/LICENSE-2.0
  1045. *
  1046. * Unless required by applicable law or agreed to in writing, software
  1047. * distributed under the License is distributed on an "AS IS" BASIS,
  1048. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1049. * See the License for the specific language governing permissions and
  1050. * limitations under the License.
  1051. */
  1052. function deleteAccount(auth, request) {
  1053. return __awaiter(this, void 0, void 0, function () {
  1054. return __generator(this, function (_a) {
  1055. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request)];
  1056. });
  1057. });
  1058. }
  1059. function deleteLinkedAccounts(auth, request) {
  1060. return __awaiter(this, void 0, void 0, function () {
  1061. return __generator(this, function (_a) {
  1062. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  1063. });
  1064. });
  1065. }
  1066. function getAccountInfo(auth, request) {
  1067. return __awaiter(this, void 0, void 0, function () {
  1068. return __generator(this, function (_a) {
  1069. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request)];
  1070. });
  1071. });
  1072. }
  1073. /**
  1074. * @license
  1075. * Copyright 2020 Google LLC
  1076. *
  1077. * Licensed under the Apache License, Version 2.0 (the "License");
  1078. * you may not use this file except in compliance with the License.
  1079. * You may obtain a copy of the License at
  1080. *
  1081. * http://www.apache.org/licenses/LICENSE-2.0
  1082. *
  1083. * Unless required by applicable law or agreed to in writing, software
  1084. * distributed under the License is distributed on an "AS IS" BASIS,
  1085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1086. * See the License for the specific language governing permissions and
  1087. * limitations under the License.
  1088. */
  1089. function utcTimestampToDateString(utcTimestamp) {
  1090. if (!utcTimestamp) {
  1091. return undefined;
  1092. }
  1093. try {
  1094. // Convert to date object.
  1095. var date = new Date(Number(utcTimestamp));
  1096. // Test date is valid.
  1097. if (!isNaN(date.getTime())) {
  1098. // Convert to UTC date string.
  1099. return date.toUTCString();
  1100. }
  1101. }
  1102. catch (e) {
  1103. // Do nothing. undefined will be returned.
  1104. }
  1105. return undefined;
  1106. }
  1107. /**
  1108. * @license
  1109. * Copyright 2020 Google LLC
  1110. *
  1111. * Licensed under the Apache License, Version 2.0 (the "License");
  1112. * you may not use this file except in compliance with the License.
  1113. * You may obtain a copy of the License at
  1114. *
  1115. * http://www.apache.org/licenses/LICENSE-2.0
  1116. *
  1117. * Unless required by applicable law or agreed to in writing, software
  1118. * distributed under the License is distributed on an "AS IS" BASIS,
  1119. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1120. * See the License for the specific language governing permissions and
  1121. * limitations under the License.
  1122. */
  1123. /**
  1124. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1125. *
  1126. * @remarks
  1127. * Returns the current token if it has not expired or if it will not expire in the next five
  1128. * minutes. Otherwise, this will refresh the token and return a new one.
  1129. *
  1130. * @param user - The user.
  1131. * @param forceRefresh - Force refresh regardless of token expiration.
  1132. *
  1133. * @public
  1134. */
  1135. function getIdToken(user, forceRefresh) {
  1136. if (forceRefresh === void 0) { forceRefresh = false; }
  1137. return getModularInstance(user).getIdToken(forceRefresh);
  1138. }
  1139. /**
  1140. * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
  1141. *
  1142. * @remarks
  1143. * Returns the current token if it has not expired or if it will not expire in the next five
  1144. * minutes. Otherwise, this will refresh the token and return a new one.
  1145. *
  1146. * @param user - The user.
  1147. * @param forceRefresh - Force refresh regardless of token expiration.
  1148. *
  1149. * @public
  1150. */
  1151. function getIdTokenResult(user, forceRefresh) {
  1152. if (forceRefresh === void 0) { forceRefresh = false; }
  1153. return __awaiter(this, void 0, void 0, function () {
  1154. var userInternal, token, claims, firebase, signInProvider;
  1155. return __generator(this, function (_a) {
  1156. switch (_a.label) {
  1157. case 0:
  1158. userInternal = getModularInstance(user);
  1159. return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
  1160. case 1:
  1161. token = _a.sent();
  1162. claims = _parseToken(token);
  1163. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1164. firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1165. signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1166. return [2 /*return*/, {
  1167. claims: claims,
  1168. token: token,
  1169. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1170. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1171. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1172. signInProvider: signInProvider || null,
  1173. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1174. }];
  1175. }
  1176. });
  1177. });
  1178. }
  1179. function secondsStringToMilliseconds(seconds) {
  1180. return Number(seconds) * 1000;
  1181. }
  1182. function _parseToken(token) {
  1183. var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
  1184. if (algorithm === undefined ||
  1185. payload === undefined ||
  1186. signature === undefined) {
  1187. _logError('JWT malformed, contained fewer than 3 sections');
  1188. return null;
  1189. }
  1190. try {
  1191. var decoded = base64Decode(payload);
  1192. if (!decoded) {
  1193. _logError('Failed to decode base64 JWT payload');
  1194. return null;
  1195. }
  1196. return JSON.parse(decoded);
  1197. }
  1198. catch (e) {
  1199. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1200. return null;
  1201. }
  1202. }
  1203. /**
  1204. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1205. */
  1206. function _tokenExpiresIn(token) {
  1207. var parsedToken = _parseToken(token);
  1208. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1209. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1210. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1211. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1212. }
  1213. /**
  1214. * @license
  1215. * Copyright 2020 Google LLC
  1216. *
  1217. * Licensed under the Apache License, Version 2.0 (the "License");
  1218. * you may not use this file except in compliance with the License.
  1219. * You may obtain a copy of the License at
  1220. *
  1221. * http://www.apache.org/licenses/LICENSE-2.0
  1222. *
  1223. * Unless required by applicable law or agreed to in writing, software
  1224. * distributed under the License is distributed on an "AS IS" BASIS,
  1225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1226. * See the License for the specific language governing permissions and
  1227. * limitations under the License.
  1228. */
  1229. function _logoutIfInvalidated(user, promise, bypassAuthState) {
  1230. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1231. return __awaiter(this, void 0, void 0, function () {
  1232. var e_1;
  1233. return __generator(this, function (_a) {
  1234. switch (_a.label) {
  1235. case 0:
  1236. if (bypassAuthState) {
  1237. return [2 /*return*/, promise];
  1238. }
  1239. _a.label = 1;
  1240. case 1:
  1241. _a.trys.push([1, 3, , 6]);
  1242. return [4 /*yield*/, promise];
  1243. case 2: return [2 /*return*/, _a.sent()];
  1244. case 3:
  1245. e_1 = _a.sent();
  1246. if (!(e_1 instanceof FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
  1247. if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
  1248. return [4 /*yield*/, user.auth.signOut()];
  1249. case 4:
  1250. _a.sent();
  1251. _a.label = 5;
  1252. case 5: throw e_1;
  1253. case 6: return [2 /*return*/];
  1254. }
  1255. });
  1256. });
  1257. }
  1258. function isUserInvalidated(_a) {
  1259. var code = _a.code;
  1260. return (code === "auth/".concat("user-disabled" /* AuthErrorCode.USER_DISABLED */) ||
  1261. code === "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */));
  1262. }
  1263. /**
  1264. * @license
  1265. * Copyright 2020 Google LLC
  1266. *
  1267. * Licensed under the Apache License, Version 2.0 (the "License");
  1268. * you may not use this file except in compliance with the License.
  1269. * You may obtain a copy of the License at
  1270. *
  1271. * http://www.apache.org/licenses/LICENSE-2.0
  1272. *
  1273. * Unless required by applicable law or agreed to in writing, software
  1274. * distributed under the License is distributed on an "AS IS" BASIS,
  1275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1276. * See the License for the specific language governing permissions and
  1277. * limitations under the License.
  1278. */
  1279. var ProactiveRefresh = /** @class */ (function () {
  1280. function ProactiveRefresh(user) {
  1281. this.user = user;
  1282. this.isRunning = false;
  1283. // Node timers and browser timers return fundamentally different types.
  1284. // We don't actually care what the value is but TS won't accept unknown and
  1285. // we can't cast properly in both environments.
  1286. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1287. this.timerId = null;
  1288. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1289. }
  1290. ProactiveRefresh.prototype._start = function () {
  1291. if (this.isRunning) {
  1292. return;
  1293. }
  1294. this.isRunning = true;
  1295. this.schedule();
  1296. };
  1297. ProactiveRefresh.prototype._stop = function () {
  1298. if (!this.isRunning) {
  1299. return;
  1300. }
  1301. this.isRunning = false;
  1302. if (this.timerId !== null) {
  1303. clearTimeout(this.timerId);
  1304. }
  1305. };
  1306. ProactiveRefresh.prototype.getInterval = function (wasError) {
  1307. var _a;
  1308. if (wasError) {
  1309. var interval = this.errorBackoff;
  1310. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1311. return interval;
  1312. }
  1313. else {
  1314. // Reset the error backoff
  1315. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1316. var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1317. var interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1318. return Math.max(0, interval);
  1319. }
  1320. };
  1321. ProactiveRefresh.prototype.schedule = function (wasError) {
  1322. var _this = this;
  1323. if (wasError === void 0) { wasError = false; }
  1324. if (!this.isRunning) {
  1325. // Just in case...
  1326. return;
  1327. }
  1328. var interval = this.getInterval(wasError);
  1329. this.timerId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
  1330. return __generator(this, function (_a) {
  1331. switch (_a.label) {
  1332. case 0: return [4 /*yield*/, this.iteration()];
  1333. case 1:
  1334. _a.sent();
  1335. return [2 /*return*/];
  1336. }
  1337. });
  1338. }); }, interval);
  1339. };
  1340. ProactiveRefresh.prototype.iteration = function () {
  1341. return __awaiter(this, void 0, void 0, function () {
  1342. var e_1;
  1343. return __generator(this, function (_a) {
  1344. switch (_a.label) {
  1345. case 0:
  1346. _a.trys.push([0, 2, , 3]);
  1347. return [4 /*yield*/, this.user.getIdToken(true)];
  1348. case 1:
  1349. _a.sent();
  1350. return [3 /*break*/, 3];
  1351. case 2:
  1352. e_1 = _a.sent();
  1353. // Only retry on network errors
  1354. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) ===
  1355. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  1356. this.schedule(/* wasError */ true);
  1357. }
  1358. return [2 /*return*/];
  1359. case 3:
  1360. this.schedule();
  1361. return [2 /*return*/];
  1362. }
  1363. });
  1364. });
  1365. };
  1366. return ProactiveRefresh;
  1367. }());
  1368. /**
  1369. * @license
  1370. * Copyright 2020 Google LLC
  1371. *
  1372. * Licensed under the Apache License, Version 2.0 (the "License");
  1373. * you may not use this file except in compliance with the License.
  1374. * You may obtain a copy of the License at
  1375. *
  1376. * http://www.apache.org/licenses/LICENSE-2.0
  1377. *
  1378. * Unless required by applicable law or agreed to in writing, software
  1379. * distributed under the License is distributed on an "AS IS" BASIS,
  1380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1381. * See the License for the specific language governing permissions and
  1382. * limitations under the License.
  1383. */
  1384. var UserMetadata = /** @class */ (function () {
  1385. function UserMetadata(createdAt, lastLoginAt) {
  1386. this.createdAt = createdAt;
  1387. this.lastLoginAt = lastLoginAt;
  1388. this._initializeTime();
  1389. }
  1390. UserMetadata.prototype._initializeTime = function () {
  1391. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1392. this.creationTime = utcTimestampToDateString(this.createdAt);
  1393. };
  1394. UserMetadata.prototype._copy = function (metadata) {
  1395. this.createdAt = metadata.createdAt;
  1396. this.lastLoginAt = metadata.lastLoginAt;
  1397. this._initializeTime();
  1398. };
  1399. UserMetadata.prototype.toJSON = function () {
  1400. return {
  1401. createdAt: this.createdAt,
  1402. lastLoginAt: this.lastLoginAt
  1403. };
  1404. };
  1405. return UserMetadata;
  1406. }());
  1407. /**
  1408. * @license
  1409. * Copyright 2019 Google LLC
  1410. *
  1411. * Licensed under the Apache License, Version 2.0 (the "License");
  1412. * you may not use this file except in compliance with the License.
  1413. * You may obtain a copy of the License at
  1414. *
  1415. * http://www.apache.org/licenses/LICENSE-2.0
  1416. *
  1417. * Unless required by applicable law or agreed to in writing, software
  1418. * distributed under the License is distributed on an "AS IS" BASIS,
  1419. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1420. * See the License for the specific language governing permissions and
  1421. * limitations under the License.
  1422. */
  1423. function _reloadWithoutSaving(user) {
  1424. var _a;
  1425. return __awaiter(this, void 0, void 0, function () {
  1426. var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
  1427. return __generator(this, function (_b) {
  1428. switch (_b.label) {
  1429. case 0:
  1430. auth = user.auth;
  1431. return [4 /*yield*/, user.getIdToken()];
  1432. case 1:
  1433. idToken = _b.sent();
  1434. return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
  1435. case 2:
  1436. response = _b.sent();
  1437. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1438. coreAccount = response.users[0];
  1439. user._notifyReloadListener(coreAccount);
  1440. newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1441. ? extractProviderData(coreAccount.providerUserInfo)
  1442. : [];
  1443. providerData = mergeProviderData(user.providerData, newProviderData);
  1444. oldIsAnonymous = user.isAnonymous;
  1445. newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1446. isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1447. updates = {
  1448. uid: coreAccount.localId,
  1449. displayName: coreAccount.displayName || null,
  1450. photoURL: coreAccount.photoUrl || null,
  1451. email: coreAccount.email || null,
  1452. emailVerified: coreAccount.emailVerified || false,
  1453. phoneNumber: coreAccount.phoneNumber || null,
  1454. tenantId: coreAccount.tenantId || null,
  1455. providerData: providerData,
  1456. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1457. isAnonymous: isAnonymous
  1458. };
  1459. Object.assign(user, updates);
  1460. return [2 /*return*/];
  1461. }
  1462. });
  1463. });
  1464. }
  1465. /**
  1466. * Reloads user account data, if signed in.
  1467. *
  1468. * @param user - The user.
  1469. *
  1470. * @public
  1471. */
  1472. function reload(user) {
  1473. return __awaiter(this, void 0, void 0, function () {
  1474. var userInternal;
  1475. return __generator(this, function (_a) {
  1476. switch (_a.label) {
  1477. case 0:
  1478. userInternal = getModularInstance(user);
  1479. return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
  1480. case 1:
  1481. _a.sent();
  1482. // Even though the current user hasn't changed, update
  1483. // current user will trigger a persistence update w/ the
  1484. // new info.
  1485. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  1486. case 2:
  1487. // Even though the current user hasn't changed, update
  1488. // current user will trigger a persistence update w/ the
  1489. // new info.
  1490. _a.sent();
  1491. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1492. return [2 /*return*/];
  1493. }
  1494. });
  1495. });
  1496. }
  1497. function mergeProviderData(original, newData) {
  1498. var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
  1499. return __spreadArray(__spreadArray([], deduped, true), newData, true);
  1500. }
  1501. function extractProviderData(providers) {
  1502. return providers.map(function (_a) {
  1503. var providerId = _a.providerId, provider = __rest(_a, ["providerId"]);
  1504. return {
  1505. providerId: providerId,
  1506. uid: provider.rawId || '',
  1507. displayName: provider.displayName || null,
  1508. email: provider.email || null,
  1509. phoneNumber: provider.phoneNumber || null,
  1510. photoURL: provider.photoUrl || null
  1511. };
  1512. });
  1513. }
  1514. /**
  1515. * @license
  1516. * Copyright 2020 Google LLC
  1517. *
  1518. * Licensed under the Apache License, Version 2.0 (the "License");
  1519. * you may not use this file except in compliance with the License.
  1520. * You may obtain a copy of the License at
  1521. *
  1522. * http://www.apache.org/licenses/LICENSE-2.0
  1523. *
  1524. * Unless required by applicable law or agreed to in writing, software
  1525. * distributed under the License is distributed on an "AS IS" BASIS,
  1526. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1527. * See the License for the specific language governing permissions and
  1528. * limitations under the License.
  1529. */
  1530. function requestStsToken(auth, refreshToken) {
  1531. return __awaiter(this, void 0, void 0, function () {
  1532. var response;
  1533. var _this = this;
  1534. return __generator(this, function (_a) {
  1535. switch (_a.label) {
  1536. case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return __awaiter(_this, void 0, void 0, function () {
  1537. var body, _a, tokenApiHost, apiKey, url, headers;
  1538. return __generator(this, function (_b) {
  1539. switch (_b.label) {
  1540. case 0:
  1541. body = querystring({
  1542. 'grant_type': 'refresh_token',
  1543. 'refresh_token': refreshToken
  1544. }).slice(1);
  1545. _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
  1546. url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, "key=".concat(apiKey));
  1547. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1548. case 1:
  1549. headers = _b.sent();
  1550. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1551. return [2 /*return*/, FetchProvider.fetch()(url, {
  1552. method: "POST" /* HttpMethod.POST */,
  1553. headers: headers,
  1554. body: body
  1555. })];
  1556. }
  1557. });
  1558. }); })];
  1559. case 1:
  1560. response = _a.sent();
  1561. // The response comes back in snake_case. Convert to camel:
  1562. return [2 /*return*/, {
  1563. accessToken: response.access_token,
  1564. expiresIn: response.expires_in,
  1565. refreshToken: response.refresh_token
  1566. }];
  1567. }
  1568. });
  1569. });
  1570. }
  1571. /**
  1572. * @license
  1573. * Copyright 2020 Google LLC
  1574. *
  1575. * Licensed under the Apache License, Version 2.0 (the "License");
  1576. * you may not use this file except in compliance with the License.
  1577. * You may obtain a copy of the License at
  1578. *
  1579. * http://www.apache.org/licenses/LICENSE-2.0
  1580. *
  1581. * Unless required by applicable law or agreed to in writing, software
  1582. * distributed under the License is distributed on an "AS IS" BASIS,
  1583. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1584. * See the License for the specific language governing permissions and
  1585. * limitations under the License.
  1586. */
  1587. /**
  1588. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1589. * it references AuthInternal which has a circular dependency with UserInternal.
  1590. *
  1591. * @internal
  1592. */
  1593. var StsTokenManager = /** @class */ (function () {
  1594. function StsTokenManager() {
  1595. this.refreshToken = null;
  1596. this.accessToken = null;
  1597. this.expirationTime = null;
  1598. }
  1599. Object.defineProperty(StsTokenManager.prototype, "isExpired", {
  1600. get: function () {
  1601. return (!this.expirationTime ||
  1602. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1603. },
  1604. enumerable: false,
  1605. configurable: true
  1606. });
  1607. StsTokenManager.prototype.updateFromServerResponse = function (response) {
  1608. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1609. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1610. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1611. var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1612. ? Number(response.expiresIn)
  1613. : _tokenExpiresIn(response.idToken);
  1614. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1615. };
  1616. StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
  1617. if (forceRefresh === void 0) { forceRefresh = false; }
  1618. return __awaiter(this, void 0, void 0, function () {
  1619. return __generator(this, function (_a) {
  1620. switch (_a.label) {
  1621. case 0:
  1622. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1623. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1624. return [2 /*return*/, this.accessToken];
  1625. }
  1626. if (!this.refreshToken) return [3 /*break*/, 2];
  1627. return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
  1628. case 1:
  1629. _a.sent();
  1630. return [2 /*return*/, this.accessToken];
  1631. case 2: return [2 /*return*/, null];
  1632. }
  1633. });
  1634. });
  1635. };
  1636. StsTokenManager.prototype.clearRefreshToken = function () {
  1637. this.refreshToken = null;
  1638. };
  1639. StsTokenManager.prototype.refresh = function (auth, oldToken) {
  1640. return __awaiter(this, void 0, void 0, function () {
  1641. var _a, accessToken, refreshToken, expiresIn;
  1642. return __generator(this, function (_b) {
  1643. switch (_b.label) {
  1644. case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
  1645. case 1:
  1646. _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
  1647. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1648. return [2 /*return*/];
  1649. }
  1650. });
  1651. });
  1652. };
  1653. StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
  1654. this.refreshToken = refreshToken || null;
  1655. this.accessToken = accessToken || null;
  1656. this.expirationTime = Date.now() + expiresInSec * 1000;
  1657. };
  1658. StsTokenManager.fromJSON = function (appName, object) {
  1659. var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
  1660. var manager = new StsTokenManager();
  1661. if (refreshToken) {
  1662. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1663. appName: appName
  1664. });
  1665. manager.refreshToken = refreshToken;
  1666. }
  1667. if (accessToken) {
  1668. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1669. appName: appName
  1670. });
  1671. manager.accessToken = accessToken;
  1672. }
  1673. if (expirationTime) {
  1674. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1675. appName: appName
  1676. });
  1677. manager.expirationTime = expirationTime;
  1678. }
  1679. return manager;
  1680. };
  1681. StsTokenManager.prototype.toJSON = function () {
  1682. return {
  1683. refreshToken: this.refreshToken,
  1684. accessToken: this.accessToken,
  1685. expirationTime: this.expirationTime
  1686. };
  1687. };
  1688. StsTokenManager.prototype._assign = function (stsTokenManager) {
  1689. this.accessToken = stsTokenManager.accessToken;
  1690. this.refreshToken = stsTokenManager.refreshToken;
  1691. this.expirationTime = stsTokenManager.expirationTime;
  1692. };
  1693. StsTokenManager.prototype._clone = function () {
  1694. return Object.assign(new StsTokenManager(), this.toJSON());
  1695. };
  1696. StsTokenManager.prototype._performRefresh = function () {
  1697. return debugFail('not implemented');
  1698. };
  1699. return StsTokenManager;
  1700. }());
  1701. /**
  1702. * @license
  1703. * Copyright 2020 Google LLC
  1704. *
  1705. * Licensed under the Apache License, Version 2.0 (the "License");
  1706. * you may not use this file except in compliance with the License.
  1707. * You may obtain a copy of the License at
  1708. *
  1709. * http://www.apache.org/licenses/LICENSE-2.0
  1710. *
  1711. * Unless required by applicable law or agreed to in writing, software
  1712. * distributed under the License is distributed on an "AS IS" BASIS,
  1713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1714. * See the License for the specific language governing permissions and
  1715. * limitations under the License.
  1716. */
  1717. function assertStringOrUndefined(assertion, appName) {
  1718. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName: appName });
  1719. }
  1720. var UserImpl = /** @class */ (function () {
  1721. function UserImpl(_a) {
  1722. var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1723. // For the user object, provider is always Firebase.
  1724. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1725. this.proactiveRefresh = new ProactiveRefresh(this);
  1726. this.reloadUserInfo = null;
  1727. this.reloadListener = null;
  1728. this.uid = uid;
  1729. this.auth = auth;
  1730. this.stsTokenManager = stsTokenManager;
  1731. this.accessToken = stsTokenManager.accessToken;
  1732. this.displayName = opt.displayName || null;
  1733. this.email = opt.email || null;
  1734. this.emailVerified = opt.emailVerified || false;
  1735. this.phoneNumber = opt.phoneNumber || null;
  1736. this.photoURL = opt.photoURL || null;
  1737. this.isAnonymous = opt.isAnonymous || false;
  1738. this.tenantId = opt.tenantId || null;
  1739. this.providerData = opt.providerData ? __spreadArray([], opt.providerData, true) : [];
  1740. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1741. }
  1742. UserImpl.prototype.getIdToken = function (forceRefresh) {
  1743. return __awaiter(this, void 0, void 0, function () {
  1744. var accessToken;
  1745. return __generator(this, function (_a) {
  1746. switch (_a.label) {
  1747. case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
  1748. case 1:
  1749. accessToken = _a.sent();
  1750. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1751. if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
  1752. this.accessToken = accessToken;
  1753. return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1754. case 2:
  1755. _a.sent();
  1756. this.auth._notifyListenersIfCurrent(this);
  1757. _a.label = 3;
  1758. case 3: return [2 /*return*/, accessToken];
  1759. }
  1760. });
  1761. });
  1762. };
  1763. UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
  1764. return getIdTokenResult(this, forceRefresh);
  1765. };
  1766. UserImpl.prototype.reload = function () {
  1767. return reload(this);
  1768. };
  1769. UserImpl.prototype._assign = function (user) {
  1770. if (this === user) {
  1771. return;
  1772. }
  1773. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1774. this.displayName = user.displayName;
  1775. this.photoURL = user.photoURL;
  1776. this.email = user.email;
  1777. this.emailVerified = user.emailVerified;
  1778. this.phoneNumber = user.phoneNumber;
  1779. this.isAnonymous = user.isAnonymous;
  1780. this.tenantId = user.tenantId;
  1781. this.providerData = user.providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  1782. this.metadata._copy(user.metadata);
  1783. this.stsTokenManager._assign(user.stsTokenManager);
  1784. };
  1785. UserImpl.prototype._clone = function (auth) {
  1786. var newUser = new UserImpl(__assign(__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
  1787. newUser.metadata._copy(this.metadata);
  1788. return newUser;
  1789. };
  1790. UserImpl.prototype._onReload = function (callback) {
  1791. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1792. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1793. this.reloadListener = callback;
  1794. if (this.reloadUserInfo) {
  1795. this._notifyReloadListener(this.reloadUserInfo);
  1796. this.reloadUserInfo = null;
  1797. }
  1798. };
  1799. UserImpl.prototype._notifyReloadListener = function (userInfo) {
  1800. if (this.reloadListener) {
  1801. this.reloadListener(userInfo);
  1802. }
  1803. else {
  1804. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1805. this.reloadUserInfo = userInfo;
  1806. }
  1807. };
  1808. UserImpl.prototype._startProactiveRefresh = function () {
  1809. this.proactiveRefresh._start();
  1810. };
  1811. UserImpl.prototype._stopProactiveRefresh = function () {
  1812. this.proactiveRefresh._stop();
  1813. };
  1814. UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
  1815. if (reload === void 0) { reload = false; }
  1816. return __awaiter(this, void 0, void 0, function () {
  1817. var tokensRefreshed;
  1818. return __generator(this, function (_a) {
  1819. switch (_a.label) {
  1820. case 0:
  1821. tokensRefreshed = false;
  1822. if (response.idToken &&
  1823. response.idToken !== this.stsTokenManager.accessToken) {
  1824. this.stsTokenManager.updateFromServerResponse(response);
  1825. tokensRefreshed = true;
  1826. }
  1827. if (!reload) return [3 /*break*/, 2];
  1828. return [4 /*yield*/, _reloadWithoutSaving(this)];
  1829. case 1:
  1830. _a.sent();
  1831. _a.label = 2;
  1832. case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1833. case 3:
  1834. _a.sent();
  1835. if (tokensRefreshed) {
  1836. this.auth._notifyListenersIfCurrent(this);
  1837. }
  1838. return [2 /*return*/];
  1839. }
  1840. });
  1841. });
  1842. };
  1843. UserImpl.prototype.delete = function () {
  1844. return __awaiter(this, void 0, void 0, function () {
  1845. var idToken;
  1846. return __generator(this, function (_a) {
  1847. switch (_a.label) {
  1848. case 0: return [4 /*yield*/, this.getIdToken()];
  1849. case 1:
  1850. idToken = _a.sent();
  1851. return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
  1852. case 2:
  1853. _a.sent();
  1854. this.stsTokenManager.clearRefreshToken();
  1855. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1856. // cancels pending actions...
  1857. return [2 /*return*/, this.auth.signOut()];
  1858. }
  1859. });
  1860. });
  1861. };
  1862. UserImpl.prototype.toJSON = function () {
  1863. return __assign(__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 (__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
  1864. // Redirect event ID must be maintained in case there is a pending
  1865. // redirect event.
  1866. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1867. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1868. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1869. };
  1870. Object.defineProperty(UserImpl.prototype, "refreshToken", {
  1871. get: function () {
  1872. return this.stsTokenManager.refreshToken || '';
  1873. },
  1874. enumerable: false,
  1875. configurable: true
  1876. });
  1877. UserImpl._fromJSON = function (auth, object) {
  1878. var _a, _b, _c, _d, _e, _f, _g, _h;
  1879. var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1880. var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1881. var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1882. var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1883. var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1884. var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1885. var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1886. var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1887. var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
  1888. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1889. var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1890. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1891. assertStringOrUndefined(displayName, auth.name);
  1892. assertStringOrUndefined(email, auth.name);
  1893. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1894. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1895. assertStringOrUndefined(phoneNumber, auth.name);
  1896. assertStringOrUndefined(photoURL, auth.name);
  1897. assertStringOrUndefined(tenantId, auth.name);
  1898. assertStringOrUndefined(_redirectEventId, auth.name);
  1899. assertStringOrUndefined(createdAt, auth.name);
  1900. assertStringOrUndefined(lastLoginAt, auth.name);
  1901. var user = new UserImpl({
  1902. uid: uid,
  1903. auth: auth,
  1904. email: email,
  1905. emailVerified: emailVerified,
  1906. displayName: displayName,
  1907. isAnonymous: isAnonymous,
  1908. photoURL: photoURL,
  1909. phoneNumber: phoneNumber,
  1910. tenantId: tenantId,
  1911. stsTokenManager: stsTokenManager,
  1912. createdAt: createdAt,
  1913. lastLoginAt: lastLoginAt
  1914. });
  1915. if (providerData && Array.isArray(providerData)) {
  1916. user.providerData = providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  1917. }
  1918. if (_redirectEventId) {
  1919. user._redirectEventId = _redirectEventId;
  1920. }
  1921. return user;
  1922. };
  1923. /**
  1924. * Initialize a User from an idToken server response
  1925. * @param auth
  1926. * @param idTokenResponse
  1927. */
  1928. UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
  1929. if (isAnonymous === void 0) { isAnonymous = false; }
  1930. return __awaiter(this, void 0, void 0, function () {
  1931. var stsTokenManager, user;
  1932. return __generator(this, function (_a) {
  1933. switch (_a.label) {
  1934. case 0:
  1935. stsTokenManager = new StsTokenManager();
  1936. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1937. user = new UserImpl({
  1938. uid: idTokenResponse.localId,
  1939. auth: auth,
  1940. stsTokenManager: stsTokenManager,
  1941. isAnonymous: isAnonymous
  1942. });
  1943. // Updates the user info and data and resolves with a user instance.
  1944. return [4 /*yield*/, _reloadWithoutSaving(user)];
  1945. case 1:
  1946. // Updates the user info and data and resolves with a user instance.
  1947. _a.sent();
  1948. return [2 /*return*/, user];
  1949. }
  1950. });
  1951. });
  1952. };
  1953. return UserImpl;
  1954. }());
  1955. /**
  1956. * @license
  1957. * Copyright 2020 Google LLC
  1958. *
  1959. * Licensed under the Apache License, Version 2.0 (the "License");
  1960. * you may not use this file except in compliance with the License.
  1961. * You may obtain a copy of the License at
  1962. *
  1963. * http://www.apache.org/licenses/LICENSE-2.0
  1964. *
  1965. * Unless required by applicable law or agreed to in writing, software
  1966. * distributed under the License is distributed on an "AS IS" BASIS,
  1967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1968. * See the License for the specific language governing permissions and
  1969. * limitations under the License.
  1970. */
  1971. var instanceCache = new Map();
  1972. function _getInstance(cls) {
  1973. debugAssert(cls instanceof Function, 'Expected a class definition');
  1974. var instance = instanceCache.get(cls);
  1975. if (instance) {
  1976. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  1977. return instance;
  1978. }
  1979. instance = new cls();
  1980. instanceCache.set(cls, instance);
  1981. return instance;
  1982. }
  1983. /**
  1984. * @license
  1985. * Copyright 2019 Google LLC
  1986. *
  1987. * Licensed under the Apache License, Version 2.0 (the "License");
  1988. * you may not use this file except in compliance with the License.
  1989. * You may obtain a copy of the License at
  1990. *
  1991. * http://www.apache.org/licenses/LICENSE-2.0
  1992. *
  1993. * Unless required by applicable law or agreed to in writing, software
  1994. * distributed under the License is distributed on an "AS IS" BASIS,
  1995. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1996. * See the License for the specific language governing permissions and
  1997. * limitations under the License.
  1998. */
  1999. var InMemoryPersistence = /** @class */ (function () {
  2000. function InMemoryPersistence() {
  2001. this.type = "NONE" /* PersistenceType.NONE */;
  2002. this.storage = {};
  2003. }
  2004. InMemoryPersistence.prototype._isAvailable = function () {
  2005. return __awaiter(this, void 0, void 0, function () {
  2006. return __generator(this, function (_a) {
  2007. return [2 /*return*/, true];
  2008. });
  2009. });
  2010. };
  2011. InMemoryPersistence.prototype._set = function (key, value) {
  2012. return __awaiter(this, void 0, void 0, function () {
  2013. return __generator(this, function (_a) {
  2014. this.storage[key] = value;
  2015. return [2 /*return*/];
  2016. });
  2017. });
  2018. };
  2019. InMemoryPersistence.prototype._get = function (key) {
  2020. return __awaiter(this, void 0, void 0, function () {
  2021. var value;
  2022. return __generator(this, function (_a) {
  2023. value = this.storage[key];
  2024. return [2 /*return*/, value === undefined ? null : value];
  2025. });
  2026. });
  2027. };
  2028. InMemoryPersistence.prototype._remove = function (key) {
  2029. return __awaiter(this, void 0, void 0, function () {
  2030. return __generator(this, function (_a) {
  2031. delete this.storage[key];
  2032. return [2 /*return*/];
  2033. });
  2034. });
  2035. };
  2036. InMemoryPersistence.prototype._addListener = function (_key, _listener) {
  2037. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2038. return;
  2039. };
  2040. InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
  2041. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2042. return;
  2043. };
  2044. InMemoryPersistence.type = 'NONE';
  2045. return InMemoryPersistence;
  2046. }());
  2047. /**
  2048. * An implementation of {@link Persistence} of type 'NONE'.
  2049. *
  2050. * @public
  2051. */
  2052. var inMemoryPersistence = InMemoryPersistence;
  2053. /**
  2054. * @license
  2055. * Copyright 2019 Google LLC
  2056. *
  2057. * Licensed under the Apache License, Version 2.0 (the "License");
  2058. * you may not use this file except in compliance with the License.
  2059. * You may obtain a copy of the License at
  2060. *
  2061. * http://www.apache.org/licenses/LICENSE-2.0
  2062. *
  2063. * Unless required by applicable law or agreed to in writing, software
  2064. * distributed under the License is distributed on an "AS IS" BASIS,
  2065. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2066. * See the License for the specific language governing permissions and
  2067. * limitations under the License.
  2068. */
  2069. function _persistenceKeyName(key, apiKey, appName) {
  2070. return "".concat("firebase" /* Namespace.PERSISTENCE */, ":").concat(key, ":").concat(apiKey, ":").concat(appName);
  2071. }
  2072. var PersistenceUserManager = /** @class */ (function () {
  2073. function PersistenceUserManager(persistence, auth, userKey) {
  2074. this.persistence = persistence;
  2075. this.auth = auth;
  2076. this.userKey = userKey;
  2077. var _a = this.auth, config = _a.config, name = _a.name;
  2078. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  2079. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  2080. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  2081. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  2082. }
  2083. PersistenceUserManager.prototype.setCurrentUser = function (user) {
  2084. return this.persistence._set(this.fullUserKey, user.toJSON());
  2085. };
  2086. PersistenceUserManager.prototype.getCurrentUser = function () {
  2087. return __awaiter(this, void 0, void 0, function () {
  2088. var blob;
  2089. return __generator(this, function (_a) {
  2090. switch (_a.label) {
  2091. case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
  2092. case 1:
  2093. blob = _a.sent();
  2094. return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
  2095. }
  2096. });
  2097. });
  2098. };
  2099. PersistenceUserManager.prototype.removeCurrentUser = function () {
  2100. return this.persistence._remove(this.fullUserKey);
  2101. };
  2102. PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
  2103. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  2104. };
  2105. PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
  2106. return __awaiter(this, void 0, void 0, function () {
  2107. var currentUser;
  2108. return __generator(this, function (_a) {
  2109. switch (_a.label) {
  2110. case 0:
  2111. if (this.persistence === newPersistence) {
  2112. return [2 /*return*/];
  2113. }
  2114. return [4 /*yield*/, this.getCurrentUser()];
  2115. case 1:
  2116. currentUser = _a.sent();
  2117. return [4 /*yield*/, this.removeCurrentUser()];
  2118. case 2:
  2119. _a.sent();
  2120. this.persistence = newPersistence;
  2121. if (currentUser) {
  2122. return [2 /*return*/, this.setCurrentUser(currentUser)];
  2123. }
  2124. return [2 /*return*/];
  2125. }
  2126. });
  2127. });
  2128. };
  2129. PersistenceUserManager.prototype.delete = function () {
  2130. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  2131. };
  2132. PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
  2133. if (userKey === void 0) { userKey = "authUser" /* KeyName.AUTH_USER */; }
  2134. return __awaiter(this, void 0, void 0, function () {
  2135. var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
  2136. var _this = this;
  2137. return __generator(this, function (_b) {
  2138. switch (_b.label) {
  2139. case 0:
  2140. if (!persistenceHierarchy.length) {
  2141. return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
  2142. }
  2143. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2144. return __generator(this, function (_a) {
  2145. switch (_a.label) {
  2146. case 0: return [4 /*yield*/, persistence._isAvailable()];
  2147. case 1:
  2148. if (_a.sent()) {
  2149. return [2 /*return*/, persistence];
  2150. }
  2151. return [2 /*return*/, undefined];
  2152. }
  2153. });
  2154. }); }))];
  2155. case 1:
  2156. availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
  2157. selectedPersistence = availablePersistences[0] ||
  2158. _getInstance(inMemoryPersistence);
  2159. key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  2160. userToMigrate = null;
  2161. _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
  2162. _b.label = 2;
  2163. case 2:
  2164. if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
  2165. persistence = persistenceHierarchy_1[_i];
  2166. _b.label = 3;
  2167. case 3:
  2168. _b.trys.push([3, 5, , 6]);
  2169. return [4 /*yield*/, persistence._get(key)];
  2170. case 4:
  2171. blob = _b.sent();
  2172. if (blob) {
  2173. user = UserImpl._fromJSON(auth, blob);
  2174. if (persistence !== selectedPersistence) {
  2175. userToMigrate = user;
  2176. }
  2177. selectedPersistence = persistence;
  2178. return [3 /*break*/, 7];
  2179. }
  2180. return [3 /*break*/, 6];
  2181. case 5:
  2182. _b.sent();
  2183. return [3 /*break*/, 6];
  2184. case 6:
  2185. _i++;
  2186. return [3 /*break*/, 2];
  2187. case 7:
  2188. migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
  2189. // If the persistence does _not_ allow migration, just finish off here
  2190. if (!selectedPersistence._shouldAllowMigration ||
  2191. !migrationHierarchy.length) {
  2192. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2193. }
  2194. selectedPersistence = migrationHierarchy[0];
  2195. if (!userToMigrate) return [3 /*break*/, 9];
  2196. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2197. // we'll just let it bubble to surface the error.
  2198. return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
  2199. case 8:
  2200. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2201. // we'll just let it bubble to surface the error.
  2202. _b.sent();
  2203. _b.label = 9;
  2204. case 9:
  2205. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2206. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2207. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2208. return __generator(this, function (_b) {
  2209. switch (_b.label) {
  2210. case 0:
  2211. if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
  2212. _b.label = 1;
  2213. case 1:
  2214. _b.trys.push([1, 3, , 4]);
  2215. return [4 /*yield*/, persistence._remove(key)];
  2216. case 2:
  2217. _b.sent();
  2218. return [3 /*break*/, 4];
  2219. case 3:
  2220. _b.sent();
  2221. return [3 /*break*/, 4];
  2222. case 4: return [2 /*return*/];
  2223. }
  2224. });
  2225. }); }))];
  2226. case 10:
  2227. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2228. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2229. _b.sent();
  2230. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2231. }
  2232. });
  2233. });
  2234. };
  2235. return PersistenceUserManager;
  2236. }());
  2237. /**
  2238. * @license
  2239. * Copyright 2020 Google LLC
  2240. *
  2241. * Licensed under the Apache License, Version 2.0 (the "License");
  2242. * you may not use this file except in compliance with the License.
  2243. * You may obtain a copy of the License at
  2244. *
  2245. * http://www.apache.org/licenses/LICENSE-2.0
  2246. *
  2247. * Unless required by applicable law or agreed to in writing, software
  2248. * distributed under the License is distributed on an "AS IS" BASIS,
  2249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2250. * See the License for the specific language governing permissions and
  2251. * limitations under the License.
  2252. */
  2253. /**
  2254. * Determine the browser for the purposes of reporting usage to the API
  2255. */
  2256. function _getBrowserName(userAgent) {
  2257. var ua = userAgent.toLowerCase();
  2258. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  2259. return "Opera" /* BrowserName.OPERA */;
  2260. }
  2261. else if (_isIEMobile(ua)) {
  2262. // Windows phone IEMobile browser.
  2263. return "IEMobile" /* BrowserName.IEMOBILE */;
  2264. }
  2265. else if (ua.includes('msie') || ua.includes('trident/')) {
  2266. return "IE" /* BrowserName.IE */;
  2267. }
  2268. else if (ua.includes('edge/')) {
  2269. return "Edge" /* BrowserName.EDGE */;
  2270. }
  2271. else if (_isFirefox(ua)) {
  2272. return "Firefox" /* BrowserName.FIREFOX */;
  2273. }
  2274. else if (ua.includes('silk/')) {
  2275. return "Silk" /* BrowserName.SILK */;
  2276. }
  2277. else if (_isBlackBerry(ua)) {
  2278. // Blackberry browser.
  2279. return "Blackberry" /* BrowserName.BLACKBERRY */;
  2280. }
  2281. else if (_isWebOS(ua)) {
  2282. // WebOS default browser.
  2283. return "Webos" /* BrowserName.WEBOS */;
  2284. }
  2285. else if (_isSafari(ua)) {
  2286. return "Safari" /* BrowserName.SAFARI */;
  2287. }
  2288. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  2289. !ua.includes('edge/')) {
  2290. return "Chrome" /* BrowserName.CHROME */;
  2291. }
  2292. else if (_isAndroid(ua)) {
  2293. // Android stock browser.
  2294. return "Android" /* BrowserName.ANDROID */;
  2295. }
  2296. else {
  2297. // Most modern browsers have name/version at end of user agent string.
  2298. var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  2299. var matches = userAgent.match(re);
  2300. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  2301. return matches[1];
  2302. }
  2303. }
  2304. return "Other" /* BrowserName.OTHER */;
  2305. }
  2306. function _isFirefox(ua) {
  2307. if (ua === void 0) { ua = getUA(); }
  2308. return /firefox\//i.test(ua);
  2309. }
  2310. function _isSafari(userAgent) {
  2311. if (userAgent === void 0) { userAgent = getUA(); }
  2312. var ua = userAgent.toLowerCase();
  2313. return (ua.includes('safari/') &&
  2314. !ua.includes('chrome/') &&
  2315. !ua.includes('crios/') &&
  2316. !ua.includes('android'));
  2317. }
  2318. function _isChromeIOS(ua) {
  2319. if (ua === void 0) { ua = getUA(); }
  2320. return /crios\//i.test(ua);
  2321. }
  2322. function _isIEMobile(ua) {
  2323. if (ua === void 0) { ua = getUA(); }
  2324. return /iemobile/i.test(ua);
  2325. }
  2326. function _isAndroid(ua) {
  2327. if (ua === void 0) { ua = getUA(); }
  2328. return /android/i.test(ua);
  2329. }
  2330. function _isBlackBerry(ua) {
  2331. if (ua === void 0) { ua = getUA(); }
  2332. return /blackberry/i.test(ua);
  2333. }
  2334. function _isWebOS(ua) {
  2335. if (ua === void 0) { ua = getUA(); }
  2336. return /webos/i.test(ua);
  2337. }
  2338. function _isIOS(ua) {
  2339. if (ua === void 0) { ua = getUA(); }
  2340. return (/iphone|ipad|ipod/i.test(ua) ||
  2341. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2342. }
  2343. function _isIOS7Or8(ua) {
  2344. if (ua === void 0) { ua = getUA(); }
  2345. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2346. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2347. }
  2348. function _isIOSStandalone(ua) {
  2349. var _a;
  2350. if (ua === void 0) { ua = getUA(); }
  2351. return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
  2352. }
  2353. function _isIE10() {
  2354. return isIE() && document.documentMode === 10;
  2355. }
  2356. function _isMobileBrowser(ua) {
  2357. if (ua === void 0) { ua = getUA(); }
  2358. // TODO: implement getBrowserName equivalent for OS.
  2359. return (_isIOS(ua) ||
  2360. _isAndroid(ua) ||
  2361. _isWebOS(ua) ||
  2362. _isBlackBerry(ua) ||
  2363. /windows phone/i.test(ua) ||
  2364. _isIEMobile(ua));
  2365. }
  2366. function _isIframe() {
  2367. try {
  2368. // Check that the current window is not the top window.
  2369. // If so, return true.
  2370. return !!(window && window !== window.top);
  2371. }
  2372. catch (e) {
  2373. return false;
  2374. }
  2375. }
  2376. /**
  2377. * @license
  2378. * Copyright 2020 Google LLC
  2379. *
  2380. * Licensed under the Apache License, Version 2.0 (the "License");
  2381. * you may not use this file except in compliance with the License.
  2382. * You may obtain a copy of the License at
  2383. *
  2384. * http://www.apache.org/licenses/LICENSE-2.0
  2385. *
  2386. * Unless required by applicable law or agreed to in writing, software
  2387. * distributed under the License is distributed on an "AS IS" BASIS,
  2388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2389. * See the License for the specific language governing permissions and
  2390. * limitations under the License.
  2391. */
  2392. /*
  2393. * Determine the SDK version string
  2394. */
  2395. function _getClientVersion(clientPlatform, frameworks) {
  2396. if (frameworks === void 0) { frameworks = []; }
  2397. var reportedPlatform;
  2398. switch (clientPlatform) {
  2399. case "Browser" /* ClientPlatform.BROWSER */:
  2400. // In a browser environment, report the browser name.
  2401. reportedPlatform = _getBrowserName(getUA());
  2402. break;
  2403. case "Worker" /* ClientPlatform.WORKER */:
  2404. // Technically a worker runs from a browser but we need to differentiate a
  2405. // worker from a browser.
  2406. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2407. reportedPlatform = "".concat(_getBrowserName(getUA()), "-").concat(clientPlatform);
  2408. break;
  2409. default:
  2410. reportedPlatform = clientPlatform;
  2411. }
  2412. var reportedFrameworks = frameworks.length
  2413. ? frameworks.join(',')
  2414. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2415. return "".concat(reportedPlatform, "/").concat("JsCore" /* ClientImplementation.CORE */, "/").concat(SDK_VERSION, "/").concat(reportedFrameworks);
  2416. }
  2417. /**
  2418. * @license
  2419. * Copyright 2020 Google LLC
  2420. *
  2421. * Licensed under the Apache License, Version 2.0 (the "License");
  2422. * you may not use this file except in compliance with the License.
  2423. * You may obtain a copy of the License at
  2424. *
  2425. * http://www.apache.org/licenses/LICENSE-2.0
  2426. *
  2427. * Unless required by applicable law or agreed to in writing, software
  2428. * distributed under the License is distributed on an "AS IS" BASIS,
  2429. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2430. * See the License for the specific language governing permissions and
  2431. * limitations under the License.
  2432. */
  2433. function getRecaptchaParams(auth) {
  2434. return __awaiter(this, void 0, void 0, function () {
  2435. return __generator(this, function (_a) {
  2436. switch (_a.label) {
  2437. case 0: return [4 /*yield*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/recaptchaParams" /* Endpoint.GET_RECAPTCHA_PARAM */)];
  2438. case 1: return [2 /*return*/, ((_a.sent()).recaptchaSiteKey || '')];
  2439. }
  2440. });
  2441. });
  2442. }
  2443. function getRecaptchaConfig(auth, request) {
  2444. return __awaiter(this, void 0, void 0, function () {
  2445. return __generator(this, function (_a) {
  2446. return [2 /*return*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v2/recaptchaConfig" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request))];
  2447. });
  2448. });
  2449. }
  2450. /**
  2451. * @license
  2452. * Copyright 2020 Google LLC
  2453. *
  2454. * Licensed under the Apache License, Version 2.0 (the "License");
  2455. * you may not use this file except in compliance with the License.
  2456. * You may obtain a copy of the License at
  2457. *
  2458. * http://www.apache.org/licenses/LICENSE-2.0
  2459. *
  2460. * Unless required by applicable law or agreed to in writing, software
  2461. * distributed under the License is distributed on an "AS IS" BASIS,
  2462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2463. * See the License for the specific language governing permissions and
  2464. * limitations under the License.
  2465. */
  2466. function isV2(grecaptcha) {
  2467. return (grecaptcha !== undefined &&
  2468. grecaptcha.getResponse !== undefined);
  2469. }
  2470. function isEnterprise(grecaptcha) {
  2471. return (grecaptcha !== undefined &&
  2472. grecaptcha.enterprise !== undefined);
  2473. }
  2474. var RecaptchaConfig = /** @class */ (function () {
  2475. function RecaptchaConfig(response) {
  2476. /**
  2477. * The reCAPTCHA site key.
  2478. */
  2479. this.siteKey = '';
  2480. /**
  2481. * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.
  2482. */
  2483. this.emailPasswordEnabled = false;
  2484. if (response.recaptchaKey === undefined) {
  2485. throw new Error('recaptchaKey undefined');
  2486. }
  2487. // Example response.recaptchaKey: "projects/proj123/keys/sitekey123"
  2488. this.siteKey = response.recaptchaKey.split('/')[3];
  2489. this.emailPasswordEnabled = response.recaptchaEnforcementState.some(function (enforcementState) {
  2490. return enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&
  2491. enforcementState.enforcementState !== 'OFF';
  2492. });
  2493. }
  2494. return RecaptchaConfig;
  2495. }());
  2496. /**
  2497. * @license
  2498. * Copyright 2020 Google LLC
  2499. *
  2500. * Licensed under the Apache License, Version 2.0 (the "License");
  2501. * you may not use this file except in compliance with the License.
  2502. * You may obtain a copy of the License at
  2503. *
  2504. * http://www.apache.org/licenses/LICENSE-2.0
  2505. *
  2506. * Unless required by applicable law or agreed to in writing, software
  2507. * distributed under the License is distributed on an "AS IS" BASIS,
  2508. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2509. * See the License for the specific language governing permissions and
  2510. * limitations under the License.
  2511. */
  2512. function getScriptParentElement() {
  2513. var _a, _b;
  2514. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  2515. }
  2516. function _loadJS(url) {
  2517. // TODO: consider adding timeout support & cancellation
  2518. return new Promise(function (resolve, reject) {
  2519. var el = document.createElement('script');
  2520. el.setAttribute('src', url);
  2521. el.onload = resolve;
  2522. el.onerror = function (e) {
  2523. var error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2524. error.customData = e;
  2525. reject(error);
  2526. };
  2527. el.type = 'text/javascript';
  2528. el.charset = 'UTF-8';
  2529. getScriptParentElement().appendChild(el);
  2530. });
  2531. }
  2532. function _generateCallbackName(prefix) {
  2533. return "__".concat(prefix).concat(Math.floor(Math.random() * 1000000));
  2534. }
  2535. /* eslint-disable @typescript-eslint/no-require-imports */
  2536. var RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';
  2537. var RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';
  2538. var FAKE_TOKEN = 'NO_RECAPTCHA';
  2539. var RecaptchaEnterpriseVerifier = /** @class */ (function () {
  2540. /**
  2541. *
  2542. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  2543. *
  2544. */
  2545. function RecaptchaEnterpriseVerifier(authExtern) {
  2546. /**
  2547. * Identifies the type of application verifier (e.g. "recaptcha-enterprise").
  2548. */
  2549. this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
  2550. this.auth = _castAuth(authExtern);
  2551. }
  2552. /**
  2553. * Executes the verification process.
  2554. *
  2555. * @returns A Promise for a token that can be used to assert the validity of a request.
  2556. */
  2557. RecaptchaEnterpriseVerifier.prototype.verify = function (action, forceRefresh) {
  2558. if (action === void 0) { action = 'verify'; }
  2559. if (forceRefresh === void 0) { forceRefresh = false; }
  2560. return __awaiter(this, void 0, void 0, function () {
  2561. function retrieveSiteKey(auth) {
  2562. return __awaiter(this, void 0, void 0, function () {
  2563. var _this = this;
  2564. return __generator(this, function (_a) {
  2565. if (!forceRefresh) {
  2566. if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {
  2567. return [2 /*return*/, auth._agentRecaptchaConfig.siteKey];
  2568. }
  2569. if (auth.tenantId != null &&
  2570. auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {
  2571. return [2 /*return*/, auth._tenantRecaptchaConfigs[auth.tenantId].siteKey];
  2572. }
  2573. }
  2574. return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  2575. return __generator(this, function (_a) {
  2576. getRecaptchaConfig(auth, {
  2577. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  2578. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2579. })
  2580. .then(function (response) {
  2581. if (response.recaptchaKey === undefined) {
  2582. reject(new Error('recaptcha Enterprise site key undefined'));
  2583. }
  2584. else {
  2585. var config = new RecaptchaConfig(response);
  2586. if (auth.tenantId == null) {
  2587. auth._agentRecaptchaConfig = config;
  2588. }
  2589. else {
  2590. auth._tenantRecaptchaConfigs[auth.tenantId] = config;
  2591. }
  2592. return resolve(config.siteKey);
  2593. }
  2594. })
  2595. .catch(function (error) {
  2596. reject(error);
  2597. });
  2598. return [2 /*return*/];
  2599. });
  2600. }); })];
  2601. });
  2602. });
  2603. }
  2604. function retrieveRecaptchaToken(siteKey, resolve, reject) {
  2605. var grecaptcha = window.grecaptcha;
  2606. if (isEnterprise(grecaptcha)) {
  2607. grecaptcha.enterprise.ready(function () {
  2608. grecaptcha.enterprise
  2609. .execute(siteKey, { action: action })
  2610. .then(function (token) {
  2611. resolve(token);
  2612. })
  2613. .catch(function () {
  2614. resolve(FAKE_TOKEN);
  2615. });
  2616. });
  2617. }
  2618. else {
  2619. reject(Error('No reCAPTCHA enterprise script loaded.'));
  2620. }
  2621. }
  2622. var _this = this;
  2623. return __generator(this, function (_a) {
  2624. return [2 /*return*/, new Promise(function (resolve, reject) {
  2625. retrieveSiteKey(_this.auth)
  2626. .then(function (siteKey) {
  2627. if (!forceRefresh && isEnterprise(window.grecaptcha)) {
  2628. retrieveRecaptchaToken(siteKey, resolve, reject);
  2629. }
  2630. else {
  2631. if (typeof window === 'undefined') {
  2632. reject(new Error('RecaptchaVerifier is only supported in browser'));
  2633. return;
  2634. }
  2635. _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)
  2636. .then(function () {
  2637. retrieveRecaptchaToken(siteKey, resolve, reject);
  2638. })
  2639. .catch(function (error) {
  2640. reject(error);
  2641. });
  2642. }
  2643. })
  2644. .catch(function (error) {
  2645. reject(error);
  2646. });
  2647. })];
  2648. });
  2649. });
  2650. };
  2651. return RecaptchaEnterpriseVerifier;
  2652. }());
  2653. function injectRecaptchaFields(auth, request, action, captchaResp) {
  2654. if (captchaResp === void 0) { captchaResp = false; }
  2655. return __awaiter(this, void 0, void 0, function () {
  2656. var verifier, captchaResponse, newRequest;
  2657. return __generator(this, function (_a) {
  2658. switch (_a.label) {
  2659. case 0:
  2660. verifier = new RecaptchaEnterpriseVerifier(auth);
  2661. _a.label = 1;
  2662. case 1:
  2663. _a.trys.push([1, 3, , 5]);
  2664. return [4 /*yield*/, verifier.verify(action)];
  2665. case 2:
  2666. captchaResponse = _a.sent();
  2667. return [3 /*break*/, 5];
  2668. case 3:
  2669. _a.sent();
  2670. return [4 /*yield*/, verifier.verify(action, true)];
  2671. case 4:
  2672. captchaResponse = _a.sent();
  2673. return [3 /*break*/, 5];
  2674. case 5:
  2675. newRequest = __assign({}, request);
  2676. if (!captchaResp) {
  2677. Object.assign(newRequest, { captchaResponse: captchaResponse });
  2678. }
  2679. else {
  2680. Object.assign(newRequest, { 'captchaResp': captchaResponse });
  2681. }
  2682. Object.assign(newRequest, { 'clientType': "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */ });
  2683. Object.assign(newRequest, {
  2684. 'recaptchaVersion': "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2685. });
  2686. return [2 /*return*/, newRequest];
  2687. }
  2688. });
  2689. });
  2690. }
  2691. /**
  2692. * @license
  2693. * Copyright 2022 Google LLC
  2694. *
  2695. * Licensed under the Apache License, Version 2.0 (the "License");
  2696. * you may not use this file except in compliance with the License.
  2697. * You may obtain a copy of the License at
  2698. *
  2699. * http://www.apache.org/licenses/LICENSE-2.0
  2700. *
  2701. * Unless required by applicable law or agreed to in writing, software
  2702. * distributed under the License is distributed on an "AS IS" BASIS,
  2703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2704. * See the License for the specific language governing permissions and
  2705. * limitations under the License.
  2706. */
  2707. var AuthMiddlewareQueue = /** @class */ (function () {
  2708. function AuthMiddlewareQueue(auth) {
  2709. this.auth = auth;
  2710. this.queue = [];
  2711. }
  2712. AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
  2713. var _this = this;
  2714. // The callback could be sync or async. Wrap it into a
  2715. // function that is always async.
  2716. var wrappedCallback = function (user) {
  2717. return new Promise(function (resolve, reject) {
  2718. try {
  2719. var result = callback(user);
  2720. // Either resolve with existing promise or wrap a non-promise
  2721. // return value into a promise.
  2722. resolve(result);
  2723. }
  2724. catch (e) {
  2725. // Sync callback throws.
  2726. reject(e);
  2727. }
  2728. });
  2729. };
  2730. // Attach the onAbort if present
  2731. wrappedCallback.onAbort = onAbort;
  2732. this.queue.push(wrappedCallback);
  2733. var index = this.queue.length - 1;
  2734. return function () {
  2735. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2736. // indexing of other elements.
  2737. _this.queue[index] = function () { return Promise.resolve(); };
  2738. };
  2739. };
  2740. AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
  2741. return __awaiter(this, void 0, void 0, function () {
  2742. var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
  2743. return __generator(this, function (_c) {
  2744. switch (_c.label) {
  2745. case 0:
  2746. if (this.auth.currentUser === nextUser) {
  2747. return [2 /*return*/];
  2748. }
  2749. onAbortStack = [];
  2750. _c.label = 1;
  2751. case 1:
  2752. _c.trys.push([1, 6, , 7]);
  2753. _i = 0, _a = this.queue;
  2754. _c.label = 2;
  2755. case 2:
  2756. if (!(_i < _a.length)) return [3 /*break*/, 5];
  2757. beforeStateCallback = _a[_i];
  2758. return [4 /*yield*/, beforeStateCallback(nextUser)];
  2759. case 3:
  2760. _c.sent();
  2761. // Only push the onAbort if the callback succeeds
  2762. if (beforeStateCallback.onAbort) {
  2763. onAbortStack.push(beforeStateCallback.onAbort);
  2764. }
  2765. _c.label = 4;
  2766. case 4:
  2767. _i++;
  2768. return [3 /*break*/, 2];
  2769. case 5: return [3 /*break*/, 7];
  2770. case 6:
  2771. e_1 = _c.sent();
  2772. // Run all onAbort, with separate try/catch to ignore any errors and
  2773. // continue
  2774. onAbortStack.reverse();
  2775. for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
  2776. onAbort = onAbortStack_1[_b];
  2777. try {
  2778. onAbort();
  2779. }
  2780. catch (_) {
  2781. /* swallow error */
  2782. }
  2783. }
  2784. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2785. originalMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  2786. });
  2787. case 7: return [2 /*return*/];
  2788. }
  2789. });
  2790. });
  2791. };
  2792. return AuthMiddlewareQueue;
  2793. }());
  2794. /**
  2795. * @license
  2796. * Copyright 2020 Google LLC
  2797. *
  2798. * Licensed under the Apache License, Version 2.0 (the "License");
  2799. * you may not use this file except in compliance with the License.
  2800. * You may obtain a copy of the License at
  2801. *
  2802. * http://www.apache.org/licenses/LICENSE-2.0
  2803. *
  2804. * Unless required by applicable law or agreed to in writing, software
  2805. * distributed under the License is distributed on an "AS IS" BASIS,
  2806. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2807. * See the License for the specific language governing permissions and
  2808. * limitations under the License.
  2809. */
  2810. var AuthImpl = /** @class */ (function () {
  2811. function AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config) {
  2812. this.app = app;
  2813. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2814. this.appCheckServiceProvider = appCheckServiceProvider;
  2815. this.config = config;
  2816. this.currentUser = null;
  2817. this.emulatorConfig = null;
  2818. this.operations = Promise.resolve();
  2819. this.authStateSubscription = new Subscription(this);
  2820. this.idTokenSubscription = new Subscription(this);
  2821. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2822. this.redirectUser = null;
  2823. this.isProactiveRefreshEnabled = false;
  2824. // Any network calls will set this to true and prevent subsequent emulator
  2825. // initialization
  2826. this._canInitEmulator = true;
  2827. this._isInitialized = false;
  2828. this._deleted = false;
  2829. this._initializationPromise = null;
  2830. this._popupRedirectResolver = null;
  2831. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2832. this._agentRecaptchaConfig = null;
  2833. this._tenantRecaptchaConfigs = {};
  2834. // Tracks the last notified UID for state change listeners to prevent
  2835. // repeated calls to the callbacks. Undefined means it's never been
  2836. // called, whereas null means it's been called with a signed out user
  2837. this.lastNotifiedUid = undefined;
  2838. this.languageCode = null;
  2839. this.tenantId = null;
  2840. this.settings = { appVerificationDisabledForTesting: false };
  2841. this.frameworks = [];
  2842. this.name = app.name;
  2843. this.clientVersion = config.sdkClientVersion;
  2844. }
  2845. AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
  2846. var _this = this;
  2847. if (popupRedirectResolver) {
  2848. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2849. }
  2850. // Have to check for app deletion throughout initialization (after each
  2851. // promise resolution)
  2852. this._initializationPromise = this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  2853. var _a;
  2854. var _b, _c;
  2855. return __generator(this, function (_d) {
  2856. switch (_d.label) {
  2857. case 0:
  2858. if (this._deleted) {
  2859. return [2 /*return*/];
  2860. }
  2861. _a = this;
  2862. return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
  2863. case 1:
  2864. _a.persistenceManager = _d.sent();
  2865. if (this._deleted) {
  2866. return [2 /*return*/];
  2867. }
  2868. if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
  2869. _d.label = 2;
  2870. case 2:
  2871. _d.trys.push([2, 4, , 5]);
  2872. return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
  2873. case 3:
  2874. _d.sent();
  2875. return [3 /*break*/, 5];
  2876. case 4:
  2877. _d.sent();
  2878. return [3 /*break*/, 5];
  2879. case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
  2880. case 6:
  2881. _d.sent();
  2882. this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
  2883. if (this._deleted) {
  2884. return [2 /*return*/];
  2885. }
  2886. this._isInitialized = true;
  2887. return [2 /*return*/];
  2888. }
  2889. });
  2890. }); });
  2891. return this._initializationPromise;
  2892. };
  2893. /**
  2894. * If the persistence is changed in another window, the user manager will let us know
  2895. */
  2896. AuthImpl.prototype._onStorageEvent = function () {
  2897. return __awaiter(this, void 0, void 0, function () {
  2898. var user;
  2899. return __generator(this, function (_a) {
  2900. switch (_a.label) {
  2901. case 0:
  2902. if (this._deleted) {
  2903. return [2 /*return*/];
  2904. }
  2905. return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2906. case 1:
  2907. user = _a.sent();
  2908. if (!this.currentUser && !user) {
  2909. // No change, do nothing (was signed out and remained signed out).
  2910. return [2 /*return*/];
  2911. }
  2912. if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
  2913. // Data update, simply copy data changes.
  2914. this._currentUser._assign(user);
  2915. // If tokens changed from previous user tokens, this will trigger
  2916. // notifyAuthListeners_.
  2917. return [4 /*yield*/, this.currentUser.getIdToken()];
  2918. case 2:
  2919. // If tokens changed from previous user tokens, this will trigger
  2920. // notifyAuthListeners_.
  2921. _a.sent();
  2922. return [2 /*return*/];
  2923. case 3:
  2924. // Update current Auth state. Either a new login or logout.
  2925. // Skip blocking callbacks, they should not apply to a change in another tab.
  2926. return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
  2927. case 4:
  2928. // Update current Auth state. Either a new login or logout.
  2929. // Skip blocking callbacks, they should not apply to a change in another tab.
  2930. _a.sent();
  2931. return [2 /*return*/];
  2932. }
  2933. });
  2934. });
  2935. };
  2936. AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
  2937. var _a;
  2938. return __awaiter(this, void 0, void 0, function () {
  2939. var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
  2940. return __generator(this, function (_b) {
  2941. switch (_b.label) {
  2942. case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2943. case 1:
  2944. previouslyStoredUser = (_b.sent());
  2945. futureCurrentUser = previouslyStoredUser;
  2946. needsTocheckMiddleware = false;
  2947. if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
  2948. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2949. case 2:
  2950. _b.sent();
  2951. redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2952. storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2953. return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
  2954. case 3:
  2955. result = _b.sent();
  2956. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2957. // matches the redirect user, then we want to initially sign in with the
  2958. // new user object from result.
  2959. // TODO(samgho): More thoroughly test all of this
  2960. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2961. (result === null || result === void 0 ? void 0 : result.user)) {
  2962. futureCurrentUser = result.user;
  2963. needsTocheckMiddleware = true;
  2964. }
  2965. _b.label = 4;
  2966. case 4:
  2967. // If no user in persistence, there is no current user. Set to null.
  2968. if (!futureCurrentUser) {
  2969. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2970. }
  2971. if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
  2972. if (!needsTocheckMiddleware) return [3 /*break*/, 8];
  2973. _b.label = 5;
  2974. case 5:
  2975. _b.trys.push([5, 7, , 8]);
  2976. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
  2977. case 6:
  2978. _b.sent();
  2979. return [3 /*break*/, 8];
  2980. case 7:
  2981. e_2 = _b.sent();
  2982. futureCurrentUser = previouslyStoredUser;
  2983. // We know this is available since the bit is only set when the
  2984. // resolver is available
  2985. this._popupRedirectResolver._overrideRedirectResult(this, function () {
  2986. return Promise.reject(e_2);
  2987. });
  2988. return [3 /*break*/, 8];
  2989. case 8:
  2990. if (futureCurrentUser) {
  2991. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2992. }
  2993. else {
  2994. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2995. }
  2996. case 9:
  2997. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2998. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2999. case 10:
  3000. _b.sent();
  3001. // If the redirect user's event ID matches the current user's event ID,
  3002. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  3003. // This is important for the reauthenticateWithRedirect() flow.
  3004. if (this.redirectUser &&
  3005. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  3006. return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
  3007. }
  3008. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  3009. }
  3010. });
  3011. });
  3012. };
  3013. AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
  3014. return __awaiter(this, void 0, void 0, function () {
  3015. var result;
  3016. return __generator(this, function (_a) {
  3017. switch (_a.label) {
  3018. case 0:
  3019. result = null;
  3020. _a.label = 1;
  3021. case 1:
  3022. _a.trys.push([1, 3, , 5]);
  3023. return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
  3024. case 2:
  3025. // We know this._popupRedirectResolver is set since redirectResolver
  3026. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  3027. result = _a.sent();
  3028. return [3 /*break*/, 5];
  3029. case 3:
  3030. _a.sent();
  3031. // Swallow any errors here; the code can retrieve them in
  3032. // getRedirectResult().
  3033. return [4 /*yield*/, this._setRedirectUser(null)];
  3034. case 4:
  3035. // Swallow any errors here; the code can retrieve them in
  3036. // getRedirectResult().
  3037. _a.sent();
  3038. return [3 /*break*/, 5];
  3039. case 5: return [2 /*return*/, result];
  3040. }
  3041. });
  3042. });
  3043. };
  3044. AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
  3045. return __awaiter(this, void 0, void 0, function () {
  3046. var e_4;
  3047. return __generator(this, function (_a) {
  3048. switch (_a.label) {
  3049. case 0:
  3050. _a.trys.push([0, 2, , 3]);
  3051. return [4 /*yield*/, _reloadWithoutSaving(user)];
  3052. case 1:
  3053. _a.sent();
  3054. return [3 /*break*/, 3];
  3055. case 2:
  3056. e_4 = _a.sent();
  3057. if ((e_4 === null || e_4 === void 0 ? void 0 : e_4.code) !==
  3058. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  3059. // Something's wrong with the user's token. Log them out and remove
  3060. // them from storage
  3061. return [2 /*return*/, this.directlySetCurrentUser(null)];
  3062. }
  3063. return [3 /*break*/, 3];
  3064. case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
  3065. }
  3066. });
  3067. });
  3068. };
  3069. AuthImpl.prototype.useDeviceLanguage = function () {
  3070. this.languageCode = _getUserLanguage();
  3071. };
  3072. AuthImpl.prototype._delete = function () {
  3073. return __awaiter(this, void 0, void 0, function () {
  3074. return __generator(this, function (_a) {
  3075. this._deleted = true;
  3076. return [2 /*return*/];
  3077. });
  3078. });
  3079. };
  3080. AuthImpl.prototype.updateCurrentUser = function (userExtern) {
  3081. return __awaiter(this, void 0, void 0, function () {
  3082. var user;
  3083. return __generator(this, function (_a) {
  3084. user = userExtern
  3085. ? getModularInstance(userExtern)
  3086. : null;
  3087. if (user) {
  3088. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  3089. }
  3090. return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
  3091. });
  3092. });
  3093. };
  3094. AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
  3095. if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
  3096. return __awaiter(this, void 0, void 0, function () {
  3097. var _this = this;
  3098. return __generator(this, function (_a) {
  3099. switch (_a.label) {
  3100. case 0:
  3101. if (this._deleted) {
  3102. return [2 /*return*/];
  3103. }
  3104. if (user) {
  3105. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  3106. }
  3107. if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
  3108. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
  3109. case 1:
  3110. _a.sent();
  3111. _a.label = 2;
  3112. case 2: return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  3113. return __generator(this, function (_a) {
  3114. switch (_a.label) {
  3115. case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
  3116. case 1:
  3117. _a.sent();
  3118. this.notifyAuthListeners();
  3119. return [2 /*return*/];
  3120. }
  3121. });
  3122. }); })];
  3123. }
  3124. });
  3125. });
  3126. };
  3127. AuthImpl.prototype.signOut = function () {
  3128. return __awaiter(this, void 0, void 0, function () {
  3129. return __generator(this, function (_a) {
  3130. switch (_a.label) {
  3131. case 0:
  3132. // Run first, to block _setRedirectUser() if any callbacks fail.
  3133. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
  3134. case 1:
  3135. // Run first, to block _setRedirectUser() if any callbacks fail.
  3136. _a.sent();
  3137. if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
  3138. return [4 /*yield*/, this._setRedirectUser(null)];
  3139. case 2:
  3140. _a.sent();
  3141. _a.label = 3;
  3142. case 3:
  3143. // Prevent callbacks from being called again in _updateCurrentUser, as
  3144. // they were already called in the first line.
  3145. return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
  3146. }
  3147. });
  3148. });
  3149. };
  3150. AuthImpl.prototype.setPersistence = function (persistence) {
  3151. var _this = this;
  3152. return this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  3153. return __generator(this, function (_a) {
  3154. switch (_a.label) {
  3155. case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
  3156. case 1:
  3157. _a.sent();
  3158. return [2 /*return*/];
  3159. }
  3160. });
  3161. }); });
  3162. };
  3163. AuthImpl.prototype.initializeRecaptchaConfig = function () {
  3164. return __awaiter(this, void 0, void 0, function () {
  3165. var response, config, verifier;
  3166. return __generator(this, function (_a) {
  3167. switch (_a.label) {
  3168. case 0: return [4 /*yield*/, getRecaptchaConfig(this, {
  3169. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  3170. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  3171. })];
  3172. case 1:
  3173. response = _a.sent();
  3174. config = new RecaptchaConfig(response);
  3175. if (this.tenantId == null) {
  3176. this._agentRecaptchaConfig = config;
  3177. }
  3178. else {
  3179. this._tenantRecaptchaConfigs[this.tenantId] = config;
  3180. }
  3181. if (config.emailPasswordEnabled) {
  3182. verifier = new RecaptchaEnterpriseVerifier(this);
  3183. void verifier.verify();
  3184. }
  3185. return [2 /*return*/];
  3186. }
  3187. });
  3188. });
  3189. };
  3190. AuthImpl.prototype._getRecaptchaConfig = function () {
  3191. if (this.tenantId == null) {
  3192. return this._agentRecaptchaConfig;
  3193. }
  3194. else {
  3195. return this._tenantRecaptchaConfigs[this.tenantId];
  3196. }
  3197. };
  3198. AuthImpl.prototype._getPersistence = function () {
  3199. return this.assertedPersistence.persistence.type;
  3200. };
  3201. AuthImpl.prototype._updateErrorMap = function (errorMap) {
  3202. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  3203. };
  3204. AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
  3205. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  3206. };
  3207. AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
  3208. return this.beforeStateQueue.pushCallback(callback, onAbort);
  3209. };
  3210. AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
  3211. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  3212. };
  3213. AuthImpl.prototype.toJSON = function () {
  3214. var _a;
  3215. return {
  3216. apiKey: this.config.apiKey,
  3217. authDomain: this.config.authDomain,
  3218. appName: this.name,
  3219. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  3220. };
  3221. };
  3222. AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
  3223. return __awaiter(this, void 0, void 0, function () {
  3224. var redirectManager;
  3225. return __generator(this, function (_a) {
  3226. switch (_a.label) {
  3227. case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
  3228. case 1:
  3229. redirectManager = _a.sent();
  3230. return [2 /*return*/, user === null
  3231. ? redirectManager.removeCurrentUser()
  3232. : redirectManager.setCurrentUser(user)];
  3233. }
  3234. });
  3235. });
  3236. };
  3237. AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
  3238. return __awaiter(this, void 0, void 0, function () {
  3239. var resolver, _a, _b;
  3240. return __generator(this, function (_c) {
  3241. switch (_c.label) {
  3242. case 0:
  3243. if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
  3244. resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  3245. this._popupRedirectResolver;
  3246. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3247. _a = this;
  3248. return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */)];
  3249. case 1:
  3250. _a.redirectPersistenceManager = _c.sent();
  3251. _b = this;
  3252. return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
  3253. case 2:
  3254. _b.redirectUser =
  3255. _c.sent();
  3256. _c.label = 3;
  3257. case 3: return [2 /*return*/, this.redirectPersistenceManager];
  3258. }
  3259. });
  3260. });
  3261. };
  3262. AuthImpl.prototype._redirectUserForId = function (id) {
  3263. var _a, _b;
  3264. return __awaiter(this, void 0, void 0, function () {
  3265. var _this = this;
  3266. return __generator(this, function (_c) {
  3267. switch (_c.label) {
  3268. case 0:
  3269. if (!this._isInitialized) return [3 /*break*/, 2];
  3270. return [4 /*yield*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3271. return [2 /*return*/];
  3272. }); }); })];
  3273. case 1:
  3274. _c.sent();
  3275. _c.label = 2;
  3276. case 2:
  3277. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  3278. return [2 /*return*/, this._currentUser];
  3279. }
  3280. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  3281. return [2 /*return*/, this.redirectUser];
  3282. }
  3283. return [2 /*return*/, null];
  3284. }
  3285. });
  3286. });
  3287. };
  3288. AuthImpl.prototype._persistUserIfCurrent = function (user) {
  3289. return __awaiter(this, void 0, void 0, function () {
  3290. var _this = this;
  3291. return __generator(this, function (_a) {
  3292. if (user === this.currentUser) {
  3293. return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3294. return [2 /*return*/, this.directlySetCurrentUser(user)];
  3295. }); }); })];
  3296. }
  3297. return [2 /*return*/];
  3298. });
  3299. });
  3300. };
  3301. /** Notifies listeners only if the user is current */
  3302. AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
  3303. if (user === this.currentUser) {
  3304. this.notifyAuthListeners();
  3305. }
  3306. };
  3307. AuthImpl.prototype._key = function () {
  3308. return "".concat(this.config.authDomain, ":").concat(this.config.apiKey, ":").concat(this.name);
  3309. };
  3310. AuthImpl.prototype._startProactiveRefresh = function () {
  3311. this.isProactiveRefreshEnabled = true;
  3312. if (this.currentUser) {
  3313. this._currentUser._startProactiveRefresh();
  3314. }
  3315. };
  3316. AuthImpl.prototype._stopProactiveRefresh = function () {
  3317. this.isProactiveRefreshEnabled = false;
  3318. if (this.currentUser) {
  3319. this._currentUser._stopProactiveRefresh();
  3320. }
  3321. };
  3322. Object.defineProperty(AuthImpl.prototype, "_currentUser", {
  3323. /** Returns the current user cast as the internal type */
  3324. get: function () {
  3325. return this.currentUser;
  3326. },
  3327. enumerable: false,
  3328. configurable: true
  3329. });
  3330. AuthImpl.prototype.notifyAuthListeners = function () {
  3331. var _a, _b;
  3332. if (!this._isInitialized) {
  3333. return;
  3334. }
  3335. this.idTokenSubscription.next(this.currentUser);
  3336. var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  3337. if (this.lastNotifiedUid !== currentUid) {
  3338. this.lastNotifiedUid = currentUid;
  3339. this.authStateSubscription.next(this.currentUser);
  3340. }
  3341. };
  3342. AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
  3343. var _this = this;
  3344. if (this._deleted) {
  3345. return function () { };
  3346. }
  3347. var cb = typeof nextOrObserver === 'function'
  3348. ? nextOrObserver
  3349. : nextOrObserver.next.bind(nextOrObserver);
  3350. var promise = this._isInitialized
  3351. ? Promise.resolve()
  3352. : this._initializationPromise;
  3353. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3354. // The callback needs to be called asynchronously per the spec.
  3355. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3356. promise.then(function () { return cb(_this.currentUser); });
  3357. if (typeof nextOrObserver === 'function') {
  3358. return subscription.addObserver(nextOrObserver, error, completed);
  3359. }
  3360. else {
  3361. return subscription.addObserver(nextOrObserver);
  3362. }
  3363. };
  3364. /**
  3365. * Unprotected (from race conditions) method to set the current user. This
  3366. * should only be called from within a queued callback. This is necessary
  3367. * because the queue shouldn't rely on another queued callback.
  3368. */
  3369. AuthImpl.prototype.directlySetCurrentUser = function (user) {
  3370. return __awaiter(this, void 0, void 0, function () {
  3371. return __generator(this, function (_a) {
  3372. switch (_a.label) {
  3373. case 0:
  3374. if (this.currentUser && this.currentUser !== user) {
  3375. this._currentUser._stopProactiveRefresh();
  3376. }
  3377. if (user && this.isProactiveRefreshEnabled) {
  3378. user._startProactiveRefresh();
  3379. }
  3380. this.currentUser = user;
  3381. if (!user) return [3 /*break*/, 2];
  3382. return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
  3383. case 1:
  3384. _a.sent();
  3385. return [3 /*break*/, 4];
  3386. case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
  3387. case 3:
  3388. _a.sent();
  3389. _a.label = 4;
  3390. case 4: return [2 /*return*/];
  3391. }
  3392. });
  3393. });
  3394. };
  3395. AuthImpl.prototype.queue = function (action) {
  3396. // In case something errors, the callback still should be called in order
  3397. // to keep the promise chain alive
  3398. this.operations = this.operations.then(action, action);
  3399. return this.operations;
  3400. };
  3401. Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
  3402. get: function () {
  3403. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3404. return this.persistenceManager;
  3405. },
  3406. enumerable: false,
  3407. configurable: true
  3408. });
  3409. AuthImpl.prototype._logFramework = function (framework) {
  3410. if (!framework || this.frameworks.includes(framework)) {
  3411. return;
  3412. }
  3413. this.frameworks.push(framework);
  3414. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  3415. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  3416. this.frameworks.sort();
  3417. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  3418. };
  3419. AuthImpl.prototype._getFrameworks = function () {
  3420. return this.frameworks;
  3421. };
  3422. AuthImpl.prototype._getAdditionalHeaders = function () {
  3423. var _a;
  3424. return __awaiter(this, void 0, void 0, function () {
  3425. var headers, heartbeatsHeader, appCheckToken;
  3426. var _b;
  3427. return __generator(this, function (_c) {
  3428. switch (_c.label) {
  3429. case 0:
  3430. headers = (_b = {},
  3431. _b["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */] = this.clientVersion,
  3432. _b);
  3433. if (this.app.options.appId) {
  3434. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  3435. }
  3436. return [4 /*yield*/, ((_a = this.heartbeatServiceProvider
  3437. .getImmediate({
  3438. optional: true
  3439. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
  3440. case 1:
  3441. heartbeatsHeader = _c.sent();
  3442. if (heartbeatsHeader) {
  3443. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  3444. }
  3445. return [4 /*yield*/, this._getAppCheckToken()];
  3446. case 2:
  3447. appCheckToken = _c.sent();
  3448. if (appCheckToken) {
  3449. headers["X-Firebase-AppCheck" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;
  3450. }
  3451. return [2 /*return*/, headers];
  3452. }
  3453. });
  3454. });
  3455. };
  3456. AuthImpl.prototype._getAppCheckToken = function () {
  3457. var _a;
  3458. return __awaiter(this, void 0, void 0, function () {
  3459. var appCheckTokenResult;
  3460. return __generator(this, function (_b) {
  3461. switch (_b.label) {
  3462. case 0: return [4 /*yield*/, ((_a = this.appCheckServiceProvider
  3463. .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken())];
  3464. case 1:
  3465. appCheckTokenResult = _b.sent();
  3466. if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
  3467. // Context: appCheck.getToken() will never throw even if an error happened.
  3468. // In the error case, a dummy token will be returned along with an error field describing
  3469. // the error. In general, we shouldn't care about the error condition and just use
  3470. // the token (actual or dummy) to send requests.
  3471. _logWarn("Error while retrieving App Check token: ".concat(appCheckTokenResult.error));
  3472. }
  3473. return [2 /*return*/, appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token];
  3474. }
  3475. });
  3476. });
  3477. };
  3478. return AuthImpl;
  3479. }());
  3480. /**
  3481. * Method to be used to cast down to our private implmentation of Auth.
  3482. * It will also handle unwrapping from the compat type if necessary
  3483. *
  3484. * @param auth Auth object passed in from developer
  3485. */
  3486. function _castAuth(auth) {
  3487. return getModularInstance(auth);
  3488. }
  3489. /** Helper class to wrap subscriber logic */
  3490. var Subscription = /** @class */ (function () {
  3491. function Subscription(auth) {
  3492. var _this = this;
  3493. this.auth = auth;
  3494. this.observer = null;
  3495. this.addObserver = createSubscribe(function (observer) { return (_this.observer = observer); });
  3496. }
  3497. Object.defineProperty(Subscription.prototype, "next", {
  3498. get: function () {
  3499. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3500. return this.observer.next.bind(this.observer);
  3501. },
  3502. enumerable: false,
  3503. configurable: true
  3504. });
  3505. return Subscription;
  3506. }());
  3507. /**
  3508. * @license
  3509. * Copyright 2020 Google LLC
  3510. *
  3511. * Licensed under the Apache License, Version 2.0 (the "License");
  3512. * you may not use this file except in compliance with the License.
  3513. * You may obtain a copy of the License at
  3514. *
  3515. * http://www.apache.org/licenses/LICENSE-2.0
  3516. *
  3517. * Unless required by applicable law or agreed to in writing, software
  3518. * distributed under the License is distributed on an "AS IS" BASIS,
  3519. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3520. * See the License for the specific language governing permissions and
  3521. * limitations under the License.
  3522. */
  3523. /**
  3524. * Initializes an {@link Auth} instance with fine-grained control over
  3525. * {@link Dependencies}.
  3526. *
  3527. * @remarks
  3528. *
  3529. * This function allows more control over the {@link Auth} instance than
  3530. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  3531. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  3532. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  3533. * need control over which persistence layer is used, or to minimize bundle
  3534. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  3535. *
  3536. * For example, if your app only uses anonymous accounts and you only want
  3537. * accounts saved for the current session, initialize `Auth` with:
  3538. *
  3539. * ```js
  3540. * const auth = initializeAuth(app, {
  3541. * persistence: browserSessionPersistence,
  3542. * popupRedirectResolver: undefined,
  3543. * });
  3544. * ```
  3545. *
  3546. * @public
  3547. */
  3548. function initializeAuth(app, deps) {
  3549. var provider = _getProvider(app, 'auth');
  3550. if (provider.isInitialized()) {
  3551. var auth_1 = provider.getImmediate();
  3552. var initialOptions = provider.getOptions();
  3553. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  3554. return auth_1;
  3555. }
  3556. else {
  3557. _fail(auth_1, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  3558. }
  3559. }
  3560. var auth = provider.initialize({ options: deps });
  3561. return auth;
  3562. }
  3563. function _initializeAuthInstance(auth, deps) {
  3564. var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  3565. var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  3566. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  3567. auth._updateErrorMap(deps.errorMap);
  3568. }
  3569. // This promise is intended to float; auth initialization happens in the
  3570. // background, meanwhile the auth object may be used by the app.
  3571. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3572. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  3573. }
  3574. /**
  3575. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  3576. * Firebase Auth services.
  3577. *
  3578. * @remarks
  3579. * This must be called synchronously immediately following the first call to
  3580. * {@link initializeAuth}. Do not use with production credentials as emulator
  3581. * traffic is not encrypted.
  3582. *
  3583. *
  3584. * @example
  3585. * ```javascript
  3586. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  3587. * ```
  3588. *
  3589. * @param auth - The {@link Auth} instance.
  3590. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  3591. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  3592. * `true` to disable the warning banner attached to the DOM.
  3593. *
  3594. * @public
  3595. */
  3596. function connectAuthEmulator(auth, url, options) {
  3597. var authInternal = _castAuth(auth);
  3598. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  3599. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  3600. var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  3601. var protocol = extractProtocol(url);
  3602. var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
  3603. var portStr = port === null ? '' : ":".concat(port);
  3604. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  3605. authInternal.config.emulator = { url: "".concat(protocol, "//").concat(host).concat(portStr, "/") };
  3606. authInternal.settings.appVerificationDisabledForTesting = true;
  3607. authInternal.emulatorConfig = Object.freeze({
  3608. host: host,
  3609. port: port,
  3610. protocol: protocol.replace(':', ''),
  3611. options: Object.freeze({ disableWarnings: disableWarnings })
  3612. });
  3613. if (!disableWarnings) {
  3614. emitEmulatorWarning();
  3615. }
  3616. }
  3617. function extractProtocol(url) {
  3618. var protocolEnd = url.indexOf(':');
  3619. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  3620. }
  3621. function extractHostAndPort(url) {
  3622. var protocol = extractProtocol(url);
  3623. var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  3624. if (!authority) {
  3625. return { host: '', port: null };
  3626. }
  3627. var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  3628. var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  3629. if (bracketedIPv6) {
  3630. var host = bracketedIPv6[1];
  3631. return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  3632. }
  3633. else {
  3634. var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
  3635. return { host: host, port: parsePort(port) };
  3636. }
  3637. }
  3638. function parsePort(portStr) {
  3639. if (!portStr) {
  3640. return null;
  3641. }
  3642. var port = Number(portStr);
  3643. if (isNaN(port)) {
  3644. return null;
  3645. }
  3646. return port;
  3647. }
  3648. function emitEmulatorWarning() {
  3649. function attachBanner() {
  3650. var el = document.createElement('p');
  3651. var sty = el.style;
  3652. el.innerText =
  3653. 'Running in emulator mode. Do not use with production credentials.';
  3654. sty.position = 'fixed';
  3655. sty.width = '100%';
  3656. sty.backgroundColor = '#ffffff';
  3657. sty.border = '.1em solid #000000';
  3658. sty.color = '#b50000';
  3659. sty.bottom = '0px';
  3660. sty.left = '0px';
  3661. sty.margin = '0px';
  3662. sty.zIndex = '10000';
  3663. sty.textAlign = 'center';
  3664. el.classList.add('firebase-emulator-warning');
  3665. document.body.appendChild(el);
  3666. }
  3667. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  3668. console.info('WARNING: You are using the Auth Emulator,' +
  3669. ' which is intended for local testing only. Do not use with' +
  3670. ' production credentials.');
  3671. }
  3672. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  3673. if (document.readyState === 'loading') {
  3674. window.addEventListener('DOMContentLoaded', attachBanner);
  3675. }
  3676. else {
  3677. attachBanner();
  3678. }
  3679. }
  3680. }
  3681. /**
  3682. * @license
  3683. * Copyright 2020 Google LLC
  3684. *
  3685. * Licensed under the Apache License, Version 2.0 (the "License");
  3686. * you may not use this file except in compliance with the License.
  3687. * You may obtain a copy of the License at
  3688. *
  3689. * http://www.apache.org/licenses/LICENSE-2.0
  3690. *
  3691. * Unless required by applicable law or agreed to in writing, software
  3692. * distributed under the License is distributed on an "AS IS" BASIS,
  3693. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3694. * See the License for the specific language governing permissions and
  3695. * limitations under the License.
  3696. */
  3697. /**
  3698. * Interface that represents the credentials returned by an {@link AuthProvider}.
  3699. *
  3700. * @remarks
  3701. * Implementations specify the details about each auth provider's credential requirements.
  3702. *
  3703. * @public
  3704. */
  3705. var AuthCredential = /** @class */ (function () {
  3706. /** @internal */
  3707. function AuthCredential(
  3708. /**
  3709. * The authentication provider ID for the credential.
  3710. *
  3711. * @remarks
  3712. * For example, 'facebook.com', or 'google.com'.
  3713. */
  3714. providerId,
  3715. /**
  3716. * The authentication sign in method for the credential.
  3717. *
  3718. * @remarks
  3719. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  3720. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  3721. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  3722. */
  3723. signInMethod) {
  3724. this.providerId = providerId;
  3725. this.signInMethod = signInMethod;
  3726. }
  3727. /**
  3728. * Returns a JSON-serializable representation of this object.
  3729. *
  3730. * @returns a JSON-serializable representation of this object.
  3731. */
  3732. AuthCredential.prototype.toJSON = function () {
  3733. return debugFail('not implemented');
  3734. };
  3735. /** @internal */
  3736. AuthCredential.prototype._getIdTokenResponse = function (_auth) {
  3737. return debugFail('not implemented');
  3738. };
  3739. /** @internal */
  3740. AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
  3741. return debugFail('not implemented');
  3742. };
  3743. /** @internal */
  3744. AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
  3745. return debugFail('not implemented');
  3746. };
  3747. return AuthCredential;
  3748. }());
  3749. /**
  3750. * @license
  3751. * Copyright 2020 Google LLC
  3752. *
  3753. * Licensed under the Apache License, Version 2.0 (the "License");
  3754. * you may not use this file except in compliance with the License.
  3755. * You may obtain a copy of the License at
  3756. *
  3757. * http://www.apache.org/licenses/LICENSE-2.0
  3758. *
  3759. * Unless required by applicable law or agreed to in writing, software
  3760. * distributed under the License is distributed on an "AS IS" BASIS,
  3761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3762. * See the License for the specific language governing permissions and
  3763. * limitations under the License.
  3764. */
  3765. function resetPassword(auth, request) {
  3766. return __awaiter(this, void 0, void 0, function () {
  3767. return __generator(this, function (_a) {
  3768. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
  3769. });
  3770. });
  3771. }
  3772. function updateEmailPassword(auth, request) {
  3773. return __awaiter(this, void 0, void 0, function () {
  3774. return __generator(this, function (_a) {
  3775. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  3776. });
  3777. });
  3778. }
  3779. function applyActionCode$1(auth, request) {
  3780. return __awaiter(this, void 0, void 0, function () {
  3781. return __generator(this, function (_a) {
  3782. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
  3783. });
  3784. });
  3785. }
  3786. /**
  3787. * @license
  3788. * Copyright 2020 Google LLC
  3789. *
  3790. * Licensed under the Apache License, Version 2.0 (the "License");
  3791. * you may not use this file except in compliance with the License.
  3792. * You may obtain a copy of the License at
  3793. *
  3794. * http://www.apache.org/licenses/LICENSE-2.0
  3795. *
  3796. * Unless required by applicable law or agreed to in writing, software
  3797. * distributed under the License is distributed on an "AS IS" BASIS,
  3798. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3799. * See the License for the specific language governing permissions and
  3800. * limitations under the License.
  3801. */
  3802. function signInWithPassword(auth, request) {
  3803. return __awaiter(this, void 0, void 0, function () {
  3804. return __generator(this, function (_a) {
  3805. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
  3806. });
  3807. });
  3808. }
  3809. function sendOobCode(auth, request) {
  3810. return __awaiter(this, void 0, void 0, function () {
  3811. return __generator(this, function (_a) {
  3812. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
  3813. });
  3814. });
  3815. }
  3816. function sendEmailVerification$1(auth, request) {
  3817. return __awaiter(this, void 0, void 0, function () {
  3818. return __generator(this, function (_a) {
  3819. return [2 /*return*/, sendOobCode(auth, request)];
  3820. });
  3821. });
  3822. }
  3823. function sendPasswordResetEmail$1(auth, request) {
  3824. return __awaiter(this, void 0, void 0, function () {
  3825. return __generator(this, function (_a) {
  3826. return [2 /*return*/, sendOobCode(auth, request)];
  3827. });
  3828. });
  3829. }
  3830. function sendSignInLinkToEmail$1(auth, request) {
  3831. return __awaiter(this, void 0, void 0, function () {
  3832. return __generator(this, function (_a) {
  3833. return [2 /*return*/, sendOobCode(auth, request)];
  3834. });
  3835. });
  3836. }
  3837. function verifyAndChangeEmail(auth, request) {
  3838. return __awaiter(this, void 0, void 0, function () {
  3839. return __generator(this, function (_a) {
  3840. return [2 /*return*/, sendOobCode(auth, request)];
  3841. });
  3842. });
  3843. }
  3844. /**
  3845. * @license
  3846. * Copyright 2020 Google LLC
  3847. *
  3848. * Licensed under the Apache License, Version 2.0 (the "License");
  3849. * you may not use this file except in compliance with the License.
  3850. * You may obtain a copy of the License at
  3851. *
  3852. * http://www.apache.org/licenses/LICENSE-2.0
  3853. *
  3854. * Unless required by applicable law or agreed to in writing, software
  3855. * distributed under the License is distributed on an "AS IS" BASIS,
  3856. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3857. * See the License for the specific language governing permissions and
  3858. * limitations under the License.
  3859. */
  3860. function signInWithEmailLink$1(auth, request) {
  3861. return __awaiter(this, void 0, void 0, function () {
  3862. return __generator(this, function (_a) {
  3863. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3864. });
  3865. });
  3866. }
  3867. function signInWithEmailLinkForLinking(auth, request) {
  3868. return __awaiter(this, void 0, void 0, function () {
  3869. return __generator(this, function (_a) {
  3870. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3871. });
  3872. });
  3873. }
  3874. /**
  3875. * @license
  3876. * Copyright 2020 Google LLC
  3877. *
  3878. * Licensed under the Apache License, Version 2.0 (the "License");
  3879. * you may not use this file except in compliance with the License.
  3880. * You may obtain a copy of the License at
  3881. *
  3882. * http://www.apache.org/licenses/LICENSE-2.0
  3883. *
  3884. * Unless required by applicable law or agreed to in writing, software
  3885. * distributed under the License is distributed on an "AS IS" BASIS,
  3886. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3887. * See the License for the specific language governing permissions and
  3888. * limitations under the License.
  3889. */
  3890. /**
  3891. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  3892. * {@link ProviderId}.PASSWORD
  3893. *
  3894. * @remarks
  3895. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  3896. * {@link SignInMethod}.EMAIL_LINK.
  3897. *
  3898. * @public
  3899. */
  3900. var EmailAuthCredential = /** @class */ (function (_super) {
  3901. __extends(EmailAuthCredential, _super);
  3902. /** @internal */
  3903. function EmailAuthCredential(
  3904. /** @internal */
  3905. _email,
  3906. /** @internal */
  3907. _password, signInMethod,
  3908. /** @internal */
  3909. _tenantId) {
  3910. if (_tenantId === void 0) { _tenantId = null; }
  3911. var _this = _super.call(this, "password" /* ProviderId.PASSWORD */, signInMethod) || this;
  3912. _this._email = _email;
  3913. _this._password = _password;
  3914. _this._tenantId = _tenantId;
  3915. return _this;
  3916. }
  3917. /** @internal */
  3918. EmailAuthCredential._fromEmailAndPassword = function (email, password) {
  3919. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  3920. };
  3921. /** @internal */
  3922. EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
  3923. if (tenantId === void 0) { tenantId = null; }
  3924. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  3925. };
  3926. /** {@inheritdoc AuthCredential.toJSON} */
  3927. EmailAuthCredential.prototype.toJSON = function () {
  3928. return {
  3929. email: this._email,
  3930. password: this._password,
  3931. signInMethod: this.signInMethod,
  3932. tenantId: this._tenantId
  3933. };
  3934. };
  3935. /**
  3936. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  3937. *
  3938. * @param json - Either `object` or the stringified representation of the object. When string is
  3939. * provided, `JSON.parse` would be called first.
  3940. *
  3941. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3942. */
  3943. EmailAuthCredential.fromJSON = function (json) {
  3944. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3945. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  3946. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  3947. return this._fromEmailAndPassword(obj.email, obj.password);
  3948. }
  3949. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  3950. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  3951. }
  3952. }
  3953. return null;
  3954. };
  3955. /** @internal */
  3956. EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3957. var _a;
  3958. return __awaiter(this, void 0, void 0, function () {
  3959. var _b, request_1, requestWithRecaptcha;
  3960. var _this = this;
  3961. return __generator(this, function (_c) {
  3962. switch (_c.label) {
  3963. case 0:
  3964. _b = this.signInMethod;
  3965. switch (_b) {
  3966. case "password" /* SignInMethod.EMAIL_PASSWORD */: return [3 /*break*/, 1];
  3967. case "emailLink" /* SignInMethod.EMAIL_LINK */: return [3 /*break*/, 4];
  3968. }
  3969. return [3 /*break*/, 5];
  3970. case 1:
  3971. request_1 = {
  3972. returnSecureToken: true,
  3973. email: this._email,
  3974. password: this._password,
  3975. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  3976. };
  3977. if (!((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  3978. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  3979. case 2:
  3980. requestWithRecaptcha = _c.sent();
  3981. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  3982. case 3: return [2 /*return*/, signInWithPassword(auth, request_1).catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  3983. var requestWithRecaptcha;
  3984. return __generator(this, function (_a) {
  3985. switch (_a.label) {
  3986. case 0:
  3987. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  3988. 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.');
  3989. return [4 /*yield*/, injectRecaptchaFields(auth, request_1, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */)];
  3990. case 1:
  3991. requestWithRecaptcha = _a.sent();
  3992. return [2 /*return*/, signInWithPassword(auth, requestWithRecaptcha)];
  3993. case 2: return [2 /*return*/, Promise.reject(error)];
  3994. }
  3995. });
  3996. }); })];
  3997. case 4: return [2 /*return*/, signInWithEmailLink$1(auth, {
  3998. email: this._email,
  3999. oobCode: this._password
  4000. })];
  4001. case 5:
  4002. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4003. _c.label = 6;
  4004. case 6: return [2 /*return*/];
  4005. }
  4006. });
  4007. });
  4008. };
  4009. /** @internal */
  4010. EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4011. return __awaiter(this, void 0, void 0, function () {
  4012. return __generator(this, function (_a) {
  4013. switch (this.signInMethod) {
  4014. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  4015. return [2 /*return*/, updateEmailPassword(auth, {
  4016. idToken: idToken,
  4017. returnSecureToken: true,
  4018. email: this._email,
  4019. password: this._password
  4020. })];
  4021. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  4022. return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
  4023. idToken: idToken,
  4024. email: this._email,
  4025. oobCode: this._password
  4026. })];
  4027. default:
  4028. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4029. }
  4030. return [2 /*return*/];
  4031. });
  4032. });
  4033. };
  4034. /** @internal */
  4035. EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4036. return this._getIdTokenResponse(auth);
  4037. };
  4038. return EmailAuthCredential;
  4039. }(AuthCredential));
  4040. /**
  4041. * @license
  4042. * Copyright 2020 Google LLC
  4043. *
  4044. * Licensed under the Apache License, Version 2.0 (the "License");
  4045. * you may not use this file except in compliance with the License.
  4046. * You may obtain a copy of the License at
  4047. *
  4048. * http://www.apache.org/licenses/LICENSE-2.0
  4049. *
  4050. * Unless required by applicable law or agreed to in writing, software
  4051. * distributed under the License is distributed on an "AS IS" BASIS,
  4052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4053. * See the License for the specific language governing permissions and
  4054. * limitations under the License.
  4055. */
  4056. function signInWithIdp(auth, request) {
  4057. return __awaiter(this, void 0, void 0, function () {
  4058. return __generator(this, function (_a) {
  4059. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
  4060. });
  4061. });
  4062. }
  4063. /**
  4064. * @license
  4065. * Copyright 2020 Google LLC
  4066. *
  4067. * Licensed under the Apache License, Version 2.0 (the "License");
  4068. * you may not use this file except in compliance with the License.
  4069. * You may obtain a copy of the License at
  4070. *
  4071. * http://www.apache.org/licenses/LICENSE-2.0
  4072. *
  4073. * Unless required by applicable law or agreed to in writing, software
  4074. * distributed under the License is distributed on an "AS IS" BASIS,
  4075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4076. * See the License for the specific language governing permissions and
  4077. * limitations under the License.
  4078. */
  4079. var IDP_REQUEST_URI$1 = 'http://localhost';
  4080. /**
  4081. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  4082. *
  4083. * @remarks
  4084. * Implementations specify the details about each auth provider's credential requirements.
  4085. *
  4086. * @public
  4087. */
  4088. var OAuthCredential = /** @class */ (function (_super) {
  4089. __extends(OAuthCredential, _super);
  4090. function OAuthCredential() {
  4091. var _this = _super !== null && _super.apply(this, arguments) || this;
  4092. _this.pendingToken = null;
  4093. return _this;
  4094. }
  4095. /** @internal */
  4096. OAuthCredential._fromParams = function (params) {
  4097. var cred = new OAuthCredential(params.providerId, params.signInMethod);
  4098. if (params.idToken || params.accessToken) {
  4099. // OAuth 2 and either ID token or access token.
  4100. if (params.idToken) {
  4101. cred.idToken = params.idToken;
  4102. }
  4103. if (params.accessToken) {
  4104. cred.accessToken = params.accessToken;
  4105. }
  4106. // Add nonce if available and no pendingToken is present.
  4107. if (params.nonce && !params.pendingToken) {
  4108. cred.nonce = params.nonce;
  4109. }
  4110. if (params.pendingToken) {
  4111. cred.pendingToken = params.pendingToken;
  4112. }
  4113. }
  4114. else if (params.oauthToken && params.oauthTokenSecret) {
  4115. // OAuth 1 and OAuth token with token secret
  4116. cred.accessToken = params.oauthToken;
  4117. cred.secret = params.oauthTokenSecret;
  4118. }
  4119. else {
  4120. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4121. }
  4122. return cred;
  4123. };
  4124. /** {@inheritdoc AuthCredential.toJSON} */
  4125. OAuthCredential.prototype.toJSON = function () {
  4126. return {
  4127. idToken: this.idToken,
  4128. accessToken: this.accessToken,
  4129. secret: this.secret,
  4130. nonce: this.nonce,
  4131. pendingToken: this.pendingToken,
  4132. providerId: this.providerId,
  4133. signInMethod: this.signInMethod
  4134. };
  4135. };
  4136. /**
  4137. * Static method to deserialize a JSON representation of an object into an
  4138. * {@link AuthCredential}.
  4139. *
  4140. * @param json - Input can be either Object or the stringified representation of the object.
  4141. * When string is provided, JSON.parse would be called first.
  4142. *
  4143. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4144. */
  4145. OAuthCredential.fromJSON = function (json) {
  4146. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4147. var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = __rest(obj, ["providerId", "signInMethod"]);
  4148. if (!providerId || !signInMethod) {
  4149. return null;
  4150. }
  4151. var cred = new OAuthCredential(providerId, signInMethod);
  4152. cred.idToken = rest.idToken || undefined;
  4153. cred.accessToken = rest.accessToken || undefined;
  4154. cred.secret = rest.secret;
  4155. cred.nonce = rest.nonce;
  4156. cred.pendingToken = rest.pendingToken || null;
  4157. return cred;
  4158. };
  4159. /** @internal */
  4160. OAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4161. var request = this.buildRequest();
  4162. return signInWithIdp(auth, request);
  4163. };
  4164. /** @internal */
  4165. OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4166. var request = this.buildRequest();
  4167. request.idToken = idToken;
  4168. return signInWithIdp(auth, request);
  4169. };
  4170. /** @internal */
  4171. OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4172. var request = this.buildRequest();
  4173. request.autoCreate = false;
  4174. return signInWithIdp(auth, request);
  4175. };
  4176. OAuthCredential.prototype.buildRequest = function () {
  4177. var request = {
  4178. requestUri: IDP_REQUEST_URI$1,
  4179. returnSecureToken: true
  4180. };
  4181. if (this.pendingToken) {
  4182. request.pendingToken = this.pendingToken;
  4183. }
  4184. else {
  4185. var postBody = {};
  4186. if (this.idToken) {
  4187. postBody['id_token'] = this.idToken;
  4188. }
  4189. if (this.accessToken) {
  4190. postBody['access_token'] = this.accessToken;
  4191. }
  4192. if (this.secret) {
  4193. postBody['oauth_token_secret'] = this.secret;
  4194. }
  4195. postBody['providerId'] = this.providerId;
  4196. if (this.nonce && !this.pendingToken) {
  4197. postBody['nonce'] = this.nonce;
  4198. }
  4199. request.postBody = querystring(postBody);
  4200. }
  4201. return request;
  4202. };
  4203. return OAuthCredential;
  4204. }(AuthCredential));
  4205. /**
  4206. * @license
  4207. * Copyright 2020 Google LLC
  4208. *
  4209. * Licensed under the Apache License, Version 2.0 (the "License");
  4210. * you may not use this file except in compliance with the License.
  4211. * You may obtain a copy of the License at
  4212. *
  4213. * http://www.apache.org/licenses/LICENSE-2.0
  4214. *
  4215. * Unless required by applicable law or agreed to in writing, software
  4216. * distributed under the License is distributed on an "AS IS" BASIS,
  4217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4218. * See the License for the specific language governing permissions and
  4219. * limitations under the License.
  4220. */
  4221. var _a;
  4222. function sendPhoneVerificationCode(auth, request) {
  4223. return __awaiter(this, void 0, void 0, function () {
  4224. return __generator(this, function (_a) {
  4225. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendVerificationCode" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
  4226. });
  4227. });
  4228. }
  4229. function signInWithPhoneNumber$1(auth, request) {
  4230. return __awaiter(this, void 0, void 0, function () {
  4231. return __generator(this, function (_a) {
  4232. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  4233. });
  4234. });
  4235. }
  4236. function linkWithPhoneNumber$1(auth, request) {
  4237. return __awaiter(this, void 0, void 0, function () {
  4238. var response;
  4239. return __generator(this, function (_a) {
  4240. switch (_a.label) {
  4241. case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  4242. case 1:
  4243. response = _a.sent();
  4244. if (response.temporaryProof) {
  4245. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  4246. }
  4247. return [2 /*return*/, response];
  4248. }
  4249. });
  4250. });
  4251. }
  4252. var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
  4253. _a["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  4254. _a);
  4255. function verifyPhoneNumberForExisting(auth, request) {
  4256. return __awaiter(this, void 0, void 0, function () {
  4257. var apiRequest;
  4258. return __generator(this, function (_a) {
  4259. apiRequest = __assign(__assign({}, request), { operation: 'REAUTH' });
  4260. 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_)];
  4261. });
  4262. });
  4263. }
  4264. /**
  4265. * @license
  4266. * Copyright 2020 Google LLC
  4267. *
  4268. * Licensed under the Apache License, Version 2.0 (the "License");
  4269. * you may not use this file except in compliance with the License.
  4270. * You may obtain a copy of the License at
  4271. *
  4272. * http://www.apache.org/licenses/LICENSE-2.0
  4273. *
  4274. * Unless required by applicable law or agreed to in writing, software
  4275. * distributed under the License is distributed on an "AS IS" BASIS,
  4276. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4277. * See the License for the specific language governing permissions and
  4278. * limitations under the License.
  4279. */
  4280. /**
  4281. * Represents the credentials returned by {@link PhoneAuthProvider}.
  4282. *
  4283. * @public
  4284. */
  4285. var PhoneAuthCredential = /** @class */ (function (_super) {
  4286. __extends(PhoneAuthCredential, _super);
  4287. function PhoneAuthCredential(params) {
  4288. var _this = _super.call(this, "phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */) || this;
  4289. _this.params = params;
  4290. return _this;
  4291. }
  4292. /** @internal */
  4293. PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
  4294. return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
  4295. };
  4296. /** @internal */
  4297. PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
  4298. return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
  4299. };
  4300. /** @internal */
  4301. PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4302. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  4303. };
  4304. /** @internal */
  4305. PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4306. return linkWithPhoneNumber$1(auth, __assign({ idToken: idToken }, this._makeVerificationRequest()));
  4307. };
  4308. /** @internal */
  4309. PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4310. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  4311. };
  4312. /** @internal */
  4313. PhoneAuthCredential.prototype._makeVerificationRequest = function () {
  4314. var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
  4315. if (temporaryProof && phoneNumber) {
  4316. return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
  4317. }
  4318. return {
  4319. sessionInfo: verificationId,
  4320. code: verificationCode
  4321. };
  4322. };
  4323. /** {@inheritdoc AuthCredential.toJSON} */
  4324. PhoneAuthCredential.prototype.toJSON = function () {
  4325. var obj = {
  4326. providerId: this.providerId
  4327. };
  4328. if (this.params.phoneNumber) {
  4329. obj.phoneNumber = this.params.phoneNumber;
  4330. }
  4331. if (this.params.temporaryProof) {
  4332. obj.temporaryProof = this.params.temporaryProof;
  4333. }
  4334. if (this.params.verificationCode) {
  4335. obj.verificationCode = this.params.verificationCode;
  4336. }
  4337. if (this.params.verificationId) {
  4338. obj.verificationId = this.params.verificationId;
  4339. }
  4340. return obj;
  4341. };
  4342. /** Generates a phone credential based on a plain object or a JSON string. */
  4343. PhoneAuthCredential.fromJSON = function (json) {
  4344. if (typeof json === 'string') {
  4345. json = JSON.parse(json);
  4346. }
  4347. var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
  4348. if (!verificationCode &&
  4349. !verificationId &&
  4350. !phoneNumber &&
  4351. !temporaryProof) {
  4352. return null;
  4353. }
  4354. return new PhoneAuthCredential({
  4355. verificationId: verificationId,
  4356. verificationCode: verificationCode,
  4357. phoneNumber: phoneNumber,
  4358. temporaryProof: temporaryProof
  4359. });
  4360. };
  4361. return PhoneAuthCredential;
  4362. }(AuthCredential));
  4363. /**
  4364. * @license
  4365. * Copyright 2020 Google LLC
  4366. *
  4367. * Licensed under the Apache License, Version 2.0 (the "License");
  4368. * you may not use this file except in compliance with the License.
  4369. * You may obtain a copy of the License at
  4370. *
  4371. * http://www.apache.org/licenses/LICENSE-2.0
  4372. *
  4373. * Unless required by applicable law or agreed to in writing, software
  4374. * distributed under the License is distributed on an "AS IS" BASIS,
  4375. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4376. * See the License for the specific language governing permissions and
  4377. * limitations under the License.
  4378. */
  4379. /**
  4380. * Maps the mode string in action code URL to Action Code Info operation.
  4381. *
  4382. * @param mode
  4383. */
  4384. function parseMode(mode) {
  4385. switch (mode) {
  4386. case 'recoverEmail':
  4387. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  4388. case 'resetPassword':
  4389. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  4390. case 'signIn':
  4391. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  4392. case 'verifyEmail':
  4393. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  4394. case 'verifyAndChangeEmail':
  4395. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  4396. case 'revertSecondFactorAddition':
  4397. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  4398. default:
  4399. return null;
  4400. }
  4401. }
  4402. /**
  4403. * Helper to parse FDL links
  4404. *
  4405. * @param url
  4406. */
  4407. function parseDeepLink(url) {
  4408. var link = querystringDecode(extractQuerystring(url))['link'];
  4409. // Double link case (automatic redirect).
  4410. var doubleDeepLink = link
  4411. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  4412. : null;
  4413. // iOS custom scheme links.
  4414. var iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  4415. var iOSDoubleDeepLink = iOSDeepLink
  4416. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  4417. : null;
  4418. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  4419. }
  4420. /**
  4421. * A utility class to parse email action URLs such as password reset, email verification,
  4422. * email link sign in, etc.
  4423. *
  4424. * @public
  4425. */
  4426. var ActionCodeURL = /** @class */ (function () {
  4427. /**
  4428. * @param actionLink - The link from which to extract the URL.
  4429. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4430. *
  4431. * @internal
  4432. */
  4433. function ActionCodeURL(actionLink) {
  4434. var _a, _b, _c, _d, _e, _f;
  4435. var searchParams = querystringDecode(extractQuerystring(actionLink));
  4436. var apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  4437. var code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  4438. var operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  4439. // Validate API key, code and mode.
  4440. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4441. this.apiKey = apiKey;
  4442. this.operation = operation;
  4443. this.code = code;
  4444. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  4445. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  4446. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  4447. }
  4448. /**
  4449. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  4450. * otherwise returns null.
  4451. *
  4452. * @param link - The email action link string.
  4453. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4454. *
  4455. * @public
  4456. */
  4457. ActionCodeURL.parseLink = function (link) {
  4458. var actionLink = parseDeepLink(link);
  4459. try {
  4460. return new ActionCodeURL(actionLink);
  4461. }
  4462. catch (_a) {
  4463. return null;
  4464. }
  4465. };
  4466. return ActionCodeURL;
  4467. }());
  4468. /**
  4469. * Parses the email action link string and returns an {@link ActionCodeURL} if
  4470. * the link is valid, otherwise returns null.
  4471. *
  4472. * @public
  4473. */
  4474. function parseActionCodeURL(link) {
  4475. return ActionCodeURL.parseLink(link);
  4476. }
  4477. /**
  4478. * @license
  4479. * Copyright 2020 Google LLC
  4480. *
  4481. * Licensed under the Apache License, Version 2.0 (the "License");
  4482. * you may not use this file except in compliance with the License.
  4483. * You may obtain a copy of the License at
  4484. *
  4485. * http://www.apache.org/licenses/LICENSE-2.0
  4486. *
  4487. * Unless required by applicable law or agreed to in writing, software
  4488. * distributed under the License is distributed on an "AS IS" BASIS,
  4489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4490. * See the License for the specific language governing permissions and
  4491. * limitations under the License.
  4492. */
  4493. /**
  4494. * Provider for generating {@link EmailAuthCredential}.
  4495. *
  4496. * @public
  4497. */
  4498. var EmailAuthProvider = /** @class */ (function () {
  4499. function EmailAuthProvider() {
  4500. /**
  4501. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4502. */
  4503. this.providerId = EmailAuthProvider.PROVIDER_ID;
  4504. }
  4505. /**
  4506. * Initialize an {@link AuthCredential} using an email and password.
  4507. *
  4508. * @example
  4509. * ```javascript
  4510. * const authCredential = EmailAuthProvider.credential(email, password);
  4511. * const userCredential = await signInWithCredential(auth, authCredential);
  4512. * ```
  4513. *
  4514. * @example
  4515. * ```javascript
  4516. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  4517. * ```
  4518. *
  4519. * @param email - Email address.
  4520. * @param password - User account password.
  4521. * @returns The auth provider credential.
  4522. */
  4523. EmailAuthProvider.credential = function (email, password) {
  4524. return EmailAuthCredential._fromEmailAndPassword(email, password);
  4525. };
  4526. /**
  4527. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  4528. * email link operation.
  4529. *
  4530. * @example
  4531. * ```javascript
  4532. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  4533. * const userCredential = await signInWithCredential(auth, authCredential);
  4534. * ```
  4535. *
  4536. * @example
  4537. * ```javascript
  4538. * await sendSignInLinkToEmail(auth, email);
  4539. * // Obtain emailLink from user.
  4540. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  4541. * ```
  4542. *
  4543. * @param auth - The {@link Auth} instance used to verify the link.
  4544. * @param email - Email address.
  4545. * @param emailLink - Sign-in email link.
  4546. * @returns - The auth provider credential.
  4547. */
  4548. EmailAuthProvider.credentialWithLink = function (email, emailLink) {
  4549. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  4550. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4551. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  4552. };
  4553. /**
  4554. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4555. */
  4556. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  4557. /**
  4558. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  4559. */
  4560. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  4561. /**
  4562. * Always set to {@link SignInMethod}.EMAIL_LINK.
  4563. */
  4564. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  4565. return EmailAuthProvider;
  4566. }());
  4567. /**
  4568. * @license
  4569. * Copyright 2020 Google LLC
  4570. *
  4571. * Licensed under the Apache License, Version 2.0 (the "License");
  4572. * you may not use this file except in compliance with the License.
  4573. * You may obtain a copy of the License at
  4574. *
  4575. * http://www.apache.org/licenses/LICENSE-2.0
  4576. *
  4577. * Unless required by applicable law or agreed to in writing, software
  4578. * distributed under the License is distributed on an "AS IS" BASIS,
  4579. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4580. * See the License for the specific language governing permissions and
  4581. * limitations under the License.
  4582. */
  4583. /**
  4584. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  4585. *
  4586. * This class is not meant to be instantiated directly.
  4587. *
  4588. * @public
  4589. */
  4590. var FederatedAuthProvider = /** @class */ (function () {
  4591. /**
  4592. * Constructor for generic OAuth providers.
  4593. *
  4594. * @param providerId - Provider for which credentials should be generated.
  4595. */
  4596. function FederatedAuthProvider(providerId) {
  4597. this.providerId = providerId;
  4598. /** @internal */
  4599. this.defaultLanguageCode = null;
  4600. /** @internal */
  4601. this.customParameters = {};
  4602. }
  4603. /**
  4604. * Set the language gode.
  4605. *
  4606. * @param languageCode - language code
  4607. */
  4608. FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
  4609. this.defaultLanguageCode = languageCode;
  4610. };
  4611. /**
  4612. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  4613. * operations.
  4614. *
  4615. * @remarks
  4616. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  4617. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  4618. *
  4619. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  4620. */
  4621. FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
  4622. this.customParameters = customOAuthParameters;
  4623. return this;
  4624. };
  4625. /**
  4626. * Retrieve the current list of {@link CustomParameters}.
  4627. */
  4628. FederatedAuthProvider.prototype.getCustomParameters = function () {
  4629. return this.customParameters;
  4630. };
  4631. return FederatedAuthProvider;
  4632. }());
  4633. /**
  4634. * @license
  4635. * Copyright 2019 Google LLC
  4636. *
  4637. * Licensed under the Apache License, Version 2.0 (the "License");
  4638. * you may not use this file except in compliance with the License.
  4639. * You may obtain a copy of the License at
  4640. *
  4641. * http://www.apache.org/licenses/LICENSE-2.0
  4642. *
  4643. * Unless required by applicable law or agreed to in writing, software
  4644. * distributed under the License is distributed on an "AS IS" BASIS,
  4645. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4646. * See the License for the specific language governing permissions and
  4647. * limitations under the License.
  4648. */
  4649. /**
  4650. * Common code to all OAuth providers. This is separate from the
  4651. * {@link OAuthProvider} so that child providers (like
  4652. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  4653. * Instead, they rely on a static `credential` method.
  4654. */
  4655. var BaseOAuthProvider = /** @class */ (function (_super) {
  4656. __extends(BaseOAuthProvider, _super);
  4657. function BaseOAuthProvider() {
  4658. var _this = _super !== null && _super.apply(this, arguments) || this;
  4659. /** @internal */
  4660. _this.scopes = [];
  4661. return _this;
  4662. }
  4663. /**
  4664. * Add an OAuth scope to the credential.
  4665. *
  4666. * @param scope - Provider OAuth scope to add.
  4667. */
  4668. BaseOAuthProvider.prototype.addScope = function (scope) {
  4669. // If not already added, add scope to list.
  4670. if (!this.scopes.includes(scope)) {
  4671. this.scopes.push(scope);
  4672. }
  4673. return this;
  4674. };
  4675. /**
  4676. * Retrieve the current list of OAuth scopes.
  4677. */
  4678. BaseOAuthProvider.prototype.getScopes = function () {
  4679. return __spreadArray([], this.scopes, true);
  4680. };
  4681. return BaseOAuthProvider;
  4682. }(FederatedAuthProvider));
  4683. /**
  4684. * Provider for generating generic {@link OAuthCredential}.
  4685. *
  4686. * @example
  4687. * ```javascript
  4688. * // Sign in using a redirect.
  4689. * const provider = new OAuthProvider('google.com');
  4690. * // Start a sign in process for an unauthenticated user.
  4691. * provider.addScope('profile');
  4692. * provider.addScope('email');
  4693. * await signInWithRedirect(auth, provider);
  4694. * // This will trigger a full page redirect away from your app
  4695. *
  4696. * // After returning from the redirect when your app initializes you can obtain the result
  4697. * const result = await getRedirectResult(auth);
  4698. * if (result) {
  4699. * // This is the signed-in user
  4700. * const user = result.user;
  4701. * // This gives you a OAuth Access Token for the provider.
  4702. * const credential = provider.credentialFromResult(auth, result);
  4703. * const token = credential.accessToken;
  4704. * }
  4705. * ```
  4706. *
  4707. * @example
  4708. * ```javascript
  4709. * // Sign in using a popup.
  4710. * const provider = new OAuthProvider('google.com');
  4711. * provider.addScope('profile');
  4712. * provider.addScope('email');
  4713. * const result = await signInWithPopup(auth, provider);
  4714. *
  4715. * // The signed-in user info.
  4716. * const user = result.user;
  4717. * // This gives you a OAuth Access Token for the provider.
  4718. * const credential = provider.credentialFromResult(auth, result);
  4719. * const token = credential.accessToken;
  4720. * ```
  4721. * @public
  4722. */
  4723. var OAuthProvider = /** @class */ (function (_super) {
  4724. __extends(OAuthProvider, _super);
  4725. function OAuthProvider() {
  4726. return _super !== null && _super.apply(this, arguments) || this;
  4727. }
  4728. /**
  4729. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  4730. * @param json - A plain object or a JSON string
  4731. */
  4732. OAuthProvider.credentialFromJSON = function (json) {
  4733. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4734. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4735. return OAuthCredential._fromParams(obj);
  4736. };
  4737. /**
  4738. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  4739. *
  4740. * @remarks
  4741. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  4742. * the raw nonce must match the nonce field in the ID token.
  4743. *
  4744. * @example
  4745. * ```javascript
  4746. * // `googleUser` from the onsuccess Google Sign In callback.
  4747. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4748. * const provider = new OAuthProvider('google.com');
  4749. * const credential = provider.credential({
  4750. * idToken: googleUser.getAuthResponse().id_token,
  4751. * });
  4752. * const result = await signInWithCredential(credential);
  4753. * ```
  4754. *
  4755. * @param params - Either the options object containing the ID token, access token and raw nonce
  4756. * or the ID token string.
  4757. */
  4758. OAuthProvider.prototype.credential = function (params) {
  4759. return this._credential(__assign(__assign({}, params), { nonce: params.rawNonce }));
  4760. };
  4761. /** An internal credential method that accepts more permissive options */
  4762. OAuthProvider.prototype._credential = function (params) {
  4763. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4764. // For OAuthCredential, sign in method is same as providerId.
  4765. return OAuthCredential._fromParams(__assign(__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  4766. };
  4767. /**
  4768. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4769. *
  4770. * @param userCredential - The user credential.
  4771. */
  4772. OAuthProvider.credentialFromResult = function (userCredential) {
  4773. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  4774. };
  4775. /**
  4776. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4777. * thrown during a sign-in, link, or reauthenticate operation.
  4778. *
  4779. * @param userCredential - The user credential.
  4780. */
  4781. OAuthProvider.credentialFromError = function (error) {
  4782. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  4783. };
  4784. OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
  4785. var tokenResponse = _a._tokenResponse;
  4786. if (!tokenResponse) {
  4787. return null;
  4788. }
  4789. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
  4790. if (!oauthAccessToken &&
  4791. !oauthTokenSecret &&
  4792. !oauthIdToken &&
  4793. !pendingToken) {
  4794. return null;
  4795. }
  4796. if (!providerId) {
  4797. return null;
  4798. }
  4799. try {
  4800. return new OAuthProvider(providerId)._credential({
  4801. idToken: oauthIdToken,
  4802. accessToken: oauthAccessToken,
  4803. nonce: nonce,
  4804. pendingToken: pendingToken
  4805. });
  4806. }
  4807. catch (e) {
  4808. return null;
  4809. }
  4810. };
  4811. return OAuthProvider;
  4812. }(BaseOAuthProvider));
  4813. /**
  4814. * @license
  4815. * Copyright 2020 Google LLC
  4816. *
  4817. * Licensed under the Apache License, Version 2.0 (the "License");
  4818. * you may not use this file except in compliance with the License.
  4819. * You may obtain a copy of the License at
  4820. *
  4821. * http://www.apache.org/licenses/LICENSE-2.0
  4822. *
  4823. * Unless required by applicable law or agreed to in writing, software
  4824. * distributed under the License is distributed on an "AS IS" BASIS,
  4825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4826. * See the License for the specific language governing permissions and
  4827. * limitations under the License.
  4828. */
  4829. /**
  4830. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  4831. *
  4832. * @example
  4833. * ```javascript
  4834. * // Sign in using a redirect.
  4835. * const provider = new FacebookAuthProvider();
  4836. * // Start a sign in process for an unauthenticated user.
  4837. * provider.addScope('user_birthday');
  4838. * await signInWithRedirect(auth, provider);
  4839. * // This will trigger a full page redirect away from your app
  4840. *
  4841. * // After returning from the redirect when your app initializes you can obtain the result
  4842. * const result = await getRedirectResult(auth);
  4843. * if (result) {
  4844. * // This is the signed-in user
  4845. * const user = result.user;
  4846. * // This gives you a Facebook Access Token.
  4847. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4848. * const token = credential.accessToken;
  4849. * }
  4850. * ```
  4851. *
  4852. * @example
  4853. * ```javascript
  4854. * // Sign in using a popup.
  4855. * const provider = new FacebookAuthProvider();
  4856. * provider.addScope('user_birthday');
  4857. * const result = await signInWithPopup(auth, provider);
  4858. *
  4859. * // The signed-in user info.
  4860. * const user = result.user;
  4861. * // This gives you a Facebook Access Token.
  4862. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4863. * const token = credential.accessToken;
  4864. * ```
  4865. *
  4866. * @public
  4867. */
  4868. var FacebookAuthProvider = /** @class */ (function (_super) {
  4869. __extends(FacebookAuthProvider, _super);
  4870. function FacebookAuthProvider() {
  4871. return _super.call(this, "facebook.com" /* ProviderId.FACEBOOK */) || this;
  4872. }
  4873. /**
  4874. * Creates a credential for Facebook.
  4875. *
  4876. * @example
  4877. * ```javascript
  4878. * // `event` from the Facebook auth.authResponseChange callback.
  4879. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  4880. * const result = await signInWithCredential(credential);
  4881. * ```
  4882. *
  4883. * @param accessToken - Facebook access token.
  4884. */
  4885. FacebookAuthProvider.credential = function (accessToken) {
  4886. return OAuthCredential._fromParams({
  4887. providerId: FacebookAuthProvider.PROVIDER_ID,
  4888. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  4889. accessToken: accessToken
  4890. });
  4891. };
  4892. /**
  4893. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4894. *
  4895. * @param userCredential - The user credential.
  4896. */
  4897. FacebookAuthProvider.credentialFromResult = function (userCredential) {
  4898. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  4899. };
  4900. /**
  4901. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4902. * thrown during a sign-in, link, or reauthenticate operation.
  4903. *
  4904. * @param userCredential - The user credential.
  4905. */
  4906. FacebookAuthProvider.credentialFromError = function (error) {
  4907. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4908. };
  4909. FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
  4910. var tokenResponse = _a._tokenResponse;
  4911. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4912. return null;
  4913. }
  4914. if (!tokenResponse.oauthAccessToken) {
  4915. return null;
  4916. }
  4917. try {
  4918. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  4919. }
  4920. catch (_b) {
  4921. return null;
  4922. }
  4923. };
  4924. /** Always set to {@link SignInMethod}.FACEBOOK. */
  4925. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  4926. /** Always set to {@link ProviderId}.FACEBOOK. */
  4927. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  4928. return FacebookAuthProvider;
  4929. }(BaseOAuthProvider));
  4930. /**
  4931. * @license
  4932. * Copyright 2020 Google LLC
  4933. *
  4934. * Licensed under the Apache License, Version 2.0 (the "License");
  4935. * you may not use this file except in compliance with the License.
  4936. * You may obtain a copy of the License at
  4937. *
  4938. * http://www.apache.org/licenses/LICENSE-2.0
  4939. *
  4940. * Unless required by applicable law or agreed to in writing, software
  4941. * distributed under the License is distributed on an "AS IS" BASIS,
  4942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4943. * See the License for the specific language governing permissions and
  4944. * limitations under the License.
  4945. */
  4946. /**
  4947. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  4948. *
  4949. * @example
  4950. * ```javascript
  4951. * // Sign in using a redirect.
  4952. * const provider = new GoogleAuthProvider();
  4953. * // Start a sign in process for an unauthenticated user.
  4954. * provider.addScope('profile');
  4955. * provider.addScope('email');
  4956. * await signInWithRedirect(auth, provider);
  4957. * // This will trigger a full page redirect away from your app
  4958. *
  4959. * // After returning from the redirect when your app initializes you can obtain the result
  4960. * const result = await getRedirectResult(auth);
  4961. * if (result) {
  4962. * // This is the signed-in user
  4963. * const user = result.user;
  4964. * // This gives you a Google Access Token.
  4965. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4966. * const token = credential.accessToken;
  4967. * }
  4968. * ```
  4969. *
  4970. * @example
  4971. * ```javascript
  4972. * // Sign in using a popup.
  4973. * const provider = new GoogleAuthProvider();
  4974. * provider.addScope('profile');
  4975. * provider.addScope('email');
  4976. * const result = await signInWithPopup(auth, provider);
  4977. *
  4978. * // The signed-in user info.
  4979. * const user = result.user;
  4980. * // This gives you a Google Access Token.
  4981. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4982. * const token = credential.accessToken;
  4983. * ```
  4984. *
  4985. * @public
  4986. */
  4987. var GoogleAuthProvider = /** @class */ (function (_super) {
  4988. __extends(GoogleAuthProvider, _super);
  4989. function GoogleAuthProvider() {
  4990. var _this = _super.call(this, "google.com" /* ProviderId.GOOGLE */) || this;
  4991. _this.addScope('profile');
  4992. return _this;
  4993. }
  4994. /**
  4995. * Creates a credential for Google. At least one of ID token and access token is required.
  4996. *
  4997. * @example
  4998. * ```javascript
  4999. * // \`googleUser\` from the onsuccess Google Sign In callback.
  5000. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  5001. * const result = await signInWithCredential(credential);
  5002. * ```
  5003. *
  5004. * @param idToken - Google ID token.
  5005. * @param accessToken - Google access token.
  5006. */
  5007. GoogleAuthProvider.credential = function (idToken, accessToken) {
  5008. return OAuthCredential._fromParams({
  5009. providerId: GoogleAuthProvider.PROVIDER_ID,
  5010. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  5011. idToken: idToken,
  5012. accessToken: accessToken
  5013. });
  5014. };
  5015. /**
  5016. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5017. *
  5018. * @param userCredential - The user credential.
  5019. */
  5020. GoogleAuthProvider.credentialFromResult = function (userCredential) {
  5021. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  5022. };
  5023. /**
  5024. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5025. * thrown during a sign-in, link, or reauthenticate operation.
  5026. *
  5027. * @param userCredential - The user credential.
  5028. */
  5029. GoogleAuthProvider.credentialFromError = function (error) {
  5030. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5031. };
  5032. GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
  5033. var tokenResponse = _a._tokenResponse;
  5034. if (!tokenResponse) {
  5035. return null;
  5036. }
  5037. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
  5038. if (!oauthIdToken && !oauthAccessToken) {
  5039. // This could be an oauth 1 credential or a phone credential
  5040. return null;
  5041. }
  5042. try {
  5043. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  5044. }
  5045. catch (_c) {
  5046. return null;
  5047. }
  5048. };
  5049. /** Always set to {@link SignInMethod}.GOOGLE. */
  5050. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  5051. /** Always set to {@link ProviderId}.GOOGLE. */
  5052. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  5053. return GoogleAuthProvider;
  5054. }(BaseOAuthProvider));
  5055. /**
  5056. * @license
  5057. * Copyright 2020 Google LLC
  5058. *
  5059. * Licensed under the Apache License, Version 2.0 (the "License");
  5060. * you may not use this file except in compliance with the License.
  5061. * You may obtain a copy of the License at
  5062. *
  5063. * http://www.apache.org/licenses/LICENSE-2.0
  5064. *
  5065. * Unless required by applicable law or agreed to in writing, software
  5066. * distributed under the License is distributed on an "AS IS" BASIS,
  5067. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5068. * See the License for the specific language governing permissions and
  5069. * limitations under the License.
  5070. */
  5071. /**
  5072. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  5073. *
  5074. * @remarks
  5075. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  5076. * the {@link signInWithPopup} handler:
  5077. *
  5078. * @example
  5079. * ```javascript
  5080. * // Sign in using a redirect.
  5081. * const provider = new GithubAuthProvider();
  5082. * // Start a sign in process for an unauthenticated user.
  5083. * provider.addScope('repo');
  5084. * await signInWithRedirect(auth, provider);
  5085. * // This will trigger a full page redirect away from your app
  5086. *
  5087. * // After returning from the redirect when your app initializes you can obtain the result
  5088. * const result = await getRedirectResult(auth);
  5089. * if (result) {
  5090. * // This is the signed-in user
  5091. * const user = result.user;
  5092. * // This gives you a Github Access Token.
  5093. * const credential = GithubAuthProvider.credentialFromResult(result);
  5094. * const token = credential.accessToken;
  5095. * }
  5096. * ```
  5097. *
  5098. * @example
  5099. * ```javascript
  5100. * // Sign in using a popup.
  5101. * const provider = new GithubAuthProvider();
  5102. * provider.addScope('repo');
  5103. * const result = await signInWithPopup(auth, provider);
  5104. *
  5105. * // The signed-in user info.
  5106. * const user = result.user;
  5107. * // This gives you a Github Access Token.
  5108. * const credential = GithubAuthProvider.credentialFromResult(result);
  5109. * const token = credential.accessToken;
  5110. * ```
  5111. * @public
  5112. */
  5113. var GithubAuthProvider = /** @class */ (function (_super) {
  5114. __extends(GithubAuthProvider, _super);
  5115. function GithubAuthProvider() {
  5116. return _super.call(this, "github.com" /* ProviderId.GITHUB */) || this;
  5117. }
  5118. /**
  5119. * Creates a credential for Github.
  5120. *
  5121. * @param accessToken - Github access token.
  5122. */
  5123. GithubAuthProvider.credential = function (accessToken) {
  5124. return OAuthCredential._fromParams({
  5125. providerId: GithubAuthProvider.PROVIDER_ID,
  5126. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  5127. accessToken: accessToken
  5128. });
  5129. };
  5130. /**
  5131. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5132. *
  5133. * @param userCredential - The user credential.
  5134. */
  5135. GithubAuthProvider.credentialFromResult = function (userCredential) {
  5136. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  5137. };
  5138. /**
  5139. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5140. * thrown during a sign-in, link, or reauthenticate operation.
  5141. *
  5142. * @param userCredential - The user credential.
  5143. */
  5144. GithubAuthProvider.credentialFromError = function (error) {
  5145. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5146. };
  5147. GithubAuthProvider.credentialFromTaggedObject = function (_a) {
  5148. var tokenResponse = _a._tokenResponse;
  5149. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  5150. return null;
  5151. }
  5152. if (!tokenResponse.oauthAccessToken) {
  5153. return null;
  5154. }
  5155. try {
  5156. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  5157. }
  5158. catch (_b) {
  5159. return null;
  5160. }
  5161. };
  5162. /** Always set to {@link SignInMethod}.GITHUB. */
  5163. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  5164. /** Always set to {@link ProviderId}.GITHUB. */
  5165. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  5166. return GithubAuthProvider;
  5167. }(BaseOAuthProvider));
  5168. /**
  5169. * @license
  5170. * Copyright 2020 Google LLC
  5171. *
  5172. * Licensed under the Apache License, Version 2.0 (the "License");
  5173. * you may not use this file except in compliance with the License.
  5174. * You may obtain a copy of the License at
  5175. *
  5176. * http://www.apache.org/licenses/LICENSE-2.0
  5177. *
  5178. * Unless required by applicable law or agreed to in writing, software
  5179. * distributed under the License is distributed on an "AS IS" BASIS,
  5180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5181. * See the License for the specific language governing permissions and
  5182. * limitations under the License.
  5183. */
  5184. var IDP_REQUEST_URI = 'http://localhost';
  5185. /**
  5186. * @public
  5187. */
  5188. var SAMLAuthCredential = /** @class */ (function (_super) {
  5189. __extends(SAMLAuthCredential, _super);
  5190. /** @internal */
  5191. function SAMLAuthCredential(providerId, pendingToken) {
  5192. var _this = _super.call(this, providerId, providerId) || this;
  5193. _this.pendingToken = pendingToken;
  5194. return _this;
  5195. }
  5196. /** @internal */
  5197. SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
  5198. var request = this.buildRequest();
  5199. return signInWithIdp(auth, request);
  5200. };
  5201. /** @internal */
  5202. SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  5203. var request = this.buildRequest();
  5204. request.idToken = idToken;
  5205. return signInWithIdp(auth, request);
  5206. };
  5207. /** @internal */
  5208. SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  5209. var request = this.buildRequest();
  5210. request.autoCreate = false;
  5211. return signInWithIdp(auth, request);
  5212. };
  5213. /** {@inheritdoc AuthCredential.toJSON} */
  5214. SAMLAuthCredential.prototype.toJSON = function () {
  5215. return {
  5216. signInMethod: this.signInMethod,
  5217. providerId: this.providerId,
  5218. pendingToken: this.pendingToken
  5219. };
  5220. };
  5221. /**
  5222. * Static method to deserialize a JSON representation of an object into an
  5223. * {@link AuthCredential}.
  5224. *
  5225. * @param json - Input can be either Object or the stringified representation of the object.
  5226. * When string is provided, JSON.parse would be called first.
  5227. *
  5228. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  5229. */
  5230. SAMLAuthCredential.fromJSON = function (json) {
  5231. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  5232. var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
  5233. if (!providerId ||
  5234. !signInMethod ||
  5235. !pendingToken ||
  5236. providerId !== signInMethod) {
  5237. return null;
  5238. }
  5239. return new SAMLAuthCredential(providerId, pendingToken);
  5240. };
  5241. /**
  5242. * Helper static method to avoid exposing the constructor to end users.
  5243. *
  5244. * @internal
  5245. */
  5246. SAMLAuthCredential._create = function (providerId, pendingToken) {
  5247. return new SAMLAuthCredential(providerId, pendingToken);
  5248. };
  5249. SAMLAuthCredential.prototype.buildRequest = function () {
  5250. return {
  5251. requestUri: IDP_REQUEST_URI,
  5252. returnSecureToken: true,
  5253. pendingToken: this.pendingToken
  5254. };
  5255. };
  5256. return SAMLAuthCredential;
  5257. }(AuthCredential));
  5258. /**
  5259. * @license
  5260. * Copyright 2020 Google LLC
  5261. *
  5262. * Licensed under the Apache License, Version 2.0 (the "License");
  5263. * you may not use this file except in compliance with the License.
  5264. * You may obtain a copy of the License at
  5265. *
  5266. * http://www.apache.org/licenses/LICENSE-2.0
  5267. *
  5268. * Unless required by applicable law or agreed to in writing, software
  5269. * distributed under the License is distributed on an "AS IS" BASIS,
  5270. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5271. * See the License for the specific language governing permissions and
  5272. * limitations under the License.
  5273. */
  5274. var SAML_PROVIDER_PREFIX = 'saml.';
  5275. /**
  5276. * An {@link AuthProvider} for SAML.
  5277. *
  5278. * @public
  5279. */
  5280. var SAMLAuthProvider = /** @class */ (function (_super) {
  5281. __extends(SAMLAuthProvider, _super);
  5282. /**
  5283. * Constructor. The providerId must start with "saml."
  5284. * @param providerId - SAML provider ID.
  5285. */
  5286. function SAMLAuthProvider(providerId) {
  5287. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5288. return _super.call(this, providerId) || this;
  5289. }
  5290. /**
  5291. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  5292. * successful SAML flow completes.
  5293. *
  5294. * @remarks
  5295. *
  5296. * For example, to get an {@link AuthCredential}, you could write the
  5297. * following code:
  5298. *
  5299. * ```js
  5300. * const userCredential = await signInWithPopup(auth, samlProvider);
  5301. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  5302. * ```
  5303. *
  5304. * @param userCredential - The user credential.
  5305. */
  5306. SAMLAuthProvider.credentialFromResult = function (userCredential) {
  5307. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  5308. };
  5309. /**
  5310. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5311. * thrown during a sign-in, link, or reauthenticate operation.
  5312. *
  5313. * @param userCredential - The user credential.
  5314. */
  5315. SAMLAuthProvider.credentialFromError = function (error) {
  5316. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  5317. };
  5318. /**
  5319. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  5320. * @param json - A plain object or a JSON string
  5321. */
  5322. SAMLAuthProvider.credentialFromJSON = function (json) {
  5323. var credential = SAMLAuthCredential.fromJSON(json);
  5324. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5325. return credential;
  5326. };
  5327. SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
  5328. var tokenResponse = _a._tokenResponse;
  5329. if (!tokenResponse) {
  5330. return null;
  5331. }
  5332. var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
  5333. if (!pendingToken || !providerId) {
  5334. return null;
  5335. }
  5336. try {
  5337. return SAMLAuthCredential._create(providerId, pendingToken);
  5338. }
  5339. catch (e) {
  5340. return null;
  5341. }
  5342. };
  5343. return SAMLAuthProvider;
  5344. }(FederatedAuthProvider));
  5345. /**
  5346. * @license
  5347. * Copyright 2020 Google LLC
  5348. *
  5349. * Licensed under the Apache License, Version 2.0 (the "License");
  5350. * you may not use this file except in compliance with the License.
  5351. * You may obtain a copy of the License at
  5352. *
  5353. * http://www.apache.org/licenses/LICENSE-2.0
  5354. *
  5355. * Unless required by applicable law or agreed to in writing, software
  5356. * distributed under the License is distributed on an "AS IS" BASIS,
  5357. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5358. * See the License for the specific language governing permissions and
  5359. * limitations under the License.
  5360. */
  5361. /**
  5362. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  5363. *
  5364. * @example
  5365. * ```javascript
  5366. * // Sign in using a redirect.
  5367. * const provider = new TwitterAuthProvider();
  5368. * // Start a sign in process for an unauthenticated user.
  5369. * await signInWithRedirect(auth, provider);
  5370. * // This will trigger a full page redirect away from your app
  5371. *
  5372. * // After returning from the redirect when your app initializes you can obtain the result
  5373. * const result = await getRedirectResult(auth);
  5374. * if (result) {
  5375. * // This is the signed-in user
  5376. * const user = result.user;
  5377. * // This gives you a Twitter Access Token and Secret.
  5378. * const credential = TwitterAuthProvider.credentialFromResult(result);
  5379. * const token = credential.accessToken;
  5380. * const secret = credential.secret;
  5381. * }
  5382. * ```
  5383. *
  5384. * @example
  5385. * ```javascript
  5386. * // Sign in using a popup.
  5387. * const provider = new TwitterAuthProvider();
  5388. * const result = await signInWithPopup(auth, provider);
  5389. *
  5390. * // The signed-in user info.
  5391. * const user = result.user;
  5392. * // This gives you a Twitter Access Token and Secret.
  5393. * const credential = TwitterAuthProvider.credentialFromResult(result);
  5394. * const token = credential.accessToken;
  5395. * const secret = credential.secret;
  5396. * ```
  5397. *
  5398. * @public
  5399. */
  5400. var TwitterAuthProvider = /** @class */ (function (_super) {
  5401. __extends(TwitterAuthProvider, _super);
  5402. function TwitterAuthProvider() {
  5403. return _super.call(this, "twitter.com" /* ProviderId.TWITTER */) || this;
  5404. }
  5405. /**
  5406. * Creates a credential for Twitter.
  5407. *
  5408. * @param token - Twitter access token.
  5409. * @param secret - Twitter secret.
  5410. */
  5411. TwitterAuthProvider.credential = function (token, secret) {
  5412. return OAuthCredential._fromParams({
  5413. providerId: TwitterAuthProvider.PROVIDER_ID,
  5414. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  5415. oauthToken: token,
  5416. oauthTokenSecret: secret
  5417. });
  5418. };
  5419. /**
  5420. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5421. *
  5422. * @param userCredential - The user credential.
  5423. */
  5424. TwitterAuthProvider.credentialFromResult = function (userCredential) {
  5425. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  5426. };
  5427. /**
  5428. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5429. * thrown during a sign-in, link, or reauthenticate operation.
  5430. *
  5431. * @param userCredential - The user credential.
  5432. */
  5433. TwitterAuthProvider.credentialFromError = function (error) {
  5434. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5435. };
  5436. TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
  5437. var tokenResponse = _a._tokenResponse;
  5438. if (!tokenResponse) {
  5439. return null;
  5440. }
  5441. var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
  5442. if (!oauthAccessToken || !oauthTokenSecret) {
  5443. return null;
  5444. }
  5445. try {
  5446. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  5447. }
  5448. catch (_c) {
  5449. return null;
  5450. }
  5451. };
  5452. /** Always set to {@link SignInMethod}.TWITTER. */
  5453. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  5454. /** Always set to {@link ProviderId}.TWITTER. */
  5455. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  5456. return TwitterAuthProvider;
  5457. }(BaseOAuthProvider));
  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. function signUp(auth, request) {
  5475. return __awaiter(this, void 0, void 0, function () {
  5476. return __generator(this, function (_a) {
  5477. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request))];
  5478. });
  5479. });
  5480. }
  5481. /**
  5482. * @license
  5483. * Copyright 2020 Google LLC
  5484. *
  5485. * Licensed under the Apache License, Version 2.0 (the "License");
  5486. * you may not use this file except in compliance with the License.
  5487. * You may obtain a copy of the License at
  5488. *
  5489. * http://www.apache.org/licenses/LICENSE-2.0
  5490. *
  5491. * Unless required by applicable law or agreed to in writing, software
  5492. * distributed under the License is distributed on an "AS IS" BASIS,
  5493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5494. * See the License for the specific language governing permissions and
  5495. * limitations under the License.
  5496. */
  5497. var UserCredentialImpl = /** @class */ (function () {
  5498. function UserCredentialImpl(params) {
  5499. this.user = params.user;
  5500. this.providerId = params.providerId;
  5501. this._tokenResponse = params._tokenResponse;
  5502. this.operationType = params.operationType;
  5503. }
  5504. UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
  5505. if (isAnonymous === void 0) { isAnonymous = false; }
  5506. return __awaiter(this, void 0, void 0, function () {
  5507. var user, providerId, userCred;
  5508. return __generator(this, function (_a) {
  5509. switch (_a.label) {
  5510. case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
  5511. case 1:
  5512. user = _a.sent();
  5513. providerId = providerIdForResponse(idTokenResponse);
  5514. userCred = new UserCredentialImpl({
  5515. user: user,
  5516. providerId: providerId,
  5517. _tokenResponse: idTokenResponse,
  5518. operationType: operationType
  5519. });
  5520. return [2 /*return*/, userCred];
  5521. }
  5522. });
  5523. });
  5524. };
  5525. UserCredentialImpl._forOperation = function (user, operationType, response) {
  5526. return __awaiter(this, void 0, void 0, function () {
  5527. var providerId;
  5528. return __generator(this, function (_a) {
  5529. switch (_a.label) {
  5530. case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  5531. case 1:
  5532. _a.sent();
  5533. providerId = providerIdForResponse(response);
  5534. return [2 /*return*/, new UserCredentialImpl({
  5535. user: user,
  5536. providerId: providerId,
  5537. _tokenResponse: response,
  5538. operationType: operationType
  5539. })];
  5540. }
  5541. });
  5542. });
  5543. };
  5544. return UserCredentialImpl;
  5545. }());
  5546. function providerIdForResponse(response) {
  5547. if (response.providerId) {
  5548. return response.providerId;
  5549. }
  5550. if ('phoneNumber' in response) {
  5551. return "phone" /* ProviderId.PHONE */;
  5552. }
  5553. return null;
  5554. }
  5555. /**
  5556. * @license
  5557. * Copyright 2020 Google LLC
  5558. *
  5559. * Licensed under the Apache License, Version 2.0 (the "License");
  5560. * you may not use this file except in compliance with the License.
  5561. * You may obtain a copy of the License at
  5562. *
  5563. * http://www.apache.org/licenses/LICENSE-2.0
  5564. *
  5565. * Unless required by applicable law or agreed to in writing, software
  5566. * distributed under the License is distributed on an "AS IS" BASIS,
  5567. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5568. * See the License for the specific language governing permissions and
  5569. * limitations under the License.
  5570. */
  5571. /**
  5572. * Asynchronously signs in as an anonymous user.
  5573. *
  5574. * @remarks
  5575. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  5576. * new anonymous user identity will be created and returned.
  5577. *
  5578. * @param auth - The {@link Auth} instance.
  5579. *
  5580. * @public
  5581. */
  5582. function signInAnonymously(auth) {
  5583. var _a;
  5584. return __awaiter(this, void 0, void 0, function () {
  5585. var authInternal, response, userCredential;
  5586. return __generator(this, function (_b) {
  5587. switch (_b.label) {
  5588. case 0:
  5589. authInternal = _castAuth(auth);
  5590. return [4 /*yield*/, authInternal._initializationPromise];
  5591. case 1:
  5592. _b.sent();
  5593. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  5594. // If an anonymous user is already signed in, no need to sign them in again.
  5595. return [2 /*return*/, new UserCredentialImpl({
  5596. user: authInternal.currentUser,
  5597. providerId: null,
  5598. operationType: "signIn" /* OperationType.SIGN_IN */
  5599. })];
  5600. }
  5601. return [4 /*yield*/, signUp(authInternal, {
  5602. returnSecureToken: true
  5603. })];
  5604. case 2:
  5605. response = _b.sent();
  5606. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true)];
  5607. case 3:
  5608. userCredential = _b.sent();
  5609. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5610. case 4:
  5611. _b.sent();
  5612. return [2 /*return*/, userCredential];
  5613. }
  5614. });
  5615. });
  5616. }
  5617. /**
  5618. * @license
  5619. * Copyright 2020 Google LLC
  5620. *
  5621. * Licensed under the Apache License, Version 2.0 (the "License");
  5622. * you may not use this file except in compliance with the License.
  5623. * You may obtain a copy of the License at
  5624. *
  5625. * http://www.apache.org/licenses/LICENSE-2.0
  5626. *
  5627. * Unless required by applicable law or agreed to in writing, software
  5628. * distributed under the License is distributed on an "AS IS" BASIS,
  5629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5630. * See the License for the specific language governing permissions and
  5631. * limitations under the License.
  5632. */
  5633. var MultiFactorError = /** @class */ (function (_super) {
  5634. __extends(MultiFactorError, _super);
  5635. function MultiFactorError(auth, error, operationType, user) {
  5636. var _this = this;
  5637. var _a;
  5638. _this = _super.call(this, error.code, error.message) || this;
  5639. _this.operationType = operationType;
  5640. _this.user = user;
  5641. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5642. Object.setPrototypeOf(_this, MultiFactorError.prototype);
  5643. _this.customData = {
  5644. appName: auth.name,
  5645. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  5646. _serverResponse: error.customData._serverResponse,
  5647. operationType: operationType
  5648. };
  5649. return _this;
  5650. }
  5651. MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
  5652. return new MultiFactorError(auth, error, operationType, user);
  5653. };
  5654. return MultiFactorError;
  5655. }(FirebaseError));
  5656. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  5657. var idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  5658. ? credential._getReauthenticationResolver(auth)
  5659. : credential._getIdTokenResponse(auth);
  5660. return idTokenProvider.catch(function (error) {
  5661. if (error.code === "auth/".concat("multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */)) {
  5662. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  5663. }
  5664. throw error;
  5665. });
  5666. }
  5667. /**
  5668. * @license
  5669. * Copyright 2020 Google LLC
  5670. *
  5671. * Licensed under the Apache License, Version 2.0 (the "License");
  5672. * you may not use this file except in compliance with the License.
  5673. * You may obtain a copy of the License at
  5674. *
  5675. * http://www.apache.org/licenses/LICENSE-2.0
  5676. *
  5677. * Unless required by applicable law or agreed to in writing, software
  5678. * distributed under the License is distributed on an "AS IS" BASIS,
  5679. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5680. * See the License for the specific language governing permissions and
  5681. * limitations under the License.
  5682. */
  5683. /**
  5684. * Takes a set of UserInfo provider data and converts it to a set of names
  5685. */
  5686. function providerDataAsNames(providerData) {
  5687. return new Set(providerData
  5688. .map(function (_a) {
  5689. var providerId = _a.providerId;
  5690. return providerId;
  5691. })
  5692. .filter(function (pid) { return !!pid; }));
  5693. }
  5694. /**
  5695. * @license
  5696. * Copyright 2019 Google LLC
  5697. *
  5698. * Licensed under the Apache License, Version 2.0 (the "License");
  5699. * you may not use this file except in compliance with the License.
  5700. * You may obtain a copy of the License at
  5701. *
  5702. * http://www.apache.org/licenses/LICENSE-2.0
  5703. *
  5704. * Unless required by applicable law or agreed to in writing, software
  5705. * distributed under the License is distributed on an "AS IS" BASIS,
  5706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5707. * See the License for the specific language governing permissions and
  5708. * limitations under the License.
  5709. */
  5710. /**
  5711. * Unlinks a provider from a user account.
  5712. *
  5713. * @param user - The user.
  5714. * @param providerId - The provider to unlink.
  5715. *
  5716. * @public
  5717. */
  5718. function unlink(user, providerId) {
  5719. return __awaiter(this, void 0, void 0, function () {
  5720. var userInternal, providerUserInfo, _a, _b, providersLeft;
  5721. var _c;
  5722. return __generator(this, function (_d) {
  5723. switch (_d.label) {
  5724. case 0:
  5725. userInternal = getModularInstance(user);
  5726. return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
  5727. case 1:
  5728. _d.sent();
  5729. _a = deleteLinkedAccounts;
  5730. _b = [userInternal.auth];
  5731. _c = {};
  5732. return [4 /*yield*/, userInternal.getIdToken()];
  5733. case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
  5734. _c.deleteProvider = [providerId],
  5735. _c)]))];
  5736. case 3:
  5737. providerUserInfo = (_d.sent()).providerUserInfo;
  5738. providersLeft = providerDataAsNames(providerUserInfo || []);
  5739. userInternal.providerData = userInternal.providerData.filter(function (pd) {
  5740. return providersLeft.has(pd.providerId);
  5741. });
  5742. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  5743. userInternal.phoneNumber = null;
  5744. }
  5745. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  5746. case 4:
  5747. _d.sent();
  5748. return [2 /*return*/, userInternal];
  5749. }
  5750. });
  5751. });
  5752. }
  5753. function _link$1(user, credential, bypassAuthState) {
  5754. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5755. return __awaiter(this, void 0, void 0, function () {
  5756. var response, _a, _b, _c, _d, _e;
  5757. return __generator(this, function (_f) {
  5758. switch (_f.label) {
  5759. case 0:
  5760. _a = _logoutIfInvalidated;
  5761. _b = [user];
  5762. _d = (_c = credential)._linkToIdToken;
  5763. _e = [user.auth];
  5764. return [4 /*yield*/, user.getIdToken()];
  5765. case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])),
  5766. bypassAuthState]))];
  5767. case 2:
  5768. response = _f.sent();
  5769. return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response)];
  5770. }
  5771. });
  5772. });
  5773. }
  5774. function _assertLinkedStatus(expected, user, provider) {
  5775. return __awaiter(this, void 0, void 0, function () {
  5776. var providerIds, code;
  5777. return __generator(this, function (_a) {
  5778. switch (_a.label) {
  5779. case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
  5780. case 1:
  5781. _a.sent();
  5782. providerIds = providerDataAsNames(user.providerData);
  5783. code = expected === false
  5784. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  5785. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  5786. _assert(providerIds.has(provider) === expected, user.auth, code);
  5787. return [2 /*return*/];
  5788. }
  5789. });
  5790. });
  5791. }
  5792. /**
  5793. * @license
  5794. * Copyright 2019 Google LLC
  5795. *
  5796. * Licensed under the Apache License, Version 2.0 (the "License");
  5797. * you may not use this file except in compliance with the License.
  5798. * You may obtain a copy of the License at
  5799. *
  5800. * http://www.apache.org/licenses/LICENSE-2.0
  5801. *
  5802. * Unless required by applicable law or agreed to in writing, software
  5803. * distributed under the License is distributed on an "AS IS" BASIS,
  5804. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5805. * See the License for the specific language governing permissions and
  5806. * limitations under the License.
  5807. */
  5808. function _reauthenticate(user, credential, bypassAuthState) {
  5809. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5810. return __awaiter(this, void 0, void 0, function () {
  5811. var auth, operationType, response, parsed, localId, e_1;
  5812. return __generator(this, function (_a) {
  5813. switch (_a.label) {
  5814. case 0:
  5815. auth = user.auth;
  5816. operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  5817. _a.label = 1;
  5818. case 1:
  5819. _a.trys.push([1, 3, , 4]);
  5820. return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
  5821. case 2:
  5822. response = _a.sent();
  5823. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5824. parsed = _parseToken(response.idToken);
  5825. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5826. localId = parsed.sub;
  5827. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5828. return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
  5829. case 3:
  5830. e_1 = _a.sent();
  5831. // Convert user deleted error into user mismatch
  5832. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/".concat("user-not-found" /* AuthErrorCode.USER_DELETED */)) {
  5833. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5834. }
  5835. throw e_1;
  5836. case 4: return [2 /*return*/];
  5837. }
  5838. });
  5839. });
  5840. }
  5841. /**
  5842. * @license
  5843. * Copyright 2020 Google LLC
  5844. *
  5845. * Licensed under the Apache License, Version 2.0 (the "License");
  5846. * you may not use this file except in compliance with the License.
  5847. * You may obtain a copy of the License at
  5848. *
  5849. * http://www.apache.org/licenses/LICENSE-2.0
  5850. *
  5851. * Unless required by applicable law or agreed to in writing, software
  5852. * distributed under the License is distributed on an "AS IS" BASIS,
  5853. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5854. * See the License for the specific language governing permissions and
  5855. * limitations under the License.
  5856. */
  5857. function _signInWithCredential(auth, credential, bypassAuthState) {
  5858. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5859. return __awaiter(this, void 0, void 0, function () {
  5860. var operationType, response, userCredential;
  5861. return __generator(this, function (_a) {
  5862. switch (_a.label) {
  5863. case 0:
  5864. operationType = "signIn" /* OperationType.SIGN_IN */;
  5865. return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
  5866. case 1:
  5867. response = _a.sent();
  5868. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
  5869. case 2:
  5870. userCredential = _a.sent();
  5871. if (!!bypassAuthState) return [3 /*break*/, 4];
  5872. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  5873. case 3:
  5874. _a.sent();
  5875. _a.label = 4;
  5876. case 4: return [2 /*return*/, userCredential];
  5877. }
  5878. });
  5879. });
  5880. }
  5881. /**
  5882. * Asynchronously signs in with the given credentials.
  5883. *
  5884. * @remarks
  5885. * An {@link AuthProvider} can be used to generate the credential.
  5886. *
  5887. * @param auth - The {@link Auth} instance.
  5888. * @param credential - The auth credential.
  5889. *
  5890. * @public
  5891. */
  5892. function signInWithCredential(auth, credential) {
  5893. return __awaiter(this, void 0, void 0, function () {
  5894. return __generator(this, function (_a) {
  5895. return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
  5896. });
  5897. });
  5898. }
  5899. /**
  5900. * Links the user account with the given credentials.
  5901. *
  5902. * @remarks
  5903. * An {@link AuthProvider} can be used to generate the credential.
  5904. *
  5905. * @param user - The user.
  5906. * @param credential - The auth credential.
  5907. *
  5908. * @public
  5909. */
  5910. function linkWithCredential(user, credential) {
  5911. return __awaiter(this, void 0, void 0, function () {
  5912. var userInternal;
  5913. return __generator(this, function (_a) {
  5914. switch (_a.label) {
  5915. case 0:
  5916. userInternal = getModularInstance(user);
  5917. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
  5918. case 1:
  5919. _a.sent();
  5920. return [2 /*return*/, _link$1(userInternal, credential)];
  5921. }
  5922. });
  5923. });
  5924. }
  5925. /**
  5926. * Re-authenticates a user using a fresh credential.
  5927. *
  5928. * @remarks
  5929. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  5930. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error
  5931. * or a `TOKEN_EXPIRED` error.
  5932. *
  5933. * @param user - The user.
  5934. * @param credential - The auth credential.
  5935. *
  5936. * @public
  5937. */
  5938. function reauthenticateWithCredential(user, credential) {
  5939. return __awaiter(this, void 0, void 0, function () {
  5940. return __generator(this, function (_a) {
  5941. return [2 /*return*/, _reauthenticate(getModularInstance(user), credential)];
  5942. });
  5943. });
  5944. }
  5945. /**
  5946. * @license
  5947. * Copyright 2020 Google LLC
  5948. *
  5949. * Licensed under the Apache License, Version 2.0 (the "License");
  5950. * you may not use this file except in compliance with the License.
  5951. * You may obtain a copy of the License at
  5952. *
  5953. * http://www.apache.org/licenses/LICENSE-2.0
  5954. *
  5955. * Unless required by applicable law or agreed to in writing, software
  5956. * distributed under the License is distributed on an "AS IS" BASIS,
  5957. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5958. * See the License for the specific language governing permissions and
  5959. * limitations under the License.
  5960. */
  5961. function signInWithCustomToken$1(auth, request) {
  5962. return __awaiter(this, void 0, void 0, function () {
  5963. return __generator(this, function (_a) {
  5964. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
  5965. });
  5966. });
  5967. }
  5968. /**
  5969. * @license
  5970. * Copyright 2020 Google LLC
  5971. *
  5972. * Licensed under the Apache License, Version 2.0 (the "License");
  5973. * you may not use this file except in compliance with the License.
  5974. * You may obtain a copy of the License at
  5975. *
  5976. * http://www.apache.org/licenses/LICENSE-2.0
  5977. *
  5978. * Unless required by applicable law or agreed to in writing, software
  5979. * distributed under the License is distributed on an "AS IS" BASIS,
  5980. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5981. * See the License for the specific language governing permissions and
  5982. * limitations under the License.
  5983. */
  5984. /**
  5985. * Asynchronously signs in using a custom token.
  5986. *
  5987. * @remarks
  5988. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  5989. * be generated by an auth backend using the
  5990. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  5991. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  5992. *
  5993. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  5994. *
  5995. * @param auth - The {@link Auth} instance.
  5996. * @param customToken - The custom token to sign in with.
  5997. *
  5998. * @public
  5999. */
  6000. function signInWithCustomToken(auth, customToken) {
  6001. return __awaiter(this, void 0, void 0, function () {
  6002. var authInternal, response, cred;
  6003. return __generator(this, function (_a) {
  6004. switch (_a.label) {
  6005. case 0:
  6006. authInternal = _castAuth(auth);
  6007. return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
  6008. token: customToken,
  6009. returnSecureToken: true
  6010. })];
  6011. case 1:
  6012. response = _a.sent();
  6013. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  6014. case 2:
  6015. cred = _a.sent();
  6016. return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
  6017. case 3:
  6018. _a.sent();
  6019. return [2 /*return*/, cred];
  6020. }
  6021. });
  6022. });
  6023. }
  6024. /**
  6025. * @license
  6026. * Copyright 2020 Google LLC
  6027. *
  6028. * Licensed under the Apache License, Version 2.0 (the "License");
  6029. * you may not use this file except in compliance with the License.
  6030. * You may obtain a copy of the License at
  6031. *
  6032. * http://www.apache.org/licenses/LICENSE-2.0
  6033. *
  6034. * Unless required by applicable law or agreed to in writing, software
  6035. * distributed under the License is distributed on an "AS IS" BASIS,
  6036. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6037. * See the License for the specific language governing permissions and
  6038. * limitations under the License.
  6039. */
  6040. var MultiFactorInfoImpl = /** @class */ (function () {
  6041. function MultiFactorInfoImpl(factorId, response) {
  6042. this.factorId = factorId;
  6043. this.uid = response.mfaEnrollmentId;
  6044. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  6045. this.displayName = response.displayName;
  6046. }
  6047. MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
  6048. if ('phoneInfo' in enrollment) {
  6049. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6050. }
  6051. else if ('totpInfo' in enrollment) {
  6052. return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6053. }
  6054. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6055. };
  6056. return MultiFactorInfoImpl;
  6057. }());
  6058. var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
  6059. __extends(PhoneMultiFactorInfoImpl, _super);
  6060. function PhoneMultiFactorInfoImpl(response) {
  6061. var _this = _super.call(this, "phone" /* FactorId.PHONE */, response) || this;
  6062. _this.phoneNumber = response.phoneInfo;
  6063. return _this;
  6064. }
  6065. PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  6066. return new PhoneMultiFactorInfoImpl(enrollment);
  6067. };
  6068. return PhoneMultiFactorInfoImpl;
  6069. }(MultiFactorInfoImpl));
  6070. var TotpMultiFactorInfoImpl = /** @class */ (function (_super) {
  6071. __extends(TotpMultiFactorInfoImpl, _super);
  6072. function TotpMultiFactorInfoImpl(response) {
  6073. return _super.call(this, "totp" /* FactorId.TOTP */, response) || this;
  6074. }
  6075. TotpMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  6076. return new TotpMultiFactorInfoImpl(enrollment);
  6077. };
  6078. return TotpMultiFactorInfoImpl;
  6079. }(MultiFactorInfoImpl));
  6080. /**
  6081. * @license
  6082. * Copyright 2020 Google LLC
  6083. *
  6084. * Licensed under the Apache License, Version 2.0 (the "License");
  6085. * you may not use this file except in compliance with the License.
  6086. * You may obtain a copy of the License at
  6087. *
  6088. * http://www.apache.org/licenses/LICENSE-2.0
  6089. *
  6090. * Unless required by applicable law or agreed to in writing, software
  6091. * distributed under the License is distributed on an "AS IS" BASIS,
  6092. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6093. * See the License for the specific language governing permissions and
  6094. * limitations under the License.
  6095. */
  6096. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  6097. var _a;
  6098. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  6099. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  6100. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  6101. request.continueUrl = actionCodeSettings.url;
  6102. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  6103. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  6104. if (actionCodeSettings.iOS) {
  6105. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  6106. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  6107. }
  6108. if (actionCodeSettings.android) {
  6109. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  6110. request.androidInstallApp = actionCodeSettings.android.installApp;
  6111. request.androidMinimumVersionCode =
  6112. actionCodeSettings.android.minimumVersion;
  6113. request.androidPackageName = actionCodeSettings.android.packageName;
  6114. }
  6115. }
  6116. /**
  6117. * @license
  6118. * Copyright 2020 Google LLC
  6119. *
  6120. * Licensed under the Apache License, Version 2.0 (the "License");
  6121. * you may not use this file except in compliance with the License.
  6122. * You may obtain a copy of the License at
  6123. *
  6124. * http://www.apache.org/licenses/LICENSE-2.0
  6125. *
  6126. * Unless required by applicable law or agreed to in writing, software
  6127. * distributed under the License is distributed on an "AS IS" BASIS,
  6128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6129. * See the License for the specific language governing permissions and
  6130. * limitations under the License.
  6131. */
  6132. /**
  6133. * Sends a password reset email to the given email address.
  6134. *
  6135. * @remarks
  6136. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  6137. * the email sent to the user, along with the new password specified by the user.
  6138. *
  6139. * @example
  6140. * ```javascript
  6141. * const actionCodeSettings = {
  6142. * url: 'https://www.example.com/?email=user@example.com',
  6143. * iOS: {
  6144. * bundleId: 'com.example.ios'
  6145. * },
  6146. * android: {
  6147. * packageName: 'com.example.android',
  6148. * installApp: true,
  6149. * minimumVersion: '12'
  6150. * },
  6151. * handleCodeInApp: true
  6152. * };
  6153. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  6154. * // Obtain code from user.
  6155. * await confirmPasswordReset('user@example.com', code);
  6156. * ```
  6157. *
  6158. * @param auth - The {@link Auth} instance.
  6159. * @param email - The user's email address.
  6160. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6161. *
  6162. * @public
  6163. */
  6164. function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  6165. var _a;
  6166. return __awaiter(this, void 0, void 0, function () {
  6167. var authInternal, request, requestWithRecaptcha;
  6168. var _this = this;
  6169. return __generator(this, function (_b) {
  6170. switch (_b.label) {
  6171. case 0:
  6172. authInternal = _castAuth(auth);
  6173. request = {
  6174. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  6175. email: email,
  6176. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6177. };
  6178. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  6179. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6180. case 1:
  6181. requestWithRecaptcha = _b.sent();
  6182. if (actionCodeSettings) {
  6183. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  6184. }
  6185. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  6186. case 2:
  6187. _b.sent();
  6188. return [3 /*break*/, 5];
  6189. case 3:
  6190. if (actionCodeSettings) {
  6191. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  6192. }
  6193. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, request)
  6194. .catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  6195. var requestWithRecaptcha;
  6196. return __generator(this, function (_a) {
  6197. switch (_a.label) {
  6198. case 0:
  6199. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  6200. console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');
  6201. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6202. case 1:
  6203. requestWithRecaptcha = _a.sent();
  6204. if (actionCodeSettings) {
  6205. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  6206. }
  6207. return [4 /*yield*/, sendPasswordResetEmail$1(authInternal, requestWithRecaptcha)];
  6208. case 2:
  6209. _a.sent();
  6210. return [3 /*break*/, 4];
  6211. case 3: return [2 /*return*/, Promise.reject(error)];
  6212. case 4: return [2 /*return*/];
  6213. }
  6214. });
  6215. }); })];
  6216. case 4:
  6217. _b.sent();
  6218. _b.label = 5;
  6219. case 5: return [2 /*return*/];
  6220. }
  6221. });
  6222. });
  6223. }
  6224. /**
  6225. * Completes the password reset process, given a confirmation code and new password.
  6226. *
  6227. * @param auth - The {@link Auth} instance.
  6228. * @param oobCode - A confirmation code sent to the user.
  6229. * @param newPassword - The new password.
  6230. *
  6231. * @public
  6232. */
  6233. function confirmPasswordReset(auth, oobCode, newPassword) {
  6234. return __awaiter(this, void 0, void 0, function () {
  6235. return __generator(this, function (_a) {
  6236. switch (_a.label) {
  6237. case 0: return [4 /*yield*/, resetPassword(getModularInstance(auth), {
  6238. oobCode: oobCode,
  6239. newPassword: newPassword
  6240. })];
  6241. case 1:
  6242. _a.sent();
  6243. return [2 /*return*/];
  6244. }
  6245. });
  6246. });
  6247. }
  6248. /**
  6249. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  6250. *
  6251. * @param auth - The {@link Auth} instance.
  6252. * @param oobCode - A verification code sent to the user.
  6253. *
  6254. * @public
  6255. */
  6256. function applyActionCode(auth, oobCode) {
  6257. return __awaiter(this, void 0, void 0, function () {
  6258. return __generator(this, function (_a) {
  6259. switch (_a.label) {
  6260. case 0: return [4 /*yield*/, applyActionCode$1(getModularInstance(auth), { oobCode: oobCode })];
  6261. case 1:
  6262. _a.sent();
  6263. return [2 /*return*/];
  6264. }
  6265. });
  6266. });
  6267. }
  6268. /**
  6269. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  6270. *
  6271. * @returns metadata about the code.
  6272. *
  6273. * @param auth - The {@link Auth} instance.
  6274. * @param oobCode - A verification code sent to the user.
  6275. *
  6276. * @public
  6277. */
  6278. function checkActionCode(auth, oobCode) {
  6279. return __awaiter(this, void 0, void 0, function () {
  6280. var authModular, response, operation, multiFactorInfo;
  6281. return __generator(this, function (_a) {
  6282. switch (_a.label) {
  6283. case 0:
  6284. authModular = getModularInstance(auth);
  6285. return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
  6286. case 1:
  6287. response = _a.sent();
  6288. operation = response.requestType;
  6289. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6290. switch (operation) {
  6291. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  6292. break;
  6293. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  6294. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6295. break;
  6296. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  6297. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6298. // fall through
  6299. default:
  6300. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6301. }
  6302. multiFactorInfo = null;
  6303. if (response.mfaInfo) {
  6304. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  6305. }
  6306. return [2 /*return*/, {
  6307. data: {
  6308. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  6309. ? response.newEmail
  6310. : response.email) || null,
  6311. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  6312. ? response.email
  6313. : response.newEmail) || null,
  6314. multiFactorInfo: multiFactorInfo
  6315. },
  6316. operation: operation
  6317. }];
  6318. }
  6319. });
  6320. });
  6321. }
  6322. /**
  6323. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  6324. *
  6325. * @returns the user's email address if valid.
  6326. *
  6327. * @param auth - The {@link Auth} instance.
  6328. * @param code - A verification code sent to the user.
  6329. *
  6330. * @public
  6331. */
  6332. function verifyPasswordResetCode(auth, code) {
  6333. return __awaiter(this, void 0, void 0, function () {
  6334. var data;
  6335. return __generator(this, function (_a) {
  6336. switch (_a.label) {
  6337. case 0: return [4 /*yield*/, checkActionCode(getModularInstance(auth), code)];
  6338. case 1:
  6339. data = (_a.sent()).data;
  6340. // Email should always be present since a code was sent to it
  6341. return [2 /*return*/, data.email];
  6342. }
  6343. });
  6344. });
  6345. }
  6346. /**
  6347. * Creates a new user account associated with the specified email address and password.
  6348. *
  6349. * @remarks
  6350. * On successful creation of the user account, this user will also be signed in to your application.
  6351. *
  6352. * User account creation can fail if the account already exists or the password is invalid.
  6353. *
  6354. * Note: The email address acts as a unique identifier for the user and enables an email-based
  6355. * password reset. This function will create a new user account and set the initial user password.
  6356. *
  6357. * @param auth - The {@link Auth} instance.
  6358. * @param email - The user's email address.
  6359. * @param password - The user's chosen password.
  6360. *
  6361. * @public
  6362. */
  6363. function createUserWithEmailAndPassword(auth, email, password) {
  6364. var _a;
  6365. return __awaiter(this, void 0, void 0, function () {
  6366. var authInternal, request, signUpResponse, requestWithRecaptcha, response, userCredential;
  6367. var _this = this;
  6368. return __generator(this, function (_b) {
  6369. switch (_b.label) {
  6370. case 0:
  6371. authInternal = _castAuth(auth);
  6372. request = {
  6373. returnSecureToken: true,
  6374. email: email,
  6375. password: password,
  6376. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6377. };
  6378. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 2];
  6379. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  6380. case 1:
  6381. requestWithRecaptcha = _b.sent();
  6382. signUpResponse = signUp(authInternal, requestWithRecaptcha);
  6383. return [3 /*break*/, 3];
  6384. case 2:
  6385. signUpResponse = signUp(authInternal, request).catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  6386. var requestWithRecaptcha;
  6387. return __generator(this, function (_a) {
  6388. switch (_a.label) {
  6389. case 0:
  6390. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 2];
  6391. console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');
  6392. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */)];
  6393. case 1:
  6394. requestWithRecaptcha = _a.sent();
  6395. return [2 /*return*/, signUp(authInternal, requestWithRecaptcha)];
  6396. case 2: return [2 /*return*/, Promise.reject(error)];
  6397. }
  6398. });
  6399. }); });
  6400. _b.label = 3;
  6401. case 3: return [4 /*yield*/, signUpResponse.catch(function (error) {
  6402. return Promise.reject(error);
  6403. })];
  6404. case 4:
  6405. response = _b.sent();
  6406. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  6407. case 5:
  6408. userCredential = _b.sent();
  6409. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  6410. case 6:
  6411. _b.sent();
  6412. return [2 /*return*/, userCredential];
  6413. }
  6414. });
  6415. });
  6416. }
  6417. /**
  6418. * Asynchronously signs in using an email and password.
  6419. *
  6420. * @remarks
  6421. * Fails with an error if the email address and password do not match.
  6422. *
  6423. * Note: The user's password is NOT the password used to access the user's email account. The
  6424. * email address serves as a unique identifier for the user, and the password is used to access
  6425. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  6426. *
  6427. * @param auth - The {@link Auth} instance.
  6428. * @param email - The users email address.
  6429. * @param password - The users password.
  6430. *
  6431. * @public
  6432. */
  6433. function signInWithEmailAndPassword(auth, email, password) {
  6434. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  6435. }
  6436. /**
  6437. * @license
  6438. * Copyright 2020 Google LLC
  6439. *
  6440. * Licensed under the Apache License, Version 2.0 (the "License");
  6441. * you may not use this file except in compliance with the License.
  6442. * You may obtain a copy of the License at
  6443. *
  6444. * http://www.apache.org/licenses/LICENSE-2.0
  6445. *
  6446. * Unless required by applicable law or agreed to in writing, software
  6447. * distributed under the License is distributed on an "AS IS" BASIS,
  6448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6449. * See the License for the specific language governing permissions and
  6450. * limitations under the License.
  6451. */
  6452. /**
  6453. * Sends a sign-in email link to the user with the specified email.
  6454. *
  6455. * @remarks
  6456. * The sign-in operation has to always be completed in the app unlike other out of band email
  6457. * actions (password reset and email verifications). This is because, at the end of the flow,
  6458. * the user is expected to be signed in and their Auth state persisted within the app.
  6459. *
  6460. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  6461. * address and the email link supplied in the email sent to the user.
  6462. *
  6463. * @example
  6464. * ```javascript
  6465. * const actionCodeSettings = {
  6466. * url: 'https://www.example.com/?email=user@example.com',
  6467. * iOS: {
  6468. * bundleId: 'com.example.ios'
  6469. * },
  6470. * android: {
  6471. * packageName: 'com.example.android',
  6472. * installApp: true,
  6473. * minimumVersion: '12'
  6474. * },
  6475. * handleCodeInApp: true
  6476. * };
  6477. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  6478. * // Obtain emailLink from the user.
  6479. * if(isSignInWithEmailLink(auth, emailLink)) {
  6480. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  6481. * }
  6482. * ```
  6483. *
  6484. * @param authInternal - The {@link Auth} instance.
  6485. * @param email - The user's email address.
  6486. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6487. *
  6488. * @public
  6489. */
  6490. function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  6491. var _a;
  6492. return __awaiter(this, void 0, void 0, function () {
  6493. function setActionCodeSettings(request, actionCodeSettings) {
  6494. _assert(actionCodeSettings.handleCodeInApp, authInternal, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6495. if (actionCodeSettings) {
  6496. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  6497. }
  6498. }
  6499. var authInternal, request, requestWithRecaptcha;
  6500. var _this = this;
  6501. return __generator(this, function (_b) {
  6502. switch (_b.label) {
  6503. case 0:
  6504. authInternal = _castAuth(auth);
  6505. request = {
  6506. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  6507. email: email,
  6508. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  6509. };
  6510. if (!((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled)) return [3 /*break*/, 3];
  6511. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6512. case 1:
  6513. requestWithRecaptcha = _b.sent();
  6514. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  6515. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  6516. case 2:
  6517. _b.sent();
  6518. return [3 /*break*/, 5];
  6519. case 3:
  6520. setActionCodeSettings(request, actionCodeSettings);
  6521. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, request)
  6522. .catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
  6523. var requestWithRecaptcha;
  6524. return __generator(this, function (_a) {
  6525. switch (_a.label) {
  6526. case 0:
  6527. if (!(error.code === "auth/".concat("missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */))) return [3 /*break*/, 3];
  6528. console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  6529. return [4 /*yield*/, injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true)];
  6530. case 1:
  6531. requestWithRecaptcha = _a.sent();
  6532. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  6533. return [4 /*yield*/, sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha)];
  6534. case 2:
  6535. _a.sent();
  6536. return [3 /*break*/, 4];
  6537. case 3: return [2 /*return*/, Promise.reject(error)];
  6538. case 4: return [2 /*return*/];
  6539. }
  6540. });
  6541. }); })];
  6542. case 4:
  6543. _b.sent();
  6544. _b.label = 5;
  6545. case 5: return [2 /*return*/];
  6546. }
  6547. });
  6548. });
  6549. }
  6550. /**
  6551. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  6552. *
  6553. * @param auth - The {@link Auth} instance.
  6554. * @param emailLink - The link sent to the user's email address.
  6555. *
  6556. * @public
  6557. */
  6558. function isSignInWithEmailLink(auth, emailLink) {
  6559. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  6560. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  6561. }
  6562. /**
  6563. * Asynchronously signs in using an email and sign-in email link.
  6564. *
  6565. * @remarks
  6566. * If no link is passed, the link is inferred from the current URL.
  6567. *
  6568. * Fails with an error if the email address is invalid or OTP in email link expires.
  6569. *
  6570. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  6571. *
  6572. * @example
  6573. * ```javascript
  6574. * const actionCodeSettings = {
  6575. * url: 'https://www.example.com/?email=user@example.com',
  6576. * iOS: {
  6577. * bundleId: 'com.example.ios'
  6578. * },
  6579. * android: {
  6580. * packageName: 'com.example.android',
  6581. * installApp: true,
  6582. * minimumVersion: '12'
  6583. * },
  6584. * handleCodeInApp: true
  6585. * };
  6586. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  6587. * // Obtain emailLink from the user.
  6588. * if(isSignInWithEmailLink(auth, emailLink)) {
  6589. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  6590. * }
  6591. * ```
  6592. *
  6593. * @param auth - The {@link Auth} instance.
  6594. * @param email - The user's email address.
  6595. * @param emailLink - The link sent to the user's email address.
  6596. *
  6597. * @public
  6598. */
  6599. function signInWithEmailLink(auth, email, emailLink) {
  6600. return __awaiter(this, void 0, void 0, function () {
  6601. var authModular, credential;
  6602. return __generator(this, function (_a) {
  6603. authModular = getModularInstance(auth);
  6604. credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  6605. // Check if the tenant ID in the email link matches the tenant ID on Auth
  6606. // instance.
  6607. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  6608. return [2 /*return*/, signInWithCredential(authModular, credential)];
  6609. });
  6610. });
  6611. }
  6612. /**
  6613. * @license
  6614. * Copyright 2020 Google LLC
  6615. *
  6616. * Licensed under the Apache License, Version 2.0 (the "License");
  6617. * you may not use this file except in compliance with the License.
  6618. * You may obtain a copy of the License at
  6619. *
  6620. * http://www.apache.org/licenses/LICENSE-2.0
  6621. *
  6622. * Unless required by applicable law or agreed to in writing, software
  6623. * distributed under the License is distributed on an "AS IS" BASIS,
  6624. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6625. * See the License for the specific language governing permissions and
  6626. * limitations under the License.
  6627. */
  6628. function createAuthUri(auth, request) {
  6629. return __awaiter(this, void 0, void 0, function () {
  6630. return __generator(this, function (_a) {
  6631. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
  6632. });
  6633. });
  6634. }
  6635. /**
  6636. * @license
  6637. * Copyright 2020 Google LLC
  6638. *
  6639. * Licensed under the Apache License, Version 2.0 (the "License");
  6640. * you may not use this file except in compliance with the License.
  6641. * You may obtain a copy of the License at
  6642. *
  6643. * http://www.apache.org/licenses/LICENSE-2.0
  6644. *
  6645. * Unless required by applicable law or agreed to in writing, software
  6646. * distributed under the License is distributed on an "AS IS" BASIS,
  6647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6648. * See the License for the specific language governing permissions and
  6649. * limitations under the License.
  6650. */
  6651. /**
  6652. * Gets the list of possible sign in methods for the given email address.
  6653. *
  6654. * @remarks
  6655. * This is useful to differentiate methods of sign-in for the same provider, eg.
  6656. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  6657. * {@link SignInMethod}.EMAIL_PASSWORD and
  6658. * {@link SignInMethod}.EMAIL_LINK.
  6659. *
  6660. * @param auth - The {@link Auth} instance.
  6661. * @param email - The user's email address.
  6662. *
  6663. * @public
  6664. */
  6665. function fetchSignInMethodsForEmail(auth, email) {
  6666. return __awaiter(this, void 0, void 0, function () {
  6667. var continueUri, request, signinMethods;
  6668. return __generator(this, function (_a) {
  6669. switch (_a.label) {
  6670. case 0:
  6671. continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  6672. request = {
  6673. identifier: email,
  6674. continueUri: continueUri
  6675. };
  6676. return [4 /*yield*/, createAuthUri(getModularInstance(auth), request)];
  6677. case 1:
  6678. signinMethods = (_a.sent()).signinMethods;
  6679. return [2 /*return*/, signinMethods || []];
  6680. }
  6681. });
  6682. });
  6683. }
  6684. /**
  6685. * Sends a verification email to a user.
  6686. *
  6687. * @remarks
  6688. * The verification process is completed by calling {@link applyActionCode}.
  6689. *
  6690. * @example
  6691. * ```javascript
  6692. * const actionCodeSettings = {
  6693. * url: 'https://www.example.com/?email=user@example.com',
  6694. * iOS: {
  6695. * bundleId: 'com.example.ios'
  6696. * },
  6697. * android: {
  6698. * packageName: 'com.example.android',
  6699. * installApp: true,
  6700. * minimumVersion: '12'
  6701. * },
  6702. * handleCodeInApp: true
  6703. * };
  6704. * await sendEmailVerification(user, actionCodeSettings);
  6705. * // Obtain code from the user.
  6706. * await applyActionCode(auth, code);
  6707. * ```
  6708. *
  6709. * @param user - The user.
  6710. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6711. *
  6712. * @public
  6713. */
  6714. function sendEmailVerification(user, actionCodeSettings) {
  6715. return __awaiter(this, void 0, void 0, function () {
  6716. var userInternal, idToken, request, email;
  6717. return __generator(this, function (_a) {
  6718. switch (_a.label) {
  6719. case 0:
  6720. userInternal = getModularInstance(user);
  6721. return [4 /*yield*/, user.getIdToken()];
  6722. case 1:
  6723. idToken = _a.sent();
  6724. request = {
  6725. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  6726. idToken: idToken
  6727. };
  6728. if (actionCodeSettings) {
  6729. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6730. }
  6731. return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
  6732. case 2:
  6733. email = (_a.sent()).email;
  6734. if (!(email !== user.email)) return [3 /*break*/, 4];
  6735. return [4 /*yield*/, user.reload()];
  6736. case 3:
  6737. _a.sent();
  6738. _a.label = 4;
  6739. case 4: return [2 /*return*/];
  6740. }
  6741. });
  6742. });
  6743. }
  6744. /**
  6745. * Sends a verification email to a new email address.
  6746. *
  6747. * @remarks
  6748. * The user's email will be updated to the new one after being verified.
  6749. *
  6750. * If you have a custom email action handler, you can complete the verification process by calling
  6751. * {@link applyActionCode}.
  6752. *
  6753. * @example
  6754. * ```javascript
  6755. * const actionCodeSettings = {
  6756. * url: 'https://www.example.com/?email=user@example.com',
  6757. * iOS: {
  6758. * bundleId: 'com.example.ios'
  6759. * },
  6760. * android: {
  6761. * packageName: 'com.example.android',
  6762. * installApp: true,
  6763. * minimumVersion: '12'
  6764. * },
  6765. * handleCodeInApp: true
  6766. * };
  6767. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  6768. * // Obtain code from the user.
  6769. * await applyActionCode(auth, code);
  6770. * ```
  6771. *
  6772. * @param user - The user.
  6773. * @param newEmail - The new email address to be verified before update.
  6774. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6775. *
  6776. * @public
  6777. */
  6778. function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  6779. return __awaiter(this, void 0, void 0, function () {
  6780. var userInternal, idToken, request, email;
  6781. return __generator(this, function (_a) {
  6782. switch (_a.label) {
  6783. case 0:
  6784. userInternal = getModularInstance(user);
  6785. return [4 /*yield*/, user.getIdToken()];
  6786. case 1:
  6787. idToken = _a.sent();
  6788. request = {
  6789. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  6790. idToken: idToken,
  6791. newEmail: newEmail
  6792. };
  6793. if (actionCodeSettings) {
  6794. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6795. }
  6796. return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
  6797. case 2:
  6798. email = (_a.sent()).email;
  6799. if (!(email !== user.email)) return [3 /*break*/, 4];
  6800. // If the local copy of the email on user is outdated, reload the
  6801. // user.
  6802. return [4 /*yield*/, user.reload()];
  6803. case 3:
  6804. // If the local copy of the email on user is outdated, reload the
  6805. // user.
  6806. _a.sent();
  6807. _a.label = 4;
  6808. case 4: return [2 /*return*/];
  6809. }
  6810. });
  6811. });
  6812. }
  6813. /**
  6814. * @license
  6815. * Copyright 2020 Google LLC
  6816. *
  6817. * Licensed under the Apache License, Version 2.0 (the "License");
  6818. * you may not use this file except in compliance with the License.
  6819. * You may obtain a copy of the License at
  6820. *
  6821. * http://www.apache.org/licenses/LICENSE-2.0
  6822. *
  6823. * Unless required by applicable law or agreed to in writing, software
  6824. * distributed under the License is distributed on an "AS IS" BASIS,
  6825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6826. * See the License for the specific language governing permissions and
  6827. * limitations under the License.
  6828. */
  6829. function updateProfile$1(auth, request) {
  6830. return __awaiter(this, void 0, void 0, function () {
  6831. return __generator(this, function (_a) {
  6832. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  6833. });
  6834. });
  6835. }
  6836. /**
  6837. * @license
  6838. * Copyright 2020 Google LLC
  6839. *
  6840. * Licensed under the Apache License, Version 2.0 (the "License");
  6841. * you may not use this file except in compliance with the License.
  6842. * You may obtain a copy of the License at
  6843. *
  6844. * http://www.apache.org/licenses/LICENSE-2.0
  6845. *
  6846. * Unless required by applicable law or agreed to in writing, software
  6847. * distributed under the License is distributed on an "AS IS" BASIS,
  6848. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6849. * See the License for the specific language governing permissions and
  6850. * limitations under the License.
  6851. */
  6852. /**
  6853. * Updates a user's profile data.
  6854. *
  6855. * @param user - The user.
  6856. * @param profile - The profile's `displayName` and `photoURL` to update.
  6857. *
  6858. * @public
  6859. */
  6860. function updateProfile(user, _a) {
  6861. var displayName = _a.displayName, photoUrl = _a.photoURL;
  6862. return __awaiter(this, void 0, void 0, function () {
  6863. var userInternal, idToken, profileRequest, response, passwordProvider;
  6864. return __generator(this, function (_b) {
  6865. switch (_b.label) {
  6866. case 0:
  6867. if (displayName === undefined && photoUrl === undefined) {
  6868. return [2 /*return*/];
  6869. }
  6870. userInternal = getModularInstance(user);
  6871. return [4 /*yield*/, userInternal.getIdToken()];
  6872. case 1:
  6873. idToken = _b.sent();
  6874. profileRequest = {
  6875. idToken: idToken,
  6876. displayName: displayName,
  6877. photoUrl: photoUrl,
  6878. returnSecureToken: true
  6879. };
  6880. return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
  6881. case 2:
  6882. response = _b.sent();
  6883. userInternal.displayName = response.displayName || null;
  6884. userInternal.photoURL = response.photoUrl || null;
  6885. passwordProvider = userInternal.providerData.find(function (_a) {
  6886. var providerId = _a.providerId;
  6887. return providerId === "password" /* ProviderId.PASSWORD */;
  6888. });
  6889. if (passwordProvider) {
  6890. passwordProvider.displayName = userInternal.displayName;
  6891. passwordProvider.photoURL = userInternal.photoURL;
  6892. }
  6893. return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
  6894. case 3:
  6895. _b.sent();
  6896. return [2 /*return*/];
  6897. }
  6898. });
  6899. });
  6900. }
  6901. /**
  6902. * Updates the user's email address.
  6903. *
  6904. * @remarks
  6905. * An email will be sent to the original email address (if it was set) that allows to revoke the
  6906. * email address change, in order to protect them from account hijacking.
  6907. *
  6908. * Important: this is a security sensitive operation that requires the user to have recently signed
  6909. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6910. * {@link reauthenticateWithCredential}.
  6911. *
  6912. * @param user - The user.
  6913. * @param newEmail - The new email address.
  6914. *
  6915. * @public
  6916. */
  6917. function updateEmail(user, newEmail) {
  6918. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  6919. }
  6920. /**
  6921. * Updates the user's password.
  6922. *
  6923. * @remarks
  6924. * Important: this is a security sensitive operation that requires the user to have recently signed
  6925. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6926. * {@link reauthenticateWithCredential}.
  6927. *
  6928. * @param user - The user.
  6929. * @param newPassword - The new password.
  6930. *
  6931. * @public
  6932. */
  6933. function updatePassword(user, newPassword) {
  6934. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  6935. }
  6936. function updateEmailOrPassword(user, email, password) {
  6937. return __awaiter(this, void 0, void 0, function () {
  6938. var auth, idToken, request, response;
  6939. return __generator(this, function (_a) {
  6940. switch (_a.label) {
  6941. case 0:
  6942. auth = user.auth;
  6943. return [4 /*yield*/, user.getIdToken()];
  6944. case 1:
  6945. idToken = _a.sent();
  6946. request = {
  6947. idToken: idToken,
  6948. returnSecureToken: true
  6949. };
  6950. if (email) {
  6951. request.email = email;
  6952. }
  6953. if (password) {
  6954. request.password = password;
  6955. }
  6956. return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
  6957. case 2:
  6958. response = _a.sent();
  6959. return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  6960. case 3:
  6961. _a.sent();
  6962. return [2 /*return*/];
  6963. }
  6964. });
  6965. });
  6966. }
  6967. /**
  6968. * @license
  6969. * Copyright 2019 Google LLC
  6970. *
  6971. * Licensed under the Apache License, Version 2.0 (the "License");
  6972. * you may not use this file except in compliance with the License.
  6973. * You may obtain a copy of the License at
  6974. *
  6975. * http://www.apache.org/licenses/LICENSE-2.0
  6976. *
  6977. * Unless required by applicable law or agreed to in writing, software
  6978. * distributed under the License is distributed on an "AS IS" BASIS,
  6979. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6980. * See the License for the specific language governing permissions and
  6981. * limitations under the License.
  6982. */
  6983. /**
  6984. * Parse the `AdditionalUserInfo` from the ID token response.
  6985. *
  6986. */
  6987. function _fromIdTokenResponse(idTokenResponse) {
  6988. var _a, _b;
  6989. if (!idTokenResponse) {
  6990. return null;
  6991. }
  6992. var providerId = idTokenResponse.providerId;
  6993. var profile = idTokenResponse.rawUserInfo
  6994. ? JSON.parse(idTokenResponse.rawUserInfo)
  6995. : {};
  6996. var isNewUser = idTokenResponse.isNewUser ||
  6997. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  6998. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  6999. 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'];
  7000. if (signInProvider) {
  7001. var filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  7002. signInProvider !== "custom" /* ProviderId.CUSTOM */
  7003. ? signInProvider
  7004. : null;
  7005. // Uses generic class in accordance with the legacy SDK.
  7006. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  7007. }
  7008. }
  7009. if (!providerId) {
  7010. return null;
  7011. }
  7012. switch (providerId) {
  7013. case "facebook.com" /* ProviderId.FACEBOOK */:
  7014. return new FacebookAdditionalUserInfo(isNewUser, profile);
  7015. case "github.com" /* ProviderId.GITHUB */:
  7016. return new GithubAdditionalUserInfo(isNewUser, profile);
  7017. case "google.com" /* ProviderId.GOOGLE */:
  7018. return new GoogleAdditionalUserInfo(isNewUser, profile);
  7019. case "twitter.com" /* ProviderId.TWITTER */:
  7020. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  7021. case "custom" /* ProviderId.CUSTOM */:
  7022. case "anonymous" /* ProviderId.ANONYMOUS */:
  7023. return new GenericAdditionalUserInfo(isNewUser, null);
  7024. default:
  7025. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  7026. }
  7027. }
  7028. var GenericAdditionalUserInfo = /** @class */ (function () {
  7029. function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
  7030. if (profile === void 0) { profile = {}; }
  7031. this.isNewUser = isNewUser;
  7032. this.providerId = providerId;
  7033. this.profile = profile;
  7034. }
  7035. return GenericAdditionalUserInfo;
  7036. }());
  7037. var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
  7038. __extends(FederatedAdditionalUserInfoWithUsername, _super);
  7039. function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
  7040. var _this = _super.call(this, isNewUser, providerId, profile) || this;
  7041. _this.username = username;
  7042. return _this;
  7043. }
  7044. return FederatedAdditionalUserInfoWithUsername;
  7045. }(GenericAdditionalUserInfo));
  7046. var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
  7047. __extends(FacebookAdditionalUserInfo, _super);
  7048. function FacebookAdditionalUserInfo(isNewUser, profile) {
  7049. return _super.call(this, isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile) || this;
  7050. }
  7051. return FacebookAdditionalUserInfo;
  7052. }(GenericAdditionalUserInfo));
  7053. var GithubAdditionalUserInfo = /** @class */ (function (_super) {
  7054. __extends(GithubAdditionalUserInfo, _super);
  7055. function GithubAdditionalUserInfo(isNewUser, profile) {
  7056. 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;
  7057. }
  7058. return GithubAdditionalUserInfo;
  7059. }(FederatedAdditionalUserInfoWithUsername));
  7060. var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
  7061. __extends(GoogleAdditionalUserInfo, _super);
  7062. function GoogleAdditionalUserInfo(isNewUser, profile) {
  7063. return _super.call(this, isNewUser, "google.com" /* ProviderId.GOOGLE */, profile) || this;
  7064. }
  7065. return GoogleAdditionalUserInfo;
  7066. }(GenericAdditionalUserInfo));
  7067. var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
  7068. __extends(TwitterAdditionalUserInfo, _super);
  7069. function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
  7070. return _super.call(this, isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName) || this;
  7071. }
  7072. return TwitterAdditionalUserInfo;
  7073. }(FederatedAdditionalUserInfoWithUsername));
  7074. /**
  7075. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  7076. *
  7077. * @param userCredential - The user credential.
  7078. *
  7079. * @public
  7080. */
  7081. function getAdditionalUserInfo(userCredential) {
  7082. var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
  7083. if (user.isAnonymous && !_tokenResponse) {
  7084. // Handle the special case where signInAnonymously() gets called twice.
  7085. // No network call is made so there's nothing to actually fill this in
  7086. return {
  7087. providerId: null,
  7088. isNewUser: false,
  7089. profile: null
  7090. };
  7091. }
  7092. return _fromIdTokenResponse(_tokenResponse);
  7093. }
  7094. /**
  7095. * @license
  7096. * Copyright 2020 Google LLC
  7097. *
  7098. * Licensed under the Apache License, Version 2.0 (the "License");
  7099. * you may not use this file except in compliance with the License.
  7100. * You may obtain a copy of the License at
  7101. *
  7102. * http://www.apache.org/licenses/LICENSE-2.0
  7103. *
  7104. * Unless required by applicable law or agreed to in writing, software
  7105. * distributed under the License is distributed on an "AS IS" BASIS,
  7106. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7107. * See the License for the specific language governing permissions and
  7108. * limitations under the License.
  7109. */
  7110. // Non-optional auth methods.
  7111. /**
  7112. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  7113. * `Auth` session and applies this type of persistence for future sign-in requests, including
  7114. * sign-in with redirect requests.
  7115. *
  7116. * @remarks
  7117. * This makes it easy for a user signing in to specify whether their session should be
  7118. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  7119. * that are shared by other users or have sensitive data.
  7120. *
  7121. * @example
  7122. * ```javascript
  7123. * setPersistence(auth, browserSessionPersistence);
  7124. * ```
  7125. *
  7126. * @param auth - The {@link Auth} instance.
  7127. * @param persistence - The {@link Persistence} to use.
  7128. * @returns A `Promise` that resolves once the persistence change has completed
  7129. *
  7130. * @public
  7131. */
  7132. function setPersistence(auth, persistence) {
  7133. return getModularInstance(auth).setPersistence(persistence);
  7134. }
  7135. /**
  7136. * Loads the reCAPTCHA configuration into the `Auth` instance.
  7137. *
  7138. * @remarks
  7139. * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA
  7140. * verification flow should be triggered for each auth provider, into the
  7141. * current Auth session.
  7142. *
  7143. * If initializeRecaptchaConfig() is not invoked, the auth flow will always start
  7144. * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA
  7145. * verification, the SDK will transparently load the reCAPTCHA config and restart the
  7146. * auth flows.
  7147. *
  7148. * Thus, by calling this optional method, you will reduce the latency of future auth flows.
  7149. * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.
  7150. *
  7151. * @example
  7152. * ```javascript
  7153. * initializeRecaptchaConfig(auth);
  7154. * ```
  7155. *
  7156. * @param auth - The {@link Auth} instance.
  7157. *
  7158. * @public
  7159. */
  7160. function initializeRecaptchaConfig(auth) {
  7161. var authInternal = _castAuth(auth);
  7162. return authInternal.initializeRecaptchaConfig();
  7163. }
  7164. /**
  7165. * Adds an observer for changes to the signed-in user's ID token.
  7166. *
  7167. * @remarks
  7168. * This includes sign-in, sign-out, and token refresh events.
  7169. * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.
  7170. *
  7171. * @param auth - The {@link Auth} instance.
  7172. * @param nextOrObserver - callback triggered on change.
  7173. * @param error - Deprecated. This callback is never triggered. Errors
  7174. * on signing in/out can be caught in promises returned from
  7175. * sign-in/sign-out functions.
  7176. * @param completed - Deprecated. This callback is never triggered.
  7177. *
  7178. * @public
  7179. */
  7180. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  7181. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  7182. }
  7183. /**
  7184. * Adds a blocking callback that runs before an auth state change
  7185. * sets a new user.
  7186. *
  7187. * @param auth - The {@link Auth} instance.
  7188. * @param callback - callback triggered before new user value is set.
  7189. * If this throws, it blocks the user from being set.
  7190. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  7191. * callback throws, allowing you to undo any side effects.
  7192. */
  7193. function beforeAuthStateChanged(auth, callback, onAbort) {
  7194. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  7195. }
  7196. /**
  7197. * Adds an observer for changes to the user's sign-in state.
  7198. *
  7199. * @remarks
  7200. * To keep the old behavior, see {@link onIdTokenChanged}.
  7201. *
  7202. * @param auth - The {@link Auth} instance.
  7203. * @param nextOrObserver - callback triggered on change.
  7204. * @param error - Deprecated. This callback is never triggered. Errors
  7205. * on signing in/out can be caught in promises returned from
  7206. * sign-in/sign-out functions.
  7207. * @param completed - Deprecated. This callback is never triggered.
  7208. *
  7209. * @public
  7210. */
  7211. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  7212. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  7213. }
  7214. /**
  7215. * Sets the current language to the default device/browser preference.
  7216. *
  7217. * @param auth - The {@link Auth} instance.
  7218. *
  7219. * @public
  7220. */
  7221. function useDeviceLanguage(auth) {
  7222. getModularInstance(auth).useDeviceLanguage();
  7223. }
  7224. /**
  7225. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  7226. * {@link Auth} instance.
  7227. *
  7228. * @remarks
  7229. * A new instance copy of the user provided will be made and set as currentUser.
  7230. *
  7231. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  7232. * like other sign in methods.
  7233. *
  7234. * The operation fails with an error if the user to be updated belongs to a different Firebase
  7235. * project.
  7236. *
  7237. * @param auth - The {@link Auth} instance.
  7238. * @param user - The new {@link User}.
  7239. *
  7240. * @public
  7241. */
  7242. function updateCurrentUser(auth, user) {
  7243. return getModularInstance(auth).updateCurrentUser(user);
  7244. }
  7245. /**
  7246. * Signs out the current user.
  7247. *
  7248. * @param auth - The {@link Auth} instance.
  7249. *
  7250. * @public
  7251. */
  7252. function signOut(auth) {
  7253. return getModularInstance(auth).signOut();
  7254. }
  7255. /**
  7256. * Deletes and signs out the user.
  7257. *
  7258. * @remarks
  7259. * Important: this is a security-sensitive operation that requires the user to have recently
  7260. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  7261. * {@link reauthenticateWithCredential}.
  7262. *
  7263. * @param user - The user.
  7264. *
  7265. * @public
  7266. */
  7267. function deleteUser(user) {
  7268. return __awaiter(this, void 0, void 0, function () {
  7269. return __generator(this, function (_a) {
  7270. return [2 /*return*/, getModularInstance(user).delete()];
  7271. });
  7272. });
  7273. }
  7274. var MultiFactorSessionImpl = /** @class */ (function () {
  7275. function MultiFactorSessionImpl(type, credential, auth) {
  7276. this.type = type;
  7277. this.credential = credential;
  7278. this.auth = auth;
  7279. }
  7280. MultiFactorSessionImpl._fromIdtoken = function (idToken, auth) {
  7281. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  7282. };
  7283. MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
  7284. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  7285. };
  7286. MultiFactorSessionImpl.prototype.toJSON = function () {
  7287. var _a;
  7288. var key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  7289. ? 'idToken'
  7290. : 'pendingCredential';
  7291. return {
  7292. multiFactorSession: (_a = {},
  7293. _a[key] = this.credential,
  7294. _a)
  7295. };
  7296. };
  7297. MultiFactorSessionImpl.fromJSON = function (obj) {
  7298. var _a, _b;
  7299. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  7300. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  7301. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  7302. }
  7303. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  7304. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  7305. }
  7306. }
  7307. return null;
  7308. };
  7309. return MultiFactorSessionImpl;
  7310. }());
  7311. /**
  7312. * @license
  7313. * Copyright 2020 Google LLC
  7314. *
  7315. * Licensed under the Apache License, Version 2.0 (the "License");
  7316. * you may not use this file except in compliance with the License.
  7317. * You may obtain a copy of the License at
  7318. *
  7319. * http://www.apache.org/licenses/LICENSE-2.0
  7320. *
  7321. * Unless required by applicable law or agreed to in writing, software
  7322. * distributed under the License is distributed on an "AS IS" BASIS,
  7323. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7324. * See the License for the specific language governing permissions and
  7325. * limitations under the License.
  7326. */
  7327. var MultiFactorResolverImpl = /** @class */ (function () {
  7328. function MultiFactorResolverImpl(session, hints, signInResolver) {
  7329. this.session = session;
  7330. this.hints = hints;
  7331. this.signInResolver = signInResolver;
  7332. }
  7333. /** @internal */
  7334. MultiFactorResolverImpl._fromError = function (authExtern, error) {
  7335. var _this = this;
  7336. var auth = _castAuth(authExtern);
  7337. var serverResponse = error.customData._serverResponse;
  7338. var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
  7339. return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  7340. });
  7341. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7342. var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  7343. return new MultiFactorResolverImpl(session, hints, function (assertion) { return __awaiter(_this, void 0, void 0, function () {
  7344. var mfaResponse, idTokenResponse, _a, userCredential;
  7345. return __generator(this, function (_b) {
  7346. switch (_b.label) {
  7347. case 0: return [4 /*yield*/, assertion._process(auth, session)];
  7348. case 1:
  7349. mfaResponse = _b.sent();
  7350. // Clear out the unneeded fields from the old login response
  7351. delete serverResponse.mfaInfo;
  7352. delete serverResponse.mfaPendingCredential;
  7353. idTokenResponse = __assign(__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  7354. _a = error.operationType;
  7355. switch (_a) {
  7356. case "signIn" /* OperationType.SIGN_IN */: return [3 /*break*/, 2];
  7357. case "reauthenticate" /* OperationType.REAUTHENTICATE */: return [3 /*break*/, 5];
  7358. }
  7359. return [3 /*break*/, 6];
  7360. case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
  7361. case 3:
  7362. userCredential = _b.sent();
  7363. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  7364. case 4:
  7365. _b.sent();
  7366. return [2 /*return*/, userCredential];
  7367. case 5:
  7368. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7369. return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
  7370. case 6:
  7371. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7372. _b.label = 7;
  7373. case 7: return [2 /*return*/];
  7374. }
  7375. });
  7376. }); });
  7377. };
  7378. MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
  7379. return __awaiter(this, void 0, void 0, function () {
  7380. var assertion;
  7381. return __generator(this, function (_a) {
  7382. assertion = assertionExtern;
  7383. return [2 /*return*/, this.signInResolver(assertion)];
  7384. });
  7385. });
  7386. };
  7387. return MultiFactorResolverImpl;
  7388. }());
  7389. /**
  7390. * Provides a {@link MultiFactorResolver} suitable for completion of a
  7391. * multi-factor flow.
  7392. *
  7393. * @param auth - The {@link Auth} instance.
  7394. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  7395. * reauthentication operation.
  7396. *
  7397. * @public
  7398. */
  7399. function getMultiFactorResolver(auth, error) {
  7400. var _a;
  7401. var authModular = getModularInstance(auth);
  7402. var errorInternal = error;
  7403. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7404. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7405. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  7406. }
  7407. /**
  7408. * @license
  7409. * Copyright 2020 Google LLC
  7410. *
  7411. * Licensed under the Apache License, Version 2.0 (the "License");
  7412. * you may not use this file except in compliance with the License.
  7413. * You may obtain a copy of the License at
  7414. *
  7415. * http://www.apache.org/licenses/LICENSE-2.0
  7416. *
  7417. * Unless required by applicable law or agreed to in writing, software
  7418. * distributed under the License is distributed on an "AS IS" BASIS,
  7419. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7420. * See the License for the specific language governing permissions and
  7421. * limitations under the License.
  7422. */
  7423. function startEnrollPhoneMfa(auth, request) {
  7424. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7425. }
  7426. function finalizeEnrollPhoneMfa(auth, request) {
  7427. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7428. }
  7429. function startEnrollTotpMfa(auth, request) {
  7430. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7431. }
  7432. function finalizeEnrollTotpMfa(auth, request) {
  7433. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  7434. }
  7435. function withdrawMfa(auth, request) {
  7436. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  7437. }
  7438. var MultiFactorUserImpl = /** @class */ (function () {
  7439. function MultiFactorUserImpl(user) {
  7440. var _this = this;
  7441. this.user = user;
  7442. this.enrolledFactors = [];
  7443. user._onReload(function (userInfo) {
  7444. if (userInfo.mfaInfo) {
  7445. _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
  7446. return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
  7447. });
  7448. }
  7449. });
  7450. }
  7451. MultiFactorUserImpl._fromUser = function (user) {
  7452. return new MultiFactorUserImpl(user);
  7453. };
  7454. MultiFactorUserImpl.prototype.getSession = function () {
  7455. return __awaiter(this, void 0, void 0, function () {
  7456. var _a, _b;
  7457. return __generator(this, function (_c) {
  7458. switch (_c.label) {
  7459. case 0:
  7460. _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
  7461. return [4 /*yield*/, this.user.getIdToken()];
  7462. case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(), this.user.auth])];
  7463. }
  7464. });
  7465. });
  7466. };
  7467. MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
  7468. return __awaiter(this, void 0, void 0, function () {
  7469. var assertion, session, finalizeMfaResponse;
  7470. return __generator(this, function (_a) {
  7471. switch (_a.label) {
  7472. case 0:
  7473. assertion = assertionExtern;
  7474. return [4 /*yield*/, this.getSession()];
  7475. case 1:
  7476. session = (_a.sent());
  7477. return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
  7478. case 2:
  7479. finalizeMfaResponse = _a.sent();
  7480. // New tokens will be issued after enrollment of the new second factors.
  7481. // They need to be updated on the user.
  7482. return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
  7483. case 3:
  7484. // New tokens will be issued after enrollment of the new second factors.
  7485. // They need to be updated on the user.
  7486. _a.sent();
  7487. // The user needs to be reloaded to get the new multi-factor information
  7488. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  7489. // will be updated.
  7490. return [2 /*return*/, this.user.reload()];
  7491. }
  7492. });
  7493. });
  7494. };
  7495. MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
  7496. return __awaiter(this, void 0, void 0, function () {
  7497. var mfaEnrollmentId, idToken, idTokenResponse, e_1;
  7498. return __generator(this, function (_a) {
  7499. switch (_a.label) {
  7500. case 0:
  7501. mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  7502. return [4 /*yield*/, this.user.getIdToken()];
  7503. case 1:
  7504. idToken = _a.sent();
  7505. _a.label = 2;
  7506. case 2:
  7507. _a.trys.push([2, 6, , 7]);
  7508. return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  7509. idToken: idToken,
  7510. mfaEnrollmentId: mfaEnrollmentId
  7511. }))];
  7512. case 3:
  7513. idTokenResponse = _a.sent();
  7514. // Remove the second factor from the user's list.
  7515. this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
  7516. var uid = _a.uid;
  7517. return uid !== mfaEnrollmentId;
  7518. });
  7519. // Depending on whether the backend decided to revoke the user's session,
  7520. // the tokenResponse may be empty. If the tokens were not updated (and they
  7521. // are now invalid), reloading the user will discover this and invalidate
  7522. // the user's state accordingly.
  7523. return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
  7524. case 4:
  7525. // Depending on whether the backend decided to revoke the user's session,
  7526. // the tokenResponse may be empty. If the tokens were not updated (and they
  7527. // are now invalid), reloading the user will discover this and invalidate
  7528. // the user's state accordingly.
  7529. _a.sent();
  7530. return [4 /*yield*/, this.user.reload()];
  7531. case 5:
  7532. _a.sent();
  7533. return [3 /*break*/, 7];
  7534. case 6:
  7535. e_1 = _a.sent();
  7536. throw e_1;
  7537. case 7: return [2 /*return*/];
  7538. }
  7539. });
  7540. });
  7541. };
  7542. return MultiFactorUserImpl;
  7543. }());
  7544. var multiFactorUserCache = new WeakMap();
  7545. /**
  7546. * The {@link MultiFactorUser} corresponding to the user.
  7547. *
  7548. * @remarks
  7549. * This is used to access all multi-factor properties and operations related to the user.
  7550. *
  7551. * @param user - The user.
  7552. *
  7553. * @public
  7554. */
  7555. function multiFactor(user) {
  7556. var userModular = getModularInstance(user);
  7557. if (!multiFactorUserCache.has(userModular)) {
  7558. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  7559. }
  7560. return multiFactorUserCache.get(userModular);
  7561. }
  7562. var STORAGE_AVAILABLE_KEY = '__sak';
  7563. /**
  7564. * @license
  7565. * Copyright 2019 Google LLC
  7566. *
  7567. * Licensed under the Apache License, Version 2.0 (the "License");
  7568. * you may not use this file except in compliance with the License.
  7569. * You may obtain a copy of the License at
  7570. *
  7571. * http://www.apache.org/licenses/LICENSE-2.0
  7572. *
  7573. * Unless required by applicable law or agreed to in writing, software
  7574. * distributed under the License is distributed on an "AS IS" BASIS,
  7575. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7576. * See the License for the specific language governing permissions and
  7577. * limitations under the License.
  7578. */
  7579. // There are two different browser persistence types: local and session.
  7580. // Both have the same implementation but use a different underlying storage
  7581. // object.
  7582. var BrowserPersistenceClass = /** @class */ (function () {
  7583. function BrowserPersistenceClass(storageRetriever, type) {
  7584. this.storageRetriever = storageRetriever;
  7585. this.type = type;
  7586. }
  7587. BrowserPersistenceClass.prototype._isAvailable = function () {
  7588. try {
  7589. if (!this.storage) {
  7590. return Promise.resolve(false);
  7591. }
  7592. this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
  7593. this.storage.removeItem(STORAGE_AVAILABLE_KEY);
  7594. return Promise.resolve(true);
  7595. }
  7596. catch (_a) {
  7597. return Promise.resolve(false);
  7598. }
  7599. };
  7600. BrowserPersistenceClass.prototype._set = function (key, value) {
  7601. this.storage.setItem(key, JSON.stringify(value));
  7602. return Promise.resolve();
  7603. };
  7604. BrowserPersistenceClass.prototype._get = function (key) {
  7605. var json = this.storage.getItem(key);
  7606. return Promise.resolve(json ? JSON.parse(json) : null);
  7607. };
  7608. BrowserPersistenceClass.prototype._remove = function (key) {
  7609. this.storage.removeItem(key);
  7610. return Promise.resolve();
  7611. };
  7612. Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
  7613. get: function () {
  7614. return this.storageRetriever();
  7615. },
  7616. enumerable: false,
  7617. configurable: true
  7618. });
  7619. return BrowserPersistenceClass;
  7620. }());
  7621. /**
  7622. * @license
  7623. * Copyright 2020 Google LLC
  7624. *
  7625. * Licensed under the Apache License, Version 2.0 (the "License");
  7626. * you may not use this file except in compliance with the License.
  7627. * You may obtain a copy of the License at
  7628. *
  7629. * http://www.apache.org/licenses/LICENSE-2.0
  7630. *
  7631. * Unless required by applicable law or agreed to in writing, software
  7632. * distributed under the License is distributed on an "AS IS" BASIS,
  7633. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7634. * See the License for the specific language governing permissions and
  7635. * limitations under the License.
  7636. */
  7637. function _iframeCannotSyncWebStorage() {
  7638. var ua = getUA();
  7639. return _isSafari(ua) || _isIOS(ua);
  7640. }
  7641. // The polling period in case events are not supported
  7642. var _POLLING_INTERVAL_MS$1 = 1000;
  7643. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  7644. var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  7645. var BrowserLocalPersistence = /** @class */ (function (_super) {
  7646. __extends(BrowserLocalPersistence, _super);
  7647. function BrowserLocalPersistence() {
  7648. var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* PersistenceType.LOCAL */) || this;
  7649. _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
  7650. _this.listeners = {};
  7651. _this.localCache = {};
  7652. // setTimeout return value is platform specific
  7653. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7654. _this.pollTimer = null;
  7655. // Safari or iOS browser and embedded in an iframe.
  7656. _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
  7657. // Whether to use polling instead of depending on window events
  7658. _this.fallbackToPolling = _isMobileBrowser();
  7659. _this._shouldAllowMigration = true;
  7660. return _this;
  7661. }
  7662. BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
  7663. // Check all keys with listeners on them.
  7664. for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
  7665. var key = _a[_i];
  7666. // Get value from localStorage.
  7667. var newValue = this.storage.getItem(key);
  7668. var oldValue = this.localCache[key];
  7669. // If local map value does not match, trigger listener with storage event.
  7670. // Differentiate this simulated event from the real storage event.
  7671. if (newValue !== oldValue) {
  7672. cb(key, oldValue, newValue);
  7673. }
  7674. }
  7675. };
  7676. BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
  7677. var _this = this;
  7678. if (poll === void 0) { poll = false; }
  7679. // Key would be null in some situations, like when localStorage is cleared
  7680. if (!event.key) {
  7681. this.forAllChangedKeys(function (key, _oldValue, newValue) {
  7682. _this.notifyListeners(key, newValue);
  7683. });
  7684. return;
  7685. }
  7686. var key = event.key;
  7687. // Check the mechanism how this event was detected.
  7688. // The first event will dictate the mechanism to be used.
  7689. if (poll) {
  7690. // Environment detects storage changes via polling.
  7691. // Remove storage event listener to prevent possible event duplication.
  7692. this.detachListener();
  7693. }
  7694. else {
  7695. // Environment detects storage changes via storage event listener.
  7696. // Remove polling listener to prevent possible event duplication.
  7697. this.stopPolling();
  7698. }
  7699. // Safari embedded iframe. Storage event will trigger with the delta
  7700. // changes but no changes will be applied to the iframe localStorage.
  7701. if (this.safariLocalStorageNotSynced) {
  7702. // Get current iframe page value.
  7703. var storedValue_1 = this.storage.getItem(key);
  7704. // Value not synchronized, synchronize manually.
  7705. if (event.newValue !== storedValue_1) {
  7706. if (event.newValue !== null) {
  7707. // Value changed from current value.
  7708. this.storage.setItem(key, event.newValue);
  7709. }
  7710. else {
  7711. // Current value deleted.
  7712. this.storage.removeItem(key);
  7713. }
  7714. }
  7715. else if (this.localCache[key] === event.newValue && !poll) {
  7716. // Already detected and processed, do not trigger listeners again.
  7717. return;
  7718. }
  7719. }
  7720. var triggerListeners = function () {
  7721. // Keep local map up to date in case storage event is triggered before
  7722. // poll.
  7723. var storedValue = _this.storage.getItem(key);
  7724. if (!poll && _this.localCache[key] === storedValue) {
  7725. // Real storage event which has already been detected, do nothing.
  7726. // This seems to trigger in some IE browsers for some reason.
  7727. return;
  7728. }
  7729. _this.notifyListeners(key, storedValue);
  7730. };
  7731. var storedValue = this.storage.getItem(key);
  7732. if (_isIE10() &&
  7733. storedValue !== event.newValue &&
  7734. event.newValue !== event.oldValue) {
  7735. // IE 10 has this weird bug where a storage event would trigger with the
  7736. // correct key, oldValue and newValue but localStorage.getItem(key) does
  7737. // not yield the updated value until a few milliseconds. This ensures
  7738. // this recovers from that situation.
  7739. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  7740. }
  7741. else {
  7742. triggerListeners();
  7743. }
  7744. };
  7745. BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
  7746. this.localCache[key] = value;
  7747. var listeners = this.listeners[key];
  7748. if (listeners) {
  7749. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  7750. var listener = _a[_i];
  7751. listener(value ? JSON.parse(value) : value);
  7752. }
  7753. }
  7754. };
  7755. BrowserLocalPersistence.prototype.startPolling = function () {
  7756. var _this = this;
  7757. this.stopPolling();
  7758. this.pollTimer = setInterval(function () {
  7759. _this.forAllChangedKeys(function (key, oldValue, newValue) {
  7760. _this.onStorageEvent(new StorageEvent('storage', {
  7761. key: key,
  7762. oldValue: oldValue,
  7763. newValue: newValue
  7764. }),
  7765. /* poll */ true);
  7766. });
  7767. }, _POLLING_INTERVAL_MS$1);
  7768. };
  7769. BrowserLocalPersistence.prototype.stopPolling = function () {
  7770. if (this.pollTimer) {
  7771. clearInterval(this.pollTimer);
  7772. this.pollTimer = null;
  7773. }
  7774. };
  7775. BrowserLocalPersistence.prototype.attachListener = function () {
  7776. window.addEventListener('storage', this.boundEventHandler);
  7777. };
  7778. BrowserLocalPersistence.prototype.detachListener = function () {
  7779. window.removeEventListener('storage', this.boundEventHandler);
  7780. };
  7781. BrowserLocalPersistence.prototype._addListener = function (key, listener) {
  7782. if (Object.keys(this.listeners).length === 0) {
  7783. // Whether browser can detect storage event when it had already been pushed to the background.
  7784. // This may happen in some mobile browsers. A localStorage change in the foreground window
  7785. // will not be detected in the background window via the storage event.
  7786. // This was detected in iOS 7.x mobile browsers
  7787. if (this.fallbackToPolling) {
  7788. this.startPolling();
  7789. }
  7790. else {
  7791. this.attachListener();
  7792. }
  7793. }
  7794. if (!this.listeners[key]) {
  7795. this.listeners[key] = new Set();
  7796. // Populate the cache to avoid spuriously triggering on first poll.
  7797. this.localCache[key] = this.storage.getItem(key);
  7798. }
  7799. this.listeners[key].add(listener);
  7800. };
  7801. BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
  7802. if (this.listeners[key]) {
  7803. this.listeners[key].delete(listener);
  7804. if (this.listeners[key].size === 0) {
  7805. delete this.listeners[key];
  7806. }
  7807. }
  7808. if (Object.keys(this.listeners).length === 0) {
  7809. this.detachListener();
  7810. this.stopPolling();
  7811. }
  7812. };
  7813. // Update local cache on base operations:
  7814. BrowserLocalPersistence.prototype._set = function (key, value) {
  7815. return __awaiter(this, void 0, void 0, function () {
  7816. return __generator(this, function (_a) {
  7817. switch (_a.label) {
  7818. case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
  7819. case 1:
  7820. _a.sent();
  7821. this.localCache[key] = JSON.stringify(value);
  7822. return [2 /*return*/];
  7823. }
  7824. });
  7825. });
  7826. };
  7827. BrowserLocalPersistence.prototype._get = function (key) {
  7828. return __awaiter(this, void 0, void 0, function () {
  7829. var value;
  7830. return __generator(this, function (_a) {
  7831. switch (_a.label) {
  7832. case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
  7833. case 1:
  7834. value = _a.sent();
  7835. this.localCache[key] = JSON.stringify(value);
  7836. return [2 /*return*/, value];
  7837. }
  7838. });
  7839. });
  7840. };
  7841. BrowserLocalPersistence.prototype._remove = function (key) {
  7842. return __awaiter(this, void 0, void 0, function () {
  7843. return __generator(this, function (_a) {
  7844. switch (_a.label) {
  7845. case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
  7846. case 1:
  7847. _a.sent();
  7848. delete this.localCache[key];
  7849. return [2 /*return*/];
  7850. }
  7851. });
  7852. });
  7853. };
  7854. BrowserLocalPersistence.type = 'LOCAL';
  7855. return BrowserLocalPersistence;
  7856. }(BrowserPersistenceClass));
  7857. /**
  7858. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  7859. * for the underlying storage.
  7860. *
  7861. * @public
  7862. */
  7863. var browserLocalPersistence = BrowserLocalPersistence;
  7864. /**
  7865. * @license
  7866. * Copyright 2020 Google LLC
  7867. *
  7868. * Licensed under the Apache License, Version 2.0 (the "License");
  7869. * you may not use this file except in compliance with the License.
  7870. * You may obtain a copy of the License at
  7871. *
  7872. * http://www.apache.org/licenses/LICENSE-2.0
  7873. *
  7874. * Unless required by applicable law or agreed to in writing, software
  7875. * distributed under the License is distributed on an "AS IS" BASIS,
  7876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7877. * See the License for the specific language governing permissions and
  7878. * limitations under the License.
  7879. */
  7880. var BrowserSessionPersistence = /** @class */ (function (_super) {
  7881. __extends(BrowserSessionPersistence, _super);
  7882. function BrowserSessionPersistence() {
  7883. return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* PersistenceType.SESSION */) || this;
  7884. }
  7885. BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
  7886. // Listeners are not supported for session storage since it cannot be shared across windows
  7887. return;
  7888. };
  7889. BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
  7890. // Listeners are not supported for session storage since it cannot be shared across windows
  7891. return;
  7892. };
  7893. BrowserSessionPersistence.type = 'SESSION';
  7894. return BrowserSessionPersistence;
  7895. }(BrowserPersistenceClass));
  7896. /**
  7897. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  7898. * for the underlying storage.
  7899. *
  7900. * @public
  7901. */
  7902. var browserSessionPersistence = BrowserSessionPersistence;
  7903. /**
  7904. * @license
  7905. * Copyright 2019 Google LLC
  7906. *
  7907. * Licensed under the Apache License, Version 2.0 (the "License");
  7908. * you may not use this file except in compliance with the License.
  7909. * You may obtain a copy of the License at
  7910. *
  7911. * http://www.apache.org/licenses/LICENSE-2.0
  7912. *
  7913. * Unless required by applicable law or agreed to in writing, software
  7914. * distributed under the License is distributed on an "AS IS" BASIS,
  7915. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7916. * See the License for the specific language governing permissions and
  7917. * limitations under the License.
  7918. */
  7919. /**
  7920. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  7921. *
  7922. * @param promises - Array of promises to wait on.
  7923. */
  7924. function _allSettled(promises) {
  7925. var _this = this;
  7926. return Promise.all(promises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
  7927. var value, reason_1;
  7928. return __generator(this, function (_a) {
  7929. switch (_a.label) {
  7930. case 0:
  7931. _a.trys.push([0, 2, , 3]);
  7932. return [4 /*yield*/, promise];
  7933. case 1:
  7934. value = _a.sent();
  7935. return [2 /*return*/, {
  7936. fulfilled: true,
  7937. value: value
  7938. }];
  7939. case 2:
  7940. reason_1 = _a.sent();
  7941. return [2 /*return*/, {
  7942. fulfilled: false,
  7943. reason: reason_1
  7944. }];
  7945. case 3: return [2 /*return*/];
  7946. }
  7947. });
  7948. }); }));
  7949. }
  7950. /**
  7951. * @license
  7952. * Copyright 2019 Google LLC
  7953. *
  7954. * Licensed under the Apache License, Version 2.0 (the "License");
  7955. * you may not use this file except in compliance with the License.
  7956. * You may obtain a copy of the License at
  7957. *
  7958. * http://www.apache.org/licenses/LICENSE-2.0
  7959. *
  7960. * Unless required by applicable law or agreed to in writing, software
  7961. * distributed under the License is distributed on an "AS IS" BASIS,
  7962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7963. * See the License for the specific language governing permissions and
  7964. * limitations under the License.
  7965. */
  7966. /**
  7967. * Interface class for receiving messages.
  7968. *
  7969. */
  7970. var Receiver = /** @class */ (function () {
  7971. function Receiver(eventTarget) {
  7972. this.eventTarget = eventTarget;
  7973. this.handlersMap = {};
  7974. this.boundEventHandler = this.handleEvent.bind(this);
  7975. }
  7976. /**
  7977. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  7978. *
  7979. * @param eventTarget - An event target (such as window or self) through which the underlying
  7980. * messages will be received.
  7981. */
  7982. Receiver._getInstance = function (eventTarget) {
  7983. // The results are stored in an array since objects can't be keys for other
  7984. // objects. In addition, setting a unique property on an event target as a
  7985. // hash map key may not be allowed due to CORS restrictions.
  7986. var existingInstance = this.receivers.find(function (receiver) {
  7987. return receiver.isListeningto(eventTarget);
  7988. });
  7989. if (existingInstance) {
  7990. return existingInstance;
  7991. }
  7992. var newInstance = new Receiver(eventTarget);
  7993. this.receivers.push(newInstance);
  7994. return newInstance;
  7995. };
  7996. Receiver.prototype.isListeningto = function (eventTarget) {
  7997. return this.eventTarget === eventTarget;
  7998. };
  7999. /**
  8000. * Fans out a MessageEvent to the appropriate listeners.
  8001. *
  8002. * @remarks
  8003. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  8004. * finished processing.
  8005. *
  8006. * @param event - The MessageEvent.
  8007. *
  8008. */
  8009. Receiver.prototype.handleEvent = function (event) {
  8010. return __awaiter(this, void 0, void 0, function () {
  8011. var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
  8012. var _this = this;
  8013. return __generator(this, function (_b) {
  8014. switch (_b.label) {
  8015. case 0:
  8016. messageEvent = event;
  8017. _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
  8018. handlers = this.handlersMap[eventType];
  8019. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  8020. return [2 /*return*/];
  8021. }
  8022. messageEvent.ports[0].postMessage({
  8023. status: "ack" /* _Status.ACK */,
  8024. eventId: eventId,
  8025. eventType: eventType
  8026. });
  8027. promises = Array.from(handlers).map(function (handler) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  8028. return [2 /*return*/, handler(messageEvent.origin, data)];
  8029. }); }); });
  8030. return [4 /*yield*/, _allSettled(promises)];
  8031. case 1:
  8032. response = _b.sent();
  8033. messageEvent.ports[0].postMessage({
  8034. status: "done" /* _Status.DONE */,
  8035. eventId: eventId,
  8036. eventType: eventType,
  8037. response: response
  8038. });
  8039. return [2 /*return*/];
  8040. }
  8041. });
  8042. });
  8043. };
  8044. /**
  8045. * Subscribe an event handler for a particular event.
  8046. *
  8047. * @param eventType - Event name to subscribe to.
  8048. * @param eventHandler - The event handler which should receive the events.
  8049. *
  8050. */
  8051. Receiver.prototype._subscribe = function (eventType, eventHandler) {
  8052. if (Object.keys(this.handlersMap).length === 0) {
  8053. this.eventTarget.addEventListener('message', this.boundEventHandler);
  8054. }
  8055. if (!this.handlersMap[eventType]) {
  8056. this.handlersMap[eventType] = new Set();
  8057. }
  8058. this.handlersMap[eventType].add(eventHandler);
  8059. };
  8060. /**
  8061. * Unsubscribe an event handler from a particular event.
  8062. *
  8063. * @param eventType - Event name to unsubscribe from.
  8064. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  8065. *
  8066. */
  8067. Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
  8068. if (this.handlersMap[eventType] && eventHandler) {
  8069. this.handlersMap[eventType].delete(eventHandler);
  8070. }
  8071. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  8072. delete this.handlersMap[eventType];
  8073. }
  8074. if (Object.keys(this.handlersMap).length === 0) {
  8075. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  8076. }
  8077. };
  8078. Receiver.receivers = [];
  8079. return Receiver;
  8080. }());
  8081. /**
  8082. * @license
  8083. * Copyright 2020 Google LLC
  8084. *
  8085. * Licensed under the Apache License, Version 2.0 (the "License");
  8086. * you may not use this file except in compliance with the License.
  8087. * You may obtain a copy of the License at
  8088. *
  8089. * http://www.apache.org/licenses/LICENSE-2.0
  8090. *
  8091. * Unless required by applicable law or agreed to in writing, software
  8092. * distributed under the License is distributed on an "AS IS" BASIS,
  8093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8094. * See the License for the specific language governing permissions and
  8095. * limitations under the License.
  8096. */
  8097. function _generateEventId(prefix, digits) {
  8098. if (prefix === void 0) { prefix = ''; }
  8099. if (digits === void 0) { digits = 10; }
  8100. var random = '';
  8101. for (var i = 0; i < digits; i++) {
  8102. random += Math.floor(Math.random() * 10);
  8103. }
  8104. return prefix + random;
  8105. }
  8106. /**
  8107. * @license
  8108. * Copyright 2019 Google LLC
  8109. *
  8110. * Licensed under the Apache License, Version 2.0 (the "License");
  8111. * you may not use this file except in compliance with the License.
  8112. * You may obtain a copy of the License at
  8113. *
  8114. * http://www.apache.org/licenses/LICENSE-2.0
  8115. *
  8116. * Unless required by applicable law or agreed to in writing, software
  8117. * distributed under the License is distributed on an "AS IS" BASIS,
  8118. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8119. * See the License for the specific language governing permissions and
  8120. * limitations under the License.
  8121. */
  8122. /**
  8123. * Interface for sending messages and waiting for a completion response.
  8124. *
  8125. */
  8126. var Sender = /** @class */ (function () {
  8127. function Sender(target) {
  8128. this.target = target;
  8129. this.handlers = new Set();
  8130. }
  8131. /**
  8132. * Unsubscribe the handler and remove it from our tracking Set.
  8133. *
  8134. * @param handler - The handler to unsubscribe.
  8135. */
  8136. Sender.prototype.removeMessageHandler = function (handler) {
  8137. if (handler.messageChannel) {
  8138. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  8139. handler.messageChannel.port1.close();
  8140. }
  8141. this.handlers.delete(handler);
  8142. };
  8143. /**
  8144. * Send a message to the Receiver located at {@link target}.
  8145. *
  8146. * @remarks
  8147. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  8148. * receiver has had a chance to fully process the event.
  8149. *
  8150. * @param eventType - Type of event to send.
  8151. * @param data - The payload of the event.
  8152. * @param timeout - Timeout for waiting on an ACK from the receiver.
  8153. *
  8154. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  8155. */
  8156. Sender.prototype._send = function (eventType, data, timeout) {
  8157. if (timeout === void 0) { timeout = 50 /* _TimeoutDuration.ACK */; }
  8158. return __awaiter(this, void 0, void 0, function () {
  8159. var messageChannel, completionTimer, handler;
  8160. var _this = this;
  8161. return __generator(this, function (_a) {
  8162. messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  8163. if (!messageChannel) {
  8164. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  8165. }
  8166. return [2 /*return*/, new Promise(function (resolve, reject) {
  8167. var eventId = _generateEventId('', 20);
  8168. messageChannel.port1.start();
  8169. var ackTimer = setTimeout(function () {
  8170. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  8171. }, timeout);
  8172. handler = {
  8173. messageChannel: messageChannel,
  8174. onMessage: function (event) {
  8175. var messageEvent = event;
  8176. if (messageEvent.data.eventId !== eventId) {
  8177. return;
  8178. }
  8179. switch (messageEvent.data.status) {
  8180. case "ack" /* _Status.ACK */:
  8181. // The receiver should ACK first.
  8182. clearTimeout(ackTimer);
  8183. completionTimer = setTimeout(function () {
  8184. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  8185. }, 3000 /* _TimeoutDuration.COMPLETION */);
  8186. break;
  8187. case "done" /* _Status.DONE */:
  8188. // Once the receiver's handlers are finished we will get the results.
  8189. clearTimeout(completionTimer);
  8190. resolve(messageEvent.data.response);
  8191. break;
  8192. default:
  8193. clearTimeout(ackTimer);
  8194. clearTimeout(completionTimer);
  8195. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  8196. break;
  8197. }
  8198. }
  8199. };
  8200. _this.handlers.add(handler);
  8201. messageChannel.port1.addEventListener('message', handler.onMessage);
  8202. _this.target.postMessage({
  8203. eventType: eventType,
  8204. eventId: eventId,
  8205. data: data
  8206. }, [messageChannel.port2]);
  8207. }).finally(function () {
  8208. if (handler) {
  8209. _this.removeMessageHandler(handler);
  8210. }
  8211. })];
  8212. });
  8213. });
  8214. };
  8215. return Sender;
  8216. }());
  8217. /**
  8218. * @license
  8219. * Copyright 2020 Google LLC
  8220. *
  8221. * Licensed under the Apache License, Version 2.0 (the "License");
  8222. * you may not use this file except in compliance with the License.
  8223. * You may obtain a copy of the License at
  8224. *
  8225. * http://www.apache.org/licenses/LICENSE-2.0
  8226. *
  8227. * Unless required by applicable law or agreed to in writing, software
  8228. * distributed under the License is distributed on an "AS IS" BASIS,
  8229. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8230. * See the License for the specific language governing permissions and
  8231. * limitations under the License.
  8232. */
  8233. /**
  8234. * Lazy accessor for window, since the compat layer won't tree shake this out,
  8235. * we need to make sure not to mess with window unless we have to
  8236. */
  8237. function _window() {
  8238. return window;
  8239. }
  8240. function _setWindowLocation(url) {
  8241. _window().location.href = url;
  8242. }
  8243. /**
  8244. * @license
  8245. * Copyright 2020 Google LLC.
  8246. *
  8247. * Licensed under the Apache License, Version 2.0 (the "License");
  8248. * you may not use this file except in compliance with the License.
  8249. * You may obtain a copy of the License at
  8250. *
  8251. * http://www.apache.org/licenses/LICENSE-2.0
  8252. *
  8253. * Unless required by applicable law or agreed to in writing, software
  8254. * distributed under the License is distributed on an "AS IS" BASIS,
  8255. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8256. * See the License for the specific language governing permissions and
  8257. * limitations under the License.
  8258. */
  8259. function _isWorker() {
  8260. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  8261. typeof _window()['importScripts'] === 'function');
  8262. }
  8263. function _getActiveServiceWorker() {
  8264. return __awaiter(this, void 0, void 0, function () {
  8265. var registration;
  8266. return __generator(this, function (_b) {
  8267. switch (_b.label) {
  8268. case 0:
  8269. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  8270. return [2 /*return*/, null];
  8271. }
  8272. _b.label = 1;
  8273. case 1:
  8274. _b.trys.push([1, 3, , 4]);
  8275. return [4 /*yield*/, navigator.serviceWorker.ready];
  8276. case 2:
  8277. registration = _b.sent();
  8278. return [2 /*return*/, registration.active];
  8279. case 3:
  8280. _b.sent();
  8281. return [2 /*return*/, null];
  8282. case 4: return [2 /*return*/];
  8283. }
  8284. });
  8285. });
  8286. }
  8287. function _getServiceWorkerController() {
  8288. var _a;
  8289. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  8290. }
  8291. function _getWorkerGlobalScope() {
  8292. return _isWorker() ? self : null;
  8293. }
  8294. /**
  8295. * @license
  8296. * Copyright 2019 Google LLC
  8297. *
  8298. * Licensed under the Apache License, Version 2.0 (the "License");
  8299. * you may not use this file except in compliance with the License.
  8300. * You may obtain a copy of the License at
  8301. *
  8302. * http://www.apache.org/licenses/LICENSE-2.0
  8303. *
  8304. * Unless required by applicable law or agreed to in writing, software
  8305. * distributed under the License is distributed on an "AS IS" BASIS,
  8306. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8307. * See the License for the specific language governing permissions and
  8308. * limitations under the License.
  8309. */
  8310. var DB_NAME = 'firebaseLocalStorageDb';
  8311. var DB_VERSION = 1;
  8312. var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  8313. var DB_DATA_KEYPATH = 'fbase_key';
  8314. /**
  8315. * Promise wrapper for IDBRequest
  8316. *
  8317. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  8318. *
  8319. */
  8320. var DBPromise = /** @class */ (function () {
  8321. function DBPromise(request) {
  8322. this.request = request;
  8323. }
  8324. DBPromise.prototype.toPromise = function () {
  8325. var _this = this;
  8326. return new Promise(function (resolve, reject) {
  8327. _this.request.addEventListener('success', function () {
  8328. resolve(_this.request.result);
  8329. });
  8330. _this.request.addEventListener('error', function () {
  8331. reject(_this.request.error);
  8332. });
  8333. });
  8334. };
  8335. return DBPromise;
  8336. }());
  8337. function getObjectStore(db, isReadWrite) {
  8338. return db
  8339. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  8340. .objectStore(DB_OBJECTSTORE_NAME);
  8341. }
  8342. function _deleteDatabase() {
  8343. var request = indexedDB.deleteDatabase(DB_NAME);
  8344. return new DBPromise(request).toPromise();
  8345. }
  8346. function _openDatabase() {
  8347. var _this = this;
  8348. var request = indexedDB.open(DB_NAME, DB_VERSION);
  8349. return new Promise(function (resolve, reject) {
  8350. request.addEventListener('error', function () {
  8351. reject(request.error);
  8352. });
  8353. request.addEventListener('upgradeneeded', function () {
  8354. var db = request.result;
  8355. try {
  8356. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  8357. }
  8358. catch (e) {
  8359. reject(e);
  8360. }
  8361. });
  8362. request.addEventListener('success', function () { return __awaiter(_this, void 0, void 0, function () {
  8363. var db, _a;
  8364. return __generator(this, function (_b) {
  8365. switch (_b.label) {
  8366. case 0:
  8367. db = request.result;
  8368. if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
  8369. // Need to close the database or else you get a `blocked` event
  8370. db.close();
  8371. return [4 /*yield*/, _deleteDatabase()];
  8372. case 1:
  8373. _b.sent();
  8374. _a = resolve;
  8375. return [4 /*yield*/, _openDatabase()];
  8376. case 2:
  8377. _a.apply(void 0, [_b.sent()]);
  8378. return [3 /*break*/, 4];
  8379. case 3:
  8380. resolve(db);
  8381. _b.label = 4;
  8382. case 4: return [2 /*return*/];
  8383. }
  8384. });
  8385. }); });
  8386. });
  8387. }
  8388. function _putObject(db, key, value) {
  8389. return __awaiter(this, void 0, void 0, function () {
  8390. var request;
  8391. var _a;
  8392. return __generator(this, function (_b) {
  8393. request = getObjectStore(db, true).put((_a = {},
  8394. _a[DB_DATA_KEYPATH] = key,
  8395. _a.value = value,
  8396. _a));
  8397. return [2 /*return*/, new DBPromise(request).toPromise()];
  8398. });
  8399. });
  8400. }
  8401. function getObject(db, key) {
  8402. return __awaiter(this, void 0, void 0, function () {
  8403. var request, data;
  8404. return __generator(this, function (_a) {
  8405. switch (_a.label) {
  8406. case 0:
  8407. request = getObjectStore(db, false).get(key);
  8408. return [4 /*yield*/, new DBPromise(request).toPromise()];
  8409. case 1:
  8410. data = _a.sent();
  8411. return [2 /*return*/, data === undefined ? null : data.value];
  8412. }
  8413. });
  8414. });
  8415. }
  8416. function _deleteObject(db, key) {
  8417. var request = getObjectStore(db, true).delete(key);
  8418. return new DBPromise(request).toPromise();
  8419. }
  8420. var _POLLING_INTERVAL_MS = 800;
  8421. var _TRANSACTION_RETRY_COUNT = 3;
  8422. var IndexedDBLocalPersistence = /** @class */ (function () {
  8423. function IndexedDBLocalPersistence() {
  8424. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  8425. this._shouldAllowMigration = true;
  8426. this.listeners = {};
  8427. this.localCache = {};
  8428. // setTimeout return value is platform specific
  8429. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8430. this.pollTimer = null;
  8431. this.pendingWrites = 0;
  8432. this.receiver = null;
  8433. this.sender = null;
  8434. this.serviceWorkerReceiverAvailable = false;
  8435. this.activeServiceWorker = null;
  8436. // Fire & forget the service worker registration as it may never resolve
  8437. this._workerInitializationPromise =
  8438. this.initializeServiceWorkerMessaging().then(function () { }, function () { });
  8439. }
  8440. IndexedDBLocalPersistence.prototype._openDb = function () {
  8441. return __awaiter(this, void 0, void 0, function () {
  8442. var _a;
  8443. return __generator(this, function (_b) {
  8444. switch (_b.label) {
  8445. case 0:
  8446. if (this.db) {
  8447. return [2 /*return*/, this.db];
  8448. }
  8449. _a = this;
  8450. return [4 /*yield*/, _openDatabase()];
  8451. case 1:
  8452. _a.db = _b.sent();
  8453. return [2 /*return*/, this.db];
  8454. }
  8455. });
  8456. });
  8457. };
  8458. IndexedDBLocalPersistence.prototype._withRetries = function (op) {
  8459. return __awaiter(this, void 0, void 0, function () {
  8460. var numAttempts, db, e_1;
  8461. return __generator(this, function (_a) {
  8462. switch (_a.label) {
  8463. case 0:
  8464. numAttempts = 0;
  8465. _a.label = 1;
  8466. case 1:
  8467. _a.label = 2;
  8468. case 2:
  8469. _a.trys.push([2, 5, , 6]);
  8470. return [4 /*yield*/, this._openDb()];
  8471. case 3:
  8472. db = _a.sent();
  8473. return [4 /*yield*/, op(db)];
  8474. case 4: return [2 /*return*/, _a.sent()];
  8475. case 5:
  8476. e_1 = _a.sent();
  8477. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  8478. throw e_1;
  8479. }
  8480. if (this.db) {
  8481. this.db.close();
  8482. this.db = undefined;
  8483. }
  8484. return [3 /*break*/, 6];
  8485. case 6: return [3 /*break*/, 1];
  8486. case 7: return [2 /*return*/];
  8487. }
  8488. });
  8489. });
  8490. };
  8491. /**
  8492. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  8493. * postMessage interface to send these events to the worker ourselves.
  8494. */
  8495. IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
  8496. return __awaiter(this, void 0, void 0, function () {
  8497. return __generator(this, function (_a) {
  8498. return [2 /*return*/, _isWorker() ? this.initializeReceiver() : this.initializeSender()];
  8499. });
  8500. });
  8501. };
  8502. /**
  8503. * As the worker we should listen to events from the main window.
  8504. */
  8505. IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
  8506. return __awaiter(this, void 0, void 0, function () {
  8507. var _this = this;
  8508. return __generator(this, function (_a) {
  8509. this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
  8510. // Refresh from persistence if we receive a KeyChanged message.
  8511. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, function (_origin, data) { return __awaiter(_this, void 0, void 0, function () {
  8512. var keys;
  8513. return __generator(this, function (_a) {
  8514. switch (_a.label) {
  8515. case 0: return [4 /*yield*/, this._poll()];
  8516. case 1:
  8517. keys = _a.sent();
  8518. return [2 /*return*/, {
  8519. keyProcessed: keys.includes(data.key)
  8520. }];
  8521. }
  8522. });
  8523. }); });
  8524. // Let the sender know that we are listening so they give us more timeout.
  8525. this.receiver._subscribe("ping" /* _EventType.PING */, function (_origin, _data) { return __awaiter(_this, void 0, void 0, function () {
  8526. return __generator(this, function (_a) {
  8527. return [2 /*return*/, ["keyChanged" /* _EventType.KEY_CHANGED */]];
  8528. });
  8529. }); });
  8530. return [2 /*return*/];
  8531. });
  8532. });
  8533. };
  8534. /**
  8535. * As the main window, we should let the worker know when keys change (set and remove).
  8536. *
  8537. * @remarks
  8538. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  8539. * may not resolve.
  8540. */
  8541. IndexedDBLocalPersistence.prototype.initializeSender = function () {
  8542. var _a, _b;
  8543. return __awaiter(this, void 0, void 0, function () {
  8544. var _c, results;
  8545. return __generator(this, function (_d) {
  8546. switch (_d.label) {
  8547. case 0:
  8548. // Check to see if there's an active service worker.
  8549. _c = this;
  8550. return [4 /*yield*/, _getActiveServiceWorker()];
  8551. case 1:
  8552. // Check to see if there's an active service worker.
  8553. _c.activeServiceWorker = _d.sent();
  8554. if (!this.activeServiceWorker) {
  8555. return [2 /*return*/];
  8556. }
  8557. this.sender = new Sender(this.activeServiceWorker);
  8558. return [4 /*yield*/, this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */)];
  8559. case 2:
  8560. results = _d.sent();
  8561. if (!results) {
  8562. return [2 /*return*/];
  8563. }
  8564. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  8565. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  8566. this.serviceWorkerReceiverAvailable = true;
  8567. }
  8568. return [2 /*return*/];
  8569. }
  8570. });
  8571. });
  8572. };
  8573. /**
  8574. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  8575. * worker will just trigger a full sync anyway.
  8576. *
  8577. * @remarks
  8578. * For now, we only support one service worker per page.
  8579. *
  8580. * @param key - Storage key which changed.
  8581. */
  8582. IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
  8583. return __awaiter(this, void 0, void 0, function () {
  8584. return __generator(this, function (_b) {
  8585. switch (_b.label) {
  8586. case 0:
  8587. if (!this.sender ||
  8588. !this.activeServiceWorker ||
  8589. _getServiceWorkerController() !== this.activeServiceWorker) {
  8590. return [2 /*return*/];
  8591. }
  8592. _b.label = 1;
  8593. case 1:
  8594. _b.trys.push([1, 3, , 4]);
  8595. return [4 /*yield*/, this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key: key },
  8596. // Use long timeout if receiver has previously responded to a ping from us.
  8597. this.serviceWorkerReceiverAvailable
  8598. ? 800 /* _TimeoutDuration.LONG_ACK */
  8599. : 50 /* _TimeoutDuration.ACK */)];
  8600. case 2:
  8601. _b.sent();
  8602. return [3 /*break*/, 4];
  8603. case 3:
  8604. _b.sent();
  8605. return [3 /*break*/, 4];
  8606. case 4: return [2 /*return*/];
  8607. }
  8608. });
  8609. });
  8610. };
  8611. IndexedDBLocalPersistence.prototype._isAvailable = function () {
  8612. return __awaiter(this, void 0, void 0, function () {
  8613. var db;
  8614. return __generator(this, function (_b) {
  8615. switch (_b.label) {
  8616. case 0:
  8617. _b.trys.push([0, 4, , 5]);
  8618. if (!indexedDB) {
  8619. return [2 /*return*/, false];
  8620. }
  8621. return [4 /*yield*/, _openDatabase()];
  8622. case 1:
  8623. db = _b.sent();
  8624. return [4 /*yield*/, _putObject(db, STORAGE_AVAILABLE_KEY, '1')];
  8625. case 2:
  8626. _b.sent();
  8627. return [4 /*yield*/, _deleteObject(db, STORAGE_AVAILABLE_KEY)];
  8628. case 3:
  8629. _b.sent();
  8630. return [2 /*return*/, true];
  8631. case 4:
  8632. _b.sent();
  8633. return [3 /*break*/, 5];
  8634. case 5: return [2 /*return*/, false];
  8635. }
  8636. });
  8637. });
  8638. };
  8639. IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
  8640. return __awaiter(this, void 0, void 0, function () {
  8641. return __generator(this, function (_a) {
  8642. switch (_a.label) {
  8643. case 0:
  8644. this.pendingWrites++;
  8645. _a.label = 1;
  8646. case 1:
  8647. _a.trys.push([1, , 3, 4]);
  8648. return [4 /*yield*/, write()];
  8649. case 2:
  8650. _a.sent();
  8651. return [3 /*break*/, 4];
  8652. case 3:
  8653. this.pendingWrites--;
  8654. return [7 /*endfinally*/];
  8655. case 4: return [2 /*return*/];
  8656. }
  8657. });
  8658. });
  8659. };
  8660. IndexedDBLocalPersistence.prototype._set = function (key, value) {
  8661. return __awaiter(this, void 0, void 0, function () {
  8662. var _this = this;
  8663. return __generator(this, function (_a) {
  8664. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  8665. return __generator(this, function (_a) {
  8666. switch (_a.label) {
  8667. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
  8668. case 1:
  8669. _a.sent();
  8670. this.localCache[key] = value;
  8671. return [2 /*return*/, this.notifyServiceWorker(key)];
  8672. }
  8673. });
  8674. }); })];
  8675. });
  8676. });
  8677. };
  8678. IndexedDBLocalPersistence.prototype._get = function (key) {
  8679. return __awaiter(this, void 0, void 0, function () {
  8680. var obj;
  8681. return __generator(this, function (_a) {
  8682. switch (_a.label) {
  8683. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  8684. return getObject(db, key);
  8685. })];
  8686. case 1:
  8687. obj = (_a.sent());
  8688. this.localCache[key] = obj;
  8689. return [2 /*return*/, obj];
  8690. }
  8691. });
  8692. });
  8693. };
  8694. IndexedDBLocalPersistence.prototype._remove = function (key) {
  8695. return __awaiter(this, void 0, void 0, function () {
  8696. var _this = this;
  8697. return __generator(this, function (_a) {
  8698. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  8699. return __generator(this, function (_a) {
  8700. switch (_a.label) {
  8701. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
  8702. case 1:
  8703. _a.sent();
  8704. delete this.localCache[key];
  8705. return [2 /*return*/, this.notifyServiceWorker(key)];
  8706. }
  8707. });
  8708. }); })];
  8709. });
  8710. });
  8711. };
  8712. IndexedDBLocalPersistence.prototype._poll = function () {
  8713. return __awaiter(this, void 0, void 0, function () {
  8714. var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
  8715. return __generator(this, function (_d) {
  8716. switch (_d.label) {
  8717. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  8718. var getAllRequest = getObjectStore(db, false).getAll();
  8719. return new DBPromise(getAllRequest).toPromise();
  8720. })];
  8721. case 1:
  8722. result = _d.sent();
  8723. if (!result) {
  8724. return [2 /*return*/, []];
  8725. }
  8726. // If we have pending writes in progress abort, we'll get picked up on the next poll
  8727. if (this.pendingWrites !== 0) {
  8728. return [2 /*return*/, []];
  8729. }
  8730. keys = [];
  8731. keysInResult = new Set();
  8732. for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
  8733. _a = result_1[_i], key = _a.fbase_key, value = _a.value;
  8734. keysInResult.add(key);
  8735. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  8736. this.notifyListeners(key, value);
  8737. keys.push(key);
  8738. }
  8739. }
  8740. for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
  8741. localKey = _c[_b];
  8742. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  8743. // Deleted
  8744. this.notifyListeners(localKey, null);
  8745. keys.push(localKey);
  8746. }
  8747. }
  8748. return [2 /*return*/, keys];
  8749. }
  8750. });
  8751. });
  8752. };
  8753. IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
  8754. this.localCache[key] = newValue;
  8755. var listeners = this.listeners[key];
  8756. if (listeners) {
  8757. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  8758. var listener = _a[_i];
  8759. listener(newValue);
  8760. }
  8761. }
  8762. };
  8763. IndexedDBLocalPersistence.prototype.startPolling = function () {
  8764. var _this = this;
  8765. this.stopPolling();
  8766. this.pollTimer = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  8767. return [2 /*return*/, this._poll()];
  8768. }); }); }, _POLLING_INTERVAL_MS);
  8769. };
  8770. IndexedDBLocalPersistence.prototype.stopPolling = function () {
  8771. if (this.pollTimer) {
  8772. clearInterval(this.pollTimer);
  8773. this.pollTimer = null;
  8774. }
  8775. };
  8776. IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
  8777. if (Object.keys(this.listeners).length === 0) {
  8778. this.startPolling();
  8779. }
  8780. if (!this.listeners[key]) {
  8781. this.listeners[key] = new Set();
  8782. // Populate the cache to avoid spuriously triggering on first poll.
  8783. void this._get(key); // This can happen in the background async and we can return immediately.
  8784. }
  8785. this.listeners[key].add(listener);
  8786. };
  8787. IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
  8788. if (this.listeners[key]) {
  8789. this.listeners[key].delete(listener);
  8790. if (this.listeners[key].size === 0) {
  8791. delete this.listeners[key];
  8792. }
  8793. }
  8794. if (Object.keys(this.listeners).length === 0) {
  8795. this.stopPolling();
  8796. }
  8797. };
  8798. IndexedDBLocalPersistence.type = 'LOCAL';
  8799. return IndexedDBLocalPersistence;
  8800. }());
  8801. /**
  8802. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  8803. * for the underlying storage.
  8804. *
  8805. * @public
  8806. */
  8807. var indexedDBLocalPersistence = IndexedDBLocalPersistence;
  8808. /**
  8809. * @license
  8810. * Copyright 2020 Google LLC
  8811. *
  8812. * Licensed under the Apache License, Version 2.0 (the "License");
  8813. * you may not use this file except in compliance with the License.
  8814. * You may obtain a copy of the License at
  8815. *
  8816. * http://www.apache.org/licenses/LICENSE-2.0
  8817. *
  8818. * Unless required by applicable law or agreed to in writing, software
  8819. * distributed under the License is distributed on an "AS IS" BASIS,
  8820. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8821. * See the License for the specific language governing permissions and
  8822. * limitations under the License.
  8823. */
  8824. function startSignInPhoneMfa(auth, request) {
  8825. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  8826. }
  8827. function finalizeSignInPhoneMfa(auth, request) {
  8828. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  8829. }
  8830. function finalizeSignInTotpMfa(auth, request) {
  8831. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  8832. }
  8833. /**
  8834. * @license
  8835. * Copyright 2020 Google LLC
  8836. *
  8837. * Licensed under the Apache License, Version 2.0 (the "License");
  8838. * you may not use this file except in compliance with the License.
  8839. * You may obtain a copy of the License at
  8840. *
  8841. * http://www.apache.org/licenses/LICENSE-2.0
  8842. *
  8843. * Unless required by applicable law or agreed to in writing, software
  8844. * distributed under the License is distributed on an "AS IS" BASIS,
  8845. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8846. * See the License for the specific language governing permissions and
  8847. * limitations under the License.
  8848. */
  8849. var _SOLVE_TIME_MS = 500;
  8850. var _EXPIRATION_TIME_MS = 60000;
  8851. var _WIDGET_ID_START = 1000000000000;
  8852. var MockReCaptcha = /** @class */ (function () {
  8853. function MockReCaptcha(auth) {
  8854. this.auth = auth;
  8855. this.counter = _WIDGET_ID_START;
  8856. this._widgets = new Map();
  8857. }
  8858. MockReCaptcha.prototype.render = function (container, parameters) {
  8859. var id = this.counter;
  8860. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  8861. this.counter++;
  8862. return id;
  8863. };
  8864. MockReCaptcha.prototype.reset = function (optWidgetId) {
  8865. var _a;
  8866. var id = optWidgetId || _WIDGET_ID_START;
  8867. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  8868. this._widgets.delete(id);
  8869. };
  8870. MockReCaptcha.prototype.getResponse = function (optWidgetId) {
  8871. var _a;
  8872. var id = optWidgetId || _WIDGET_ID_START;
  8873. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  8874. };
  8875. MockReCaptcha.prototype.execute = function (optWidgetId) {
  8876. var _a;
  8877. return __awaiter(this, void 0, void 0, function () {
  8878. var id;
  8879. return __generator(this, function (_b) {
  8880. id = optWidgetId || _WIDGET_ID_START;
  8881. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  8882. return [2 /*return*/, ''];
  8883. });
  8884. });
  8885. };
  8886. return MockReCaptcha;
  8887. }());
  8888. var MockWidget = /** @class */ (function () {
  8889. function MockWidget(containerOrId, appName, params) {
  8890. var _this = this;
  8891. this.params = params;
  8892. this.timerId = null;
  8893. this.deleted = false;
  8894. this.responseToken = null;
  8895. this.clickHandler = function () {
  8896. _this.execute();
  8897. };
  8898. var container = typeof containerOrId === 'string'
  8899. ? document.getElementById(containerOrId)
  8900. : containerOrId;
  8901. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName: appName });
  8902. this.container = container;
  8903. this.isVisible = this.params.size !== 'invisible';
  8904. if (this.isVisible) {
  8905. this.execute();
  8906. }
  8907. else {
  8908. this.container.addEventListener('click', this.clickHandler);
  8909. }
  8910. }
  8911. MockWidget.prototype.getResponse = function () {
  8912. this.checkIfDeleted();
  8913. return this.responseToken;
  8914. };
  8915. MockWidget.prototype.delete = function () {
  8916. this.checkIfDeleted();
  8917. this.deleted = true;
  8918. if (this.timerId) {
  8919. clearTimeout(this.timerId);
  8920. this.timerId = null;
  8921. }
  8922. this.container.removeEventListener('click', this.clickHandler);
  8923. };
  8924. MockWidget.prototype.execute = function () {
  8925. var _this = this;
  8926. this.checkIfDeleted();
  8927. if (this.timerId) {
  8928. return;
  8929. }
  8930. this.timerId = window.setTimeout(function () {
  8931. _this.responseToken = generateRandomAlphaNumericString(50);
  8932. var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
  8933. if (callback) {
  8934. try {
  8935. callback(_this.responseToken);
  8936. }
  8937. catch (e) { }
  8938. }
  8939. _this.timerId = window.setTimeout(function () {
  8940. _this.timerId = null;
  8941. _this.responseToken = null;
  8942. if (expiredCallback) {
  8943. try {
  8944. expiredCallback();
  8945. }
  8946. catch (e) { }
  8947. }
  8948. if (_this.isVisible) {
  8949. _this.execute();
  8950. }
  8951. }, _EXPIRATION_TIME_MS);
  8952. }, _SOLVE_TIME_MS);
  8953. };
  8954. MockWidget.prototype.checkIfDeleted = function () {
  8955. if (this.deleted) {
  8956. throw new Error('reCAPTCHA mock was already deleted!');
  8957. }
  8958. };
  8959. return MockWidget;
  8960. }());
  8961. function generateRandomAlphaNumericString(len) {
  8962. var chars = [];
  8963. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  8964. for (var i = 0; i < len; i++) {
  8965. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  8966. }
  8967. return chars.join('');
  8968. }
  8969. /**
  8970. * @license
  8971. * Copyright 2020 Google LLC
  8972. *
  8973. * Licensed under the Apache License, Version 2.0 (the "License");
  8974. * you may not use this file except in compliance with the License.
  8975. * You may obtain a copy of the License at
  8976. *
  8977. * http://www.apache.org/licenses/LICENSE-2.0
  8978. *
  8979. * Unless required by applicable law or agreed to in writing, software
  8980. * distributed under the License is distributed on an "AS IS" BASIS,
  8981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8982. * See the License for the specific language governing permissions and
  8983. * limitations under the License.
  8984. */
  8985. // ReCaptcha will load using the same callback, so the callback function needs
  8986. // to be kept around
  8987. var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  8988. var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  8989. var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  8990. /**
  8991. * Loader for the GReCaptcha library. There should only ever be one of this.
  8992. */
  8993. var ReCaptchaLoaderImpl = /** @class */ (function () {
  8994. function ReCaptchaLoaderImpl() {
  8995. var _a;
  8996. this.hostLanguage = '';
  8997. this.counter = 0;
  8998. /**
  8999. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  9000. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  9001. * `window.grecaptcha.render()` will not. Another load will add it.
  9002. */
  9003. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  9004. }
  9005. ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
  9006. var _this = this;
  9007. if (hl === void 0) { hl = ''; }
  9008. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9009. if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {
  9010. return Promise.resolve(_window().grecaptcha);
  9011. }
  9012. return new Promise(function (resolve, reject) {
  9013. var networkTimeout = _window().setTimeout(function () {
  9014. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  9015. }, NETWORK_TIMEOUT_DELAY.get());
  9016. _window()[_JSLOAD_CALLBACK] = function () {
  9017. _window().clearTimeout(networkTimeout);
  9018. delete _window()[_JSLOAD_CALLBACK];
  9019. var recaptcha = _window().grecaptcha;
  9020. if (!recaptcha || !isV2(recaptcha)) {
  9021. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  9022. return;
  9023. }
  9024. // Wrap the greptcha render function so that we know if the developer has
  9025. // called it separately
  9026. var render = recaptcha.render;
  9027. recaptcha.render = function (container, params) {
  9028. var widgetId = render(container, params);
  9029. _this.counter++;
  9030. return widgetId;
  9031. };
  9032. _this.hostLanguage = hl;
  9033. resolve(recaptcha);
  9034. };
  9035. var url = "".concat(RECAPTCHA_BASE, "?").concat(querystring({
  9036. onload: _JSLOAD_CALLBACK,
  9037. render: 'explicit',
  9038. hl: hl
  9039. }));
  9040. _loadJS(url).catch(function () {
  9041. clearTimeout(networkTimeout);
  9042. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  9043. });
  9044. });
  9045. };
  9046. ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
  9047. this.counter--;
  9048. };
  9049. ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
  9050. var _a;
  9051. // We can resolve immediately if:
  9052. // • grecaptcha is already defined AND (
  9053. // 1. the requested language codes are the same OR
  9054. // 2. there exists already a ReCaptcha on the page
  9055. // 3. the library was already loaded by the app
  9056. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  9057. // that are already in the page
  9058. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  9059. (hl === this.hostLanguage ||
  9060. this.counter > 0 ||
  9061. this.librarySeparatelyLoaded));
  9062. };
  9063. return ReCaptchaLoaderImpl;
  9064. }());
  9065. function isHostLanguageValid(hl) {
  9066. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  9067. }
  9068. var MockReCaptchaLoaderImpl = /** @class */ (function () {
  9069. function MockReCaptchaLoaderImpl() {
  9070. }
  9071. MockReCaptchaLoaderImpl.prototype.load = function (auth) {
  9072. return __awaiter(this, void 0, void 0, function () {
  9073. return __generator(this, function (_a) {
  9074. return [2 /*return*/, new MockReCaptcha(auth)];
  9075. });
  9076. });
  9077. };
  9078. MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
  9079. return MockReCaptchaLoaderImpl;
  9080. }());
  9081. /**
  9082. * @license
  9083. * Copyright 2020 Google LLC
  9084. *
  9085. * Licensed under the Apache License, Version 2.0 (the "License");
  9086. * you may not use this file except in compliance with the License.
  9087. * You may obtain a copy of the License at
  9088. *
  9089. * http://www.apache.org/licenses/LICENSE-2.0
  9090. *
  9091. * Unless required by applicable law or agreed to in writing, software
  9092. * distributed under the License is distributed on an "AS IS" BASIS,
  9093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9094. * See the License for the specific language governing permissions and
  9095. * limitations under the License.
  9096. */
  9097. var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  9098. var DEFAULT_PARAMS = {
  9099. theme: 'light',
  9100. type: 'image'
  9101. };
  9102. /**
  9103. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  9104. *
  9105. * @public
  9106. */
  9107. var RecaptchaVerifier = /** @class */ (function () {
  9108. /**
  9109. *
  9110. * @param containerOrId - The reCAPTCHA container parameter.
  9111. *
  9112. * @remarks
  9113. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  9114. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  9115. * an element ID. The corresponding element must also must be in the DOM at the time of
  9116. * initialization.
  9117. *
  9118. * @param parameters - The optional reCAPTCHA parameters.
  9119. *
  9120. * @remarks
  9121. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  9122. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  9123. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  9124. * 'invisible'.
  9125. *
  9126. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  9127. */
  9128. function RecaptchaVerifier(containerOrId, parameters, authExtern) {
  9129. if (parameters === void 0) { parameters = __assign({}, DEFAULT_PARAMS); }
  9130. this.parameters = parameters;
  9131. /**
  9132. * The application verifier type.
  9133. *
  9134. * @remarks
  9135. * For a reCAPTCHA verifier, this is 'recaptcha'.
  9136. */
  9137. this.type = RECAPTCHA_VERIFIER_TYPE;
  9138. this.destroyed = false;
  9139. this.widgetId = null;
  9140. this.tokenChangeListeners = new Set();
  9141. this.renderPromise = null;
  9142. this.recaptcha = null;
  9143. this.auth = _castAuth(authExtern);
  9144. this.isInvisible = this.parameters.size === 'invisible';
  9145. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  9146. var container = typeof containerOrId === 'string'
  9147. ? document.getElementById(containerOrId)
  9148. : containerOrId;
  9149. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9150. this.container = container;
  9151. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  9152. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  9153. ? new MockReCaptchaLoaderImpl()
  9154. : new ReCaptchaLoaderImpl();
  9155. this.validateStartingState();
  9156. // TODO: Figure out if sdk version is needed
  9157. }
  9158. /**
  9159. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  9160. *
  9161. * @returns A Promise for the reCAPTCHA token.
  9162. */
  9163. RecaptchaVerifier.prototype.verify = function () {
  9164. return __awaiter(this, void 0, void 0, function () {
  9165. var id, recaptcha, response;
  9166. var _this = this;
  9167. return __generator(this, function (_a) {
  9168. switch (_a.label) {
  9169. case 0:
  9170. this.assertNotDestroyed();
  9171. return [4 /*yield*/, this.render()];
  9172. case 1:
  9173. id = _a.sent();
  9174. recaptcha = this.getAssertedRecaptcha();
  9175. response = recaptcha.getResponse(id);
  9176. if (response) {
  9177. return [2 /*return*/, response];
  9178. }
  9179. return [2 /*return*/, new Promise(function (resolve) {
  9180. var tokenChange = function (token) {
  9181. if (!token) {
  9182. return; // Ignore token expirations.
  9183. }
  9184. _this.tokenChangeListeners.delete(tokenChange);
  9185. resolve(token);
  9186. };
  9187. _this.tokenChangeListeners.add(tokenChange);
  9188. if (_this.isInvisible) {
  9189. recaptcha.execute(id);
  9190. }
  9191. })];
  9192. }
  9193. });
  9194. });
  9195. };
  9196. /**
  9197. * Renders the reCAPTCHA widget on the page.
  9198. *
  9199. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  9200. */
  9201. RecaptchaVerifier.prototype.render = function () {
  9202. var _this = this;
  9203. try {
  9204. this.assertNotDestroyed();
  9205. }
  9206. catch (e) {
  9207. // This method returns a promise. Since it's not async (we want to return the
  9208. // _same_ promise if rendering is still occurring), the API surface should
  9209. // reject with the error rather than just throw
  9210. return Promise.reject(e);
  9211. }
  9212. if (this.renderPromise) {
  9213. return this.renderPromise;
  9214. }
  9215. this.renderPromise = this.makeRenderPromise().catch(function (e) {
  9216. _this.renderPromise = null;
  9217. throw e;
  9218. });
  9219. return this.renderPromise;
  9220. };
  9221. /** @internal */
  9222. RecaptchaVerifier.prototype._reset = function () {
  9223. this.assertNotDestroyed();
  9224. if (this.widgetId !== null) {
  9225. this.getAssertedRecaptcha().reset(this.widgetId);
  9226. }
  9227. };
  9228. /**
  9229. * Clears the reCAPTCHA widget from the page and destroys the instance.
  9230. */
  9231. RecaptchaVerifier.prototype.clear = function () {
  9232. var _this = this;
  9233. this.assertNotDestroyed();
  9234. this.destroyed = true;
  9235. this._recaptchaLoader.clearedOneInstance();
  9236. if (!this.isInvisible) {
  9237. this.container.childNodes.forEach(function (node) {
  9238. _this.container.removeChild(node);
  9239. });
  9240. }
  9241. };
  9242. RecaptchaVerifier.prototype.validateStartingState = function () {
  9243. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9244. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9245. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  9246. };
  9247. RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
  9248. var _this = this;
  9249. return function (token) {
  9250. _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
  9251. if (typeof existing === 'function') {
  9252. existing(token);
  9253. }
  9254. else if (typeof existing === 'string') {
  9255. var globalFunc = _window()[existing];
  9256. if (typeof globalFunc === 'function') {
  9257. globalFunc(token);
  9258. }
  9259. }
  9260. };
  9261. };
  9262. RecaptchaVerifier.prototype.assertNotDestroyed = function () {
  9263. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9264. };
  9265. RecaptchaVerifier.prototype.makeRenderPromise = function () {
  9266. return __awaiter(this, void 0, void 0, function () {
  9267. var container, guaranteedEmpty;
  9268. return __generator(this, function (_a) {
  9269. switch (_a.label) {
  9270. case 0: return [4 /*yield*/, this.init()];
  9271. case 1:
  9272. _a.sent();
  9273. if (!this.widgetId) {
  9274. container = this.container;
  9275. if (!this.isInvisible) {
  9276. guaranteedEmpty = document.createElement('div');
  9277. container.appendChild(guaranteedEmpty);
  9278. container = guaranteedEmpty;
  9279. }
  9280. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  9281. }
  9282. return [2 /*return*/, this.widgetId];
  9283. }
  9284. });
  9285. });
  9286. };
  9287. RecaptchaVerifier.prototype.init = function () {
  9288. return __awaiter(this, void 0, void 0, function () {
  9289. var _a, siteKey;
  9290. return __generator(this, function (_b) {
  9291. switch (_b.label) {
  9292. case 0:
  9293. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9294. return [4 /*yield*/, domReady()];
  9295. case 1:
  9296. _b.sent();
  9297. _a = this;
  9298. return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
  9299. case 2:
  9300. _a.recaptcha = _b.sent();
  9301. return [4 /*yield*/, getRecaptchaParams(this.auth)];
  9302. case 3:
  9303. siteKey = _b.sent();
  9304. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9305. this.parameters.sitekey = siteKey;
  9306. return [2 /*return*/];
  9307. }
  9308. });
  9309. });
  9310. };
  9311. RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
  9312. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9313. return this.recaptcha;
  9314. };
  9315. return RecaptchaVerifier;
  9316. }());
  9317. function domReady() {
  9318. var resolver = null;
  9319. return new Promise(function (resolve) {
  9320. if (document.readyState === 'complete') {
  9321. resolve();
  9322. return;
  9323. }
  9324. // Document not ready, wait for load before resolving.
  9325. // Save resolver, so we can remove listener in case it was externally
  9326. // cancelled.
  9327. resolver = function () { return resolve(); };
  9328. window.addEventListener('load', resolver);
  9329. }).catch(function (e) {
  9330. if (resolver) {
  9331. window.removeEventListener('load', resolver);
  9332. }
  9333. throw e;
  9334. });
  9335. }
  9336. /**
  9337. * @license
  9338. * Copyright 2020 Google LLC
  9339. *
  9340. * Licensed under the Apache License, Version 2.0 (the "License");
  9341. * you may not use this file except in compliance with the License.
  9342. * You may obtain a copy of the License at
  9343. *
  9344. * http://www.apache.org/licenses/LICENSE-2.0
  9345. *
  9346. * Unless required by applicable law or agreed to in writing, software
  9347. * distributed under the License is distributed on an "AS IS" BASIS,
  9348. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9349. * See the License for the specific language governing permissions and
  9350. * limitations under the License.
  9351. */
  9352. var ConfirmationResultImpl = /** @class */ (function () {
  9353. function ConfirmationResultImpl(verificationId, onConfirmation) {
  9354. this.verificationId = verificationId;
  9355. this.onConfirmation = onConfirmation;
  9356. }
  9357. ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
  9358. var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  9359. return this.onConfirmation(authCredential);
  9360. };
  9361. return ConfirmationResultImpl;
  9362. }());
  9363. /**
  9364. * Asynchronously signs in using a phone number.
  9365. *
  9366. * @remarks
  9367. * This method sends a code via SMS to the given
  9368. * phone number, and returns a {@link ConfirmationResult}. After the user
  9369. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  9370. * with the code to sign the user in.
  9371. *
  9372. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  9373. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  9374. * This function can work on other platforms that do not support the
  9375. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  9376. * third-party {@link ApplicationVerifier} implementation.
  9377. *
  9378. * @example
  9379. * ```javascript
  9380. * // 'recaptcha-container' is the ID of an element in the DOM.
  9381. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  9382. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  9383. * // Obtain a verificationCode from the user.
  9384. * const credential = await confirmationResult.confirm(verificationCode);
  9385. * ```
  9386. *
  9387. * @param auth - The {@link Auth} instance.
  9388. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  9389. * @param appVerifier - The {@link ApplicationVerifier}.
  9390. *
  9391. * @public
  9392. */
  9393. function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  9394. return __awaiter(this, void 0, void 0, function () {
  9395. var authInternal, verificationId;
  9396. return __generator(this, function (_a) {
  9397. switch (_a.label) {
  9398. case 0:
  9399. authInternal = _castAuth(auth);
  9400. return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier))];
  9401. case 1:
  9402. verificationId = _a.sent();
  9403. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  9404. return signInWithCredential(authInternal, cred);
  9405. })];
  9406. }
  9407. });
  9408. });
  9409. }
  9410. /**
  9411. * Links the user account with the given phone number.
  9412. *
  9413. * @param user - The user.
  9414. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  9415. * @param appVerifier - The {@link ApplicationVerifier}.
  9416. *
  9417. * @public
  9418. */
  9419. function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  9420. return __awaiter(this, void 0, void 0, function () {
  9421. var userInternal, verificationId;
  9422. return __generator(this, function (_a) {
  9423. switch (_a.label) {
  9424. case 0:
  9425. userInternal = getModularInstance(user);
  9426. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */)];
  9427. case 1:
  9428. _a.sent();
  9429. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  9430. case 2:
  9431. verificationId = _a.sent();
  9432. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  9433. return linkWithCredential(userInternal, cred);
  9434. })];
  9435. }
  9436. });
  9437. });
  9438. }
  9439. /**
  9440. * Re-authenticates a user using a fresh phone credential.
  9441. *
  9442. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  9443. *
  9444. * @param user - The user.
  9445. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  9446. * @param appVerifier - The {@link ApplicationVerifier}.
  9447. *
  9448. * @public
  9449. */
  9450. function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  9451. return __awaiter(this, void 0, void 0, function () {
  9452. var userInternal, verificationId;
  9453. return __generator(this, function (_a) {
  9454. switch (_a.label) {
  9455. case 0:
  9456. userInternal = getModularInstance(user);
  9457. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  9458. case 1:
  9459. verificationId = _a.sent();
  9460. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  9461. return reauthenticateWithCredential(userInternal, cred);
  9462. })];
  9463. }
  9464. });
  9465. });
  9466. }
  9467. /**
  9468. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  9469. *
  9470. */
  9471. function _verifyPhoneNumber(auth, options, verifier) {
  9472. var _a;
  9473. return __awaiter(this, void 0, void 0, function () {
  9474. var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
  9475. return __generator(this, function (_b) {
  9476. switch (_b.label) {
  9477. case 0: return [4 /*yield*/, verifier.verify()];
  9478. case 1:
  9479. recaptchaToken = _b.sent();
  9480. _b.label = 2;
  9481. case 2:
  9482. _b.trys.push([2, , 10, 11]);
  9483. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9484. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9485. phoneInfoOptions = void 0;
  9486. if (typeof options === 'string') {
  9487. phoneInfoOptions = {
  9488. phoneNumber: options
  9489. };
  9490. }
  9491. else {
  9492. phoneInfoOptions = options;
  9493. }
  9494. if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
  9495. session = phoneInfoOptions.session;
  9496. if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
  9497. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9498. return [4 /*yield*/, startEnrollPhoneMfa(auth, {
  9499. idToken: session.credential,
  9500. phoneEnrollmentInfo: {
  9501. phoneNumber: phoneInfoOptions.phoneNumber,
  9502. recaptchaToken: recaptchaToken
  9503. }
  9504. })];
  9505. case 3:
  9506. response = _b.sent();
  9507. return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
  9508. case 4:
  9509. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9510. mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  9511. phoneInfoOptions.multiFactorUid;
  9512. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  9513. return [4 /*yield*/, startSignInPhoneMfa(auth, {
  9514. mfaPendingCredential: session.credential,
  9515. mfaEnrollmentId: mfaEnrollmentId,
  9516. phoneSignInInfo: {
  9517. recaptchaToken: recaptchaToken
  9518. }
  9519. })];
  9520. case 5:
  9521. response = _b.sent();
  9522. return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
  9523. case 6: return [3 /*break*/, 9];
  9524. case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
  9525. phoneNumber: phoneInfoOptions.phoneNumber,
  9526. recaptchaToken: recaptchaToken
  9527. })];
  9528. case 8:
  9529. sessionInfo = (_b.sent()).sessionInfo;
  9530. return [2 /*return*/, sessionInfo];
  9531. case 9: return [3 /*break*/, 11];
  9532. case 10:
  9533. verifier._reset();
  9534. return [7 /*endfinally*/];
  9535. case 11: return [2 /*return*/];
  9536. }
  9537. });
  9538. });
  9539. }
  9540. /**
  9541. * Updates the user's phone number.
  9542. *
  9543. * @example
  9544. * ```
  9545. * // 'recaptcha-container' is the ID of an element in the DOM.
  9546. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  9547. * const provider = new PhoneAuthProvider(auth);
  9548. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  9549. * // Obtain the verificationCode from the user.
  9550. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9551. * await updatePhoneNumber(user, phoneCredential);
  9552. * ```
  9553. *
  9554. * @param user - The user.
  9555. * @param credential - A credential authenticating the new phone number.
  9556. *
  9557. * @public
  9558. */
  9559. function updatePhoneNumber(user, credential) {
  9560. return __awaiter(this, void 0, void 0, function () {
  9561. return __generator(this, function (_a) {
  9562. switch (_a.label) {
  9563. case 0: return [4 /*yield*/, _link$1(getModularInstance(user), credential)];
  9564. case 1:
  9565. _a.sent();
  9566. return [2 /*return*/];
  9567. }
  9568. });
  9569. });
  9570. }
  9571. /**
  9572. * @license
  9573. * Copyright 2020 Google LLC
  9574. *
  9575. * Licensed under the Apache License, Version 2.0 (the "License");
  9576. * you may not use this file except in compliance with the License.
  9577. * You may obtain a copy of the License at
  9578. *
  9579. * http://www.apache.org/licenses/LICENSE-2.0
  9580. *
  9581. * Unless required by applicable law or agreed to in writing, software
  9582. * distributed under the License is distributed on an "AS IS" BASIS,
  9583. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9584. * See the License for the specific language governing permissions and
  9585. * limitations under the License.
  9586. */
  9587. /**
  9588. * Provider for generating an {@link PhoneAuthCredential}.
  9589. *
  9590. * @example
  9591. * ```javascript
  9592. * // 'recaptcha-container' is the ID of an element in the DOM.
  9593. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  9594. * const provider = new PhoneAuthProvider(auth);
  9595. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  9596. * // Obtain the verificationCode from the user.
  9597. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9598. * const userCredential = await signInWithCredential(auth, phoneCredential);
  9599. * ```
  9600. *
  9601. * @public
  9602. */
  9603. var PhoneAuthProvider = /** @class */ (function () {
  9604. /**
  9605. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  9606. *
  9607. */
  9608. function PhoneAuthProvider(auth) {
  9609. /** Always set to {@link ProviderId}.PHONE. */
  9610. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  9611. this.auth = _castAuth(auth);
  9612. }
  9613. /**
  9614. *
  9615. * Starts a phone number authentication flow by sending a verification code to the given phone
  9616. * number.
  9617. *
  9618. * @example
  9619. * ```javascript
  9620. * const provider = new PhoneAuthProvider(auth);
  9621. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  9622. * // Obtain verificationCode from the user.
  9623. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9624. * const userCredential = await signInWithCredential(auth, authCredential);
  9625. * ```
  9626. *
  9627. * @example
  9628. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  9629. * ```javascript
  9630. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  9631. * // Obtain verificationCode from the user.
  9632. * const userCredential = confirmationResult.confirm(verificationCode);
  9633. * ```
  9634. *
  9635. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  9636. * E.164 format (e.g. +16505550101).
  9637. * @param applicationVerifier - For abuse prevention, this method also requires a
  9638. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  9639. * {@link RecaptchaVerifier}.
  9640. *
  9641. * @returns A Promise for a verification ID that can be passed to
  9642. * {@link PhoneAuthProvider.credential} to identify this flow..
  9643. */
  9644. PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
  9645. return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  9646. };
  9647. /**
  9648. * Creates a phone auth credential, given the verification ID from
  9649. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  9650. * mobile device.
  9651. *
  9652. * @example
  9653. * ```javascript
  9654. * const provider = new PhoneAuthProvider(auth);
  9655. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  9656. * // Obtain verificationCode from the user.
  9657. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9658. * const userCredential = signInWithCredential(auth, authCredential);
  9659. * ```
  9660. *
  9661. * @example
  9662. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  9663. * ```javascript
  9664. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  9665. * // Obtain verificationCode from the user.
  9666. * const userCredential = await confirmationResult.confirm(verificationCode);
  9667. * ```
  9668. *
  9669. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  9670. * @param verificationCode - The verification code sent to the user's mobile device.
  9671. *
  9672. * @returns The auth provider credential.
  9673. */
  9674. PhoneAuthProvider.credential = function (verificationId, verificationCode) {
  9675. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  9676. };
  9677. /**
  9678. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  9679. * @param userCredential - The user credential.
  9680. */
  9681. PhoneAuthProvider.credentialFromResult = function (userCredential) {
  9682. var credential = userCredential;
  9683. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  9684. };
  9685. /**
  9686. * Returns an {@link AuthCredential} when passed an error.
  9687. *
  9688. * @remarks
  9689. *
  9690. * This method works for errors like
  9691. * `auth/account-exists-with-different-credentials`. This is useful for
  9692. * recovering when attempting to set a user's phone number but the number
  9693. * in question is already tied to another account. For example, the following
  9694. * code tries to update the current user's phone number, and if that
  9695. * fails, links the user with the account associated with that number:
  9696. *
  9697. * ```js
  9698. * const provider = new PhoneAuthProvider(auth);
  9699. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  9700. * try {
  9701. * const code = ''; // Prompt the user for the verification code
  9702. * await updatePhoneNumber(
  9703. * auth.currentUser,
  9704. * PhoneAuthProvider.credential(verificationId, code));
  9705. * } catch (e) {
  9706. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  9707. * const cred = PhoneAuthProvider.credentialFromError(e);
  9708. * await linkWithCredential(auth.currentUser, cred);
  9709. * }
  9710. * }
  9711. *
  9712. * // At this point, auth.currentUser.phoneNumber === number.
  9713. * ```
  9714. *
  9715. * @param error - The error to generate a credential from.
  9716. */
  9717. PhoneAuthProvider.credentialFromError = function (error) {
  9718. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  9719. };
  9720. PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
  9721. var tokenResponse = _a._tokenResponse;
  9722. if (!tokenResponse) {
  9723. return null;
  9724. }
  9725. var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
  9726. if (phoneNumber && temporaryProof) {
  9727. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  9728. }
  9729. return null;
  9730. };
  9731. /** Always set to {@link ProviderId}.PHONE. */
  9732. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  9733. /** Always set to {@link SignInMethod}.PHONE. */
  9734. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  9735. return PhoneAuthProvider;
  9736. }());
  9737. /**
  9738. * @license
  9739. * Copyright 2021 Google LLC
  9740. *
  9741. * Licensed under the Apache License, Version 2.0 (the "License");
  9742. * you may not use this file except in compliance with the License.
  9743. * You may obtain a copy of the License at
  9744. *
  9745. * http://www.apache.org/licenses/LICENSE-2.0
  9746. *
  9747. * Unless required by applicable law or agreed to in writing, software
  9748. * distributed under the License is distributed on an "AS IS" BASIS,
  9749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9750. * See the License for the specific language governing permissions and
  9751. * limitations under the License.
  9752. */
  9753. /**
  9754. * Chooses a popup/redirect resolver to use. This prefers the override (which
  9755. * is directly passed in), and falls back to the property set on the auth
  9756. * object. If neither are available, this function errors w/ an argument error.
  9757. */
  9758. function _withDefaultResolver(auth, resolverOverride) {
  9759. if (resolverOverride) {
  9760. return _getInstance(resolverOverride);
  9761. }
  9762. _assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9763. return auth._popupRedirectResolver;
  9764. }
  9765. /**
  9766. * @license
  9767. * Copyright 2019 Google LLC
  9768. *
  9769. * Licensed under the Apache License, Version 2.0 (the "License");
  9770. * you may not use this file except in compliance with the License.
  9771. * You may obtain a copy of the License at
  9772. *
  9773. * http://www.apache.org/licenses/LICENSE-2.0
  9774. *
  9775. * Unless required by applicable law or agreed to in writing, software
  9776. * distributed under the License is distributed on an "AS IS" BASIS,
  9777. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9778. * See the License for the specific language governing permissions and
  9779. * limitations under the License.
  9780. */
  9781. var IdpCredential = /** @class */ (function (_super) {
  9782. __extends(IdpCredential, _super);
  9783. function IdpCredential(params) {
  9784. var _this = _super.call(this, "custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */) || this;
  9785. _this.params = params;
  9786. return _this;
  9787. }
  9788. IdpCredential.prototype._getIdTokenResponse = function (auth) {
  9789. return signInWithIdp(auth, this._buildIdpRequest());
  9790. };
  9791. IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
  9792. return signInWithIdp(auth, this._buildIdpRequest(idToken));
  9793. };
  9794. IdpCredential.prototype._getReauthenticationResolver = function (auth) {
  9795. return signInWithIdp(auth, this._buildIdpRequest());
  9796. };
  9797. IdpCredential.prototype._buildIdpRequest = function (idToken) {
  9798. var request = {
  9799. requestUri: this.params.requestUri,
  9800. sessionId: this.params.sessionId,
  9801. postBody: this.params.postBody,
  9802. tenantId: this.params.tenantId,
  9803. pendingToken: this.params.pendingToken,
  9804. returnSecureToken: true,
  9805. returnIdpCredential: true
  9806. };
  9807. if (idToken) {
  9808. request.idToken = idToken;
  9809. }
  9810. return request;
  9811. };
  9812. return IdpCredential;
  9813. }(AuthCredential));
  9814. function _signIn(params) {
  9815. return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  9816. }
  9817. function _reauth(params) {
  9818. var auth = params.auth, user = params.user;
  9819. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9820. return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  9821. }
  9822. function _link(params) {
  9823. return __awaiter(this, void 0, void 0, function () {
  9824. var auth, user;
  9825. return __generator(this, function (_a) {
  9826. auth = params.auth, user = params.user;
  9827. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9828. return [2 /*return*/, _link$1(user, new IdpCredential(params), params.bypassAuthState)];
  9829. });
  9830. });
  9831. }
  9832. /**
  9833. * @license
  9834. * Copyright 2020 Google LLC
  9835. *
  9836. * Licensed under the Apache License, Version 2.0 (the "License");
  9837. * you may not use this file except in compliance with the License.
  9838. * You may obtain a copy of the License at
  9839. *
  9840. * http://www.apache.org/licenses/LICENSE-2.0
  9841. *
  9842. * Unless required by applicable law or agreed to in writing, software
  9843. * distributed under the License is distributed on an "AS IS" BASIS,
  9844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9845. * See the License for the specific language governing permissions and
  9846. * limitations under the License.
  9847. */
  9848. /**
  9849. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  9850. * events
  9851. */
  9852. var AbstractPopupRedirectOperation = /** @class */ (function () {
  9853. function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
  9854. if (bypassAuthState === void 0) { bypassAuthState = false; }
  9855. this.auth = auth;
  9856. this.resolver = resolver;
  9857. this.user = user;
  9858. this.bypassAuthState = bypassAuthState;
  9859. this.pendingPromise = null;
  9860. this.eventManager = null;
  9861. this.filter = Array.isArray(filter) ? filter : [filter];
  9862. }
  9863. AbstractPopupRedirectOperation.prototype.execute = function () {
  9864. var _this = this;
  9865. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  9866. var _a, e_1;
  9867. return __generator(this, function (_b) {
  9868. switch (_b.label) {
  9869. case 0:
  9870. this.pendingPromise = { resolve: resolve, reject: reject };
  9871. _b.label = 1;
  9872. case 1:
  9873. _b.trys.push([1, 4, , 5]);
  9874. _a = this;
  9875. return [4 /*yield*/, this.resolver._initialize(this.auth)];
  9876. case 2:
  9877. _a.eventManager = _b.sent();
  9878. return [4 /*yield*/, this.onExecution()];
  9879. case 3:
  9880. _b.sent();
  9881. this.eventManager.registerConsumer(this);
  9882. return [3 /*break*/, 5];
  9883. case 4:
  9884. e_1 = _b.sent();
  9885. this.reject(e_1);
  9886. return [3 /*break*/, 5];
  9887. case 5: return [2 /*return*/];
  9888. }
  9889. });
  9890. }); });
  9891. };
  9892. AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
  9893. return __awaiter(this, void 0, void 0, function () {
  9894. var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
  9895. return __generator(this, function (_b) {
  9896. switch (_b.label) {
  9897. case 0:
  9898. urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
  9899. if (error) {
  9900. this.reject(error);
  9901. return [2 /*return*/];
  9902. }
  9903. params = {
  9904. auth: this.auth,
  9905. requestUri: urlResponse,
  9906. sessionId: sessionId,
  9907. tenantId: tenantId || undefined,
  9908. postBody: postBody || undefined,
  9909. user: this.user,
  9910. bypassAuthState: this.bypassAuthState
  9911. };
  9912. _b.label = 1;
  9913. case 1:
  9914. _b.trys.push([1, 3, , 4]);
  9915. _a = this.resolve;
  9916. return [4 /*yield*/, this.getIdpTask(type)(params)];
  9917. case 2:
  9918. _a.apply(this, [_b.sent()]);
  9919. return [3 /*break*/, 4];
  9920. case 3:
  9921. e_2 = _b.sent();
  9922. this.reject(e_2);
  9923. return [3 /*break*/, 4];
  9924. case 4: return [2 /*return*/];
  9925. }
  9926. });
  9927. });
  9928. };
  9929. AbstractPopupRedirectOperation.prototype.onError = function (error) {
  9930. this.reject(error);
  9931. };
  9932. AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
  9933. switch (type) {
  9934. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  9935. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  9936. return _signIn;
  9937. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  9938. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  9939. return _link;
  9940. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  9941. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  9942. return _reauth;
  9943. default:
  9944. _fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9945. }
  9946. };
  9947. AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
  9948. debugAssert(this.pendingPromise, 'Pending promise was never set');
  9949. this.pendingPromise.resolve(cred);
  9950. this.unregisterAndCleanUp();
  9951. };
  9952. AbstractPopupRedirectOperation.prototype.reject = function (error) {
  9953. debugAssert(this.pendingPromise, 'Pending promise was never set');
  9954. this.pendingPromise.reject(error);
  9955. this.unregisterAndCleanUp();
  9956. };
  9957. AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
  9958. if (this.eventManager) {
  9959. this.eventManager.unregisterConsumer(this);
  9960. }
  9961. this.pendingPromise = null;
  9962. this.cleanUp();
  9963. };
  9964. return AbstractPopupRedirectOperation;
  9965. }());
  9966. /**
  9967. * @license
  9968. * Copyright 2020 Google LLC
  9969. *
  9970. * Licensed under the Apache License, Version 2.0 (the "License");
  9971. * you may not use this file except in compliance with the License.
  9972. * You may obtain a copy of the License at
  9973. *
  9974. * http://www.apache.org/licenses/LICENSE-2.0
  9975. *
  9976. * Unless required by applicable law or agreed to in writing, software
  9977. * distributed under the License is distributed on an "AS IS" BASIS,
  9978. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9979. * See the License for the specific language governing permissions and
  9980. * limitations under the License.
  9981. */
  9982. var _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
  9983. /**
  9984. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  9985. *
  9986. * @remarks
  9987. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  9988. * unsuccessful, returns an error object containing additional information about the error.
  9989. *
  9990. * @example
  9991. * ```javascript
  9992. * // Sign in using a popup.
  9993. * const provider = new FacebookAuthProvider();
  9994. * const result = await signInWithPopup(auth, provider);
  9995. *
  9996. * // The signed-in user info.
  9997. * const user = result.user;
  9998. * // This gives you a Facebook Access Token.
  9999. * const credential = provider.credentialFromResult(auth, result);
  10000. * const token = credential.accessToken;
  10001. * ```
  10002. *
  10003. * @param auth - The {@link Auth} instance.
  10004. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10005. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10006. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10007. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10008. *
  10009. *
  10010. * @public
  10011. */
  10012. function signInWithPopup(auth, provider, resolver) {
  10013. return __awaiter(this, void 0, void 0, function () {
  10014. var authInternal, resolverInternal, action;
  10015. return __generator(this, function (_a) {
  10016. authInternal = _castAuth(auth);
  10017. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  10018. resolverInternal = _withDefaultResolver(authInternal, resolver);
  10019. action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  10020. return [2 /*return*/, action.executeNotNull()];
  10021. });
  10022. });
  10023. }
  10024. /**
  10025. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  10026. * OAuth flow.
  10027. *
  10028. * @remarks
  10029. * If the reauthentication is successful, the returned result will contain the user and the
  10030. * provider's credential.
  10031. *
  10032. * @example
  10033. * ```javascript
  10034. * // Sign in using a popup.
  10035. * const provider = new FacebookAuthProvider();
  10036. * const result = await signInWithPopup(auth, provider);
  10037. * // Reauthenticate using a popup.
  10038. * await reauthenticateWithPopup(result.user, provider);
  10039. * ```
  10040. *
  10041. * @param user - The user.
  10042. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10043. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10044. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10045. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10046. *
  10047. * @public
  10048. */
  10049. function reauthenticateWithPopup(user, provider, resolver) {
  10050. return __awaiter(this, void 0, void 0, function () {
  10051. var userInternal, resolverInternal, action;
  10052. return __generator(this, function (_a) {
  10053. userInternal = getModularInstance(user);
  10054. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10055. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10056. action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  10057. return [2 /*return*/, action.executeNotNull()];
  10058. });
  10059. });
  10060. }
  10061. /**
  10062. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  10063. *
  10064. * @remarks
  10065. * If the linking is successful, the returned result will contain the user and the provider's credential.
  10066. *
  10067. *
  10068. * @example
  10069. * ```javascript
  10070. * // Sign in using some other provider.
  10071. * const result = await signInWithEmailAndPassword(auth, email, password);
  10072. * // Link using a popup.
  10073. * const provider = new FacebookAuthProvider();
  10074. * await linkWithPopup(result.user, provider);
  10075. * ```
  10076. *
  10077. * @param user - The user.
  10078. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10079. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10080. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10081. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10082. *
  10083. * @public
  10084. */
  10085. function linkWithPopup(user, provider, resolver) {
  10086. return __awaiter(this, void 0, void 0, function () {
  10087. var userInternal, resolverInternal, action;
  10088. return __generator(this, function (_a) {
  10089. userInternal = getModularInstance(user);
  10090. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10091. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10092. action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  10093. return [2 /*return*/, action.executeNotNull()];
  10094. });
  10095. });
  10096. }
  10097. /**
  10098. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  10099. * events
  10100. *
  10101. */
  10102. var PopupOperation = /** @class */ (function (_super) {
  10103. __extends(PopupOperation, _super);
  10104. function PopupOperation(auth, filter, provider, resolver, user) {
  10105. var _this = _super.call(this, auth, filter, resolver, user) || this;
  10106. _this.provider = provider;
  10107. _this.authWindow = null;
  10108. _this.pollId = null;
  10109. if (PopupOperation.currentPopupAction) {
  10110. PopupOperation.currentPopupAction.cancel();
  10111. }
  10112. PopupOperation.currentPopupAction = _this;
  10113. return _this;
  10114. }
  10115. PopupOperation.prototype.executeNotNull = function () {
  10116. return __awaiter(this, void 0, void 0, function () {
  10117. var result;
  10118. return __generator(this, function (_a) {
  10119. switch (_a.label) {
  10120. case 0: return [4 /*yield*/, this.execute()];
  10121. case 1:
  10122. result = _a.sent();
  10123. _assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  10124. return [2 /*return*/, result];
  10125. }
  10126. });
  10127. });
  10128. };
  10129. PopupOperation.prototype.onExecution = function () {
  10130. return __awaiter(this, void 0, void 0, function () {
  10131. var eventId, _a;
  10132. var _this = this;
  10133. return __generator(this, function (_b) {
  10134. switch (_b.label) {
  10135. case 0:
  10136. debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  10137. eventId = _generateEventId();
  10138. _a = this;
  10139. return [4 /*yield*/, this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  10140. eventId)];
  10141. case 1:
  10142. _a.authWindow = _b.sent();
  10143. this.authWindow.associatedEvent = eventId;
  10144. // Check for web storage support and origin validation _after_ the popup is
  10145. // loaded. These operations are slow (~1 second or so) Rather than
  10146. // waiting on them before opening the window, optimistically open the popup
  10147. // and check for storage support at the same time. If storage support is
  10148. // not available, this will cause the whole thing to reject properly. It
  10149. // will also close the popup, but since the promise has already rejected,
  10150. // the popup closed by user poll will reject into the void.
  10151. this.resolver._originValidation(this.auth).catch(function (e) {
  10152. _this.reject(e);
  10153. });
  10154. this.resolver._isIframeWebStorageSupported(this.auth, function (isSupported) {
  10155. if (!isSupported) {
  10156. _this.reject(_createError(_this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  10157. }
  10158. });
  10159. // Handle user closure. Notice this does *not* use await
  10160. this.pollUserCancellation();
  10161. return [2 /*return*/];
  10162. }
  10163. });
  10164. });
  10165. };
  10166. Object.defineProperty(PopupOperation.prototype, "eventId", {
  10167. get: function () {
  10168. var _a;
  10169. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  10170. },
  10171. enumerable: false,
  10172. configurable: true
  10173. });
  10174. PopupOperation.prototype.cancel = function () {
  10175. this.reject(_createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  10176. };
  10177. PopupOperation.prototype.cleanUp = function () {
  10178. if (this.authWindow) {
  10179. this.authWindow.close();
  10180. }
  10181. if (this.pollId) {
  10182. window.clearTimeout(this.pollId);
  10183. }
  10184. this.authWindow = null;
  10185. this.pollId = null;
  10186. PopupOperation.currentPopupAction = null;
  10187. };
  10188. PopupOperation.prototype.pollUserCancellation = function () {
  10189. var _this = this;
  10190. var poll = function () {
  10191. var _a, _b;
  10192. if ((_b = (_a = _this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  10193. // Make sure that there is sufficient time for whatever action to
  10194. // complete. The window could have closed but the sign in network
  10195. // call could still be in flight. This is specifically true for
  10196. // Firefox or if the opener is in an iframe, in which case the oauth
  10197. // helper closes the popup.
  10198. _this.pollId = window.setTimeout(function () {
  10199. _this.pollId = null;
  10200. _this.reject(_createError(_this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  10201. }, 8000 /* _Timeout.AUTH_EVENT */);
  10202. return;
  10203. }
  10204. _this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  10205. };
  10206. poll();
  10207. };
  10208. // Only one popup is ever shown at once. The lifecycle of the current popup
  10209. // can be managed / cancelled by the constructor.
  10210. PopupOperation.currentPopupAction = null;
  10211. return PopupOperation;
  10212. }(AbstractPopupRedirectOperation));
  10213. /**
  10214. * @license
  10215. * Copyright 2020 Google LLC
  10216. *
  10217. * Licensed under the Apache License, Version 2.0 (the "License");
  10218. * you may not use this file except in compliance with the License.
  10219. * You may obtain a copy of the License at
  10220. *
  10221. * http://www.apache.org/licenses/LICENSE-2.0
  10222. *
  10223. * Unless required by applicable law or agreed to in writing, software
  10224. * distributed under the License is distributed on an "AS IS" BASIS,
  10225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10226. * See the License for the specific language governing permissions and
  10227. * limitations under the License.
  10228. */
  10229. var PENDING_REDIRECT_KEY = 'pendingRedirect';
  10230. // We only get one redirect outcome for any one auth, so just store it
  10231. // in here.
  10232. var redirectOutcomeMap = new Map();
  10233. var RedirectAction = /** @class */ (function (_super) {
  10234. __extends(RedirectAction, _super);
  10235. function RedirectAction(auth, resolver, bypassAuthState) {
  10236. if (bypassAuthState === void 0) { bypassAuthState = false; }
  10237. var _this = _super.call(this, auth, [
  10238. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  10239. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  10240. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  10241. "unknown" /* AuthEventType.UNKNOWN */
  10242. ], resolver, undefined, bypassAuthState) || this;
  10243. _this.eventId = null;
  10244. return _this;
  10245. }
  10246. /**
  10247. * Override the execute function; if we already have a redirect result, then
  10248. * just return it.
  10249. */
  10250. RedirectAction.prototype.execute = function () {
  10251. return __awaiter(this, void 0, void 0, function () {
  10252. var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
  10253. return __generator(this, function (_b) {
  10254. switch (_b.label) {
  10255. case 0:
  10256. readyOutcome = redirectOutcomeMap.get(this.auth._key());
  10257. if (!!readyOutcome) return [3 /*break*/, 8];
  10258. _b.label = 1;
  10259. case 1:
  10260. _b.trys.push([1, 6, , 7]);
  10261. return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
  10262. case 2:
  10263. hasPendingRedirect = _b.sent();
  10264. if (!hasPendingRedirect) return [3 /*break*/, 4];
  10265. return [4 /*yield*/, _super.prototype.execute.call(this)];
  10266. case 3:
  10267. _a = _b.sent();
  10268. return [3 /*break*/, 5];
  10269. case 4:
  10270. _a = null;
  10271. _b.label = 5;
  10272. case 5:
  10273. result_1 = _a;
  10274. readyOutcome = function () { return Promise.resolve(result_1); };
  10275. return [3 /*break*/, 7];
  10276. case 6:
  10277. e_1 = _b.sent();
  10278. readyOutcome = function () { return Promise.reject(e_1); };
  10279. return [3 /*break*/, 7];
  10280. case 7:
  10281. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  10282. _b.label = 8;
  10283. case 8:
  10284. // If we're not bypassing auth state, the ready outcome should be set to
  10285. // null.
  10286. if (!this.bypassAuthState) {
  10287. redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
  10288. }
  10289. return [2 /*return*/, readyOutcome()];
  10290. }
  10291. });
  10292. });
  10293. };
  10294. RedirectAction.prototype.onAuthEvent = function (event) {
  10295. return __awaiter(this, void 0, void 0, function () {
  10296. var user;
  10297. return __generator(this, function (_a) {
  10298. switch (_a.label) {
  10299. case 0:
  10300. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  10301. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  10302. }
  10303. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  10304. // This is a sentinel value indicating there's no pending redirect
  10305. this.resolve(null);
  10306. return [2 /*return*/];
  10307. }
  10308. if (!event.eventId) return [3 /*break*/, 2];
  10309. return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
  10310. case 1:
  10311. user = _a.sent();
  10312. if (user) {
  10313. this.user = user;
  10314. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  10315. }
  10316. else {
  10317. this.resolve(null);
  10318. }
  10319. _a.label = 2;
  10320. case 2: return [2 /*return*/];
  10321. }
  10322. });
  10323. });
  10324. };
  10325. RedirectAction.prototype.onExecution = function () {
  10326. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  10327. return [2 /*return*/];
  10328. }); });
  10329. };
  10330. RedirectAction.prototype.cleanUp = function () { };
  10331. return RedirectAction;
  10332. }(AbstractPopupRedirectOperation));
  10333. function _getAndClearPendingRedirectStatus(resolver, auth) {
  10334. return __awaiter(this, void 0, void 0, function () {
  10335. var key, persistence, hasPendingRedirect;
  10336. return __generator(this, function (_a) {
  10337. switch (_a.label) {
  10338. case 0:
  10339. key = pendingRedirectKey(auth);
  10340. persistence = resolverPersistence(resolver);
  10341. return [4 /*yield*/, persistence._isAvailable()];
  10342. case 1:
  10343. if (!(_a.sent())) {
  10344. return [2 /*return*/, false];
  10345. }
  10346. return [4 /*yield*/, persistence._get(key)];
  10347. case 2:
  10348. hasPendingRedirect = (_a.sent()) === 'true';
  10349. return [4 /*yield*/, persistence._remove(key)];
  10350. case 3:
  10351. _a.sent();
  10352. return [2 /*return*/, hasPendingRedirect];
  10353. }
  10354. });
  10355. });
  10356. }
  10357. function _setPendingRedirectStatus(resolver, auth) {
  10358. return __awaiter(this, void 0, void 0, function () {
  10359. return __generator(this, function (_a) {
  10360. return [2 /*return*/, resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true')];
  10361. });
  10362. });
  10363. }
  10364. function _clearRedirectOutcomes() {
  10365. redirectOutcomeMap.clear();
  10366. }
  10367. function _overrideRedirectResult(auth, result) {
  10368. redirectOutcomeMap.set(auth._key(), result);
  10369. }
  10370. function resolverPersistence(resolver) {
  10371. return _getInstance(resolver._redirectPersistence);
  10372. }
  10373. function pendingRedirectKey(auth) {
  10374. return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  10375. }
  10376. /**
  10377. * @license
  10378. * Copyright 2020 Google LLC
  10379. *
  10380. * Licensed under the Apache License, Version 2.0 (the "License");
  10381. * you may not use this file except in compliance with the License.
  10382. * You may obtain a copy of the License at
  10383. *
  10384. * http://www.apache.org/licenses/LICENSE-2.0
  10385. *
  10386. * Unless required by applicable law or agreed to in writing, software
  10387. * distributed under the License is distributed on an "AS IS" BASIS,
  10388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10389. * See the License for the specific language governing permissions and
  10390. * limitations under the License.
  10391. */
  10392. /**
  10393. * Authenticates a Firebase client using a full-page redirect flow.
  10394. *
  10395. * @remarks
  10396. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  10397. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  10398. * | best practices} when using {@link signInWithRedirect}.
  10399. *
  10400. * @example
  10401. * ```javascript
  10402. * // Sign in using a redirect.
  10403. * const provider = new FacebookAuthProvider();
  10404. * // You can add additional scopes to the provider:
  10405. * provider.addScope('user_birthday');
  10406. * // Start a sign in process for an unauthenticated user.
  10407. * await signInWithRedirect(auth, provider);
  10408. * // This will trigger a full page redirect away from your app
  10409. *
  10410. * // After returning from the redirect when your app initializes you can obtain the result
  10411. * const result = await getRedirectResult(auth);
  10412. * if (result) {
  10413. * // This is the signed-in user
  10414. * const user = result.user;
  10415. * // This gives you a Facebook Access Token.
  10416. * const credential = provider.credentialFromResult(auth, result);
  10417. * const token = credential.accessToken;
  10418. * }
  10419. * // As this API can be used for sign-in, linking and reauthentication,
  10420. * // check the operationType to determine what triggered this redirect
  10421. * // operation.
  10422. * const operationType = result.operationType;
  10423. * ```
  10424. *
  10425. * @param auth - The {@link Auth} instance.
  10426. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10427. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10428. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10429. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10430. *
  10431. * @public
  10432. */
  10433. function signInWithRedirect(auth, provider, resolver) {
  10434. return _signInWithRedirect(auth, provider, resolver);
  10435. }
  10436. function _signInWithRedirect(auth, provider, resolver) {
  10437. return __awaiter(this, void 0, void 0, function () {
  10438. var authInternal, resolverInternal;
  10439. return __generator(this, function (_a) {
  10440. switch (_a.label) {
  10441. case 0:
  10442. authInternal = _castAuth(auth);
  10443. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  10444. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10445. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10446. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10447. return [4 /*yield*/, authInternal._initializationPromise];
  10448. case 1:
  10449. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10450. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10451. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10452. _a.sent();
  10453. resolverInternal = _withDefaultResolver(authInternal, resolver);
  10454. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, authInternal)];
  10455. case 2:
  10456. _a.sent();
  10457. return [2 /*return*/, resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */)];
  10458. }
  10459. });
  10460. });
  10461. }
  10462. /**
  10463. * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
  10464. * @remarks
  10465. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  10466. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  10467. * | best practices} when using {@link reauthenticateWithRedirect}.
  10468. *
  10469. * @example
  10470. * ```javascript
  10471. * // Sign in using a redirect.
  10472. * const provider = new FacebookAuthProvider();
  10473. * const result = await signInWithRedirect(auth, provider);
  10474. * // This will trigger a full page redirect away from your app
  10475. *
  10476. * // After returning from the redirect when your app initializes you can obtain the result
  10477. * const result = await getRedirectResult(auth);
  10478. * // Reauthenticate using a redirect.
  10479. * await reauthenticateWithRedirect(result.user, provider);
  10480. * // This will again trigger a full page redirect away from your app
  10481. *
  10482. * // After returning from the redirect when your app initializes you can obtain the result
  10483. * const result = await getRedirectResult(auth);
  10484. * ```
  10485. *
  10486. * @param user - The user.
  10487. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10488. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10489. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10490. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10491. *
  10492. * @public
  10493. */
  10494. function reauthenticateWithRedirect(user, provider, resolver) {
  10495. return _reauthenticateWithRedirect(user, provider, resolver);
  10496. }
  10497. function _reauthenticateWithRedirect(user, provider, resolver) {
  10498. return __awaiter(this, void 0, void 0, function () {
  10499. var userInternal, resolverInternal, eventId;
  10500. return __generator(this, function (_a) {
  10501. switch (_a.label) {
  10502. case 0:
  10503. userInternal = getModularInstance(user);
  10504. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10505. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10506. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10507. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10508. return [4 /*yield*/, userInternal.auth._initializationPromise];
  10509. case 1:
  10510. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10511. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10512. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10513. _a.sent();
  10514. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10515. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  10516. case 2:
  10517. _a.sent();
  10518. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  10519. case 3:
  10520. eventId = _a.sent();
  10521. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId)];
  10522. }
  10523. });
  10524. });
  10525. }
  10526. /**
  10527. * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
  10528. * @remarks
  10529. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  10530. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  10531. * | best practices} when using {@link linkWithRedirect}.
  10532. *
  10533. * @example
  10534. * ```javascript
  10535. * // Sign in using some other provider.
  10536. * const result = await signInWithEmailAndPassword(auth, email, password);
  10537. * // Link using a redirect.
  10538. * const provider = new FacebookAuthProvider();
  10539. * await linkWithRedirect(result.user, provider);
  10540. * // This will trigger a full page redirect away from your app
  10541. *
  10542. * // After returning from the redirect when your app initializes you can obtain the result
  10543. * const result = await getRedirectResult(auth);
  10544. * ```
  10545. *
  10546. * @param user - The user.
  10547. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10548. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10549. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10550. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10551. *
  10552. *
  10553. * @public
  10554. */
  10555. function linkWithRedirect(user, provider, resolver) {
  10556. return _linkWithRedirect(user, provider, resolver);
  10557. }
  10558. function _linkWithRedirect(user, provider, resolver) {
  10559. return __awaiter(this, void 0, void 0, function () {
  10560. var userInternal, resolverInternal, eventId;
  10561. return __generator(this, function (_a) {
  10562. switch (_a.label) {
  10563. case 0:
  10564. userInternal = getModularInstance(user);
  10565. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10566. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10567. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10568. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10569. return [4 /*yield*/, userInternal.auth._initializationPromise];
  10570. case 1:
  10571. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10572. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10573. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10574. _a.sent();
  10575. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10576. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, provider.providerId)];
  10577. case 2:
  10578. _a.sent();
  10579. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  10580. case 3:
  10581. _a.sent();
  10582. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  10583. case 4:
  10584. eventId = _a.sent();
  10585. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */, eventId)];
  10586. }
  10587. });
  10588. });
  10589. }
  10590. /**
  10591. * Returns a {@link UserCredential} from the redirect-based sign-in flow.
  10592. *
  10593. * @remarks
  10594. * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
  10595. * error. If no redirect operation was called, returns `null`.
  10596. *
  10597. * @example
  10598. * ```javascript
  10599. * // Sign in using a redirect.
  10600. * const provider = new FacebookAuthProvider();
  10601. * // You can add additional scopes to the provider:
  10602. * provider.addScope('user_birthday');
  10603. * // Start a sign in process for an unauthenticated user.
  10604. * await signInWithRedirect(auth, provider);
  10605. * // This will trigger a full page redirect away from your app
  10606. *
  10607. * // After returning from the redirect when your app initializes you can obtain the result
  10608. * const result = await getRedirectResult(auth);
  10609. * if (result) {
  10610. * // This is the signed-in user
  10611. * const user = result.user;
  10612. * // This gives you a Facebook Access Token.
  10613. * const credential = provider.credentialFromResult(auth, result);
  10614. * const token = credential.accessToken;
  10615. * }
  10616. * // As this API can be used for sign-in, linking and reauthentication,
  10617. * // check the operationType to determine what triggered this redirect
  10618. * // operation.
  10619. * const operationType = result.operationType;
  10620. * ```
  10621. *
  10622. * @param auth - The {@link Auth} instance.
  10623. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10624. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10625. *
  10626. * @public
  10627. */
  10628. function getRedirectResult(auth, resolver) {
  10629. return __awaiter(this, void 0, void 0, function () {
  10630. return __generator(this, function (_a) {
  10631. switch (_a.label) {
  10632. case 0: return [4 /*yield*/, _castAuth(auth)._initializationPromise];
  10633. case 1:
  10634. _a.sent();
  10635. return [2 /*return*/, _getRedirectResult(auth, resolver, false)];
  10636. }
  10637. });
  10638. });
  10639. }
  10640. function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
  10641. if (bypassAuthState === void 0) { bypassAuthState = false; }
  10642. return __awaiter(this, void 0, void 0, function () {
  10643. var authInternal, resolver, action, result;
  10644. return __generator(this, function (_a) {
  10645. switch (_a.label) {
  10646. case 0:
  10647. authInternal = _castAuth(auth);
  10648. resolver = _withDefaultResolver(authInternal, resolverExtern);
  10649. action = new RedirectAction(authInternal, resolver, bypassAuthState);
  10650. return [4 /*yield*/, action.execute()];
  10651. case 1:
  10652. result = _a.sent();
  10653. if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
  10654. delete result.user._redirectEventId;
  10655. return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
  10656. case 2:
  10657. _a.sent();
  10658. return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
  10659. case 3:
  10660. _a.sent();
  10661. _a.label = 4;
  10662. case 4: return [2 /*return*/, result];
  10663. }
  10664. });
  10665. });
  10666. }
  10667. function prepareUserForRedirect(user) {
  10668. return __awaiter(this, void 0, void 0, function () {
  10669. var eventId;
  10670. return __generator(this, function (_a) {
  10671. switch (_a.label) {
  10672. case 0:
  10673. eventId = _generateEventId("".concat(user.uid, ":::"));
  10674. user._redirectEventId = eventId;
  10675. return [4 /*yield*/, user.auth._setRedirectUser(user)];
  10676. case 1:
  10677. _a.sent();
  10678. return [4 /*yield*/, user.auth._persistUserIfCurrent(user)];
  10679. case 2:
  10680. _a.sent();
  10681. return [2 /*return*/, eventId];
  10682. }
  10683. });
  10684. });
  10685. }
  10686. /**
  10687. * @license
  10688. * Copyright 2020 Google LLC
  10689. *
  10690. * Licensed under the Apache License, Version 2.0 (the "License");
  10691. * you may not use this file except in compliance with the License.
  10692. * You may obtain a copy of the License at
  10693. *
  10694. * http://www.apache.org/licenses/LICENSE-2.0
  10695. *
  10696. * Unless required by applicable law or agreed to in writing, software
  10697. * distributed under the License is distributed on an "AS IS" BASIS,
  10698. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10699. * See the License for the specific language governing permissions and
  10700. * limitations under the License.
  10701. */
  10702. // The amount of time to store the UIDs of seen events; this is
  10703. // set to 10 min by default
  10704. var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  10705. var AuthEventManager = /** @class */ (function () {
  10706. function AuthEventManager(auth) {
  10707. this.auth = auth;
  10708. this.cachedEventUids = new Set();
  10709. this.consumers = new Set();
  10710. this.queuedRedirectEvent = null;
  10711. this.hasHandledPotentialRedirect = false;
  10712. this.lastProcessedEventTime = Date.now();
  10713. }
  10714. AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
  10715. this.consumers.add(authEventConsumer);
  10716. if (this.queuedRedirectEvent &&
  10717. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  10718. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  10719. this.saveEventToCache(this.queuedRedirectEvent);
  10720. this.queuedRedirectEvent = null;
  10721. }
  10722. };
  10723. AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
  10724. this.consumers.delete(authEventConsumer);
  10725. };
  10726. AuthEventManager.prototype.onEvent = function (event) {
  10727. var _this = this;
  10728. // Check if the event has already been handled
  10729. if (this.hasEventBeenHandled(event)) {
  10730. return false;
  10731. }
  10732. var handled = false;
  10733. this.consumers.forEach(function (consumer) {
  10734. if (_this.isEventForConsumer(event, consumer)) {
  10735. handled = true;
  10736. _this.sendToConsumer(event, consumer);
  10737. _this.saveEventToCache(event);
  10738. }
  10739. });
  10740. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  10741. // If we've already seen a redirect before, or this is a popup event,
  10742. // bail now
  10743. return handled;
  10744. }
  10745. this.hasHandledPotentialRedirect = true;
  10746. // If the redirect wasn't handled, hang on to it
  10747. if (!handled) {
  10748. this.queuedRedirectEvent = event;
  10749. handled = true;
  10750. }
  10751. return handled;
  10752. };
  10753. AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
  10754. var _a;
  10755. if (event.error && !isNullRedirectEvent(event)) {
  10756. var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  10757. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  10758. consumer.onError(_createError(this.auth, code));
  10759. }
  10760. else {
  10761. consumer.onAuthEvent(event);
  10762. }
  10763. };
  10764. AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
  10765. var eventIdMatches = consumer.eventId === null ||
  10766. (!!event.eventId && event.eventId === consumer.eventId);
  10767. return consumer.filter.includes(event.type) && eventIdMatches;
  10768. };
  10769. AuthEventManager.prototype.hasEventBeenHandled = function (event) {
  10770. if (Date.now() - this.lastProcessedEventTime >=
  10771. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  10772. this.cachedEventUids.clear();
  10773. }
  10774. return this.cachedEventUids.has(eventUid(event));
  10775. };
  10776. AuthEventManager.prototype.saveEventToCache = function (event) {
  10777. this.cachedEventUids.add(eventUid(event));
  10778. this.lastProcessedEventTime = Date.now();
  10779. };
  10780. return AuthEventManager;
  10781. }());
  10782. function eventUid(e) {
  10783. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
  10784. }
  10785. function isNullRedirectEvent(_a) {
  10786. var type = _a.type, error = _a.error;
  10787. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  10788. (error === null || error === void 0 ? void 0 : error.code) === "auth/".concat("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */));
  10789. }
  10790. function isRedirectEvent(event) {
  10791. switch (event.type) {
  10792. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  10793. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  10794. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  10795. return true;
  10796. case "unknown" /* AuthEventType.UNKNOWN */:
  10797. return isNullRedirectEvent(event);
  10798. default:
  10799. return false;
  10800. }
  10801. }
  10802. /**
  10803. * @license
  10804. * Copyright 2020 Google LLC
  10805. *
  10806. * Licensed under the Apache License, Version 2.0 (the "License");
  10807. * you may not use this file except in compliance with the License.
  10808. * You may obtain a copy of the License at
  10809. *
  10810. * http://www.apache.org/licenses/LICENSE-2.0
  10811. *
  10812. * Unless required by applicable law or agreed to in writing, software
  10813. * distributed under the License is distributed on an "AS IS" BASIS,
  10814. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10815. * See the License for the specific language governing permissions and
  10816. * limitations under the License.
  10817. */
  10818. function _getProjectConfig(auth, request) {
  10819. if (request === void 0) { request = {}; }
  10820. return __awaiter(this, void 0, void 0, function () {
  10821. return __generator(this, function (_a) {
  10822. return [2 /*return*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request)];
  10823. });
  10824. });
  10825. }
  10826. /**
  10827. * @license
  10828. * Copyright 2020 Google LLC
  10829. *
  10830. * Licensed under the Apache License, Version 2.0 (the "License");
  10831. * you may not use this file except in compliance with the License.
  10832. * You may obtain a copy of the License at
  10833. *
  10834. * http://www.apache.org/licenses/LICENSE-2.0
  10835. *
  10836. * Unless required by applicable law or agreed to in writing, software
  10837. * distributed under the License is distributed on an "AS IS" BASIS,
  10838. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10839. * See the License for the specific language governing permissions and
  10840. * limitations under the License.
  10841. */
  10842. var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  10843. var HTTP_REGEX = /^https?/;
  10844. function _validateOrigin(auth) {
  10845. return __awaiter(this, void 0, void 0, function () {
  10846. var authorizedDomains, _i, authorizedDomains_1, domain;
  10847. return __generator(this, function (_a) {
  10848. switch (_a.label) {
  10849. case 0:
  10850. // Skip origin validation if we are in an emulated environment
  10851. if (auth.config.emulator) {
  10852. return [2 /*return*/];
  10853. }
  10854. return [4 /*yield*/, _getProjectConfig(auth)];
  10855. case 1:
  10856. authorizedDomains = (_a.sent()).authorizedDomains;
  10857. for (_i = 0, authorizedDomains_1 = authorizedDomains; _i < authorizedDomains_1.length; _i++) {
  10858. domain = authorizedDomains_1[_i];
  10859. try {
  10860. if (matchDomain(domain)) {
  10861. return [2 /*return*/];
  10862. }
  10863. }
  10864. catch (_b) {
  10865. // Do nothing if there's a URL error; just continue searching
  10866. }
  10867. }
  10868. // In the old SDK, this error also provides helpful messages.
  10869. _fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  10870. return [2 /*return*/];
  10871. }
  10872. });
  10873. });
  10874. }
  10875. function matchDomain(expected) {
  10876. var currentUrl = _getCurrentUrl();
  10877. var _a = new URL(currentUrl), protocol = _a.protocol, hostname = _a.hostname;
  10878. if (expected.startsWith('chrome-extension://')) {
  10879. var ceUrl = new URL(expected);
  10880. if (ceUrl.hostname === '' && hostname === '') {
  10881. // For some reason we're not parsing chrome URLs properly
  10882. return (protocol === 'chrome-extension:' &&
  10883. expected.replace('chrome-extension://', '') ===
  10884. currentUrl.replace('chrome-extension://', ''));
  10885. }
  10886. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  10887. }
  10888. if (!HTTP_REGEX.test(protocol)) {
  10889. return false;
  10890. }
  10891. if (IP_ADDRESS_REGEX.test(expected)) {
  10892. // The domain has to be exactly equal to the pattern, as an IP domain will
  10893. // only contain the IP, no extra character.
  10894. return hostname === expected;
  10895. }
  10896. // Dots in pattern should be escaped.
  10897. var escapedDomainPattern = expected.replace(/\./g, '\\.');
  10898. // Non ip address domains.
  10899. // domain.com = *.domain.com OR domain.com
  10900. var re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  10901. return re.test(hostname);
  10902. }
  10903. /**
  10904. * @license
  10905. * Copyright 2020 Google LLC.
  10906. *
  10907. * Licensed under the Apache License, Version 2.0 (the "License");
  10908. * you may not use this file except in compliance with the License.
  10909. * You may obtain a copy of the License at
  10910. *
  10911. * http://www.apache.org/licenses/LICENSE-2.0
  10912. *
  10913. * Unless required by applicable law or agreed to in writing, software
  10914. * distributed under the License is distributed on an "AS IS" BASIS,
  10915. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10916. * See the License for the specific language governing permissions and
  10917. * limitations under the License.
  10918. */
  10919. var NETWORK_TIMEOUT = new Delay(30000, 60000);
  10920. /**
  10921. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  10922. * it will stop working after a retrial. This is a hack to fix this issue.
  10923. */
  10924. function resetUnloadedGapiModules() {
  10925. // Clear last failed gapi.load state to force next gapi.load to first
  10926. // load the failed gapi.iframes module.
  10927. // Get gapix.beacon context.
  10928. var beacon = _window().___jsl;
  10929. // Get current hint.
  10930. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  10931. // Get gapi hint.
  10932. for (var _i = 0, _a = Object.keys(beacon.H); _i < _a.length; _i++) {
  10933. var hint = _a[_i];
  10934. // Requested modules.
  10935. beacon.H[hint].r = beacon.H[hint].r || [];
  10936. // Loaded modules.
  10937. beacon.H[hint].L = beacon.H[hint].L || [];
  10938. // Set requested modules to a copy of the loaded modules.
  10939. beacon.H[hint].r = __spreadArray([], beacon.H[hint].L, true);
  10940. // Clear pending callbacks.
  10941. if (beacon.CP) {
  10942. for (var i = 0; i < beacon.CP.length; i++) {
  10943. // Remove all failed pending callbacks.
  10944. beacon.CP[i] = null;
  10945. }
  10946. }
  10947. }
  10948. }
  10949. }
  10950. function loadGapi(auth) {
  10951. return new Promise(function (resolve, reject) {
  10952. var _a, _b, _c;
  10953. // Function to run when gapi.load is ready.
  10954. function loadGapiIframe() {
  10955. // The developer may have tried to previously run gapi.load and failed.
  10956. // Run this to fix that.
  10957. resetUnloadedGapiModules();
  10958. gapi.load('gapi.iframes', {
  10959. callback: function () {
  10960. resolve(gapi.iframes.getContext());
  10961. },
  10962. ontimeout: function () {
  10963. // The above reset may be sufficient, but having this reset after
  10964. // failure ensures that if the developer calls gapi.load after the
  10965. // connection is re-established and before another attempt to embed
  10966. // the iframe, it would work and would not be broken because of our
  10967. // failed attempt.
  10968. // Timeout when gapi.iframes.Iframe not loaded.
  10969. resetUnloadedGapiModules();
  10970. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  10971. },
  10972. timeout: NETWORK_TIMEOUT.get()
  10973. });
  10974. }
  10975. if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  10976. // If gapi.iframes.Iframe available, resolve.
  10977. resolve(gapi.iframes.getContext());
  10978. }
  10979. else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  10980. // Gapi loader ready, load gapi.iframes.
  10981. loadGapiIframe();
  10982. }
  10983. else {
  10984. // Create a new iframe callback when this is called so as not to overwrite
  10985. // any previous defined callback. This happens if this method is called
  10986. // multiple times in parallel and could result in the later callback
  10987. // overwriting the previous one. This would end up with a iframe
  10988. // timeout.
  10989. var cbName = _generateCallbackName('iframefcb');
  10990. // GApi loader not available, dynamically load platform.js.
  10991. _window()[cbName] = function () {
  10992. // GApi loader should be ready.
  10993. if (!!gapi.load) {
  10994. loadGapiIframe();
  10995. }
  10996. else {
  10997. // Gapi loader failed, throw error.
  10998. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  10999. }
  11000. };
  11001. // Load GApi loader.
  11002. return _loadJS("https://apis.google.com/js/api.js?onload=".concat(cbName))
  11003. .catch(function (e) { return reject(e); });
  11004. }
  11005. }).catch(function (error) {
  11006. // Reset cached promise to allow for retrial.
  11007. cachedGApiLoader = null;
  11008. throw error;
  11009. });
  11010. }
  11011. var cachedGApiLoader = null;
  11012. function _loadGapi(auth) {
  11013. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  11014. return cachedGApiLoader;
  11015. }
  11016. /**
  11017. * @license
  11018. * Copyright 2020 Google LLC.
  11019. *
  11020. * Licensed under the Apache License, Version 2.0 (the "License");
  11021. * you may not use this file except in compliance with the License.
  11022. * You may obtain a copy of the License at
  11023. *
  11024. * http://www.apache.org/licenses/LICENSE-2.0
  11025. *
  11026. * Unless required by applicable law or agreed to in writing, software
  11027. * distributed under the License is distributed on an "AS IS" BASIS,
  11028. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11029. * See the License for the specific language governing permissions and
  11030. * limitations under the License.
  11031. */
  11032. var PING_TIMEOUT = new Delay(5000, 15000);
  11033. var IFRAME_PATH = '__/auth/iframe';
  11034. var EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  11035. var IFRAME_ATTRIBUTES = {
  11036. style: {
  11037. position: 'absolute',
  11038. top: '-100px',
  11039. width: '1px',
  11040. height: '1px'
  11041. },
  11042. 'aria-hidden': 'true',
  11043. tabindex: '-1'
  11044. };
  11045. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  11046. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  11047. var EID_FROM_APIHOST = new Map([
  11048. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  11049. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  11050. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  11051. ]);
  11052. function getIframeUrl(auth) {
  11053. var config = auth.config;
  11054. _assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  11055. var url = config.emulator
  11056. ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
  11057. : "https://".concat(auth.config.authDomain, "/").concat(IFRAME_PATH);
  11058. var params = {
  11059. apiKey: config.apiKey,
  11060. appName: auth.name,
  11061. v: SDK_VERSION
  11062. };
  11063. var eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  11064. if (eid) {
  11065. params.eid = eid;
  11066. }
  11067. var frameworks = auth._getFrameworks();
  11068. if (frameworks.length) {
  11069. params.fw = frameworks.join(',');
  11070. }
  11071. return "".concat(url, "?").concat(querystring(params).slice(1));
  11072. }
  11073. function _openIframe(auth) {
  11074. return __awaiter(this, void 0, void 0, function () {
  11075. var context, gapi;
  11076. var _this = this;
  11077. return __generator(this, function (_a) {
  11078. switch (_a.label) {
  11079. case 0: return [4 /*yield*/, _loadGapi(auth)];
  11080. case 1:
  11081. context = _a.sent();
  11082. gapi = _window().gapi;
  11083. _assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  11084. return [2 /*return*/, context.open({
  11085. where: document.body,
  11086. url: getIframeUrl(auth),
  11087. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  11088. attributes: IFRAME_ATTRIBUTES,
  11089. dontclear: true
  11090. }, function (iframe) {
  11091. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  11092. // Clear timer and resolve pending iframe ready promise.
  11093. function clearTimerAndResolve() {
  11094. _window().clearTimeout(networkErrorTimer);
  11095. resolve(iframe);
  11096. }
  11097. var networkError, networkErrorTimer;
  11098. return __generator(this, function (_a) {
  11099. switch (_a.label) {
  11100. case 0: return [4 /*yield*/, iframe.restyle({
  11101. // Prevent iframe from closing on mouse out.
  11102. setHideOnLeave: false
  11103. })];
  11104. case 1:
  11105. _a.sent();
  11106. networkError = _createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  11107. networkErrorTimer = _window().setTimeout(function () {
  11108. reject(networkError);
  11109. }, PING_TIMEOUT.get());
  11110. // This returns an IThenable. However the reject part does not call
  11111. // when the iframe is not loaded.
  11112. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, function () {
  11113. reject(networkError);
  11114. });
  11115. return [2 /*return*/];
  11116. }
  11117. });
  11118. }); });
  11119. })];
  11120. }
  11121. });
  11122. });
  11123. }
  11124. /**
  11125. * @license
  11126. * Copyright 2020 Google LLC.
  11127. *
  11128. * Licensed under the Apache License, Version 2.0 (the "License");
  11129. * you may not use this file except in compliance with the License.
  11130. * You may obtain a copy of the License at
  11131. *
  11132. * http://www.apache.org/licenses/LICENSE-2.0
  11133. *
  11134. * Unless required by applicable law or agreed to in writing, software
  11135. * distributed under the License is distributed on an "AS IS" BASIS,
  11136. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11137. * See the License for the specific language governing permissions and
  11138. * limitations under the License.
  11139. */
  11140. var BASE_POPUP_OPTIONS = {
  11141. location: 'yes',
  11142. resizable: 'yes',
  11143. statusbar: 'yes',
  11144. toolbar: 'no'
  11145. };
  11146. var DEFAULT_WIDTH = 500;
  11147. var DEFAULT_HEIGHT = 600;
  11148. var TARGET_BLANK = '_blank';
  11149. var FIREFOX_EMPTY_URL = 'http://localhost';
  11150. var AuthPopup = /** @class */ (function () {
  11151. function AuthPopup(window) {
  11152. this.window = window;
  11153. this.associatedEvent = null;
  11154. }
  11155. AuthPopup.prototype.close = function () {
  11156. if (this.window) {
  11157. try {
  11158. this.window.close();
  11159. }
  11160. catch (e) { }
  11161. }
  11162. };
  11163. return AuthPopup;
  11164. }());
  11165. function _open(auth, url, name, width, height) {
  11166. if (width === void 0) { width = DEFAULT_WIDTH; }
  11167. if (height === void 0) { height = DEFAULT_HEIGHT; }
  11168. var top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  11169. var left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  11170. var target = '';
  11171. var options = __assign(__assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top: top, left: left });
  11172. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  11173. // specified, even though the popup is not necessarily blocked.
  11174. var ua = getUA().toLowerCase();
  11175. if (name) {
  11176. target = _isChromeIOS(ua) ? TARGET_BLANK : name;
  11177. }
  11178. if (_isFirefox(ua)) {
  11179. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  11180. url = url || FIREFOX_EMPTY_URL;
  11181. // Firefox disables by default scrolling on popup windows, which can create
  11182. // issues when the user has many Google accounts, for instance.
  11183. options.scrollbars = 'yes';
  11184. }
  11185. var optionsString = Object.entries(options).reduce(function (accum, _a) {
  11186. var key = _a[0], value = _a[1];
  11187. return "".concat(accum).concat(key, "=").concat(value, ",");
  11188. }, '');
  11189. if (_isIOSStandalone(ua) && target !== '_self') {
  11190. openAsNewWindowIOS(url || '', target);
  11191. return new AuthPopup(null);
  11192. }
  11193. // about:blank getting sanitized causing browsers like IE/Edge to display
  11194. // brief error message before redirecting to handler.
  11195. var newWin = window.open(url || '', target, optionsString);
  11196. _assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  11197. // Flaky on IE edge, encapsulate with a try and catch.
  11198. try {
  11199. newWin.focus();
  11200. }
  11201. catch (e) { }
  11202. return new AuthPopup(newWin);
  11203. }
  11204. function openAsNewWindowIOS(url, target) {
  11205. var el = document.createElement('a');
  11206. el.href = url;
  11207. el.target = target;
  11208. var click = document.createEvent('MouseEvent');
  11209. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  11210. el.dispatchEvent(click);
  11211. }
  11212. /**
  11213. * @license
  11214. * Copyright 2021 Google LLC
  11215. *
  11216. * Licensed under the Apache License, Version 2.0 (the "License");
  11217. * you may not use this file except in compliance with the License.
  11218. * You may obtain a copy of the License at
  11219. *
  11220. * http://www.apache.org/licenses/LICENSE-2.0
  11221. *
  11222. * Unless required by applicable law or agreed to in writing, software
  11223. * distributed under the License is distributed on an "AS IS" BASIS,
  11224. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11225. * See the License for the specific language governing permissions and
  11226. * limitations under the License.
  11227. */
  11228. /**
  11229. * URL for Authentication widget which will initiate the OAuth handshake
  11230. *
  11231. * @internal
  11232. */
  11233. var WIDGET_PATH = '__/auth/handler';
  11234. /**
  11235. * URL for emulated environment
  11236. *
  11237. * @internal
  11238. */
  11239. var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  11240. /**
  11241. * Fragment name for the App Check token that gets passed to the widget
  11242. *
  11243. * @internal
  11244. */
  11245. var FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');
  11246. function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  11247. return __awaiter(this, void 0, void 0, function () {
  11248. var params, _i, _a, _b, key, value, scopes, paramsDict, _c, _d, key, appCheckToken, appCheckTokenFragment;
  11249. return __generator(this, function (_e) {
  11250. switch (_e.label) {
  11251. case 0:
  11252. _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  11253. _assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  11254. params = {
  11255. apiKey: auth.config.apiKey,
  11256. appName: auth.name,
  11257. authType: authType,
  11258. redirectUrl: redirectUrl,
  11259. v: SDK_VERSION,
  11260. eventId: eventId
  11261. };
  11262. if (provider instanceof FederatedAuthProvider) {
  11263. provider.setDefaultLanguage(auth.languageCode);
  11264. params.providerId = provider.providerId || '';
  11265. if (!isEmpty(provider.getCustomParameters())) {
  11266. params.customParameters = JSON.stringify(provider.getCustomParameters());
  11267. }
  11268. // TODO set additionalParams from the provider as well?
  11269. for (_i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
  11270. _b = _a[_i], key = _b[0], value = _b[1];
  11271. params[key] = value;
  11272. }
  11273. }
  11274. if (provider instanceof BaseOAuthProvider) {
  11275. scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
  11276. if (scopes.length > 0) {
  11277. params.scopes = scopes.join(',');
  11278. }
  11279. }
  11280. if (auth.tenantId) {
  11281. params.tid = auth.tenantId;
  11282. }
  11283. paramsDict = params;
  11284. for (_c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
  11285. key = _d[_c];
  11286. if (paramsDict[key] === undefined) {
  11287. delete paramsDict[key];
  11288. }
  11289. }
  11290. return [4 /*yield*/, auth._getAppCheckToken()];
  11291. case 1:
  11292. appCheckToken = _e.sent();
  11293. appCheckTokenFragment = appCheckToken
  11294. ? "#".concat(FIREBASE_APP_CHECK_FRAGMENT_ID, "=").concat(encodeURIComponent(appCheckToken))
  11295. : '';
  11296. // Start at index 1 to skip the leading '&' in the query string
  11297. return [2 /*return*/, "".concat(getHandlerBase(auth), "?").concat(querystring(paramsDict).slice(1)).concat(appCheckTokenFragment)];
  11298. }
  11299. });
  11300. });
  11301. }
  11302. function getHandlerBase(_a) {
  11303. var config = _a.config;
  11304. if (!config.emulator) {
  11305. return "https://".concat(config.authDomain, "/").concat(WIDGET_PATH);
  11306. }
  11307. return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
  11308. }
  11309. /**
  11310. * @license
  11311. * Copyright 2020 Google LLC
  11312. *
  11313. * Licensed under the Apache License, Version 2.0 (the "License");
  11314. * you may not use this file except in compliance with the License.
  11315. * You may obtain a copy of the License at
  11316. *
  11317. * http://www.apache.org/licenses/LICENSE-2.0
  11318. *
  11319. * Unless required by applicable law or agreed to in writing, software
  11320. * distributed under the License is distributed on an "AS IS" BASIS,
  11321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11322. * See the License for the specific language governing permissions and
  11323. * limitations under the License.
  11324. */
  11325. /**
  11326. * The special web storage event
  11327. *
  11328. */
  11329. var WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  11330. var BrowserPopupRedirectResolver = /** @class */ (function () {
  11331. function BrowserPopupRedirectResolver() {
  11332. this.eventManagers = {};
  11333. this.iframes = {};
  11334. this.originValidationPromises = {};
  11335. this._redirectPersistence = browserSessionPersistence;
  11336. this._completeRedirectFn = _getRedirectResult;
  11337. this._overrideRedirectResult = _overrideRedirectResult;
  11338. }
  11339. // Wrapping in async even though we don't await anywhere in order
  11340. // to make sure errors are raised as promise rejections
  11341. BrowserPopupRedirectResolver.prototype._openPopup = function (auth, provider, authType, eventId) {
  11342. var _a;
  11343. return __awaiter(this, void 0, void 0, function () {
  11344. var url;
  11345. return __generator(this, function (_b) {
  11346. switch (_b.label) {
  11347. case 0:
  11348. debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  11349. return [4 /*yield*/, _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)];
  11350. case 1:
  11351. url = _b.sent();
  11352. return [2 /*return*/, _open(auth, url, _generateEventId())];
  11353. }
  11354. });
  11355. });
  11356. };
  11357. BrowserPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  11358. return __awaiter(this, void 0, void 0, function () {
  11359. var url;
  11360. return __generator(this, function (_a) {
  11361. switch (_a.label) {
  11362. case 0: return [4 /*yield*/, this._originValidation(auth)];
  11363. case 1:
  11364. _a.sent();
  11365. return [4 /*yield*/, _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)];
  11366. case 2:
  11367. url = _a.sent();
  11368. _setWindowLocation(url);
  11369. return [2 /*return*/, new Promise(function () { })];
  11370. }
  11371. });
  11372. });
  11373. };
  11374. BrowserPopupRedirectResolver.prototype._initialize = function (auth) {
  11375. var _this = this;
  11376. var key = auth._key();
  11377. if (this.eventManagers[key]) {
  11378. var _a = this.eventManagers[key], manager = _a.manager, promise_1 = _a.promise;
  11379. if (manager) {
  11380. return Promise.resolve(manager);
  11381. }
  11382. else {
  11383. debugAssert(promise_1, 'If manager is not set, promise should be');
  11384. return promise_1;
  11385. }
  11386. }
  11387. var promise = this.initAndGetManager(auth);
  11388. this.eventManagers[key] = { promise: promise };
  11389. // If the promise is rejected, the key should be removed so that the
  11390. // operation can be retried later.
  11391. promise.catch(function () {
  11392. delete _this.eventManagers[key];
  11393. });
  11394. return promise;
  11395. };
  11396. BrowserPopupRedirectResolver.prototype.initAndGetManager = function (auth) {
  11397. return __awaiter(this, void 0, void 0, function () {
  11398. var iframe, manager;
  11399. return __generator(this, function (_a) {
  11400. switch (_a.label) {
  11401. case 0: return [4 /*yield*/, _openIframe(auth)];
  11402. case 1:
  11403. iframe = _a.sent();
  11404. manager = new AuthEventManager(auth);
  11405. iframe.register('authEvent', function (iframeEvent) {
  11406. _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  11407. // TODO: Consider splitting redirect and popup events earlier on
  11408. var handled = manager.onEvent(iframeEvent.authEvent);
  11409. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  11410. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  11411. this.eventManagers[auth._key()] = { manager: manager };
  11412. this.iframes[auth._key()] = iframe;
  11413. return [2 /*return*/, manager];
  11414. }
  11415. });
  11416. });
  11417. };
  11418. BrowserPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (auth, cb) {
  11419. var iframe = this.iframes[auth._key()];
  11420. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, function (result) {
  11421. var _a;
  11422. var isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  11423. if (isSupported !== undefined) {
  11424. cb(!!isSupported);
  11425. }
  11426. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  11427. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  11428. };
  11429. BrowserPopupRedirectResolver.prototype._originValidation = function (auth) {
  11430. var key = auth._key();
  11431. if (!this.originValidationPromises[key]) {
  11432. this.originValidationPromises[key] = _validateOrigin(auth);
  11433. }
  11434. return this.originValidationPromises[key];
  11435. };
  11436. Object.defineProperty(BrowserPopupRedirectResolver.prototype, "_shouldInitProactively", {
  11437. get: function () {
  11438. // Mobile browsers and Safari need to optimistically initialize
  11439. return _isMobileBrowser() || _isSafari() || _isIOS();
  11440. },
  11441. enumerable: false,
  11442. configurable: true
  11443. });
  11444. return BrowserPopupRedirectResolver;
  11445. }());
  11446. /**
  11447. * An implementation of {@link PopupRedirectResolver} suitable for browser
  11448. * based applications.
  11449. *
  11450. * @public
  11451. */
  11452. var browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  11453. var MultiFactorAssertionImpl = /** @class */ (function () {
  11454. function MultiFactorAssertionImpl(factorId) {
  11455. this.factorId = factorId;
  11456. }
  11457. MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
  11458. switch (session.type) {
  11459. case "enroll" /* MultiFactorSessionType.ENROLL */:
  11460. return this._finalizeEnroll(auth, session.credential, displayName);
  11461. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  11462. return this._finalizeSignIn(auth, session.credential);
  11463. default:
  11464. return debugFail('unexpected MultiFactorSessionType');
  11465. }
  11466. };
  11467. return MultiFactorAssertionImpl;
  11468. }());
  11469. /**
  11470. * {@inheritdoc PhoneMultiFactorAssertion}
  11471. *
  11472. * @public
  11473. */
  11474. var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
  11475. __extends(PhoneMultiFactorAssertionImpl, _super);
  11476. function PhoneMultiFactorAssertionImpl(credential) {
  11477. var _this = _super.call(this, "phone" /* FactorId.PHONE */) || this;
  11478. _this.credential = credential;
  11479. return _this;
  11480. }
  11481. /** @internal */
  11482. PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
  11483. return new PhoneMultiFactorAssertionImpl(credential);
  11484. };
  11485. /** @internal */
  11486. PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  11487. return finalizeEnrollPhoneMfa(auth, {
  11488. idToken: idToken,
  11489. displayName: displayName,
  11490. phoneVerificationInfo: this.credential._makeVerificationRequest()
  11491. });
  11492. };
  11493. /** @internal */
  11494. PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  11495. return finalizeSignInPhoneMfa(auth, {
  11496. mfaPendingCredential: mfaPendingCredential,
  11497. phoneVerificationInfo: this.credential._makeVerificationRequest()
  11498. });
  11499. };
  11500. return PhoneMultiFactorAssertionImpl;
  11501. }(MultiFactorAssertionImpl));
  11502. /**
  11503. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  11504. *
  11505. * @public
  11506. */
  11507. var PhoneMultiFactorGenerator = /** @class */ (function () {
  11508. function PhoneMultiFactorGenerator() {
  11509. }
  11510. /**
  11511. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  11512. *
  11513. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  11514. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  11515. * {@link MultiFactorResolver.resolveSignIn}
  11516. */
  11517. PhoneMultiFactorGenerator.assertion = function (credential) {
  11518. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  11519. };
  11520. /**
  11521. * The identifier of the phone second factor: `phone`.
  11522. */
  11523. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  11524. return PhoneMultiFactorGenerator;
  11525. }());
  11526. /**
  11527. * Provider for generating a {@link TotpMultiFactorAssertion}.
  11528. *
  11529. * @public
  11530. */
  11531. var TotpMultiFactorGenerator = /** @class */ (function () {
  11532. function TotpMultiFactorGenerator() {
  11533. }
  11534. /**
  11535. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of
  11536. * the TOTP (time-based one-time password) second factor.
  11537. * This assertion is used to complete enrollment in TOTP second factor.
  11538. *
  11539. * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.
  11540. * @param oneTimePassword One-time password from TOTP App.
  11541. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  11542. * {@link MultiFactorUser.enroll}.
  11543. */
  11544. TotpMultiFactorGenerator.assertionForEnrollment = function (secret, oneTimePassword) {
  11545. return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);
  11546. };
  11547. /**
  11548. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.
  11549. * This assertion is used to complete signIn with TOTP as the second factor.
  11550. *
  11551. * @param enrollmentId identifies the enrolled TOTP second factor.
  11552. * @param oneTimePassword One-time password from TOTP App.
  11553. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  11554. * {@link MultiFactorResolver.resolveSignIn}.
  11555. */
  11556. TotpMultiFactorGenerator.assertionForSignIn = function (enrollmentId, oneTimePassword) {
  11557. return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);
  11558. };
  11559. /**
  11560. * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.
  11561. * Creates a TOTP secret as part of enrolling a TOTP second factor.
  11562. * Used for generating a QR code URL or inputting into a TOTP app.
  11563. * This method uses the auth instance corresponding to the user in the multiFactorSession.
  11564. *
  11565. * @param session The {@link MultiFactorSession} that the user is part of.
  11566. * @returns A promise to {@link TotpSecret}.
  11567. */
  11568. TotpMultiFactorGenerator.generateSecret = function (session) {
  11569. return __awaiter(this, void 0, void 0, function () {
  11570. var mfaSession, response;
  11571. return __generator(this, function (_a) {
  11572. switch (_a.label) {
  11573. case 0:
  11574. mfaSession = session;
  11575. _assert(typeof mfaSession.auth !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  11576. return [4 /*yield*/, startEnrollTotpMfa(mfaSession.auth, {
  11577. idToken: mfaSession.credential,
  11578. totpEnrollmentInfo: {}
  11579. })];
  11580. case 1:
  11581. response = _a.sent();
  11582. return [2 /*return*/, TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.auth)];
  11583. }
  11584. });
  11585. });
  11586. };
  11587. /**
  11588. * The identifier of the TOTP second factor: `totp`.
  11589. */
  11590. TotpMultiFactorGenerator.FACTOR_ID = "totp" /* FactorId.TOTP */;
  11591. return TotpMultiFactorGenerator;
  11592. }());
  11593. var TotpMultiFactorAssertionImpl = /** @class */ (function (_super) {
  11594. __extends(TotpMultiFactorAssertionImpl, _super);
  11595. function TotpMultiFactorAssertionImpl(otp, enrollmentId, secret) {
  11596. var _this = _super.call(this, "totp" /* FactorId.TOTP */) || this;
  11597. _this.otp = otp;
  11598. _this.enrollmentId = enrollmentId;
  11599. _this.secret = secret;
  11600. return _this;
  11601. }
  11602. /** @internal */
  11603. TotpMultiFactorAssertionImpl._fromSecret = function (secret, otp) {
  11604. return new TotpMultiFactorAssertionImpl(otp, undefined, secret);
  11605. };
  11606. /** @internal */
  11607. TotpMultiFactorAssertionImpl._fromEnrollmentId = function (enrollmentId, otp) {
  11608. return new TotpMultiFactorAssertionImpl(otp, enrollmentId);
  11609. };
  11610. /** @internal */
  11611. TotpMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  11612. return __awaiter(this, void 0, void 0, function () {
  11613. return __generator(this, function (_a) {
  11614. _assert(typeof this.secret !== 'undefined', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  11615. return [2 /*return*/, finalizeEnrollTotpMfa(auth, {
  11616. idToken: idToken,
  11617. displayName: displayName,
  11618. totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)
  11619. })];
  11620. });
  11621. });
  11622. };
  11623. /** @internal */
  11624. TotpMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  11625. return __awaiter(this, void 0, void 0, function () {
  11626. var totpVerificationInfo;
  11627. return __generator(this, function (_a) {
  11628. _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  11629. totpVerificationInfo = { verificationCode: this.otp };
  11630. return [2 /*return*/, finalizeSignInTotpMfa(auth, {
  11631. mfaPendingCredential: mfaPendingCredential,
  11632. mfaEnrollmentId: this.enrollmentId,
  11633. totpVerificationInfo: totpVerificationInfo
  11634. })];
  11635. });
  11636. });
  11637. };
  11638. return TotpMultiFactorAssertionImpl;
  11639. }(MultiFactorAssertionImpl));
  11640. /**
  11641. * Provider for generating a {@link TotpMultiFactorAssertion}.
  11642. *
  11643. * Stores the shared secret key and other parameters to generate time-based OTPs.
  11644. * Implements methods to retrieve the shared secret key and generate a QR code URL.
  11645. * @public
  11646. */
  11647. var TotpSecret = /** @class */ (function () {
  11648. // The public members are declared outside the constructor so the docs can be generated.
  11649. function TotpSecret(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {
  11650. this.sessionInfo = sessionInfo;
  11651. this.auth = auth;
  11652. this.secretKey = secretKey;
  11653. this.hashingAlgorithm = hashingAlgorithm;
  11654. this.codeLength = codeLength;
  11655. this.codeIntervalSeconds = codeIntervalSeconds;
  11656. this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;
  11657. }
  11658. /** @internal */
  11659. TotpSecret._fromStartTotpMfaEnrollmentResponse = function (response, auth) {
  11660. return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);
  11661. };
  11662. /** @internal */
  11663. TotpSecret.prototype._makeTotpVerificationInfo = function (otp) {
  11664. return { sessionInfo: this.sessionInfo, verificationCode: otp };
  11665. };
  11666. /**
  11667. * Returns a QR code URL as described in
  11668. * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
  11669. * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.
  11670. * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.
  11671. *
  11672. * @param accountName the name of the account/app along with a user identifier.
  11673. * @param issuer issuer of the TOTP (likely the app name).
  11674. * @returns A QR code URL string.
  11675. */
  11676. TotpSecret.prototype.generateQrCodeUrl = function (accountName, issuer) {
  11677. var _a;
  11678. var useDefaults = false;
  11679. if (_isEmptyString(accountName) || _isEmptyString(issuer)) {
  11680. useDefaults = true;
  11681. }
  11682. if (useDefaults) {
  11683. if (_isEmptyString(accountName)) {
  11684. accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';
  11685. }
  11686. if (_isEmptyString(issuer)) {
  11687. issuer = this.auth.name;
  11688. }
  11689. }
  11690. return "otpauth://totp/".concat(issuer, ":").concat(accountName, "?secret=").concat(this.secretKey, "&issuer=").concat(issuer, "&algorithm=").concat(this.hashingAlgorithm, "&digits=").concat(this.codeLength);
  11691. };
  11692. return TotpSecret;
  11693. }());
  11694. /** @internal */
  11695. function _isEmptyString(input) {
  11696. return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;
  11697. }
  11698. var name = "@firebase/auth";
  11699. var version = "0.23.2";
  11700. /**
  11701. * @license
  11702. * Copyright 2020 Google LLC
  11703. *
  11704. * Licensed under the Apache License, Version 2.0 (the "License");
  11705. * you may not use this file except in compliance with the License.
  11706. * You may obtain a copy of the License at
  11707. *
  11708. * http://www.apache.org/licenses/LICENSE-2.0
  11709. *
  11710. * Unless required by applicable law or agreed to in writing, software
  11711. * distributed under the License is distributed on an "AS IS" BASIS,
  11712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11713. * See the License for the specific language governing permissions and
  11714. * limitations under the License.
  11715. */
  11716. var AuthInterop = /** @class */ (function () {
  11717. function AuthInterop(auth) {
  11718. this.auth = auth;
  11719. this.internalListeners = new Map();
  11720. }
  11721. AuthInterop.prototype.getUid = function () {
  11722. var _a;
  11723. this.assertAuthConfigured();
  11724. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  11725. };
  11726. AuthInterop.prototype.getToken = function (forceRefresh) {
  11727. return __awaiter(this, void 0, void 0, function () {
  11728. var accessToken;
  11729. return __generator(this, function (_a) {
  11730. switch (_a.label) {
  11731. case 0:
  11732. this.assertAuthConfigured();
  11733. return [4 /*yield*/, this.auth._initializationPromise];
  11734. case 1:
  11735. _a.sent();
  11736. if (!this.auth.currentUser) {
  11737. return [2 /*return*/, null];
  11738. }
  11739. return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
  11740. case 2:
  11741. accessToken = _a.sent();
  11742. return [2 /*return*/, { accessToken: accessToken }];
  11743. }
  11744. });
  11745. });
  11746. };
  11747. AuthInterop.prototype.addAuthTokenListener = function (listener) {
  11748. this.assertAuthConfigured();
  11749. if (this.internalListeners.has(listener)) {
  11750. return;
  11751. }
  11752. var unsubscribe = this.auth.onIdTokenChanged(function (user) {
  11753. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  11754. });
  11755. this.internalListeners.set(listener, unsubscribe);
  11756. this.updateProactiveRefresh();
  11757. };
  11758. AuthInterop.prototype.removeAuthTokenListener = function (listener) {
  11759. this.assertAuthConfigured();
  11760. var unsubscribe = this.internalListeners.get(listener);
  11761. if (!unsubscribe) {
  11762. return;
  11763. }
  11764. this.internalListeners.delete(listener);
  11765. unsubscribe();
  11766. this.updateProactiveRefresh();
  11767. };
  11768. AuthInterop.prototype.assertAuthConfigured = function () {
  11769. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  11770. };
  11771. AuthInterop.prototype.updateProactiveRefresh = function () {
  11772. if (this.internalListeners.size > 0) {
  11773. this.auth._startProactiveRefresh();
  11774. }
  11775. else {
  11776. this.auth._stopProactiveRefresh();
  11777. }
  11778. };
  11779. return AuthInterop;
  11780. }());
  11781. /**
  11782. * @license
  11783. * Copyright 2020 Google LLC
  11784. *
  11785. * Licensed under the Apache License, Version 2.0 (the "License");
  11786. * you may not use this file except in compliance with the License.
  11787. * You may obtain a copy of the License at
  11788. *
  11789. * http://www.apache.org/licenses/LICENSE-2.0
  11790. *
  11791. * Unless required by applicable law or agreed to in writing, software
  11792. * distributed under the License is distributed on an "AS IS" BASIS,
  11793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11794. * See the License for the specific language governing permissions and
  11795. * limitations under the License.
  11796. */
  11797. function getVersionForPlatform(clientPlatform) {
  11798. switch (clientPlatform) {
  11799. case "Node" /* ClientPlatform.NODE */:
  11800. return 'node';
  11801. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  11802. return 'rn';
  11803. case "Worker" /* ClientPlatform.WORKER */:
  11804. return 'webworker';
  11805. case "Cordova" /* ClientPlatform.CORDOVA */:
  11806. return 'cordova';
  11807. default:
  11808. return undefined;
  11809. }
  11810. }
  11811. /** @internal */
  11812. function registerAuth(clientPlatform) {
  11813. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, function (container, _a) {
  11814. var deps = _a.options;
  11815. var app = container.getProvider('app').getImmediate();
  11816. var heartbeatServiceProvider = container.getProvider('heartbeat');
  11817. var appCheckServiceProvider = container.getProvider('app-check-internal');
  11818. var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
  11819. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  11820. var config = {
  11821. apiKey: apiKey,
  11822. authDomain: authDomain,
  11823. clientPlatform: clientPlatform,
  11824. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  11825. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  11826. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  11827. sdkClientVersion: _getClientVersion(clientPlatform)
  11828. };
  11829. var authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);
  11830. _initializeAuthInstance(authInstance, deps);
  11831. return authInstance;
  11832. }, "PUBLIC" /* ComponentType.PUBLIC */)
  11833. /**
  11834. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  11835. * For why we do this, See go/firebase-next-auth-init
  11836. */
  11837. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  11838. /**
  11839. * Because all firebase products that depend on auth depend on auth-internal directly,
  11840. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  11841. */
  11842. .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
  11843. var authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  11844. authInternalProvider.initialize();
  11845. }));
  11846. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, function (container) {
  11847. var auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  11848. return (function (auth) { return new AuthInterop(auth); })(auth);
  11849. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  11850. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  11851. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  11852. registerVersion(name, version, 'esm5');
  11853. }
  11854. /**
  11855. * @license
  11856. * Copyright 2021 Google LLC
  11857. *
  11858. * Licensed under the Apache License, Version 2.0 (the "License");
  11859. * you may not use this file except in compliance with the License.
  11860. * You may obtain a copy of the License at
  11861. *
  11862. * http://www.apache.org/licenses/LICENSE-2.0
  11863. *
  11864. * Unless required by applicable law or agreed to in writing, software
  11865. * distributed under the License is distributed on an "AS IS" BASIS,
  11866. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11867. * See the License for the specific language governing permissions and
  11868. * limitations under the License.
  11869. */
  11870. var DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  11871. var authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  11872. var lastPostedIdToken = null;
  11873. var mintCookieFactory = function (url) { return function (user) { return __awaiter(void 0, void 0, void 0, function () {
  11874. var idTokenResult, _a, idTokenAge, idToken;
  11875. return __generator(this, function (_b) {
  11876. switch (_b.label) {
  11877. case 0:
  11878. _a = user;
  11879. if (!_a) return [3 /*break*/, 2];
  11880. return [4 /*yield*/, user.getIdTokenResult()];
  11881. case 1:
  11882. _a = (_b.sent());
  11883. _b.label = 2;
  11884. case 2:
  11885. idTokenResult = _a;
  11886. idTokenAge = idTokenResult &&
  11887. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  11888. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  11889. return [2 /*return*/];
  11890. }
  11891. idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  11892. if (lastPostedIdToken === idToken) {
  11893. return [2 /*return*/];
  11894. }
  11895. lastPostedIdToken = idToken;
  11896. return [4 /*yield*/, fetch(url, {
  11897. method: idToken ? 'POST' : 'DELETE',
  11898. headers: idToken
  11899. ? {
  11900. 'Authorization': "Bearer ".concat(idToken)
  11901. }
  11902. : {}
  11903. })];
  11904. case 3:
  11905. _b.sent();
  11906. return [2 /*return*/];
  11907. }
  11908. });
  11909. }); }; };
  11910. /**
  11911. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  11912. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  11913. *
  11914. * @param app - The Firebase App.
  11915. *
  11916. * @public
  11917. */
  11918. function getAuth(app) {
  11919. if (app === void 0) { app = getApp(); }
  11920. var provider = _getProvider(app, 'auth');
  11921. if (provider.isInitialized()) {
  11922. return provider.getImmediate();
  11923. }
  11924. var auth = initializeAuth(app, {
  11925. popupRedirectResolver: browserPopupRedirectResolver,
  11926. persistence: [
  11927. indexedDBLocalPersistence,
  11928. browserLocalPersistence,
  11929. browserSessionPersistence
  11930. ]
  11931. });
  11932. var authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');
  11933. if (authTokenSyncUrl) {
  11934. var mintCookie_1 = mintCookieFactory(authTokenSyncUrl);
  11935. beforeAuthStateChanged(auth, mintCookie_1, function () {
  11936. return mintCookie_1(auth.currentUser);
  11937. });
  11938. onIdTokenChanged(auth, function (user) { return mintCookie_1(user); });
  11939. }
  11940. var authEmulatorHost = getDefaultEmulatorHost('auth');
  11941. if (authEmulatorHost) {
  11942. connectAuthEmulator(auth, "http://".concat(authEmulatorHost));
  11943. }
  11944. return auth;
  11945. }
  11946. registerAuth("Browser" /* ClientPlatform.BROWSER */);
  11947. export { signInWithCredential as $, ActionCodeOperation as A, signOut as B, deleteUser as C, debugErrorMap as D, prodErrorMap as E, FactorId as F, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as G, initializeAuth as H, connectAuthEmulator as I, AuthCredential as J, EmailAuthCredential as K, OAuthCredential as L, PhoneAuthCredential as M, inMemoryPersistence as N, OperationType as O, PhoneAuthProvider as P, EmailAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, FacebookAuthProvider as U, GoogleAuthProvider as V, GithubAuthProvider as W, OAuthProvider as X, SAMLAuthProvider as Y, TwitterAuthProvider as Z, signInAnonymously as _, browserSessionPersistence as a, linkWithCredential as a0, reauthenticateWithCredential as a1, signInWithCustomToken as a2, sendPasswordResetEmail as a3, confirmPasswordReset as a4, applyActionCode as a5, checkActionCode as a6, verifyPasswordResetCode as a7, createUserWithEmailAndPassword as a8, signInWithEmailAndPassword as a9, _createError as aA, AuthEventManager as aB, _getInstance as aC, _persistenceKeyName as aD, _clearRedirectOutcomes as aE, _getRedirectResult as aF, _overrideRedirectResult as aG, _castAuth as aH, UserImpl as aI, AuthImpl as aJ, _getClientVersion as aK, _generateEventId as aL, AuthPopup as aM, FetchProvider as aN, SAMLAuthCredential as aO, sendSignInLinkToEmail as aa, isSignInWithEmailLink as ab, signInWithEmailLink as ac, fetchSignInMethodsForEmail as ad, sendEmailVerification as ae, verifyBeforeUpdateEmail as af, ActionCodeURL as ag, parseActionCodeURL as ah, updateProfile as ai, updateEmail as aj, updatePassword as ak, getIdToken as al, getIdTokenResult as am, unlink as an, getAdditionalUserInfo as ao, reload as ap, getMultiFactorResolver as aq, multiFactor as ar, _isIOS as as, _isAndroid as at, _fail as au, _getRedirectUrl as av, debugAssert as aw, _getProjectConfig as ax, _isIOS7Or8 as ay, _assert as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, onIdTokenChanged as v, beforeAuthStateChanged as w, onAuthStateChanged as x, useDeviceLanguage as y, updateCurrentUser as z };
  11948. //# sourceMappingURL=index-cb0c5deb.js.map