index-e3d5d3f4.js 412 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088
  1. import { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';
  2. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  3. import { __rest } from 'tslib';
  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. const FactorId = {
  28. /** Phone as second factor */
  29. PHONE: 'phone',
  30. TOTP: 'totp'
  31. };
  32. /**
  33. * Enumeration of supported providers.
  34. *
  35. * @public
  36. */
  37. const 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. const 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. const 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. const 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. return {
  122. ["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',
  123. ["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */]: '',
  124. ["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: "This app, identified by the domain where it's hosted, is not " +
  125. 'authorized to use Firebase Authentication with the provided API key. ' +
  126. 'Review your key configuration in the Google API console.',
  127. ["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +
  128. 'Android package name or iOS bundle ID) provided is not installed on ' +
  129. 'this device.',
  130. ["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +
  131. 'already used or the domain associated with it does not match the list ' +
  132. 'of whitelisted domains.',
  133. ["code-expired" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +
  134. 'again.',
  135. ["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',
  136. ["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',
  137. ["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',
  138. ["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',
  139. ["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +
  140. 'again before retrying this request.',
  141. ["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 ' +
  142. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  143. 'starting any other Firebase SDK.',
  144. ["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  145. 'conditions.',
  146. ["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',
  147. ["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',
  148. ["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +
  149. 'no longer be configured to use the emulator. Try calling ' +
  150. '"connectAuthEmulator()" sooner.',
  151. ["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',
  152. ["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',
  153. ["internal-error" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',
  154. ["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +
  155. ' The reCAPTCHA token response is either invalid or expired.',
  156. ["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',
  157. ["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */]: "This user's credential isn't valid for this project. This can happen " +
  158. "if the user's token has been tampered with, or if the user isn't for " +
  159. 'the project associated with this API key.',
  160. ["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  161. ["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +
  162. 'invalid. Please resend the verification code sms and be sure to use the ' +
  163. 'verification code provided by the user.',
  164. ["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',
  165. ["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  166. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  167. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  168. 'cordova-plugin-customurlscheme.',
  169. ["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',
  170. ["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',
  171. ["invalid-email" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',
  172. ["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',
  173. ["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',
  174. ["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',
  175. ["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',
  176. ["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +
  177. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  178. ["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',
  179. ["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +
  180. 'only supports OAuth providers.',
  181. ["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +
  182. 'specified API key.',
  183. ["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +
  184. 'project. Edit the list of authorized domains from the Firebase console.',
  185. ["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +
  186. 'expired, or has already been used.',
  187. ["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',
  188. ["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',
  189. ["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +
  190. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  191. 'phone numbers are written in the format [+][country code][subscriber ' +
  192. 'number including area code].',
  193. ["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',
  194. ["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +
  195. 'recipient email address is invalid.',
  196. ["invalid-sender" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +
  197. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  198. ["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',
  199. ["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */]: "The Auth instance's tenant ID is invalid.",
  200. ["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',
  201. ["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.',
  202. ["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  203. 'by following the instructions in the Firebase console.',
  204. ["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +
  205. 'assertion. A reCAPTCHA response token needs to be provided.',
  206. ["missing-verification-code" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',
  207. ["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',
  208. ["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',
  209. ["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  210. ["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +
  211. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  212. 'in the ID token payload.',
  213. ["missing-password" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',
  214. ["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',
  215. ["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',
  216. ["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',
  217. ["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',
  218. ["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',
  219. ["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',
  220. ["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',
  221. ["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +
  222. 'sign-in credentials. Sign in using a provider associated with this ' +
  223. 'email address.',
  224. ["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  225. ["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  226. ["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',
  227. ["null-user" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +
  228. 'requires a non-null user object.',
  229. ["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +
  230. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  231. 'Auth section.',
  232. ["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +
  233. 'running on. "location.protocol" must be http, https or chrome-extension' +
  234. ' and web storage must be enabled.',
  235. ["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  236. ["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',
  237. ["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',
  238. ["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */]: "The project's quota for this operation has been exceeded.",
  239. ["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',
  240. ["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',
  241. ["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',
  242. ["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',
  243. ["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',
  244. ["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */]: "The provided tenant ID does not match the Auth instance's tenant ID",
  245. ["timeout" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',
  246. ["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */]: "The user's credential is no longer valid. The user must sign in again.",
  247. ["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +
  248. 'Try again later.',
  249. ["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  250. 'the domain in the Firebase console.',
  251. ["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.',
  252. ["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',
  253. ["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',
  254. ["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',
  255. ["user-cancelled" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',
  256. ["user-not-found" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +
  257. 'have been deleted.',
  258. ["user-disabled" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',
  259. ["user-mismatch" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',
  260. ["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */]: '',
  261. ["weak-password" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',
  262. ["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',
  263. ["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +
  264. 'different options. To avoid this error, call initializeAuth() with the ' +
  265. 'same options as when it was originally called, or call getAuth() to return the' +
  266. ' already initialized instance.',
  267. ["missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',
  268. ["invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',
  269. ["invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',
  270. ["recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',
  271. ["missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',
  272. ["missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',
  273. ["invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',
  274. ["invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.'
  275. };
  276. }
  277. function _prodErrorMap() {
  278. // We will include this one message in the prod error map since by the very
  279. // nature of this error, developers will never be able to see the message
  280. // using the debugErrorMap (which is installed during auth initialization).
  281. return {
  282. ["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 ' +
  283. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  284. 'starting any other Firebase SDK.'
  285. };
  286. }
  287. /**
  288. * A verbose error map with detailed descriptions for most error codes.
  289. *
  290. * See discussion at {@link AuthErrorMap}
  291. *
  292. * @public
  293. */
  294. const debugErrorMap = _debugErrorMap;
  295. /**
  296. * A minimal error map with all verbose error messages stripped.
  297. *
  298. * See discussion at {@link AuthErrorMap}
  299. *
  300. * @public
  301. */
  302. const prodErrorMap = _prodErrorMap;
  303. const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  304. /**
  305. * A map of potential `Auth` error codes, for easier comparison with errors
  306. * thrown by the SDK.
  307. *
  308. * @remarks
  309. * Note that you can't tree-shake individual keys
  310. * in the map, so by using the map you might substantially increase your
  311. * bundle size.
  312. *
  313. * @public
  314. */
  315. const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  316. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  317. ARGUMENT_ERROR: 'auth/argument-error',
  318. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  319. APP_NOT_INSTALLED: 'auth/app-not-installed',
  320. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  321. CODE_EXPIRED: 'auth/code-expired',
  322. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  323. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  324. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  325. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  326. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  327. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  328. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  329. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  330. EMAIL_EXISTS: 'auth/email-already-in-use',
  331. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  332. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  333. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  334. INTERNAL_ERROR: 'auth/internal-error',
  335. INVALID_API_KEY: 'auth/invalid-api-key',
  336. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  337. INVALID_APP_ID: 'auth/invalid-app-id',
  338. INVALID_AUTH: 'auth/invalid-user-token',
  339. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  340. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  341. INVALID_CODE: 'auth/invalid-verification-code',
  342. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  343. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  344. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  345. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  346. INVALID_EMAIL: 'auth/invalid-email',
  347. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  348. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  349. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  350. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  351. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  352. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  353. INVALID_OOB_CODE: 'auth/invalid-action-code',
  354. INVALID_ORIGIN: 'auth/unauthorized-domain',
  355. INVALID_PASSWORD: 'auth/wrong-password',
  356. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  357. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  358. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  359. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  360. INVALID_SENDER: 'auth/invalid-sender',
  361. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  362. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  363. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  364. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  365. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  366. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  367. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  368. MISSING_CODE: 'auth/missing-verification-code',
  369. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  370. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  371. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  372. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  373. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  374. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  375. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  376. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  377. MODULE_DESTROYED: 'auth/app-deleted',
  378. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  379. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  380. NULL_USER: 'auth/null-user',
  381. NO_AUTH_EVENT: 'auth/no-auth-event',
  382. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  383. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  384. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  385. POPUP_BLOCKED: 'auth/popup-blocked',
  386. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  387. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  388. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  389. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  390. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  391. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  392. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  393. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  394. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  395. TIMEOUT: 'auth/timeout',
  396. TOKEN_EXPIRED: 'auth/user-token-expired',
  397. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  398. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  399. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  400. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  401. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  402. UNVERIFIED_EMAIL: 'auth/unverified-email',
  403. USER_CANCELLED: 'auth/user-cancelled',
  404. USER_DELETED: 'auth/user-not-found',
  405. USER_DISABLED: 'auth/user-disabled',
  406. USER_MISMATCH: 'auth/user-mismatch',
  407. USER_SIGNED_OUT: 'auth/user-signed-out',
  408. WEAK_PASSWORD: 'auth/weak-password',
  409. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  410. ALREADY_INITIALIZED: 'auth/already-initialized',
  411. RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',
  412. MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',
  413. INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',
  414. INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',
  415. MISSING_CLIENT_TYPE: 'auth/missing-client-type',
  416. MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',
  417. INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',
  418. INVALID_REQ_TYPE: 'auth/invalid-req-type'
  419. };
  420. /**
  421. * @license
  422. * Copyright 2020 Google LLC
  423. *
  424. * Licensed under the Apache License, Version 2.0 (the "License");
  425. * you may not use this file except in compliance with the License.
  426. * You may obtain a copy of the License at
  427. *
  428. * http://www.apache.org/licenses/LICENSE-2.0
  429. *
  430. * Unless required by applicable law or agreed to in writing, software
  431. * distributed under the License is distributed on an "AS IS" BASIS,
  432. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  433. * See the License for the specific language governing permissions and
  434. * limitations under the License.
  435. */
  436. const logClient = new Logger('@firebase/auth');
  437. function _logWarn(msg, ...args) {
  438. if (logClient.logLevel <= LogLevel.WARN) {
  439. logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);
  440. }
  441. }
  442. function _logError(msg, ...args) {
  443. if (logClient.logLevel <= LogLevel.ERROR) {
  444. logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);
  445. }
  446. }
  447. /**
  448. * @license
  449. * Copyright 2020 Google LLC
  450. *
  451. * Licensed under the Apache License, Version 2.0 (the "License");
  452. * you may not use this file except in compliance with the License.
  453. * You may obtain a copy of the License at
  454. *
  455. * http://www.apache.org/licenses/LICENSE-2.0
  456. *
  457. * Unless required by applicable law or agreed to in writing, software
  458. * distributed under the License is distributed on an "AS IS" BASIS,
  459. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  460. * See the License for the specific language governing permissions and
  461. * limitations under the License.
  462. */
  463. function _fail(authOrCode, ...rest) {
  464. throw createErrorInternal(authOrCode, ...rest);
  465. }
  466. function _createError(authOrCode, ...rest) {
  467. return createErrorInternal(authOrCode, ...rest);
  468. }
  469. function _errorWithCustomMessage(auth, code, message) {
  470. const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });
  471. const factory = new ErrorFactory('auth', 'Firebase', errorMap);
  472. return factory.create(code, {
  473. appName: auth.name
  474. });
  475. }
  476. function _assertInstanceOf(auth, object, instance) {
  477. const constructorInstance = instance;
  478. if (!(object instanceof constructorInstance)) {
  479. if (constructorInstance.name !== object.constructor.name) {
  480. _fail(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  481. }
  482. throw _errorWithCustomMessage(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +
  483. `Did you pass a reference from a different Auth SDK?`);
  484. }
  485. }
  486. function createErrorInternal(authOrCode, ...rest) {
  487. if (typeof authOrCode !== 'string') {
  488. const code = rest[0];
  489. const fullParams = [...rest.slice(1)];
  490. if (fullParams[0]) {
  491. fullParams[0].appName = authOrCode.name;
  492. }
  493. return authOrCode._errorFactory.create(code, ...fullParams);
  494. }
  495. return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);
  496. }
  497. function _assert(assertion, authOrCode, ...rest) {
  498. if (!assertion) {
  499. throw createErrorInternal(authOrCode, ...rest);
  500. }
  501. }
  502. /**
  503. * Unconditionally fails, throwing an internal error with the given message.
  504. *
  505. * @param failure type of failure encountered
  506. * @throws Error
  507. */
  508. function debugFail(failure) {
  509. // Log the failure in addition to throw an exception, just in case the
  510. // exception is swallowed.
  511. const message = `INTERNAL ASSERTION FAILED: ` + failure;
  512. _logError(message);
  513. // NOTE: We don't use FirebaseError here because these are internal failures
  514. // that cannot be handled by the user. (Also it would create a circular
  515. // dependency between the error and assert modules which doesn't work.)
  516. throw new Error(message);
  517. }
  518. /**
  519. * Fails if the given assertion condition is false, throwing an Error with the
  520. * given message if it did.
  521. *
  522. * @param assertion
  523. * @param message
  524. */
  525. function debugAssert(assertion, message) {
  526. if (!assertion) {
  527. debugFail(message);
  528. }
  529. }
  530. /**
  531. * @license
  532. * Copyright 2020 Google LLC
  533. *
  534. * Licensed under the Apache License, Version 2.0 (the "License");
  535. * you may not use this file except in compliance with the License.
  536. * You may obtain a copy of the License at
  537. *
  538. * http://www.apache.org/licenses/LICENSE-2.0
  539. *
  540. * Unless required by applicable law or agreed to in writing, software
  541. * distributed under the License is distributed on an "AS IS" BASIS,
  542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  543. * See the License for the specific language governing permissions and
  544. * limitations under the License.
  545. */
  546. function _getCurrentUrl() {
  547. var _a;
  548. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  549. }
  550. function _isHttpOrHttps() {
  551. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  552. }
  553. function _getCurrentScheme() {
  554. var _a;
  555. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  556. }
  557. /**
  558. * @license
  559. * Copyright 2020 Google LLC
  560. *
  561. * Licensed under the Apache License, Version 2.0 (the "License");
  562. * you may not use this file except in compliance with the License.
  563. * You may obtain a copy of the License at
  564. *
  565. * http://www.apache.org/licenses/LICENSE-2.0
  566. *
  567. * Unless required by applicable law or agreed to in writing, software
  568. * distributed under the License is distributed on an "AS IS" BASIS,
  569. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  570. * See the License for the specific language governing permissions and
  571. * limitations under the License.
  572. */
  573. /**
  574. * Determine whether the browser is working online
  575. */
  576. function _isOnline() {
  577. if (typeof navigator !== 'undefined' &&
  578. navigator &&
  579. 'onLine' in navigator &&
  580. typeof navigator.onLine === 'boolean' &&
  581. // Apply only for traditional web apps and Chrome extensions.
  582. // This is especially true for Cordova apps which have unreliable
  583. // navigator.onLine behavior unless cordova-plugin-network-information is
  584. // installed which overwrites the native navigator.onLine value and
  585. // defines navigator.connection.
  586. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  587. return navigator.onLine;
  588. }
  589. // If we can't determine the state, assume it is online.
  590. return true;
  591. }
  592. function _getUserLanguage() {
  593. if (typeof navigator === 'undefined') {
  594. return null;
  595. }
  596. const navigatorLanguage = navigator;
  597. return (
  598. // Most reliable, but only supported in Chrome/Firefox.
  599. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  600. // Supported in most browsers, but returns the language of the browser
  601. // UI, not the language set in browser settings.
  602. navigatorLanguage.language ||
  603. // Couldn't determine language.
  604. null);
  605. }
  606. /**
  607. * @license
  608. * Copyright 2020 Google LLC
  609. *
  610. * Licensed under the Apache License, Version 2.0 (the "License");
  611. * you may not use this file except in compliance with the License.
  612. * You may obtain a copy of the License at
  613. *
  614. * http://www.apache.org/licenses/LICENSE-2.0
  615. *
  616. * Unless required by applicable law or agreed to in writing, software
  617. * distributed under the License is distributed on an "AS IS" BASIS,
  618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  619. * See the License for the specific language governing permissions and
  620. * limitations under the License.
  621. */
  622. /**
  623. * A structure to help pick between a range of long and short delay durations
  624. * depending on the current environment. In general, the long delay is used for
  625. * mobile environments whereas short delays are used for desktop environments.
  626. */
  627. class Delay {
  628. constructor(shortDelay, longDelay) {
  629. this.shortDelay = shortDelay;
  630. this.longDelay = longDelay;
  631. // Internal error when improperly initialized.
  632. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  633. this.isMobile = isMobileCordova() || isReactNative();
  634. }
  635. get() {
  636. if (!_isOnline()) {
  637. // Pick the shorter timeout.
  638. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  639. }
  640. // If running in a mobile environment, return the long delay, otherwise
  641. // return the short delay.
  642. // This could be improved in the future to dynamically change based on other
  643. // variables instead of just reading the current environment.
  644. return this.isMobile ? this.longDelay : this.shortDelay;
  645. }
  646. }
  647. /**
  648. * @license
  649. * Copyright 2020 Google LLC
  650. *
  651. * Licensed under the Apache License, Version 2.0 (the "License");
  652. * you may not use this file except in compliance with the License.
  653. * You may obtain a copy of the License at
  654. *
  655. * http://www.apache.org/licenses/LICENSE-2.0
  656. *
  657. * Unless required by applicable law or agreed to in writing, software
  658. * distributed under the License is distributed on an "AS IS" BASIS,
  659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  660. * See the License for the specific language governing permissions and
  661. * limitations under the License.
  662. */
  663. function _emulatorUrl(config, path) {
  664. debugAssert(config.emulator, 'Emulator should always be set here');
  665. const { url } = config.emulator;
  666. if (!path) {
  667. return url;
  668. }
  669. return `${url}${path.startsWith('/') ? path.slice(1) : path}`;
  670. }
  671. /**
  672. * @license
  673. * Copyright 2020 Google LLC
  674. *
  675. * Licensed under the Apache License, Version 2.0 (the "License");
  676. * you may not use this file except in compliance with the License.
  677. * You may obtain a copy of the License at
  678. *
  679. * http://www.apache.org/licenses/LICENSE-2.0
  680. *
  681. * Unless required by applicable law or agreed to in writing, software
  682. * distributed under the License is distributed on an "AS IS" BASIS,
  683. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  684. * See the License for the specific language governing permissions and
  685. * limitations under the License.
  686. */
  687. class FetchProvider {
  688. static initialize(fetchImpl, headersImpl, responseImpl) {
  689. this.fetchImpl = fetchImpl;
  690. if (headersImpl) {
  691. this.headersImpl = headersImpl;
  692. }
  693. if (responseImpl) {
  694. this.responseImpl = responseImpl;
  695. }
  696. }
  697. static fetch() {
  698. if (this.fetchImpl) {
  699. return this.fetchImpl;
  700. }
  701. if (typeof self !== 'undefined' && 'fetch' in self) {
  702. return self.fetch;
  703. }
  704. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  705. }
  706. static headers() {
  707. if (this.headersImpl) {
  708. return this.headersImpl;
  709. }
  710. if (typeof self !== 'undefined' && 'Headers' in self) {
  711. return self.Headers;
  712. }
  713. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  714. }
  715. static response() {
  716. if (this.responseImpl) {
  717. return this.responseImpl;
  718. }
  719. if (typeof self !== 'undefined' && 'Response' in self) {
  720. return self.Response;
  721. }
  722. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  723. }
  724. }
  725. /**
  726. * @license
  727. * Copyright 2020 Google LLC
  728. *
  729. * Licensed under the Apache License, Version 2.0 (the "License");
  730. * you may not use this file except in compliance with the License.
  731. * You may obtain a copy of the License at
  732. *
  733. * http://www.apache.org/licenses/LICENSE-2.0
  734. *
  735. * Unless required by applicable law or agreed to in writing, software
  736. * distributed under the License is distributed on an "AS IS" BASIS,
  737. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  738. * See the License for the specific language governing permissions and
  739. * limitations under the License.
  740. */
  741. /**
  742. * Map from errors returned by the server to errors to developer visible errors
  743. */
  744. const SERVER_ERROR_MAP = {
  745. // Custom token errors.
  746. ["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */]: "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  747. // This can only happen if the SDK sends a bad request.
  748. ["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  749. // Create Auth URI errors.
  750. ["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */]: "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  751. // This can only happen if the SDK sends a bad request.
  752. ["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  753. // Sign in with email and password errors (some apply to sign up too).
  754. ["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */]: "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  755. // This can only happen if the SDK sends a bad request.
  756. ["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */]: "missing-password" /* AuthErrorCode.MISSING_PASSWORD */,
  757. // Sign up with email and password errors.
  758. ["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */]: "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  759. ["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */]: "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  760. // Verify assertion for sign in with credential errors:
  761. ["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  762. ["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  763. ["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  764. // This can only happen if the SDK sends a bad request.
  765. ["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  766. // Send Password reset email errors:
  767. ["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */,
  768. ["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  769. ["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */]: "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  770. ["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */]: "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  771. // This can only happen if the SDK sends a bad request.
  772. ["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  773. // Operations that require ID token in request:
  774. ["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  775. ["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */]: "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  776. ["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  777. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  778. // Other errors.
  779. ["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  780. // Phone Auth related errors.
  781. ["INVALID_CODE" /* ServerError.INVALID_CODE */]: "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  782. ["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */]: "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  783. ["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  784. ["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */]: "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  785. ["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */]: "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  786. // Other action code errors when additional settings passed.
  787. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  788. // This is OK as this error will be caught by client side validation.
  789. ["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  790. ["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */]: "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  791. // getProjectConfig errors when clientId is passed.
  792. ["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  793. // User actions (sign-up or deletion) disabled errors.
  794. ["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */]: "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  795. // Multi factor related errors.
  796. ["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  797. ["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  798. ["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  799. ["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  800. ["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */]: "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  801. ["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  802. // Blocking functions related errors.
  803. ["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  804. // Recaptcha related errors.
  805. ["RECAPTCHA_NOT_ENABLED" /* ServerError.RECAPTCHA_NOT_ENABLED */]: "recaptcha-not-enabled" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,
  806. ["MISSING_RECAPTCHA_TOKEN" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: "missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,
  807. ["INVALID_RECAPTCHA_TOKEN" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: "invalid-recaptcha-token" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,
  808. ["INVALID_RECAPTCHA_ACTION" /* ServerError.INVALID_RECAPTCHA_ACTION */]: "invalid-recaptcha-action" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,
  809. ["MISSING_CLIENT_TYPE" /* ServerError.MISSING_CLIENT_TYPE */]: "missing-client-type" /* AuthErrorCode.MISSING_CLIENT_TYPE */,
  810. ["MISSING_RECAPTCHA_VERSION" /* ServerError.MISSING_RECAPTCHA_VERSION */]: "missing-recaptcha-version" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,
  811. ["INVALID_RECAPTCHA_VERSION" /* ServerError.INVALID_RECAPTCHA_VERSION */]: "invalid-recaptcha-version" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,
  812. ["INVALID_REQ_TYPE" /* ServerError.INVALID_REQ_TYPE */]: "invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */
  813. };
  814. /**
  815. * @license
  816. * Copyright 2020 Google LLC
  817. *
  818. * Licensed under the Apache License, Version 2.0 (the "License");
  819. * you may not use this file except in compliance with the License.
  820. * You may obtain a copy of the License at
  821. *
  822. * http://www.apache.org/licenses/LICENSE-2.0
  823. *
  824. * Unless required by applicable law or agreed to in writing, software
  825. * distributed under the License is distributed on an "AS IS" BASIS,
  826. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  827. * See the License for the specific language governing permissions and
  828. * limitations under the License.
  829. */
  830. const DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  831. function _addTidIfNecessary(auth, request) {
  832. if (auth.tenantId && !request.tenantId) {
  833. return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });
  834. }
  835. return request;
  836. }
  837. async function _performApiRequest(auth, method, path, request, customErrorMap = {}) {
  838. return _performFetchWithErrorHandling(auth, customErrorMap, async () => {
  839. let body = {};
  840. let params = {};
  841. if (request) {
  842. if (method === "GET" /* HttpMethod.GET */) {
  843. params = request;
  844. }
  845. else {
  846. body = {
  847. body: JSON.stringify(request)
  848. };
  849. }
  850. }
  851. const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);
  852. const headers = await auth._getAdditionalHeaders();
  853. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  854. if (auth.languageCode) {
  855. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  856. }
  857. return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,
  858. headers, referrerPolicy: 'no-referrer' }, body));
  859. });
  860. }
  861. async function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  862. auth._canInitEmulator = false;
  863. const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);
  864. try {
  865. const networkTimeout = new NetworkTimeout(auth);
  866. const response = await Promise.race([
  867. fetchFn(),
  868. networkTimeout.promise
  869. ]);
  870. // If we've reached this point, the fetch succeeded and the networkTimeout
  871. // didn't throw; clear the network timeout delay so that Node won't hang
  872. networkTimeout.clearNetworkTimeout();
  873. const json = await response.json();
  874. if ('needConfirmation' in json) {
  875. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  876. }
  877. if (response.ok && !('errorMessage' in json)) {
  878. return json;
  879. }
  880. else {
  881. const errorMessage = response.ok ? json.errorMessage : json.error.message;
  882. const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');
  883. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  884. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  885. }
  886. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  887. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  888. }
  889. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  890. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  891. }
  892. const authError = errorMap[serverErrorCode] ||
  893. serverErrorCode
  894. .toLowerCase()
  895. .replace(/[_\s]+/g, '-');
  896. if (serverErrorMessage) {
  897. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  898. }
  899. else {
  900. _fail(auth, authError);
  901. }
  902. }
  903. }
  904. catch (e) {
  905. if (e instanceof FirebaseError) {
  906. throw e;
  907. }
  908. // Changing this to a different error code will log user out when there is a network error
  909. // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.
  910. // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316
  911. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });
  912. }
  913. }
  914. async function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {
  915. const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));
  916. if ('mfaPendingCredential' in serverResponse) {
  917. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  918. _serverResponse: serverResponse
  919. });
  920. }
  921. return serverResponse;
  922. }
  923. function _getFinalTarget(auth, host, path, query) {
  924. const base = `${host}${path}?${query}`;
  925. if (!auth.config.emulator) {
  926. return `${auth.config.apiScheme}://${base}`;
  927. }
  928. return _emulatorUrl(auth.config, base);
  929. }
  930. class NetworkTimeout {
  931. constructor(auth) {
  932. this.auth = auth;
  933. // Node timers and browser timers are fundamentally incompatible, but we
  934. // don't care about the value here
  935. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  936. this.timer = null;
  937. this.promise = new Promise((_, reject) => {
  938. this.timer = setTimeout(() => {
  939. return reject(_createError(this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  940. }, DEFAULT_API_TIMEOUT_MS.get());
  941. });
  942. }
  943. clearNetworkTimeout() {
  944. clearTimeout(this.timer);
  945. }
  946. }
  947. function _makeTaggedError(auth, code, response) {
  948. const errorParams = {
  949. appName: auth.name
  950. };
  951. if (response.email) {
  952. errorParams.email = response.email;
  953. }
  954. if (response.phoneNumber) {
  955. errorParams.phoneNumber = response.phoneNumber;
  956. }
  957. const error = _createError(auth, code, errorParams);
  958. // We know customData is defined on error because errorParams is defined
  959. error.customData._tokenResponse = response;
  960. return error;
  961. }
  962. /**
  963. * @license
  964. * Copyright 2020 Google LLC
  965. *
  966. * Licensed under the Apache License, Version 2.0 (the "License");
  967. * you may not use this file except in compliance with the License.
  968. * You may obtain a copy of the License at
  969. *
  970. * http://www.apache.org/licenses/LICENSE-2.0
  971. *
  972. * Unless required by applicable law or agreed to in writing, software
  973. * distributed under the License is distributed on an "AS IS" BASIS,
  974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  975. * See the License for the specific language governing permissions and
  976. * limitations under the License.
  977. */
  978. async function deleteAccount(auth, request) {
  979. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request);
  980. }
  981. async function deleteLinkedAccounts(auth, request) {
  982. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  983. }
  984. async function getAccountInfo(auth, request) {
  985. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request);
  986. }
  987. /**
  988. * @license
  989. * Copyright 2020 Google LLC
  990. *
  991. * Licensed under the Apache License, Version 2.0 (the "License");
  992. * you may not use this file except in compliance with the License.
  993. * You may obtain a copy of the License at
  994. *
  995. * http://www.apache.org/licenses/LICENSE-2.0
  996. *
  997. * Unless required by applicable law or agreed to in writing, software
  998. * distributed under the License is distributed on an "AS IS" BASIS,
  999. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1000. * See the License for the specific language governing permissions and
  1001. * limitations under the License.
  1002. */
  1003. function utcTimestampToDateString(utcTimestamp) {
  1004. if (!utcTimestamp) {
  1005. return undefined;
  1006. }
  1007. try {
  1008. // Convert to date object.
  1009. const date = new Date(Number(utcTimestamp));
  1010. // Test date is valid.
  1011. if (!isNaN(date.getTime())) {
  1012. // Convert to UTC date string.
  1013. return date.toUTCString();
  1014. }
  1015. }
  1016. catch (e) {
  1017. // Do nothing. undefined will be returned.
  1018. }
  1019. return undefined;
  1020. }
  1021. /**
  1022. * @license
  1023. * Copyright 2020 Google LLC
  1024. *
  1025. * Licensed under the Apache License, Version 2.0 (the "License");
  1026. * you may not use this file except in compliance with the License.
  1027. * You may obtain a copy of the License at
  1028. *
  1029. * http://www.apache.org/licenses/LICENSE-2.0
  1030. *
  1031. * Unless required by applicable law or agreed to in writing, software
  1032. * distributed under the License is distributed on an "AS IS" BASIS,
  1033. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1034. * See the License for the specific language governing permissions and
  1035. * limitations under the License.
  1036. */
  1037. /**
  1038. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1039. *
  1040. * @remarks
  1041. * Returns the current token if it has not expired or if it will not expire in the next five
  1042. * minutes. Otherwise, this will refresh the token and return a new one.
  1043. *
  1044. * @param user - The user.
  1045. * @param forceRefresh - Force refresh regardless of token expiration.
  1046. *
  1047. * @public
  1048. */
  1049. function getIdToken(user, forceRefresh = false) {
  1050. return getModularInstance(user).getIdToken(forceRefresh);
  1051. }
  1052. /**
  1053. * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
  1054. *
  1055. * @remarks
  1056. * Returns the current token if it has not expired or if it will not expire in the next five
  1057. * minutes. Otherwise, this will refresh the token and return a new one.
  1058. *
  1059. * @param user - The user.
  1060. * @param forceRefresh - Force refresh regardless of token expiration.
  1061. *
  1062. * @public
  1063. */
  1064. async function getIdTokenResult(user, forceRefresh = false) {
  1065. const userInternal = getModularInstance(user);
  1066. const token = await userInternal.getIdToken(forceRefresh);
  1067. const claims = _parseToken(token);
  1068. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1069. const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1070. const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1071. return {
  1072. claims,
  1073. token,
  1074. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1075. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1076. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1077. signInProvider: signInProvider || null,
  1078. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1079. };
  1080. }
  1081. function secondsStringToMilliseconds(seconds) {
  1082. return Number(seconds) * 1000;
  1083. }
  1084. function _parseToken(token) {
  1085. const [algorithm, payload, signature] = token.split('.');
  1086. if (algorithm === undefined ||
  1087. payload === undefined ||
  1088. signature === undefined) {
  1089. _logError('JWT malformed, contained fewer than 3 sections');
  1090. return null;
  1091. }
  1092. try {
  1093. const decoded = base64Decode(payload);
  1094. if (!decoded) {
  1095. _logError('Failed to decode base64 JWT payload');
  1096. return null;
  1097. }
  1098. return JSON.parse(decoded);
  1099. }
  1100. catch (e) {
  1101. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1102. return null;
  1103. }
  1104. }
  1105. /**
  1106. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1107. */
  1108. function _tokenExpiresIn(token) {
  1109. const parsedToken = _parseToken(token);
  1110. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1111. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1112. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1113. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1114. }
  1115. /**
  1116. * @license
  1117. * Copyright 2020 Google LLC
  1118. *
  1119. * Licensed under the Apache License, Version 2.0 (the "License");
  1120. * you may not use this file except in compliance with the License.
  1121. * You may obtain a copy of the License at
  1122. *
  1123. * http://www.apache.org/licenses/LICENSE-2.0
  1124. *
  1125. * Unless required by applicable law or agreed to in writing, software
  1126. * distributed under the License is distributed on an "AS IS" BASIS,
  1127. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1128. * See the License for the specific language governing permissions and
  1129. * limitations under the License.
  1130. */
  1131. async function _logoutIfInvalidated(user, promise, bypassAuthState = false) {
  1132. if (bypassAuthState) {
  1133. return promise;
  1134. }
  1135. try {
  1136. return await promise;
  1137. }
  1138. catch (e) {
  1139. if (e instanceof FirebaseError && isUserInvalidated(e)) {
  1140. if (user.auth.currentUser === user) {
  1141. await user.auth.signOut();
  1142. }
  1143. }
  1144. throw e;
  1145. }
  1146. }
  1147. function isUserInvalidated({ code }) {
  1148. return (code === `auth/${"user-disabled" /* AuthErrorCode.USER_DISABLED */}` ||
  1149. code === `auth/${"user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */}`);
  1150. }
  1151. /**
  1152. * @license
  1153. * Copyright 2020 Google LLC
  1154. *
  1155. * Licensed under the Apache License, Version 2.0 (the "License");
  1156. * you may not use this file except in compliance with the License.
  1157. * You may obtain a copy of the License at
  1158. *
  1159. * http://www.apache.org/licenses/LICENSE-2.0
  1160. *
  1161. * Unless required by applicable law or agreed to in writing, software
  1162. * distributed under the License is distributed on an "AS IS" BASIS,
  1163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1164. * See the License for the specific language governing permissions and
  1165. * limitations under the License.
  1166. */
  1167. class ProactiveRefresh {
  1168. constructor(user) {
  1169. this.user = user;
  1170. this.isRunning = false;
  1171. // Node timers and browser timers return fundamentally different types.
  1172. // We don't actually care what the value is but TS won't accept unknown and
  1173. // we can't cast properly in both environments.
  1174. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1175. this.timerId = null;
  1176. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1177. }
  1178. _start() {
  1179. if (this.isRunning) {
  1180. return;
  1181. }
  1182. this.isRunning = true;
  1183. this.schedule();
  1184. }
  1185. _stop() {
  1186. if (!this.isRunning) {
  1187. return;
  1188. }
  1189. this.isRunning = false;
  1190. if (this.timerId !== null) {
  1191. clearTimeout(this.timerId);
  1192. }
  1193. }
  1194. getInterval(wasError) {
  1195. var _a;
  1196. if (wasError) {
  1197. const interval = this.errorBackoff;
  1198. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1199. return interval;
  1200. }
  1201. else {
  1202. // Reset the error backoff
  1203. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1204. const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1205. const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1206. return Math.max(0, interval);
  1207. }
  1208. }
  1209. schedule(wasError = false) {
  1210. if (!this.isRunning) {
  1211. // Just in case...
  1212. return;
  1213. }
  1214. const interval = this.getInterval(wasError);
  1215. this.timerId = setTimeout(async () => {
  1216. await this.iteration();
  1217. }, interval);
  1218. }
  1219. async iteration() {
  1220. try {
  1221. await this.user.getIdToken(true);
  1222. }
  1223. catch (e) {
  1224. // Only retry on network errors
  1225. if ((e === null || e === void 0 ? void 0 : e.code) ===
  1226. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  1227. this.schedule(/* wasError */ true);
  1228. }
  1229. return;
  1230. }
  1231. this.schedule();
  1232. }
  1233. }
  1234. /**
  1235. * @license
  1236. * Copyright 2020 Google LLC
  1237. *
  1238. * Licensed under the Apache License, Version 2.0 (the "License");
  1239. * you may not use this file except in compliance with the License.
  1240. * You may obtain a copy of the License at
  1241. *
  1242. * http://www.apache.org/licenses/LICENSE-2.0
  1243. *
  1244. * Unless required by applicable law or agreed to in writing, software
  1245. * distributed under the License is distributed on an "AS IS" BASIS,
  1246. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1247. * See the License for the specific language governing permissions and
  1248. * limitations under the License.
  1249. */
  1250. class UserMetadata {
  1251. constructor(createdAt, lastLoginAt) {
  1252. this.createdAt = createdAt;
  1253. this.lastLoginAt = lastLoginAt;
  1254. this._initializeTime();
  1255. }
  1256. _initializeTime() {
  1257. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1258. this.creationTime = utcTimestampToDateString(this.createdAt);
  1259. }
  1260. _copy(metadata) {
  1261. this.createdAt = metadata.createdAt;
  1262. this.lastLoginAt = metadata.lastLoginAt;
  1263. this._initializeTime();
  1264. }
  1265. toJSON() {
  1266. return {
  1267. createdAt: this.createdAt,
  1268. lastLoginAt: this.lastLoginAt
  1269. };
  1270. }
  1271. }
  1272. /**
  1273. * @license
  1274. * Copyright 2019 Google LLC
  1275. *
  1276. * Licensed under the Apache License, Version 2.0 (the "License");
  1277. * you may not use this file except in compliance with the License.
  1278. * You may obtain a copy of the License at
  1279. *
  1280. * http://www.apache.org/licenses/LICENSE-2.0
  1281. *
  1282. * Unless required by applicable law or agreed to in writing, software
  1283. * distributed under the License is distributed on an "AS IS" BASIS,
  1284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1285. * See the License for the specific language governing permissions and
  1286. * limitations under the License.
  1287. */
  1288. async function _reloadWithoutSaving(user) {
  1289. var _a;
  1290. const auth = user.auth;
  1291. const idToken = await user.getIdToken();
  1292. const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));
  1293. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1294. const coreAccount = response.users[0];
  1295. user._notifyReloadListener(coreAccount);
  1296. const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1297. ? extractProviderData(coreAccount.providerUserInfo)
  1298. : [];
  1299. const providerData = mergeProviderData(user.providerData, newProviderData);
  1300. // Preserves the non-nonymous status of the stored user, even if no more
  1301. // credentials (federated or email/password) are linked to the user. If
  1302. // the user was previously anonymous, then use provider data to update.
  1303. // On the other hand, if it was not anonymous before, it should never be
  1304. // considered anonymous now.
  1305. const oldIsAnonymous = user.isAnonymous;
  1306. const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1307. const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1308. const updates = {
  1309. uid: coreAccount.localId,
  1310. displayName: coreAccount.displayName || null,
  1311. photoURL: coreAccount.photoUrl || null,
  1312. email: coreAccount.email || null,
  1313. emailVerified: coreAccount.emailVerified || false,
  1314. phoneNumber: coreAccount.phoneNumber || null,
  1315. tenantId: coreAccount.tenantId || null,
  1316. providerData,
  1317. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1318. isAnonymous
  1319. };
  1320. Object.assign(user, updates);
  1321. }
  1322. /**
  1323. * Reloads user account data, if signed in.
  1324. *
  1325. * @param user - The user.
  1326. *
  1327. * @public
  1328. */
  1329. async function reload(user) {
  1330. const userInternal = getModularInstance(user);
  1331. await _reloadWithoutSaving(userInternal);
  1332. // Even though the current user hasn't changed, update
  1333. // current user will trigger a persistence update w/ the
  1334. // new info.
  1335. await userInternal.auth._persistUserIfCurrent(userInternal);
  1336. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1337. }
  1338. function mergeProviderData(original, newData) {
  1339. const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));
  1340. return [...deduped, ...newData];
  1341. }
  1342. function extractProviderData(providers) {
  1343. return providers.map((_a) => {
  1344. var { providerId } = _a, provider = __rest(_a, ["providerId"]);
  1345. return {
  1346. providerId,
  1347. uid: provider.rawId || '',
  1348. displayName: provider.displayName || null,
  1349. email: provider.email || null,
  1350. phoneNumber: provider.phoneNumber || null,
  1351. photoURL: provider.photoUrl || null
  1352. };
  1353. });
  1354. }
  1355. /**
  1356. * @license
  1357. * Copyright 2020 Google LLC
  1358. *
  1359. * Licensed under the Apache License, Version 2.0 (the "License");
  1360. * you may not use this file except in compliance with the License.
  1361. * You may obtain a copy of the License at
  1362. *
  1363. * http://www.apache.org/licenses/LICENSE-2.0
  1364. *
  1365. * Unless required by applicable law or agreed to in writing, software
  1366. * distributed under the License is distributed on an "AS IS" BASIS,
  1367. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1368. * See the License for the specific language governing permissions and
  1369. * limitations under the License.
  1370. */
  1371. async function requestStsToken(auth, refreshToken) {
  1372. const response = await _performFetchWithErrorHandling(auth, {}, async () => {
  1373. const body = querystring({
  1374. 'grant_type': 'refresh_token',
  1375. 'refresh_token': refreshToken
  1376. }).slice(1);
  1377. const { tokenApiHost, apiKey } = auth.config;
  1378. const url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, `key=${apiKey}`);
  1379. const headers = await auth._getAdditionalHeaders();
  1380. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1381. return FetchProvider.fetch()(url, {
  1382. method: "POST" /* HttpMethod.POST */,
  1383. headers,
  1384. body
  1385. });
  1386. });
  1387. // The response comes back in snake_case. Convert to camel:
  1388. return {
  1389. accessToken: response.access_token,
  1390. expiresIn: response.expires_in,
  1391. refreshToken: response.refresh_token
  1392. };
  1393. }
  1394. /**
  1395. * @license
  1396. * Copyright 2020 Google LLC
  1397. *
  1398. * Licensed under the Apache License, Version 2.0 (the "License");
  1399. * you may not use this file except in compliance with the License.
  1400. * You may obtain a copy of the License at
  1401. *
  1402. * http://www.apache.org/licenses/LICENSE-2.0
  1403. *
  1404. * Unless required by applicable law or agreed to in writing, software
  1405. * distributed under the License is distributed on an "AS IS" BASIS,
  1406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1407. * See the License for the specific language governing permissions and
  1408. * limitations under the License.
  1409. */
  1410. /**
  1411. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1412. * it references AuthInternal which has a circular dependency with UserInternal.
  1413. *
  1414. * @internal
  1415. */
  1416. class StsTokenManager {
  1417. constructor() {
  1418. this.refreshToken = null;
  1419. this.accessToken = null;
  1420. this.expirationTime = null;
  1421. }
  1422. get isExpired() {
  1423. return (!this.expirationTime ||
  1424. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1425. }
  1426. updateFromServerResponse(response) {
  1427. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1428. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1429. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1430. const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1431. ? Number(response.expiresIn)
  1432. : _tokenExpiresIn(response.idToken);
  1433. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1434. }
  1435. async getToken(auth, forceRefresh = false) {
  1436. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1437. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1438. return this.accessToken;
  1439. }
  1440. if (this.refreshToken) {
  1441. await this.refresh(auth, this.refreshToken);
  1442. return this.accessToken;
  1443. }
  1444. return null;
  1445. }
  1446. clearRefreshToken() {
  1447. this.refreshToken = null;
  1448. }
  1449. async refresh(auth, oldToken) {
  1450. const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);
  1451. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1452. }
  1453. updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {
  1454. this.refreshToken = refreshToken || null;
  1455. this.accessToken = accessToken || null;
  1456. this.expirationTime = Date.now() + expiresInSec * 1000;
  1457. }
  1458. static fromJSON(appName, object) {
  1459. const { refreshToken, accessToken, expirationTime } = object;
  1460. const manager = new StsTokenManager();
  1461. if (refreshToken) {
  1462. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1463. appName
  1464. });
  1465. manager.refreshToken = refreshToken;
  1466. }
  1467. if (accessToken) {
  1468. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1469. appName
  1470. });
  1471. manager.accessToken = accessToken;
  1472. }
  1473. if (expirationTime) {
  1474. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1475. appName
  1476. });
  1477. manager.expirationTime = expirationTime;
  1478. }
  1479. return manager;
  1480. }
  1481. toJSON() {
  1482. return {
  1483. refreshToken: this.refreshToken,
  1484. accessToken: this.accessToken,
  1485. expirationTime: this.expirationTime
  1486. };
  1487. }
  1488. _assign(stsTokenManager) {
  1489. this.accessToken = stsTokenManager.accessToken;
  1490. this.refreshToken = stsTokenManager.refreshToken;
  1491. this.expirationTime = stsTokenManager.expirationTime;
  1492. }
  1493. _clone() {
  1494. return Object.assign(new StsTokenManager(), this.toJSON());
  1495. }
  1496. _performRefresh() {
  1497. return debugFail('not implemented');
  1498. }
  1499. }
  1500. /**
  1501. * @license
  1502. * Copyright 2020 Google LLC
  1503. *
  1504. * Licensed under the Apache License, Version 2.0 (the "License");
  1505. * you may not use this file except in compliance with the License.
  1506. * You may obtain a copy of the License at
  1507. *
  1508. * http://www.apache.org/licenses/LICENSE-2.0
  1509. *
  1510. * Unless required by applicable law or agreed to in writing, software
  1511. * distributed under the License is distributed on an "AS IS" BASIS,
  1512. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1513. * See the License for the specific language governing permissions and
  1514. * limitations under the License.
  1515. */
  1516. function assertStringOrUndefined(assertion, appName) {
  1517. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName });
  1518. }
  1519. class UserImpl {
  1520. constructor(_a) {
  1521. var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1522. // For the user object, provider is always Firebase.
  1523. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1524. this.proactiveRefresh = new ProactiveRefresh(this);
  1525. this.reloadUserInfo = null;
  1526. this.reloadListener = null;
  1527. this.uid = uid;
  1528. this.auth = auth;
  1529. this.stsTokenManager = stsTokenManager;
  1530. this.accessToken = stsTokenManager.accessToken;
  1531. this.displayName = opt.displayName || null;
  1532. this.email = opt.email || null;
  1533. this.emailVerified = opt.emailVerified || false;
  1534. this.phoneNumber = opt.phoneNumber || null;
  1535. this.photoURL = opt.photoURL || null;
  1536. this.isAnonymous = opt.isAnonymous || false;
  1537. this.tenantId = opt.tenantId || null;
  1538. this.providerData = opt.providerData ? [...opt.providerData] : [];
  1539. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1540. }
  1541. async getIdToken(forceRefresh) {
  1542. const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));
  1543. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1544. if (this.accessToken !== accessToken) {
  1545. this.accessToken = accessToken;
  1546. await this.auth._persistUserIfCurrent(this);
  1547. this.auth._notifyListenersIfCurrent(this);
  1548. }
  1549. return accessToken;
  1550. }
  1551. getIdTokenResult(forceRefresh) {
  1552. return getIdTokenResult(this, forceRefresh);
  1553. }
  1554. reload() {
  1555. return reload(this);
  1556. }
  1557. _assign(user) {
  1558. if (this === user) {
  1559. return;
  1560. }
  1561. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1562. this.displayName = user.displayName;
  1563. this.photoURL = user.photoURL;
  1564. this.email = user.email;
  1565. this.emailVerified = user.emailVerified;
  1566. this.phoneNumber = user.phoneNumber;
  1567. this.isAnonymous = user.isAnonymous;
  1568. this.tenantId = user.tenantId;
  1569. this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));
  1570. this.metadata._copy(user.metadata);
  1571. this.stsTokenManager._assign(user.stsTokenManager);
  1572. }
  1573. _clone(auth) {
  1574. const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));
  1575. newUser.metadata._copy(this.metadata);
  1576. return newUser;
  1577. }
  1578. _onReload(callback) {
  1579. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1580. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1581. this.reloadListener = callback;
  1582. if (this.reloadUserInfo) {
  1583. this._notifyReloadListener(this.reloadUserInfo);
  1584. this.reloadUserInfo = null;
  1585. }
  1586. }
  1587. _notifyReloadListener(userInfo) {
  1588. if (this.reloadListener) {
  1589. this.reloadListener(userInfo);
  1590. }
  1591. else {
  1592. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1593. this.reloadUserInfo = userInfo;
  1594. }
  1595. }
  1596. _startProactiveRefresh() {
  1597. this.proactiveRefresh._start();
  1598. }
  1599. _stopProactiveRefresh() {
  1600. this.proactiveRefresh._stop();
  1601. }
  1602. async _updateTokensIfNecessary(response, reload = false) {
  1603. let tokensRefreshed = false;
  1604. if (response.idToken &&
  1605. response.idToken !== this.stsTokenManager.accessToken) {
  1606. this.stsTokenManager.updateFromServerResponse(response);
  1607. tokensRefreshed = true;
  1608. }
  1609. if (reload) {
  1610. await _reloadWithoutSaving(this);
  1611. }
  1612. await this.auth._persistUserIfCurrent(this);
  1613. if (tokensRefreshed) {
  1614. this.auth._notifyListenersIfCurrent(this);
  1615. }
  1616. }
  1617. async delete() {
  1618. const idToken = await this.getIdToken();
  1619. await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));
  1620. this.stsTokenManager.clearRefreshToken();
  1621. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1622. // cancels pending actions...
  1623. return this.auth.signOut();
  1624. }
  1625. toJSON() {
  1626. return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(),
  1627. // Redirect event ID must be maintained in case there is a pending
  1628. // redirect event.
  1629. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1630. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1631. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1632. }
  1633. get refreshToken() {
  1634. return this.stsTokenManager.refreshToken || '';
  1635. }
  1636. static _fromJSON(auth, object) {
  1637. var _a, _b, _c, _d, _e, _f, _g, _h;
  1638. const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1639. const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1640. const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1641. const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1642. const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1643. const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1644. const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1645. const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1646. const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;
  1647. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1648. const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1649. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1650. assertStringOrUndefined(displayName, auth.name);
  1651. assertStringOrUndefined(email, auth.name);
  1652. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1653. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1654. assertStringOrUndefined(phoneNumber, auth.name);
  1655. assertStringOrUndefined(photoURL, auth.name);
  1656. assertStringOrUndefined(tenantId, auth.name);
  1657. assertStringOrUndefined(_redirectEventId, auth.name);
  1658. assertStringOrUndefined(createdAt, auth.name);
  1659. assertStringOrUndefined(lastLoginAt, auth.name);
  1660. const user = new UserImpl({
  1661. uid,
  1662. auth,
  1663. email,
  1664. emailVerified,
  1665. displayName,
  1666. isAnonymous,
  1667. photoURL,
  1668. phoneNumber,
  1669. tenantId,
  1670. stsTokenManager,
  1671. createdAt,
  1672. lastLoginAt
  1673. });
  1674. if (providerData && Array.isArray(providerData)) {
  1675. user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));
  1676. }
  1677. if (_redirectEventId) {
  1678. user._redirectEventId = _redirectEventId;
  1679. }
  1680. return user;
  1681. }
  1682. /**
  1683. * Initialize a User from an idToken server response
  1684. * @param auth
  1685. * @param idTokenResponse
  1686. */
  1687. static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {
  1688. const stsTokenManager = new StsTokenManager();
  1689. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1690. // Initialize the Firebase Auth user.
  1691. const user = new UserImpl({
  1692. uid: idTokenResponse.localId,
  1693. auth,
  1694. stsTokenManager,
  1695. isAnonymous
  1696. });
  1697. // Updates the user info and data and resolves with a user instance.
  1698. await _reloadWithoutSaving(user);
  1699. return user;
  1700. }
  1701. }
  1702. /**
  1703. * @license
  1704. * Copyright 2020 Google LLC
  1705. *
  1706. * Licensed under the Apache License, Version 2.0 (the "License");
  1707. * you may not use this file except in compliance with the License.
  1708. * You may obtain a copy of the License at
  1709. *
  1710. * http://www.apache.org/licenses/LICENSE-2.0
  1711. *
  1712. * Unless required by applicable law or agreed to in writing, software
  1713. * distributed under the License is distributed on an "AS IS" BASIS,
  1714. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1715. * See the License for the specific language governing permissions and
  1716. * limitations under the License.
  1717. */
  1718. const instanceCache = new Map();
  1719. function _getInstance(cls) {
  1720. debugAssert(cls instanceof Function, 'Expected a class definition');
  1721. let instance = instanceCache.get(cls);
  1722. if (instance) {
  1723. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  1724. return instance;
  1725. }
  1726. instance = new cls();
  1727. instanceCache.set(cls, instance);
  1728. return instance;
  1729. }
  1730. /**
  1731. * @license
  1732. * Copyright 2019 Google LLC
  1733. *
  1734. * Licensed under the Apache License, Version 2.0 (the "License");
  1735. * you may not use this file except in compliance with the License.
  1736. * You may obtain a copy of the License at
  1737. *
  1738. * http://www.apache.org/licenses/LICENSE-2.0
  1739. *
  1740. * Unless required by applicable law or agreed to in writing, software
  1741. * distributed under the License is distributed on an "AS IS" BASIS,
  1742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1743. * See the License for the specific language governing permissions and
  1744. * limitations under the License.
  1745. */
  1746. class InMemoryPersistence {
  1747. constructor() {
  1748. this.type = "NONE" /* PersistenceType.NONE */;
  1749. this.storage = {};
  1750. }
  1751. async _isAvailable() {
  1752. return true;
  1753. }
  1754. async _set(key, value) {
  1755. this.storage[key] = value;
  1756. }
  1757. async _get(key) {
  1758. const value = this.storage[key];
  1759. return value === undefined ? null : value;
  1760. }
  1761. async _remove(key) {
  1762. delete this.storage[key];
  1763. }
  1764. _addListener(_key, _listener) {
  1765. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1766. return;
  1767. }
  1768. _removeListener(_key, _listener) {
  1769. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1770. return;
  1771. }
  1772. }
  1773. InMemoryPersistence.type = 'NONE';
  1774. /**
  1775. * An implementation of {@link Persistence} of type 'NONE'.
  1776. *
  1777. * @public
  1778. */
  1779. const inMemoryPersistence = InMemoryPersistence;
  1780. /**
  1781. * @license
  1782. * Copyright 2019 Google LLC
  1783. *
  1784. * Licensed under the Apache License, Version 2.0 (the "License");
  1785. * you may not use this file except in compliance with the License.
  1786. * You may obtain a copy of the License at
  1787. *
  1788. * http://www.apache.org/licenses/LICENSE-2.0
  1789. *
  1790. * Unless required by applicable law or agreed to in writing, software
  1791. * distributed under the License is distributed on an "AS IS" BASIS,
  1792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1793. * See the License for the specific language governing permissions and
  1794. * limitations under the License.
  1795. */
  1796. function _persistenceKeyName(key, apiKey, appName) {
  1797. return `${"firebase" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;
  1798. }
  1799. class PersistenceUserManager {
  1800. constructor(persistence, auth, userKey) {
  1801. this.persistence = persistence;
  1802. this.auth = auth;
  1803. this.userKey = userKey;
  1804. const { config, name } = this.auth;
  1805. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  1806. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  1807. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  1808. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  1809. }
  1810. setCurrentUser(user) {
  1811. return this.persistence._set(this.fullUserKey, user.toJSON());
  1812. }
  1813. async getCurrentUser() {
  1814. const blob = await this.persistence._get(this.fullUserKey);
  1815. return blob ? UserImpl._fromJSON(this.auth, blob) : null;
  1816. }
  1817. removeCurrentUser() {
  1818. return this.persistence._remove(this.fullUserKey);
  1819. }
  1820. savePersistenceForRedirect() {
  1821. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  1822. }
  1823. async setPersistence(newPersistence) {
  1824. if (this.persistence === newPersistence) {
  1825. return;
  1826. }
  1827. const currentUser = await this.getCurrentUser();
  1828. await this.removeCurrentUser();
  1829. this.persistence = newPersistence;
  1830. if (currentUser) {
  1831. return this.setCurrentUser(currentUser);
  1832. }
  1833. }
  1834. delete() {
  1835. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  1836. }
  1837. static async create(auth, persistenceHierarchy, userKey = "authUser" /* KeyName.AUTH_USER */) {
  1838. if (!persistenceHierarchy.length) {
  1839. return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);
  1840. }
  1841. // Eliminate any persistences that are not available
  1842. const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1843. if (await persistence._isAvailable()) {
  1844. return persistence;
  1845. }
  1846. return undefined;
  1847. }))).filter(persistence => persistence);
  1848. // Fall back to the first persistence listed, or in memory if none available
  1849. let selectedPersistence = availablePersistences[0] ||
  1850. _getInstance(inMemoryPersistence);
  1851. const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  1852. // Pull out the existing user, setting the chosen persistence to that
  1853. // persistence if the user exists.
  1854. let userToMigrate = null;
  1855. // Note, here we check for a user in _all_ persistences, not just the
  1856. // ones deemed available. If we can migrate a user out of a broken
  1857. // persistence, we will (but only if that persistence supports migration).
  1858. for (const persistence of persistenceHierarchy) {
  1859. try {
  1860. const blob = await persistence._get(key);
  1861. if (blob) {
  1862. const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)
  1863. if (persistence !== selectedPersistence) {
  1864. userToMigrate = user;
  1865. }
  1866. selectedPersistence = persistence;
  1867. break;
  1868. }
  1869. }
  1870. catch (_a) { }
  1871. }
  1872. // If we find the user in a persistence that does support migration, use
  1873. // that migration path (of only persistences that support migration)
  1874. const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);
  1875. // If the persistence does _not_ allow migration, just finish off here
  1876. if (!selectedPersistence._shouldAllowMigration ||
  1877. !migrationHierarchy.length) {
  1878. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1879. }
  1880. selectedPersistence = migrationHierarchy[0];
  1881. if (userToMigrate) {
  1882. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  1883. // we'll just let it bubble to surface the error.
  1884. await selectedPersistence._set(key, userToMigrate.toJSON());
  1885. }
  1886. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  1887. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  1888. await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1889. if (persistence !== selectedPersistence) {
  1890. try {
  1891. await persistence._remove(key);
  1892. }
  1893. catch (_a) { }
  1894. }
  1895. }));
  1896. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1897. }
  1898. }
  1899. /**
  1900. * @license
  1901. * Copyright 2020 Google LLC
  1902. *
  1903. * Licensed under the Apache License, Version 2.0 (the "License");
  1904. * you may not use this file except in compliance with the License.
  1905. * You may obtain a copy of the License at
  1906. *
  1907. * http://www.apache.org/licenses/LICENSE-2.0
  1908. *
  1909. * Unless required by applicable law or agreed to in writing, software
  1910. * distributed under the License is distributed on an "AS IS" BASIS,
  1911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1912. * See the License for the specific language governing permissions and
  1913. * limitations under the License.
  1914. */
  1915. /**
  1916. * Determine the browser for the purposes of reporting usage to the API
  1917. */
  1918. function _getBrowserName(userAgent) {
  1919. const ua = userAgent.toLowerCase();
  1920. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  1921. return "Opera" /* BrowserName.OPERA */;
  1922. }
  1923. else if (_isIEMobile(ua)) {
  1924. // Windows phone IEMobile browser.
  1925. return "IEMobile" /* BrowserName.IEMOBILE */;
  1926. }
  1927. else if (ua.includes('msie') || ua.includes('trident/')) {
  1928. return "IE" /* BrowserName.IE */;
  1929. }
  1930. else if (ua.includes('edge/')) {
  1931. return "Edge" /* BrowserName.EDGE */;
  1932. }
  1933. else if (_isFirefox(ua)) {
  1934. return "Firefox" /* BrowserName.FIREFOX */;
  1935. }
  1936. else if (ua.includes('silk/')) {
  1937. return "Silk" /* BrowserName.SILK */;
  1938. }
  1939. else if (_isBlackBerry(ua)) {
  1940. // Blackberry browser.
  1941. return "Blackberry" /* BrowserName.BLACKBERRY */;
  1942. }
  1943. else if (_isWebOS(ua)) {
  1944. // WebOS default browser.
  1945. return "Webos" /* BrowserName.WEBOS */;
  1946. }
  1947. else if (_isSafari(ua)) {
  1948. return "Safari" /* BrowserName.SAFARI */;
  1949. }
  1950. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  1951. !ua.includes('edge/')) {
  1952. return "Chrome" /* BrowserName.CHROME */;
  1953. }
  1954. else if (_isAndroid(ua)) {
  1955. // Android stock browser.
  1956. return "Android" /* BrowserName.ANDROID */;
  1957. }
  1958. else {
  1959. // Most modern browsers have name/version at end of user agent string.
  1960. const re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  1961. const matches = userAgent.match(re);
  1962. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  1963. return matches[1];
  1964. }
  1965. }
  1966. return "Other" /* BrowserName.OTHER */;
  1967. }
  1968. function _isFirefox(ua = getUA()) {
  1969. return /firefox\//i.test(ua);
  1970. }
  1971. function _isSafari(userAgent = getUA()) {
  1972. const ua = userAgent.toLowerCase();
  1973. return (ua.includes('safari/') &&
  1974. !ua.includes('chrome/') &&
  1975. !ua.includes('crios/') &&
  1976. !ua.includes('android'));
  1977. }
  1978. function _isChromeIOS(ua = getUA()) {
  1979. return /crios\//i.test(ua);
  1980. }
  1981. function _isIEMobile(ua = getUA()) {
  1982. return /iemobile/i.test(ua);
  1983. }
  1984. function _isAndroid(ua = getUA()) {
  1985. return /android/i.test(ua);
  1986. }
  1987. function _isBlackBerry(ua = getUA()) {
  1988. return /blackberry/i.test(ua);
  1989. }
  1990. function _isWebOS(ua = getUA()) {
  1991. return /webos/i.test(ua);
  1992. }
  1993. function _isIOS(ua = getUA()) {
  1994. return (/iphone|ipad|ipod/i.test(ua) ||
  1995. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  1996. }
  1997. function _isIOS7Or8(ua = getUA()) {
  1998. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  1999. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2000. }
  2001. function _isIOSStandalone(ua = getUA()) {
  2002. var _a;
  2003. return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
  2004. }
  2005. function _isIE10() {
  2006. return isIE() && document.documentMode === 10;
  2007. }
  2008. function _isMobileBrowser(ua = getUA()) {
  2009. // TODO: implement getBrowserName equivalent for OS.
  2010. return (_isIOS(ua) ||
  2011. _isAndroid(ua) ||
  2012. _isWebOS(ua) ||
  2013. _isBlackBerry(ua) ||
  2014. /windows phone/i.test(ua) ||
  2015. _isIEMobile(ua));
  2016. }
  2017. function _isIframe() {
  2018. try {
  2019. // Check that the current window is not the top window.
  2020. // If so, return true.
  2021. return !!(window && window !== window.top);
  2022. }
  2023. catch (e) {
  2024. return false;
  2025. }
  2026. }
  2027. /**
  2028. * @license
  2029. * Copyright 2020 Google LLC
  2030. *
  2031. * Licensed under the Apache License, Version 2.0 (the "License");
  2032. * you may not use this file except in compliance with the License.
  2033. * You may obtain a copy of the License at
  2034. *
  2035. * http://www.apache.org/licenses/LICENSE-2.0
  2036. *
  2037. * Unless required by applicable law or agreed to in writing, software
  2038. * distributed under the License is distributed on an "AS IS" BASIS,
  2039. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2040. * See the License for the specific language governing permissions and
  2041. * limitations under the License.
  2042. */
  2043. /*
  2044. * Determine the SDK version string
  2045. */
  2046. function _getClientVersion(clientPlatform, frameworks = []) {
  2047. let reportedPlatform;
  2048. switch (clientPlatform) {
  2049. case "Browser" /* ClientPlatform.BROWSER */:
  2050. // In a browser environment, report the browser name.
  2051. reportedPlatform = _getBrowserName(getUA());
  2052. break;
  2053. case "Worker" /* ClientPlatform.WORKER */:
  2054. // Technically a worker runs from a browser but we need to differentiate a
  2055. // worker from a browser.
  2056. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2057. reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;
  2058. break;
  2059. default:
  2060. reportedPlatform = clientPlatform;
  2061. }
  2062. const reportedFrameworks = frameworks.length
  2063. ? frameworks.join(',')
  2064. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2065. return `${reportedPlatform}/${"JsCore" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;
  2066. }
  2067. /**
  2068. * @license
  2069. * Copyright 2020 Google LLC
  2070. *
  2071. * Licensed under the Apache License, Version 2.0 (the "License");
  2072. * you may not use this file except in compliance with the License.
  2073. * You may obtain a copy of the License at
  2074. *
  2075. * http://www.apache.org/licenses/LICENSE-2.0
  2076. *
  2077. * Unless required by applicable law or agreed to in writing, software
  2078. * distributed under the License is distributed on an "AS IS" BASIS,
  2079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2080. * See the License for the specific language governing permissions and
  2081. * limitations under the License.
  2082. */
  2083. async function getRecaptchaParams(auth) {
  2084. return ((await _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/recaptchaParams" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');
  2085. }
  2086. async function getRecaptchaConfig(auth, request) {
  2087. return _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v2/recaptchaConfig" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));
  2088. }
  2089. /**
  2090. * @license
  2091. * Copyright 2020 Google LLC
  2092. *
  2093. * Licensed under the Apache License, Version 2.0 (the "License");
  2094. * you may not use this file except in compliance with the License.
  2095. * You may obtain a copy of the License at
  2096. *
  2097. * http://www.apache.org/licenses/LICENSE-2.0
  2098. *
  2099. * Unless required by applicable law or agreed to in writing, software
  2100. * distributed under the License is distributed on an "AS IS" BASIS,
  2101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2102. * See the License for the specific language governing permissions and
  2103. * limitations under the License.
  2104. */
  2105. function isV2(grecaptcha) {
  2106. return (grecaptcha !== undefined &&
  2107. grecaptcha.getResponse !== undefined);
  2108. }
  2109. function isEnterprise(grecaptcha) {
  2110. return (grecaptcha !== undefined &&
  2111. grecaptcha.enterprise !== undefined);
  2112. }
  2113. class RecaptchaConfig {
  2114. constructor(response) {
  2115. /**
  2116. * The reCAPTCHA site key.
  2117. */
  2118. this.siteKey = '';
  2119. /**
  2120. * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.
  2121. */
  2122. this.emailPasswordEnabled = false;
  2123. if (response.recaptchaKey === undefined) {
  2124. throw new Error('recaptchaKey undefined');
  2125. }
  2126. // Example response.recaptchaKey: "projects/proj123/keys/sitekey123"
  2127. this.siteKey = response.recaptchaKey.split('/')[3];
  2128. this.emailPasswordEnabled = response.recaptchaEnforcementState.some(enforcementState => enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&
  2129. enforcementState.enforcementState !== 'OFF');
  2130. }
  2131. }
  2132. /**
  2133. * @license
  2134. * Copyright 2020 Google LLC
  2135. *
  2136. * Licensed under the Apache License, Version 2.0 (the "License");
  2137. * you may not use this file except in compliance with the License.
  2138. * You may obtain a copy of the License at
  2139. *
  2140. * http://www.apache.org/licenses/LICENSE-2.0
  2141. *
  2142. * Unless required by applicable law or agreed to in writing, software
  2143. * distributed under the License is distributed on an "AS IS" BASIS,
  2144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2145. * See the License for the specific language governing permissions and
  2146. * limitations under the License.
  2147. */
  2148. function getScriptParentElement() {
  2149. var _a, _b;
  2150. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  2151. }
  2152. function _loadJS(url) {
  2153. // TODO: consider adding timeout support & cancellation
  2154. return new Promise((resolve, reject) => {
  2155. const el = document.createElement('script');
  2156. el.setAttribute('src', url);
  2157. el.onload = resolve;
  2158. el.onerror = e => {
  2159. const error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2160. error.customData = e;
  2161. reject(error);
  2162. };
  2163. el.type = 'text/javascript';
  2164. el.charset = 'UTF-8';
  2165. getScriptParentElement().appendChild(el);
  2166. });
  2167. }
  2168. function _generateCallbackName(prefix) {
  2169. return `__${prefix}${Math.floor(Math.random() * 1000000)}`;
  2170. }
  2171. /* eslint-disable @typescript-eslint/no-require-imports */
  2172. const RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';
  2173. const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';
  2174. const FAKE_TOKEN = 'NO_RECAPTCHA';
  2175. class RecaptchaEnterpriseVerifier {
  2176. /**
  2177. *
  2178. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  2179. *
  2180. */
  2181. constructor(authExtern) {
  2182. /**
  2183. * Identifies the type of application verifier (e.g. "recaptcha-enterprise").
  2184. */
  2185. this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
  2186. this.auth = _castAuth(authExtern);
  2187. }
  2188. /**
  2189. * Executes the verification process.
  2190. *
  2191. * @returns A Promise for a token that can be used to assert the validity of a request.
  2192. */
  2193. async verify(action = 'verify', forceRefresh = false) {
  2194. async function retrieveSiteKey(auth) {
  2195. if (!forceRefresh) {
  2196. if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {
  2197. return auth._agentRecaptchaConfig.siteKey;
  2198. }
  2199. if (auth.tenantId != null &&
  2200. auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {
  2201. return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;
  2202. }
  2203. }
  2204. return new Promise(async (resolve, reject) => {
  2205. getRecaptchaConfig(auth, {
  2206. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  2207. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2208. })
  2209. .then(response => {
  2210. if (response.recaptchaKey === undefined) {
  2211. reject(new Error('recaptcha Enterprise site key undefined'));
  2212. }
  2213. else {
  2214. const config = new RecaptchaConfig(response);
  2215. if (auth.tenantId == null) {
  2216. auth._agentRecaptchaConfig = config;
  2217. }
  2218. else {
  2219. auth._tenantRecaptchaConfigs[auth.tenantId] = config;
  2220. }
  2221. return resolve(config.siteKey);
  2222. }
  2223. })
  2224. .catch(error => {
  2225. reject(error);
  2226. });
  2227. });
  2228. }
  2229. function retrieveRecaptchaToken(siteKey, resolve, reject) {
  2230. const grecaptcha = window.grecaptcha;
  2231. if (isEnterprise(grecaptcha)) {
  2232. grecaptcha.enterprise.ready(() => {
  2233. grecaptcha.enterprise
  2234. .execute(siteKey, { action })
  2235. .then(token => {
  2236. resolve(token);
  2237. })
  2238. .catch(() => {
  2239. resolve(FAKE_TOKEN);
  2240. });
  2241. });
  2242. }
  2243. else {
  2244. reject(Error('No reCAPTCHA enterprise script loaded.'));
  2245. }
  2246. }
  2247. return new Promise((resolve, reject) => {
  2248. retrieveSiteKey(this.auth)
  2249. .then(siteKey => {
  2250. if (!forceRefresh && isEnterprise(window.grecaptcha)) {
  2251. retrieveRecaptchaToken(siteKey, resolve, reject);
  2252. }
  2253. else {
  2254. if (typeof window === 'undefined') {
  2255. reject(new Error('RecaptchaVerifier is only supported in browser'));
  2256. return;
  2257. }
  2258. _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)
  2259. .then(() => {
  2260. retrieveRecaptchaToken(siteKey, resolve, reject);
  2261. })
  2262. .catch(error => {
  2263. reject(error);
  2264. });
  2265. }
  2266. })
  2267. .catch(error => {
  2268. reject(error);
  2269. });
  2270. });
  2271. }
  2272. }
  2273. async function injectRecaptchaFields(auth, request, action, captchaResp = false) {
  2274. const verifier = new RecaptchaEnterpriseVerifier(auth);
  2275. let captchaResponse;
  2276. try {
  2277. captchaResponse = await verifier.verify(action);
  2278. }
  2279. catch (error) {
  2280. captchaResponse = await verifier.verify(action, true);
  2281. }
  2282. const newRequest = Object.assign({}, request);
  2283. if (!captchaResp) {
  2284. Object.assign(newRequest, { captchaResponse });
  2285. }
  2286. else {
  2287. Object.assign(newRequest, { 'captchaResp': captchaResponse });
  2288. }
  2289. Object.assign(newRequest, { 'clientType': "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */ });
  2290. Object.assign(newRequest, {
  2291. 'recaptchaVersion': "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2292. });
  2293. return newRequest;
  2294. }
  2295. /**
  2296. * @license
  2297. * Copyright 2022 Google LLC
  2298. *
  2299. * Licensed under the Apache License, Version 2.0 (the "License");
  2300. * you may not use this file except in compliance with the License.
  2301. * You may obtain a copy of the License at
  2302. *
  2303. * http://www.apache.org/licenses/LICENSE-2.0
  2304. *
  2305. * Unless required by applicable law or agreed to in writing, software
  2306. * distributed under the License is distributed on an "AS IS" BASIS,
  2307. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2308. * See the License for the specific language governing permissions and
  2309. * limitations under the License.
  2310. */
  2311. class AuthMiddlewareQueue {
  2312. constructor(auth) {
  2313. this.auth = auth;
  2314. this.queue = [];
  2315. }
  2316. pushCallback(callback, onAbort) {
  2317. // The callback could be sync or async. Wrap it into a
  2318. // function that is always async.
  2319. const wrappedCallback = (user) => new Promise((resolve, reject) => {
  2320. try {
  2321. const result = callback(user);
  2322. // Either resolve with existing promise or wrap a non-promise
  2323. // return value into a promise.
  2324. resolve(result);
  2325. }
  2326. catch (e) {
  2327. // Sync callback throws.
  2328. reject(e);
  2329. }
  2330. });
  2331. // Attach the onAbort if present
  2332. wrappedCallback.onAbort = onAbort;
  2333. this.queue.push(wrappedCallback);
  2334. const index = this.queue.length - 1;
  2335. return () => {
  2336. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2337. // indexing of other elements.
  2338. this.queue[index] = () => Promise.resolve();
  2339. };
  2340. }
  2341. async runMiddleware(nextUser) {
  2342. if (this.auth.currentUser === nextUser) {
  2343. return;
  2344. }
  2345. // While running the middleware, build a temporary stack of onAbort
  2346. // callbacks to call if one middleware callback rejects.
  2347. const onAbortStack = [];
  2348. try {
  2349. for (const beforeStateCallback of this.queue) {
  2350. await beforeStateCallback(nextUser);
  2351. // Only push the onAbort if the callback succeeds
  2352. if (beforeStateCallback.onAbort) {
  2353. onAbortStack.push(beforeStateCallback.onAbort);
  2354. }
  2355. }
  2356. }
  2357. catch (e) {
  2358. // Run all onAbort, with separate try/catch to ignore any errors and
  2359. // continue
  2360. onAbortStack.reverse();
  2361. for (const onAbort of onAbortStack) {
  2362. try {
  2363. onAbort();
  2364. }
  2365. catch (_) {
  2366. /* swallow error */
  2367. }
  2368. }
  2369. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2370. originalMessage: e === null || e === void 0 ? void 0 : e.message
  2371. });
  2372. }
  2373. }
  2374. }
  2375. /**
  2376. * @license
  2377. * Copyright 2020 Google LLC
  2378. *
  2379. * Licensed under the Apache License, Version 2.0 (the "License");
  2380. * you may not use this file except in compliance with the License.
  2381. * You may obtain a copy of the License at
  2382. *
  2383. * http://www.apache.org/licenses/LICENSE-2.0
  2384. *
  2385. * Unless required by applicable law or agreed to in writing, software
  2386. * distributed under the License is distributed on an "AS IS" BASIS,
  2387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2388. * See the License for the specific language governing permissions and
  2389. * limitations under the License.
  2390. */
  2391. class AuthImpl {
  2392. constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {
  2393. this.app = app;
  2394. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2395. this.appCheckServiceProvider = appCheckServiceProvider;
  2396. this.config = config;
  2397. this.currentUser = null;
  2398. this.emulatorConfig = null;
  2399. this.operations = Promise.resolve();
  2400. this.authStateSubscription = new Subscription(this);
  2401. this.idTokenSubscription = new Subscription(this);
  2402. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2403. this.redirectUser = null;
  2404. this.isProactiveRefreshEnabled = false;
  2405. // Any network calls will set this to true and prevent subsequent emulator
  2406. // initialization
  2407. this._canInitEmulator = true;
  2408. this._isInitialized = false;
  2409. this._deleted = false;
  2410. this._initializationPromise = null;
  2411. this._popupRedirectResolver = null;
  2412. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2413. this._agentRecaptchaConfig = null;
  2414. this._tenantRecaptchaConfigs = {};
  2415. // Tracks the last notified UID for state change listeners to prevent
  2416. // repeated calls to the callbacks. Undefined means it's never been
  2417. // called, whereas null means it's been called with a signed out user
  2418. this.lastNotifiedUid = undefined;
  2419. this.languageCode = null;
  2420. this.tenantId = null;
  2421. this.settings = { appVerificationDisabledForTesting: false };
  2422. this.frameworks = [];
  2423. this.name = app.name;
  2424. this.clientVersion = config.sdkClientVersion;
  2425. }
  2426. _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {
  2427. if (popupRedirectResolver) {
  2428. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2429. }
  2430. // Have to check for app deletion throughout initialization (after each
  2431. // promise resolution)
  2432. this._initializationPromise = this.queue(async () => {
  2433. var _a, _b;
  2434. if (this._deleted) {
  2435. return;
  2436. }
  2437. this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);
  2438. if (this._deleted) {
  2439. return;
  2440. }
  2441. // Initialize the resolver early if necessary (only applicable to web:
  2442. // this will cause the iframe to load immediately in certain cases)
  2443. if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {
  2444. // If this fails, don't halt auth loading
  2445. try {
  2446. await this._popupRedirectResolver._initialize(this);
  2447. }
  2448. catch (e) {
  2449. /* Ignore the error */
  2450. }
  2451. }
  2452. await this.initializeCurrentUser(popupRedirectResolver);
  2453. this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;
  2454. if (this._deleted) {
  2455. return;
  2456. }
  2457. this._isInitialized = true;
  2458. });
  2459. return this._initializationPromise;
  2460. }
  2461. /**
  2462. * If the persistence is changed in another window, the user manager will let us know
  2463. */
  2464. async _onStorageEvent() {
  2465. if (this._deleted) {
  2466. return;
  2467. }
  2468. const user = await this.assertedPersistence.getCurrentUser();
  2469. if (!this.currentUser && !user) {
  2470. // No change, do nothing (was signed out and remained signed out).
  2471. return;
  2472. }
  2473. // If the same user is to be synchronized.
  2474. if (this.currentUser && user && this.currentUser.uid === user.uid) {
  2475. // Data update, simply copy data changes.
  2476. this._currentUser._assign(user);
  2477. // If tokens changed from previous user tokens, this will trigger
  2478. // notifyAuthListeners_.
  2479. await this.currentUser.getIdToken();
  2480. return;
  2481. }
  2482. // Update current Auth state. Either a new login or logout.
  2483. // Skip blocking callbacks, they should not apply to a change in another tab.
  2484. await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);
  2485. }
  2486. async initializeCurrentUser(popupRedirectResolver) {
  2487. var _a;
  2488. // First check to see if we have a pending redirect event.
  2489. const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());
  2490. let futureCurrentUser = previouslyStoredUser;
  2491. let needsTocheckMiddleware = false;
  2492. if (popupRedirectResolver && this.config.authDomain) {
  2493. await this.getOrInitRedirectPersistenceManager();
  2494. const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2495. const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2496. const result = await this.tryRedirectSignIn(popupRedirectResolver);
  2497. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2498. // matches the redirect user, then we want to initially sign in with the
  2499. // new user object from result.
  2500. // TODO(samgho): More thoroughly test all of this
  2501. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2502. (result === null || result === void 0 ? void 0 : result.user)) {
  2503. futureCurrentUser = result.user;
  2504. needsTocheckMiddleware = true;
  2505. }
  2506. }
  2507. // If no user in persistence, there is no current user. Set to null.
  2508. if (!futureCurrentUser) {
  2509. return this.directlySetCurrentUser(null);
  2510. }
  2511. if (!futureCurrentUser._redirectEventId) {
  2512. // This isn't a redirect link operation, we can reload and bail.
  2513. // First though, ensure that we check the middleware is happy.
  2514. if (needsTocheckMiddleware) {
  2515. try {
  2516. await this.beforeStateQueue.runMiddleware(futureCurrentUser);
  2517. }
  2518. catch (e) {
  2519. futureCurrentUser = previouslyStoredUser;
  2520. // We know this is available since the bit is only set when the
  2521. // resolver is available
  2522. this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));
  2523. }
  2524. }
  2525. if (futureCurrentUser) {
  2526. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2527. }
  2528. else {
  2529. return this.directlySetCurrentUser(null);
  2530. }
  2531. }
  2532. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2533. await this.getOrInitRedirectPersistenceManager();
  2534. // If the redirect user's event ID matches the current user's event ID,
  2535. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2536. // This is important for the reauthenticateWithRedirect() flow.
  2537. if (this.redirectUser &&
  2538. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2539. return this.directlySetCurrentUser(futureCurrentUser);
  2540. }
  2541. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2542. }
  2543. async tryRedirectSignIn(redirectResolver) {
  2544. // The redirect user needs to be checked (and signed in if available)
  2545. // during auth initialization. All of the normal sign in and link/reauth
  2546. // flows call back into auth and push things onto the promise queue. We
  2547. // need to await the result of the redirect sign in *inside the promise
  2548. // queue*. This presents a problem: we run into deadlock. See:
  2549. // ┌> [Initialization] ─────┐
  2550. // ┌> [<other queue tasks>] │
  2551. // └─ [getRedirectResult] <─┘
  2552. // where [] are tasks on the queue and arrows denote awaits
  2553. // Initialization will never complete because it's waiting on something
  2554. // that's waiting for initialization to complete!
  2555. //
  2556. // Instead, this method calls getRedirectResult() (stored in
  2557. // _completeRedirectFn) with an optional parameter that instructs all of
  2558. // the underlying auth operations to skip anything that mutates auth state.
  2559. let result = null;
  2560. try {
  2561. // We know this._popupRedirectResolver is set since redirectResolver
  2562. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2563. result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);
  2564. }
  2565. catch (e) {
  2566. // Swallow any errors here; the code can retrieve them in
  2567. // getRedirectResult().
  2568. await this._setRedirectUser(null);
  2569. }
  2570. return result;
  2571. }
  2572. async reloadAndSetCurrentUserOrClear(user) {
  2573. try {
  2574. await _reloadWithoutSaving(user);
  2575. }
  2576. catch (e) {
  2577. if ((e === null || e === void 0 ? void 0 : e.code) !==
  2578. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  2579. // Something's wrong with the user's token. Log them out and remove
  2580. // them from storage
  2581. return this.directlySetCurrentUser(null);
  2582. }
  2583. }
  2584. return this.directlySetCurrentUser(user);
  2585. }
  2586. useDeviceLanguage() {
  2587. this.languageCode = _getUserLanguage();
  2588. }
  2589. async _delete() {
  2590. this._deleted = true;
  2591. }
  2592. async updateCurrentUser(userExtern) {
  2593. // The public updateCurrentUser method needs to make a copy of the user,
  2594. // and also check that the project matches
  2595. const user = userExtern
  2596. ? getModularInstance(userExtern)
  2597. : null;
  2598. if (user) {
  2599. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2600. }
  2601. return this._updateCurrentUser(user && user._clone(this));
  2602. }
  2603. async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {
  2604. if (this._deleted) {
  2605. return;
  2606. }
  2607. if (user) {
  2608. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  2609. }
  2610. if (!skipBeforeStateCallbacks) {
  2611. await this.beforeStateQueue.runMiddleware(user);
  2612. }
  2613. return this.queue(async () => {
  2614. await this.directlySetCurrentUser(user);
  2615. this.notifyAuthListeners();
  2616. });
  2617. }
  2618. async signOut() {
  2619. // Run first, to block _setRedirectUser() if any callbacks fail.
  2620. await this.beforeStateQueue.runMiddleware(null);
  2621. // Clear the redirect user when signOut is called
  2622. if (this.redirectPersistenceManager || this._popupRedirectResolver) {
  2623. await this._setRedirectUser(null);
  2624. }
  2625. // Prevent callbacks from being called again in _updateCurrentUser, as
  2626. // they were already called in the first line.
  2627. return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);
  2628. }
  2629. setPersistence(persistence) {
  2630. return this.queue(async () => {
  2631. await this.assertedPersistence.setPersistence(_getInstance(persistence));
  2632. });
  2633. }
  2634. async initializeRecaptchaConfig() {
  2635. const response = await getRecaptchaConfig(this, {
  2636. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */,
  2637. version: "RECAPTCHA_ENTERPRISE" /* RecaptchaVersion.ENTERPRISE */
  2638. });
  2639. const config = new RecaptchaConfig(response);
  2640. if (this.tenantId == null) {
  2641. this._agentRecaptchaConfig = config;
  2642. }
  2643. else {
  2644. this._tenantRecaptchaConfigs[this.tenantId] = config;
  2645. }
  2646. if (config.emailPasswordEnabled) {
  2647. const verifier = new RecaptchaEnterpriseVerifier(this);
  2648. void verifier.verify();
  2649. }
  2650. }
  2651. _getRecaptchaConfig() {
  2652. if (this.tenantId == null) {
  2653. return this._agentRecaptchaConfig;
  2654. }
  2655. else {
  2656. return this._tenantRecaptchaConfigs[this.tenantId];
  2657. }
  2658. }
  2659. _getPersistence() {
  2660. return this.assertedPersistence.persistence.type;
  2661. }
  2662. _updateErrorMap(errorMap) {
  2663. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  2664. }
  2665. onAuthStateChanged(nextOrObserver, error, completed) {
  2666. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  2667. }
  2668. beforeAuthStateChanged(callback, onAbort) {
  2669. return this.beforeStateQueue.pushCallback(callback, onAbort);
  2670. }
  2671. onIdTokenChanged(nextOrObserver, error, completed) {
  2672. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  2673. }
  2674. toJSON() {
  2675. var _a;
  2676. return {
  2677. apiKey: this.config.apiKey,
  2678. authDomain: this.config.authDomain,
  2679. appName: this.name,
  2680. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  2681. };
  2682. }
  2683. async _setRedirectUser(user, popupRedirectResolver) {
  2684. const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);
  2685. return user === null
  2686. ? redirectManager.removeCurrentUser()
  2687. : redirectManager.setCurrentUser(user);
  2688. }
  2689. async getOrInitRedirectPersistenceManager(popupRedirectResolver) {
  2690. if (!this.redirectPersistenceManager) {
  2691. const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  2692. this._popupRedirectResolver;
  2693. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2694. this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */);
  2695. this.redirectUser =
  2696. await this.redirectPersistenceManager.getCurrentUser();
  2697. }
  2698. return this.redirectPersistenceManager;
  2699. }
  2700. async _redirectUserForId(id) {
  2701. var _a, _b;
  2702. // Make sure we've cleared any pending persistence actions if we're not in
  2703. // the initializer
  2704. if (this._isInitialized) {
  2705. await this.queue(async () => { });
  2706. }
  2707. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  2708. return this._currentUser;
  2709. }
  2710. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  2711. return this.redirectUser;
  2712. }
  2713. return null;
  2714. }
  2715. async _persistUserIfCurrent(user) {
  2716. if (user === this.currentUser) {
  2717. return this.queue(async () => this.directlySetCurrentUser(user));
  2718. }
  2719. }
  2720. /** Notifies listeners only if the user is current */
  2721. _notifyListenersIfCurrent(user) {
  2722. if (user === this.currentUser) {
  2723. this.notifyAuthListeners();
  2724. }
  2725. }
  2726. _key() {
  2727. return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
  2728. }
  2729. _startProactiveRefresh() {
  2730. this.isProactiveRefreshEnabled = true;
  2731. if (this.currentUser) {
  2732. this._currentUser._startProactiveRefresh();
  2733. }
  2734. }
  2735. _stopProactiveRefresh() {
  2736. this.isProactiveRefreshEnabled = false;
  2737. if (this.currentUser) {
  2738. this._currentUser._stopProactiveRefresh();
  2739. }
  2740. }
  2741. /** Returns the current user cast as the internal type */
  2742. get _currentUser() {
  2743. return this.currentUser;
  2744. }
  2745. notifyAuthListeners() {
  2746. var _a, _b;
  2747. if (!this._isInitialized) {
  2748. return;
  2749. }
  2750. this.idTokenSubscription.next(this.currentUser);
  2751. const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  2752. if (this.lastNotifiedUid !== currentUid) {
  2753. this.lastNotifiedUid = currentUid;
  2754. this.authStateSubscription.next(this.currentUser);
  2755. }
  2756. }
  2757. registerStateListener(subscription, nextOrObserver, error, completed) {
  2758. if (this._deleted) {
  2759. return () => { };
  2760. }
  2761. const cb = typeof nextOrObserver === 'function'
  2762. ? nextOrObserver
  2763. : nextOrObserver.next.bind(nextOrObserver);
  2764. const promise = this._isInitialized
  2765. ? Promise.resolve()
  2766. : this._initializationPromise;
  2767. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2768. // The callback needs to be called asynchronously per the spec.
  2769. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2770. promise.then(() => cb(this.currentUser));
  2771. if (typeof nextOrObserver === 'function') {
  2772. return subscription.addObserver(nextOrObserver, error, completed);
  2773. }
  2774. else {
  2775. return subscription.addObserver(nextOrObserver);
  2776. }
  2777. }
  2778. /**
  2779. * Unprotected (from race conditions) method to set the current user. This
  2780. * should only be called from within a queued callback. This is necessary
  2781. * because the queue shouldn't rely on another queued callback.
  2782. */
  2783. async directlySetCurrentUser(user) {
  2784. if (this.currentUser && this.currentUser !== user) {
  2785. this._currentUser._stopProactiveRefresh();
  2786. }
  2787. if (user && this.isProactiveRefreshEnabled) {
  2788. user._startProactiveRefresh();
  2789. }
  2790. this.currentUser = user;
  2791. if (user) {
  2792. await this.assertedPersistence.setCurrentUser(user);
  2793. }
  2794. else {
  2795. await this.assertedPersistence.removeCurrentUser();
  2796. }
  2797. }
  2798. queue(action) {
  2799. // In case something errors, the callback still should be called in order
  2800. // to keep the promise chain alive
  2801. this.operations = this.operations.then(action, action);
  2802. return this.operations;
  2803. }
  2804. get assertedPersistence() {
  2805. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2806. return this.persistenceManager;
  2807. }
  2808. _logFramework(framework) {
  2809. if (!framework || this.frameworks.includes(framework)) {
  2810. return;
  2811. }
  2812. this.frameworks.push(framework);
  2813. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  2814. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  2815. this.frameworks.sort();
  2816. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  2817. }
  2818. _getFrameworks() {
  2819. return this.frameworks;
  2820. }
  2821. async _getAdditionalHeaders() {
  2822. var _a;
  2823. // Additional headers on every request
  2824. const headers = {
  2825. ["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion
  2826. };
  2827. if (this.app.options.appId) {
  2828. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  2829. }
  2830. // If the heartbeat service exists, add the heartbeat string
  2831. const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider
  2832. .getImmediate({
  2833. optional: true
  2834. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());
  2835. if (heartbeatsHeader) {
  2836. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  2837. }
  2838. // If the App Check service exists, add the App Check token in the headers
  2839. const appCheckToken = await this._getAppCheckToken();
  2840. if (appCheckToken) {
  2841. headers["X-Firebase-AppCheck" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;
  2842. }
  2843. return headers;
  2844. }
  2845. async _getAppCheckToken() {
  2846. var _a;
  2847. const appCheckTokenResult = await ((_a = this.appCheckServiceProvider
  2848. .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());
  2849. if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
  2850. // Context: appCheck.getToken() will never throw even if an error happened.
  2851. // In the error case, a dummy token will be returned along with an error field describing
  2852. // the error. In general, we shouldn't care about the error condition and just use
  2853. // the token (actual or dummy) to send requests.
  2854. _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);
  2855. }
  2856. return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;
  2857. }
  2858. }
  2859. /**
  2860. * Method to be used to cast down to our private implmentation of Auth.
  2861. * It will also handle unwrapping from the compat type if necessary
  2862. *
  2863. * @param auth Auth object passed in from developer
  2864. */
  2865. function _castAuth(auth) {
  2866. return getModularInstance(auth);
  2867. }
  2868. /** Helper class to wrap subscriber logic */
  2869. class Subscription {
  2870. constructor(auth) {
  2871. this.auth = auth;
  2872. this.observer = null;
  2873. this.addObserver = createSubscribe(observer => (this.observer = observer));
  2874. }
  2875. get next() {
  2876. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2877. return this.observer.next.bind(this.observer);
  2878. }
  2879. }
  2880. /**
  2881. * @license
  2882. * Copyright 2020 Google LLC
  2883. *
  2884. * Licensed under the Apache License, Version 2.0 (the "License");
  2885. * you may not use this file except in compliance with the License.
  2886. * You may obtain a copy of the License at
  2887. *
  2888. * http://www.apache.org/licenses/LICENSE-2.0
  2889. *
  2890. * Unless required by applicable law or agreed to in writing, software
  2891. * distributed under the License is distributed on an "AS IS" BASIS,
  2892. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2893. * See the License for the specific language governing permissions and
  2894. * limitations under the License.
  2895. */
  2896. /**
  2897. * Initializes an {@link Auth} instance with fine-grained control over
  2898. * {@link Dependencies}.
  2899. *
  2900. * @remarks
  2901. *
  2902. * This function allows more control over the {@link Auth} instance than
  2903. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  2904. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  2905. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  2906. * need control over which persistence layer is used, or to minimize bundle
  2907. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  2908. *
  2909. * For example, if your app only uses anonymous accounts and you only want
  2910. * accounts saved for the current session, initialize `Auth` with:
  2911. *
  2912. * ```js
  2913. * const auth = initializeAuth(app, {
  2914. * persistence: browserSessionPersistence,
  2915. * popupRedirectResolver: undefined,
  2916. * });
  2917. * ```
  2918. *
  2919. * @public
  2920. */
  2921. function initializeAuth(app, deps) {
  2922. const provider = _getProvider(app, 'auth');
  2923. if (provider.isInitialized()) {
  2924. const auth = provider.getImmediate();
  2925. const initialOptions = provider.getOptions();
  2926. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  2927. return auth;
  2928. }
  2929. else {
  2930. _fail(auth, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  2931. }
  2932. }
  2933. const auth = provider.initialize({ options: deps });
  2934. return auth;
  2935. }
  2936. function _initializeAuthInstance(auth, deps) {
  2937. const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  2938. const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  2939. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  2940. auth._updateErrorMap(deps.errorMap);
  2941. }
  2942. // This promise is intended to float; auth initialization happens in the
  2943. // background, meanwhile the auth object may be used by the app.
  2944. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2945. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  2946. }
  2947. /**
  2948. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  2949. * Firebase Auth services.
  2950. *
  2951. * @remarks
  2952. * This must be called synchronously immediately following the first call to
  2953. * {@link initializeAuth}. Do not use with production credentials as emulator
  2954. * traffic is not encrypted.
  2955. *
  2956. *
  2957. * @example
  2958. * ```javascript
  2959. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  2960. * ```
  2961. *
  2962. * @param auth - The {@link Auth} instance.
  2963. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  2964. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  2965. * `true` to disable the warning banner attached to the DOM.
  2966. *
  2967. * @public
  2968. */
  2969. function connectAuthEmulator(auth, url, options) {
  2970. const authInternal = _castAuth(auth);
  2971. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  2972. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  2973. const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  2974. const protocol = extractProtocol(url);
  2975. const { host, port } = extractHostAndPort(url);
  2976. const portStr = port === null ? '' : `:${port}`;
  2977. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  2978. authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };
  2979. authInternal.settings.appVerificationDisabledForTesting = true;
  2980. authInternal.emulatorConfig = Object.freeze({
  2981. host,
  2982. port,
  2983. protocol: protocol.replace(':', ''),
  2984. options: Object.freeze({ disableWarnings })
  2985. });
  2986. if (!disableWarnings) {
  2987. emitEmulatorWarning();
  2988. }
  2989. }
  2990. function extractProtocol(url) {
  2991. const protocolEnd = url.indexOf(':');
  2992. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  2993. }
  2994. function extractHostAndPort(url) {
  2995. const protocol = extractProtocol(url);
  2996. const authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  2997. if (!authority) {
  2998. return { host: '', port: null };
  2999. }
  3000. const hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  3001. const bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  3002. if (bracketedIPv6) {
  3003. const host = bracketedIPv6[1];
  3004. return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  3005. }
  3006. else {
  3007. const [host, port] = hostAndPort.split(':');
  3008. return { host, port: parsePort(port) };
  3009. }
  3010. }
  3011. function parsePort(portStr) {
  3012. if (!portStr) {
  3013. return null;
  3014. }
  3015. const port = Number(portStr);
  3016. if (isNaN(port)) {
  3017. return null;
  3018. }
  3019. return port;
  3020. }
  3021. function emitEmulatorWarning() {
  3022. function attachBanner() {
  3023. const el = document.createElement('p');
  3024. const sty = el.style;
  3025. el.innerText =
  3026. 'Running in emulator mode. Do not use with production credentials.';
  3027. sty.position = 'fixed';
  3028. sty.width = '100%';
  3029. sty.backgroundColor = '#ffffff';
  3030. sty.border = '.1em solid #000000';
  3031. sty.color = '#b50000';
  3032. sty.bottom = '0px';
  3033. sty.left = '0px';
  3034. sty.margin = '0px';
  3035. sty.zIndex = '10000';
  3036. sty.textAlign = 'center';
  3037. el.classList.add('firebase-emulator-warning');
  3038. document.body.appendChild(el);
  3039. }
  3040. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  3041. console.info('WARNING: You are using the Auth Emulator,' +
  3042. ' which is intended for local testing only. Do not use with' +
  3043. ' production credentials.');
  3044. }
  3045. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  3046. if (document.readyState === 'loading') {
  3047. window.addEventListener('DOMContentLoaded', attachBanner);
  3048. }
  3049. else {
  3050. attachBanner();
  3051. }
  3052. }
  3053. }
  3054. /**
  3055. * @license
  3056. * Copyright 2020 Google LLC
  3057. *
  3058. * Licensed under the Apache License, Version 2.0 (the "License");
  3059. * you may not use this file except in compliance with the License.
  3060. * You may obtain a copy of the License at
  3061. *
  3062. * http://www.apache.org/licenses/LICENSE-2.0
  3063. *
  3064. * Unless required by applicable law or agreed to in writing, software
  3065. * distributed under the License is distributed on an "AS IS" BASIS,
  3066. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3067. * See the License for the specific language governing permissions and
  3068. * limitations under the License.
  3069. */
  3070. /**
  3071. * Interface that represents the credentials returned by an {@link AuthProvider}.
  3072. *
  3073. * @remarks
  3074. * Implementations specify the details about each auth provider's credential requirements.
  3075. *
  3076. * @public
  3077. */
  3078. class AuthCredential {
  3079. /** @internal */
  3080. constructor(
  3081. /**
  3082. * The authentication provider ID for the credential.
  3083. *
  3084. * @remarks
  3085. * For example, 'facebook.com', or 'google.com'.
  3086. */
  3087. providerId,
  3088. /**
  3089. * The authentication sign in method for the credential.
  3090. *
  3091. * @remarks
  3092. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  3093. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  3094. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  3095. */
  3096. signInMethod) {
  3097. this.providerId = providerId;
  3098. this.signInMethod = signInMethod;
  3099. }
  3100. /**
  3101. * Returns a JSON-serializable representation of this object.
  3102. *
  3103. * @returns a JSON-serializable representation of this object.
  3104. */
  3105. toJSON() {
  3106. return debugFail('not implemented');
  3107. }
  3108. /** @internal */
  3109. _getIdTokenResponse(_auth) {
  3110. return debugFail('not implemented');
  3111. }
  3112. /** @internal */
  3113. _linkToIdToken(_auth, _idToken) {
  3114. return debugFail('not implemented');
  3115. }
  3116. /** @internal */
  3117. _getReauthenticationResolver(_auth) {
  3118. return debugFail('not implemented');
  3119. }
  3120. }
  3121. /**
  3122. * @license
  3123. * Copyright 2020 Google LLC
  3124. *
  3125. * Licensed under the Apache License, Version 2.0 (the "License");
  3126. * you may not use this file except in compliance with the License.
  3127. * You may obtain a copy of the License at
  3128. *
  3129. * http://www.apache.org/licenses/LICENSE-2.0
  3130. *
  3131. * Unless required by applicable law or agreed to in writing, software
  3132. * distributed under the License is distributed on an "AS IS" BASIS,
  3133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3134. * See the License for the specific language governing permissions and
  3135. * limitations under the License.
  3136. */
  3137. async function resetPassword(auth, request) {
  3138. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));
  3139. }
  3140. async function updateEmailPassword(auth, request) {
  3141. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  3142. }
  3143. async function applyActionCode$1(auth, request) {
  3144. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));
  3145. }
  3146. /**
  3147. * @license
  3148. * Copyright 2020 Google LLC
  3149. *
  3150. * Licensed under the Apache License, Version 2.0 (the "License");
  3151. * you may not use this file except in compliance with the License.
  3152. * You may obtain a copy of the License at
  3153. *
  3154. * http://www.apache.org/licenses/LICENSE-2.0
  3155. *
  3156. * Unless required by applicable law or agreed to in writing, software
  3157. * distributed under the License is distributed on an "AS IS" BASIS,
  3158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3159. * See the License for the specific language governing permissions and
  3160. * limitations under the License.
  3161. */
  3162. async function signInWithPassword(auth, request) {
  3163. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));
  3164. }
  3165. async function sendOobCode(auth, request) {
  3166. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));
  3167. }
  3168. async function sendEmailVerification$1(auth, request) {
  3169. return sendOobCode(auth, request);
  3170. }
  3171. async function sendPasswordResetEmail$1(auth, request) {
  3172. return sendOobCode(auth, request);
  3173. }
  3174. async function sendSignInLinkToEmail$1(auth, request) {
  3175. return sendOobCode(auth, request);
  3176. }
  3177. async function verifyAndChangeEmail(auth, request) {
  3178. return sendOobCode(auth, request);
  3179. }
  3180. /**
  3181. * @license
  3182. * Copyright 2020 Google LLC
  3183. *
  3184. * Licensed under the Apache License, Version 2.0 (the "License");
  3185. * you may not use this file except in compliance with the License.
  3186. * You may obtain a copy of the License at
  3187. *
  3188. * http://www.apache.org/licenses/LICENSE-2.0
  3189. *
  3190. * Unless required by applicable law or agreed to in writing, software
  3191. * distributed under the License is distributed on an "AS IS" BASIS,
  3192. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3193. * See the License for the specific language governing permissions and
  3194. * limitations under the License.
  3195. */
  3196. async function signInWithEmailLink$1(auth, request) {
  3197. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  3198. }
  3199. async function signInWithEmailLinkForLinking(auth, request) {
  3200. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  3201. }
  3202. /**
  3203. * @license
  3204. * Copyright 2020 Google LLC
  3205. *
  3206. * Licensed under the Apache License, Version 2.0 (the "License");
  3207. * you may not use this file except in compliance with the License.
  3208. * You may obtain a copy of the License at
  3209. *
  3210. * http://www.apache.org/licenses/LICENSE-2.0
  3211. *
  3212. * Unless required by applicable law or agreed to in writing, software
  3213. * distributed under the License is distributed on an "AS IS" BASIS,
  3214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3215. * See the License for the specific language governing permissions and
  3216. * limitations under the License.
  3217. */
  3218. /**
  3219. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  3220. * {@link ProviderId}.PASSWORD
  3221. *
  3222. * @remarks
  3223. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  3224. * {@link SignInMethod}.EMAIL_LINK.
  3225. *
  3226. * @public
  3227. */
  3228. class EmailAuthCredential extends AuthCredential {
  3229. /** @internal */
  3230. constructor(
  3231. /** @internal */
  3232. _email,
  3233. /** @internal */
  3234. _password, signInMethod,
  3235. /** @internal */
  3236. _tenantId = null) {
  3237. super("password" /* ProviderId.PASSWORD */, signInMethod);
  3238. this._email = _email;
  3239. this._password = _password;
  3240. this._tenantId = _tenantId;
  3241. }
  3242. /** @internal */
  3243. static _fromEmailAndPassword(email, password) {
  3244. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  3245. }
  3246. /** @internal */
  3247. static _fromEmailAndCode(email, oobCode, tenantId = null) {
  3248. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  3249. }
  3250. /** {@inheritdoc AuthCredential.toJSON} */
  3251. toJSON() {
  3252. return {
  3253. email: this._email,
  3254. password: this._password,
  3255. signInMethod: this.signInMethod,
  3256. tenantId: this._tenantId
  3257. };
  3258. }
  3259. /**
  3260. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  3261. *
  3262. * @param json - Either `object` or the stringified representation of the object. When string is
  3263. * provided, `JSON.parse` would be called first.
  3264. *
  3265. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3266. */
  3267. static fromJSON(json) {
  3268. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3269. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  3270. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  3271. return this._fromEmailAndPassword(obj.email, obj.password);
  3272. }
  3273. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  3274. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  3275. }
  3276. }
  3277. return null;
  3278. }
  3279. /** @internal */
  3280. async _getIdTokenResponse(auth) {
  3281. var _a;
  3282. switch (this.signInMethod) {
  3283. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3284. const request = {
  3285. returnSecureToken: true,
  3286. email: this._email,
  3287. password: this._password,
  3288. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  3289. };
  3290. if ((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {
  3291. const requestWithRecaptcha = await injectRecaptchaFields(auth, request, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);
  3292. return signInWithPassword(auth, requestWithRecaptcha);
  3293. }
  3294. else {
  3295. return signInWithPassword(auth, request).catch(async (error) => {
  3296. if (error.code === `auth/${"missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {
  3297. 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.');
  3298. const requestWithRecaptcha = await injectRecaptchaFields(auth, request, "signInWithPassword" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);
  3299. return signInWithPassword(auth, requestWithRecaptcha);
  3300. }
  3301. else {
  3302. return Promise.reject(error);
  3303. }
  3304. });
  3305. }
  3306. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3307. return signInWithEmailLink$1(auth, {
  3308. email: this._email,
  3309. oobCode: this._password
  3310. });
  3311. default:
  3312. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3313. }
  3314. }
  3315. /** @internal */
  3316. async _linkToIdToken(auth, idToken) {
  3317. switch (this.signInMethod) {
  3318. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3319. return updateEmailPassword(auth, {
  3320. idToken,
  3321. returnSecureToken: true,
  3322. email: this._email,
  3323. password: this._password
  3324. });
  3325. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3326. return signInWithEmailLinkForLinking(auth, {
  3327. idToken,
  3328. email: this._email,
  3329. oobCode: this._password
  3330. });
  3331. default:
  3332. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3333. }
  3334. }
  3335. /** @internal */
  3336. _getReauthenticationResolver(auth) {
  3337. return this._getIdTokenResponse(auth);
  3338. }
  3339. }
  3340. /**
  3341. * @license
  3342. * Copyright 2020 Google LLC
  3343. *
  3344. * Licensed under the Apache License, Version 2.0 (the "License");
  3345. * you may not use this file except in compliance with the License.
  3346. * You may obtain a copy of the License at
  3347. *
  3348. * http://www.apache.org/licenses/LICENSE-2.0
  3349. *
  3350. * Unless required by applicable law or agreed to in writing, software
  3351. * distributed under the License is distributed on an "AS IS" BASIS,
  3352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3353. * See the License for the specific language governing permissions and
  3354. * limitations under the License.
  3355. */
  3356. async function signInWithIdp(auth, request) {
  3357. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));
  3358. }
  3359. /**
  3360. * @license
  3361. * Copyright 2020 Google LLC
  3362. *
  3363. * Licensed under the Apache License, Version 2.0 (the "License");
  3364. * you may not use this file except in compliance with the License.
  3365. * You may obtain a copy of the License at
  3366. *
  3367. * http://www.apache.org/licenses/LICENSE-2.0
  3368. *
  3369. * Unless required by applicable law or agreed to in writing, software
  3370. * distributed under the License is distributed on an "AS IS" BASIS,
  3371. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3372. * See the License for the specific language governing permissions and
  3373. * limitations under the License.
  3374. */
  3375. const IDP_REQUEST_URI$1 = 'http://localhost';
  3376. /**
  3377. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  3378. *
  3379. * @remarks
  3380. * Implementations specify the details about each auth provider's credential requirements.
  3381. *
  3382. * @public
  3383. */
  3384. class OAuthCredential extends AuthCredential {
  3385. constructor() {
  3386. super(...arguments);
  3387. this.pendingToken = null;
  3388. }
  3389. /** @internal */
  3390. static _fromParams(params) {
  3391. const cred = new OAuthCredential(params.providerId, params.signInMethod);
  3392. if (params.idToken || params.accessToken) {
  3393. // OAuth 2 and either ID token or access token.
  3394. if (params.idToken) {
  3395. cred.idToken = params.idToken;
  3396. }
  3397. if (params.accessToken) {
  3398. cred.accessToken = params.accessToken;
  3399. }
  3400. // Add nonce if available and no pendingToken is present.
  3401. if (params.nonce && !params.pendingToken) {
  3402. cred.nonce = params.nonce;
  3403. }
  3404. if (params.pendingToken) {
  3405. cred.pendingToken = params.pendingToken;
  3406. }
  3407. }
  3408. else if (params.oauthToken && params.oauthTokenSecret) {
  3409. // OAuth 1 and OAuth token with token secret
  3410. cred.accessToken = params.oauthToken;
  3411. cred.secret = params.oauthTokenSecret;
  3412. }
  3413. else {
  3414. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3415. }
  3416. return cred;
  3417. }
  3418. /** {@inheritdoc AuthCredential.toJSON} */
  3419. toJSON() {
  3420. return {
  3421. idToken: this.idToken,
  3422. accessToken: this.accessToken,
  3423. secret: this.secret,
  3424. nonce: this.nonce,
  3425. pendingToken: this.pendingToken,
  3426. providerId: this.providerId,
  3427. signInMethod: this.signInMethod
  3428. };
  3429. }
  3430. /**
  3431. * Static method to deserialize a JSON representation of an object into an
  3432. * {@link AuthCredential}.
  3433. *
  3434. * @param json - Input can be either Object or the stringified representation of the object.
  3435. * When string is provided, JSON.parse would be called first.
  3436. *
  3437. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3438. */
  3439. static fromJSON(json) {
  3440. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3441. const { providerId, signInMethod } = obj, rest = __rest(obj, ["providerId", "signInMethod"]);
  3442. if (!providerId || !signInMethod) {
  3443. return null;
  3444. }
  3445. const cred = new OAuthCredential(providerId, signInMethod);
  3446. cred.idToken = rest.idToken || undefined;
  3447. cred.accessToken = rest.accessToken || undefined;
  3448. cred.secret = rest.secret;
  3449. cred.nonce = rest.nonce;
  3450. cred.pendingToken = rest.pendingToken || null;
  3451. return cred;
  3452. }
  3453. /** @internal */
  3454. _getIdTokenResponse(auth) {
  3455. const request = this.buildRequest();
  3456. return signInWithIdp(auth, request);
  3457. }
  3458. /** @internal */
  3459. _linkToIdToken(auth, idToken) {
  3460. const request = this.buildRequest();
  3461. request.idToken = idToken;
  3462. return signInWithIdp(auth, request);
  3463. }
  3464. /** @internal */
  3465. _getReauthenticationResolver(auth) {
  3466. const request = this.buildRequest();
  3467. request.autoCreate = false;
  3468. return signInWithIdp(auth, request);
  3469. }
  3470. buildRequest() {
  3471. const request = {
  3472. requestUri: IDP_REQUEST_URI$1,
  3473. returnSecureToken: true
  3474. };
  3475. if (this.pendingToken) {
  3476. request.pendingToken = this.pendingToken;
  3477. }
  3478. else {
  3479. const postBody = {};
  3480. if (this.idToken) {
  3481. postBody['id_token'] = this.idToken;
  3482. }
  3483. if (this.accessToken) {
  3484. postBody['access_token'] = this.accessToken;
  3485. }
  3486. if (this.secret) {
  3487. postBody['oauth_token_secret'] = this.secret;
  3488. }
  3489. postBody['providerId'] = this.providerId;
  3490. if (this.nonce && !this.pendingToken) {
  3491. postBody['nonce'] = this.nonce;
  3492. }
  3493. request.postBody = querystring(postBody);
  3494. }
  3495. return request;
  3496. }
  3497. }
  3498. /**
  3499. * @license
  3500. * Copyright 2020 Google LLC
  3501. *
  3502. * Licensed under the Apache License, Version 2.0 (the "License");
  3503. * you may not use this file except in compliance with the License.
  3504. * You may obtain a copy of the License at
  3505. *
  3506. * http://www.apache.org/licenses/LICENSE-2.0
  3507. *
  3508. * Unless required by applicable law or agreed to in writing, software
  3509. * distributed under the License is distributed on an "AS IS" BASIS,
  3510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3511. * See the License for the specific language governing permissions and
  3512. * limitations under the License.
  3513. */
  3514. async function sendPhoneVerificationCode(auth, request) {
  3515. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendVerificationCode" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));
  3516. }
  3517. async function signInWithPhoneNumber$1(auth, request) {
  3518. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3519. }
  3520. async function linkWithPhoneNumber$1(auth, request) {
  3521. const response = await _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3522. if (response.temporaryProof) {
  3523. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  3524. }
  3525. return response;
  3526. }
  3527. const VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {
  3528. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */
  3529. };
  3530. async function verifyPhoneNumberForExisting(auth, request) {
  3531. const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });
  3532. 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_);
  3533. }
  3534. /**
  3535. * @license
  3536. * Copyright 2020 Google LLC
  3537. *
  3538. * Licensed under the Apache License, Version 2.0 (the "License");
  3539. * you may not use this file except in compliance with the License.
  3540. * You may obtain a copy of the License at
  3541. *
  3542. * http://www.apache.org/licenses/LICENSE-2.0
  3543. *
  3544. * Unless required by applicable law or agreed to in writing, software
  3545. * distributed under the License is distributed on an "AS IS" BASIS,
  3546. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3547. * See the License for the specific language governing permissions and
  3548. * limitations under the License.
  3549. */
  3550. /**
  3551. * Represents the credentials returned by {@link PhoneAuthProvider}.
  3552. *
  3553. * @public
  3554. */
  3555. class PhoneAuthCredential extends AuthCredential {
  3556. constructor(params) {
  3557. super("phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */);
  3558. this.params = params;
  3559. }
  3560. /** @internal */
  3561. static _fromVerification(verificationId, verificationCode) {
  3562. return new PhoneAuthCredential({ verificationId, verificationCode });
  3563. }
  3564. /** @internal */
  3565. static _fromTokenResponse(phoneNumber, temporaryProof) {
  3566. return new PhoneAuthCredential({ phoneNumber, temporaryProof });
  3567. }
  3568. /** @internal */
  3569. _getIdTokenResponse(auth) {
  3570. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  3571. }
  3572. /** @internal */
  3573. _linkToIdToken(auth, idToken) {
  3574. return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));
  3575. }
  3576. /** @internal */
  3577. _getReauthenticationResolver(auth) {
  3578. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  3579. }
  3580. /** @internal */
  3581. _makeVerificationRequest() {
  3582. const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;
  3583. if (temporaryProof && phoneNumber) {
  3584. return { temporaryProof, phoneNumber };
  3585. }
  3586. return {
  3587. sessionInfo: verificationId,
  3588. code: verificationCode
  3589. };
  3590. }
  3591. /** {@inheritdoc AuthCredential.toJSON} */
  3592. toJSON() {
  3593. const obj = {
  3594. providerId: this.providerId
  3595. };
  3596. if (this.params.phoneNumber) {
  3597. obj.phoneNumber = this.params.phoneNumber;
  3598. }
  3599. if (this.params.temporaryProof) {
  3600. obj.temporaryProof = this.params.temporaryProof;
  3601. }
  3602. if (this.params.verificationCode) {
  3603. obj.verificationCode = this.params.verificationCode;
  3604. }
  3605. if (this.params.verificationId) {
  3606. obj.verificationId = this.params.verificationId;
  3607. }
  3608. return obj;
  3609. }
  3610. /** Generates a phone credential based on a plain object or a JSON string. */
  3611. static fromJSON(json) {
  3612. if (typeof json === 'string') {
  3613. json = JSON.parse(json);
  3614. }
  3615. const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;
  3616. if (!verificationCode &&
  3617. !verificationId &&
  3618. !phoneNumber &&
  3619. !temporaryProof) {
  3620. return null;
  3621. }
  3622. return new PhoneAuthCredential({
  3623. verificationId,
  3624. verificationCode,
  3625. phoneNumber,
  3626. temporaryProof
  3627. });
  3628. }
  3629. }
  3630. /**
  3631. * @license
  3632. * Copyright 2020 Google LLC
  3633. *
  3634. * Licensed under the Apache License, Version 2.0 (the "License");
  3635. * you may not use this file except in compliance with the License.
  3636. * You may obtain a copy of the License at
  3637. *
  3638. * http://www.apache.org/licenses/LICENSE-2.0
  3639. *
  3640. * Unless required by applicable law or agreed to in writing, software
  3641. * distributed under the License is distributed on an "AS IS" BASIS,
  3642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3643. * See the License for the specific language governing permissions and
  3644. * limitations under the License.
  3645. */
  3646. /**
  3647. * Maps the mode string in action code URL to Action Code Info operation.
  3648. *
  3649. * @param mode
  3650. */
  3651. function parseMode(mode) {
  3652. switch (mode) {
  3653. case 'recoverEmail':
  3654. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  3655. case 'resetPassword':
  3656. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  3657. case 'signIn':
  3658. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  3659. case 'verifyEmail':
  3660. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  3661. case 'verifyAndChangeEmail':
  3662. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  3663. case 'revertSecondFactorAddition':
  3664. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  3665. default:
  3666. return null;
  3667. }
  3668. }
  3669. /**
  3670. * Helper to parse FDL links
  3671. *
  3672. * @param url
  3673. */
  3674. function parseDeepLink(url) {
  3675. const link = querystringDecode(extractQuerystring(url))['link'];
  3676. // Double link case (automatic redirect).
  3677. const doubleDeepLink = link
  3678. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  3679. : null;
  3680. // iOS custom scheme links.
  3681. const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  3682. const iOSDoubleDeepLink = iOSDeepLink
  3683. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  3684. : null;
  3685. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  3686. }
  3687. /**
  3688. * A utility class to parse email action URLs such as password reset, email verification,
  3689. * email link sign in, etc.
  3690. *
  3691. * @public
  3692. */
  3693. class ActionCodeURL {
  3694. /**
  3695. * @param actionLink - The link from which to extract the URL.
  3696. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3697. *
  3698. * @internal
  3699. */
  3700. constructor(actionLink) {
  3701. var _a, _b, _c, _d, _e, _f;
  3702. const searchParams = querystringDecode(extractQuerystring(actionLink));
  3703. const apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  3704. const code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  3705. const operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  3706. // Validate API key, code and mode.
  3707. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3708. this.apiKey = apiKey;
  3709. this.operation = operation;
  3710. this.code = code;
  3711. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  3712. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  3713. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  3714. }
  3715. /**
  3716. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  3717. * otherwise returns null.
  3718. *
  3719. * @param link - The email action link string.
  3720. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3721. *
  3722. * @public
  3723. */
  3724. static parseLink(link) {
  3725. const actionLink = parseDeepLink(link);
  3726. try {
  3727. return new ActionCodeURL(actionLink);
  3728. }
  3729. catch (_a) {
  3730. return null;
  3731. }
  3732. }
  3733. }
  3734. /**
  3735. * Parses the email action link string and returns an {@link ActionCodeURL} if
  3736. * the link is valid, otherwise returns null.
  3737. *
  3738. * @public
  3739. */
  3740. function parseActionCodeURL(link) {
  3741. return ActionCodeURL.parseLink(link);
  3742. }
  3743. /**
  3744. * @license
  3745. * Copyright 2020 Google LLC
  3746. *
  3747. * Licensed under the Apache License, Version 2.0 (the "License");
  3748. * you may not use this file except in compliance with the License.
  3749. * You may obtain a copy of the License at
  3750. *
  3751. * http://www.apache.org/licenses/LICENSE-2.0
  3752. *
  3753. * Unless required by applicable law or agreed to in writing, software
  3754. * distributed under the License is distributed on an "AS IS" BASIS,
  3755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3756. * See the License for the specific language governing permissions and
  3757. * limitations under the License.
  3758. */
  3759. /**
  3760. * Provider for generating {@link EmailAuthCredential}.
  3761. *
  3762. * @public
  3763. */
  3764. class EmailAuthProvider {
  3765. constructor() {
  3766. /**
  3767. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3768. */
  3769. this.providerId = EmailAuthProvider.PROVIDER_ID;
  3770. }
  3771. /**
  3772. * Initialize an {@link AuthCredential} using an email and password.
  3773. *
  3774. * @example
  3775. * ```javascript
  3776. * const authCredential = EmailAuthProvider.credential(email, password);
  3777. * const userCredential = await signInWithCredential(auth, authCredential);
  3778. * ```
  3779. *
  3780. * @example
  3781. * ```javascript
  3782. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  3783. * ```
  3784. *
  3785. * @param email - Email address.
  3786. * @param password - User account password.
  3787. * @returns The auth provider credential.
  3788. */
  3789. static credential(email, password) {
  3790. return EmailAuthCredential._fromEmailAndPassword(email, password);
  3791. }
  3792. /**
  3793. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  3794. * email link operation.
  3795. *
  3796. * @example
  3797. * ```javascript
  3798. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  3799. * const userCredential = await signInWithCredential(auth, authCredential);
  3800. * ```
  3801. *
  3802. * @example
  3803. * ```javascript
  3804. * await sendSignInLinkToEmail(auth, email);
  3805. * // Obtain emailLink from user.
  3806. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  3807. * ```
  3808. *
  3809. * @param auth - The {@link Auth} instance used to verify the link.
  3810. * @param email - Email address.
  3811. * @param emailLink - Sign-in email link.
  3812. * @returns - The auth provider credential.
  3813. */
  3814. static credentialWithLink(email, emailLink) {
  3815. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  3816. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3817. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  3818. }
  3819. }
  3820. /**
  3821. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3822. */
  3823. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  3824. /**
  3825. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  3826. */
  3827. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  3828. /**
  3829. * Always set to {@link SignInMethod}.EMAIL_LINK.
  3830. */
  3831. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  3832. /**
  3833. * @license
  3834. * Copyright 2020 Google LLC
  3835. *
  3836. * Licensed under the Apache License, Version 2.0 (the "License");
  3837. * you may not use this file except in compliance with the License.
  3838. * You may obtain a copy of the License at
  3839. *
  3840. * http://www.apache.org/licenses/LICENSE-2.0
  3841. *
  3842. * Unless required by applicable law or agreed to in writing, software
  3843. * distributed under the License is distributed on an "AS IS" BASIS,
  3844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3845. * See the License for the specific language governing permissions and
  3846. * limitations under the License.
  3847. */
  3848. /**
  3849. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  3850. *
  3851. * This class is not meant to be instantiated directly.
  3852. *
  3853. * @public
  3854. */
  3855. class FederatedAuthProvider {
  3856. /**
  3857. * Constructor for generic OAuth providers.
  3858. *
  3859. * @param providerId - Provider for which credentials should be generated.
  3860. */
  3861. constructor(providerId) {
  3862. this.providerId = providerId;
  3863. /** @internal */
  3864. this.defaultLanguageCode = null;
  3865. /** @internal */
  3866. this.customParameters = {};
  3867. }
  3868. /**
  3869. * Set the language gode.
  3870. *
  3871. * @param languageCode - language code
  3872. */
  3873. setDefaultLanguage(languageCode) {
  3874. this.defaultLanguageCode = languageCode;
  3875. }
  3876. /**
  3877. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  3878. * operations.
  3879. *
  3880. * @remarks
  3881. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  3882. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  3883. *
  3884. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  3885. */
  3886. setCustomParameters(customOAuthParameters) {
  3887. this.customParameters = customOAuthParameters;
  3888. return this;
  3889. }
  3890. /**
  3891. * Retrieve the current list of {@link CustomParameters}.
  3892. */
  3893. getCustomParameters() {
  3894. return this.customParameters;
  3895. }
  3896. }
  3897. /**
  3898. * @license
  3899. * Copyright 2019 Google LLC
  3900. *
  3901. * Licensed under the Apache License, Version 2.0 (the "License");
  3902. * you may not use this file except in compliance with the License.
  3903. * You may obtain a copy of the License at
  3904. *
  3905. * http://www.apache.org/licenses/LICENSE-2.0
  3906. *
  3907. * Unless required by applicable law or agreed to in writing, software
  3908. * distributed under the License is distributed on an "AS IS" BASIS,
  3909. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3910. * See the License for the specific language governing permissions and
  3911. * limitations under the License.
  3912. */
  3913. /**
  3914. * Common code to all OAuth providers. This is separate from the
  3915. * {@link OAuthProvider} so that child providers (like
  3916. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  3917. * Instead, they rely on a static `credential` method.
  3918. */
  3919. class BaseOAuthProvider extends FederatedAuthProvider {
  3920. constructor() {
  3921. super(...arguments);
  3922. /** @internal */
  3923. this.scopes = [];
  3924. }
  3925. /**
  3926. * Add an OAuth scope to the credential.
  3927. *
  3928. * @param scope - Provider OAuth scope to add.
  3929. */
  3930. addScope(scope) {
  3931. // If not already added, add scope to list.
  3932. if (!this.scopes.includes(scope)) {
  3933. this.scopes.push(scope);
  3934. }
  3935. return this;
  3936. }
  3937. /**
  3938. * Retrieve the current list of OAuth scopes.
  3939. */
  3940. getScopes() {
  3941. return [...this.scopes];
  3942. }
  3943. }
  3944. /**
  3945. * Provider for generating generic {@link OAuthCredential}.
  3946. *
  3947. * @example
  3948. * ```javascript
  3949. * // Sign in using a redirect.
  3950. * const provider = new OAuthProvider('google.com');
  3951. * // Start a sign in process for an unauthenticated user.
  3952. * provider.addScope('profile');
  3953. * provider.addScope('email');
  3954. * await signInWithRedirect(auth, provider);
  3955. * // This will trigger a full page redirect away from your app
  3956. *
  3957. * // After returning from the redirect when your app initializes you can obtain the result
  3958. * const result = await getRedirectResult(auth);
  3959. * if (result) {
  3960. * // This is the signed-in user
  3961. * const user = result.user;
  3962. * // This gives you a OAuth Access Token for the provider.
  3963. * const credential = provider.credentialFromResult(auth, result);
  3964. * const token = credential.accessToken;
  3965. * }
  3966. * ```
  3967. *
  3968. * @example
  3969. * ```javascript
  3970. * // Sign in using a popup.
  3971. * const provider = new OAuthProvider('google.com');
  3972. * provider.addScope('profile');
  3973. * provider.addScope('email');
  3974. * const result = await signInWithPopup(auth, provider);
  3975. *
  3976. * // The signed-in user info.
  3977. * const user = result.user;
  3978. * // This gives you a OAuth Access Token for the provider.
  3979. * const credential = provider.credentialFromResult(auth, result);
  3980. * const token = credential.accessToken;
  3981. * ```
  3982. * @public
  3983. */
  3984. class OAuthProvider extends BaseOAuthProvider {
  3985. /**
  3986. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  3987. * @param json - A plain object or a JSON string
  3988. */
  3989. static credentialFromJSON(json) {
  3990. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3991. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3992. return OAuthCredential._fromParams(obj);
  3993. }
  3994. /**
  3995. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  3996. *
  3997. * @remarks
  3998. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  3999. * the raw nonce must match the nonce field in the ID token.
  4000. *
  4001. * @example
  4002. * ```javascript
  4003. * // `googleUser` from the onsuccess Google Sign In callback.
  4004. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4005. * const provider = new OAuthProvider('google.com');
  4006. * const credential = provider.credential({
  4007. * idToken: googleUser.getAuthResponse().id_token,
  4008. * });
  4009. * const result = await signInWithCredential(credential);
  4010. * ```
  4011. *
  4012. * @param params - Either the options object containing the ID token, access token and raw nonce
  4013. * or the ID token string.
  4014. */
  4015. credential(params) {
  4016. return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));
  4017. }
  4018. /** An internal credential method that accepts more permissive options */
  4019. _credential(params) {
  4020. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4021. // For OAuthCredential, sign in method is same as providerId.
  4022. return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  4023. }
  4024. /**
  4025. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4026. *
  4027. * @param userCredential - The user credential.
  4028. */
  4029. static credentialFromResult(userCredential) {
  4030. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  4031. }
  4032. /**
  4033. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4034. * thrown during a sign-in, link, or reauthenticate operation.
  4035. *
  4036. * @param userCredential - The user credential.
  4037. */
  4038. static credentialFromError(error) {
  4039. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  4040. }
  4041. static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4042. if (!tokenResponse) {
  4043. return null;
  4044. }
  4045. const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;
  4046. if (!oauthAccessToken &&
  4047. !oauthTokenSecret &&
  4048. !oauthIdToken &&
  4049. !pendingToken) {
  4050. return null;
  4051. }
  4052. if (!providerId) {
  4053. return null;
  4054. }
  4055. try {
  4056. return new OAuthProvider(providerId)._credential({
  4057. idToken: oauthIdToken,
  4058. accessToken: oauthAccessToken,
  4059. nonce,
  4060. pendingToken
  4061. });
  4062. }
  4063. catch (e) {
  4064. return null;
  4065. }
  4066. }
  4067. }
  4068. /**
  4069. * @license
  4070. * Copyright 2020 Google LLC
  4071. *
  4072. * Licensed under the Apache License, Version 2.0 (the "License");
  4073. * you may not use this file except in compliance with the License.
  4074. * You may obtain a copy of the License at
  4075. *
  4076. * http://www.apache.org/licenses/LICENSE-2.0
  4077. *
  4078. * Unless required by applicable law or agreed to in writing, software
  4079. * distributed under the License is distributed on an "AS IS" BASIS,
  4080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4081. * See the License for the specific language governing permissions and
  4082. * limitations under the License.
  4083. */
  4084. /**
  4085. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  4086. *
  4087. * @example
  4088. * ```javascript
  4089. * // Sign in using a redirect.
  4090. * const provider = new FacebookAuthProvider();
  4091. * // Start a sign in process for an unauthenticated user.
  4092. * provider.addScope('user_birthday');
  4093. * await signInWithRedirect(auth, provider);
  4094. * // This will trigger a full page redirect away from your app
  4095. *
  4096. * // After returning from the redirect when your app initializes you can obtain the result
  4097. * const result = await getRedirectResult(auth);
  4098. * if (result) {
  4099. * // This is the signed-in user
  4100. * const user = result.user;
  4101. * // This gives you a Facebook Access Token.
  4102. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4103. * const token = credential.accessToken;
  4104. * }
  4105. * ```
  4106. *
  4107. * @example
  4108. * ```javascript
  4109. * // Sign in using a popup.
  4110. * const provider = new FacebookAuthProvider();
  4111. * provider.addScope('user_birthday');
  4112. * const result = await signInWithPopup(auth, provider);
  4113. *
  4114. * // The signed-in user info.
  4115. * const user = result.user;
  4116. * // This gives you a Facebook Access Token.
  4117. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4118. * const token = credential.accessToken;
  4119. * ```
  4120. *
  4121. * @public
  4122. */
  4123. class FacebookAuthProvider extends BaseOAuthProvider {
  4124. constructor() {
  4125. super("facebook.com" /* ProviderId.FACEBOOK */);
  4126. }
  4127. /**
  4128. * Creates a credential for Facebook.
  4129. *
  4130. * @example
  4131. * ```javascript
  4132. * // `event` from the Facebook auth.authResponseChange callback.
  4133. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  4134. * const result = await signInWithCredential(credential);
  4135. * ```
  4136. *
  4137. * @param accessToken - Facebook access token.
  4138. */
  4139. static credential(accessToken) {
  4140. return OAuthCredential._fromParams({
  4141. providerId: FacebookAuthProvider.PROVIDER_ID,
  4142. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  4143. accessToken
  4144. });
  4145. }
  4146. /**
  4147. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4148. *
  4149. * @param userCredential - The user credential.
  4150. */
  4151. static credentialFromResult(userCredential) {
  4152. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  4153. }
  4154. /**
  4155. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4156. * thrown during a sign-in, link, or reauthenticate operation.
  4157. *
  4158. * @param userCredential - The user credential.
  4159. */
  4160. static credentialFromError(error) {
  4161. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4162. }
  4163. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4164. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4165. return null;
  4166. }
  4167. if (!tokenResponse.oauthAccessToken) {
  4168. return null;
  4169. }
  4170. try {
  4171. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  4172. }
  4173. catch (_a) {
  4174. return null;
  4175. }
  4176. }
  4177. }
  4178. /** Always set to {@link SignInMethod}.FACEBOOK. */
  4179. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  4180. /** Always set to {@link ProviderId}.FACEBOOK. */
  4181. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  4182. /**
  4183. * @license
  4184. * Copyright 2020 Google LLC
  4185. *
  4186. * Licensed under the Apache License, Version 2.0 (the "License");
  4187. * you may not use this file except in compliance with the License.
  4188. * You may obtain a copy of the License at
  4189. *
  4190. * http://www.apache.org/licenses/LICENSE-2.0
  4191. *
  4192. * Unless required by applicable law or agreed to in writing, software
  4193. * distributed under the License is distributed on an "AS IS" BASIS,
  4194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4195. * See the License for the specific language governing permissions and
  4196. * limitations under the License.
  4197. */
  4198. /**
  4199. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  4200. *
  4201. * @example
  4202. * ```javascript
  4203. * // Sign in using a redirect.
  4204. * const provider = new GoogleAuthProvider();
  4205. * // Start a sign in process for an unauthenticated user.
  4206. * provider.addScope('profile');
  4207. * provider.addScope('email');
  4208. * await signInWithRedirect(auth, provider);
  4209. * // This will trigger a full page redirect away from your app
  4210. *
  4211. * // After returning from the redirect when your app initializes you can obtain the result
  4212. * const result = await getRedirectResult(auth);
  4213. * if (result) {
  4214. * // This is the signed-in user
  4215. * const user = result.user;
  4216. * // This gives you a Google Access Token.
  4217. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4218. * const token = credential.accessToken;
  4219. * }
  4220. * ```
  4221. *
  4222. * @example
  4223. * ```javascript
  4224. * // Sign in using a popup.
  4225. * const provider = new GoogleAuthProvider();
  4226. * provider.addScope('profile');
  4227. * provider.addScope('email');
  4228. * const result = await signInWithPopup(auth, provider);
  4229. *
  4230. * // The signed-in user info.
  4231. * const user = result.user;
  4232. * // This gives you a Google Access Token.
  4233. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4234. * const token = credential.accessToken;
  4235. * ```
  4236. *
  4237. * @public
  4238. */
  4239. class GoogleAuthProvider extends BaseOAuthProvider {
  4240. constructor() {
  4241. super("google.com" /* ProviderId.GOOGLE */);
  4242. this.addScope('profile');
  4243. }
  4244. /**
  4245. * Creates a credential for Google. At least one of ID token and access token is required.
  4246. *
  4247. * @example
  4248. * ```javascript
  4249. * // \`googleUser\` from the onsuccess Google Sign In callback.
  4250. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  4251. * const result = await signInWithCredential(credential);
  4252. * ```
  4253. *
  4254. * @param idToken - Google ID token.
  4255. * @param accessToken - Google access token.
  4256. */
  4257. static credential(idToken, accessToken) {
  4258. return OAuthCredential._fromParams({
  4259. providerId: GoogleAuthProvider.PROVIDER_ID,
  4260. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  4261. idToken,
  4262. accessToken
  4263. });
  4264. }
  4265. /**
  4266. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4267. *
  4268. * @param userCredential - The user credential.
  4269. */
  4270. static credentialFromResult(userCredential) {
  4271. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  4272. }
  4273. /**
  4274. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4275. * thrown during a sign-in, link, or reauthenticate operation.
  4276. *
  4277. * @param userCredential - The user credential.
  4278. */
  4279. static credentialFromError(error) {
  4280. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4281. }
  4282. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4283. if (!tokenResponse) {
  4284. return null;
  4285. }
  4286. const { oauthIdToken, oauthAccessToken } = tokenResponse;
  4287. if (!oauthIdToken && !oauthAccessToken) {
  4288. // This could be an oauth 1 credential or a phone credential
  4289. return null;
  4290. }
  4291. try {
  4292. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  4293. }
  4294. catch (_a) {
  4295. return null;
  4296. }
  4297. }
  4298. }
  4299. /** Always set to {@link SignInMethod}.GOOGLE. */
  4300. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  4301. /** Always set to {@link ProviderId}.GOOGLE. */
  4302. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  4303. /**
  4304. * @license
  4305. * Copyright 2020 Google LLC
  4306. *
  4307. * Licensed under the Apache License, Version 2.0 (the "License");
  4308. * you may not use this file except in compliance with the License.
  4309. * You may obtain a copy of the License at
  4310. *
  4311. * http://www.apache.org/licenses/LICENSE-2.0
  4312. *
  4313. * Unless required by applicable law or agreed to in writing, software
  4314. * distributed under the License is distributed on an "AS IS" BASIS,
  4315. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4316. * See the License for the specific language governing permissions and
  4317. * limitations under the License.
  4318. */
  4319. /**
  4320. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  4321. *
  4322. * @remarks
  4323. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  4324. * the {@link signInWithPopup} handler:
  4325. *
  4326. * @example
  4327. * ```javascript
  4328. * // Sign in using a redirect.
  4329. * const provider = new GithubAuthProvider();
  4330. * // Start a sign in process for an unauthenticated user.
  4331. * provider.addScope('repo');
  4332. * await signInWithRedirect(auth, provider);
  4333. * // This will trigger a full page redirect away from your app
  4334. *
  4335. * // After returning from the redirect when your app initializes you can obtain the result
  4336. * const result = await getRedirectResult(auth);
  4337. * if (result) {
  4338. * // This is the signed-in user
  4339. * const user = result.user;
  4340. * // This gives you a Github Access Token.
  4341. * const credential = GithubAuthProvider.credentialFromResult(result);
  4342. * const token = credential.accessToken;
  4343. * }
  4344. * ```
  4345. *
  4346. * @example
  4347. * ```javascript
  4348. * // Sign in using a popup.
  4349. * const provider = new GithubAuthProvider();
  4350. * provider.addScope('repo');
  4351. * const result = await signInWithPopup(auth, provider);
  4352. *
  4353. * // The signed-in user info.
  4354. * const user = result.user;
  4355. * // This gives you a Github Access Token.
  4356. * const credential = GithubAuthProvider.credentialFromResult(result);
  4357. * const token = credential.accessToken;
  4358. * ```
  4359. * @public
  4360. */
  4361. class GithubAuthProvider extends BaseOAuthProvider {
  4362. constructor() {
  4363. super("github.com" /* ProviderId.GITHUB */);
  4364. }
  4365. /**
  4366. * Creates a credential for Github.
  4367. *
  4368. * @param accessToken - Github access token.
  4369. */
  4370. static credential(accessToken) {
  4371. return OAuthCredential._fromParams({
  4372. providerId: GithubAuthProvider.PROVIDER_ID,
  4373. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  4374. accessToken
  4375. });
  4376. }
  4377. /**
  4378. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4379. *
  4380. * @param userCredential - The user credential.
  4381. */
  4382. static credentialFromResult(userCredential) {
  4383. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  4384. }
  4385. /**
  4386. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4387. * thrown during a sign-in, link, or reauthenticate operation.
  4388. *
  4389. * @param userCredential - The user credential.
  4390. */
  4391. static credentialFromError(error) {
  4392. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4393. }
  4394. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4395. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4396. return null;
  4397. }
  4398. if (!tokenResponse.oauthAccessToken) {
  4399. return null;
  4400. }
  4401. try {
  4402. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  4403. }
  4404. catch (_a) {
  4405. return null;
  4406. }
  4407. }
  4408. }
  4409. /** Always set to {@link SignInMethod}.GITHUB. */
  4410. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  4411. /** Always set to {@link ProviderId}.GITHUB. */
  4412. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  4413. /**
  4414. * @license
  4415. * Copyright 2020 Google LLC
  4416. *
  4417. * Licensed under the Apache License, Version 2.0 (the "License");
  4418. * you may not use this file except in compliance with the License.
  4419. * You may obtain a copy of the License at
  4420. *
  4421. * http://www.apache.org/licenses/LICENSE-2.0
  4422. *
  4423. * Unless required by applicable law or agreed to in writing, software
  4424. * distributed under the License is distributed on an "AS IS" BASIS,
  4425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4426. * See the License for the specific language governing permissions and
  4427. * limitations under the License.
  4428. */
  4429. const IDP_REQUEST_URI = 'http://localhost';
  4430. /**
  4431. * @public
  4432. */
  4433. class SAMLAuthCredential extends AuthCredential {
  4434. /** @internal */
  4435. constructor(providerId, pendingToken) {
  4436. super(providerId, providerId);
  4437. this.pendingToken = pendingToken;
  4438. }
  4439. /** @internal */
  4440. _getIdTokenResponse(auth) {
  4441. const request = this.buildRequest();
  4442. return signInWithIdp(auth, request);
  4443. }
  4444. /** @internal */
  4445. _linkToIdToken(auth, idToken) {
  4446. const request = this.buildRequest();
  4447. request.idToken = idToken;
  4448. return signInWithIdp(auth, request);
  4449. }
  4450. /** @internal */
  4451. _getReauthenticationResolver(auth) {
  4452. const request = this.buildRequest();
  4453. request.autoCreate = false;
  4454. return signInWithIdp(auth, request);
  4455. }
  4456. /** {@inheritdoc AuthCredential.toJSON} */
  4457. toJSON() {
  4458. return {
  4459. signInMethod: this.signInMethod,
  4460. providerId: this.providerId,
  4461. pendingToken: this.pendingToken
  4462. };
  4463. }
  4464. /**
  4465. * Static method to deserialize a JSON representation of an object into an
  4466. * {@link AuthCredential}.
  4467. *
  4468. * @param json - Input can be either Object or the stringified representation of the object.
  4469. * When string is provided, JSON.parse would be called first.
  4470. *
  4471. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4472. */
  4473. static fromJSON(json) {
  4474. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  4475. const { providerId, signInMethod, pendingToken } = obj;
  4476. if (!providerId ||
  4477. !signInMethod ||
  4478. !pendingToken ||
  4479. providerId !== signInMethod) {
  4480. return null;
  4481. }
  4482. return new SAMLAuthCredential(providerId, pendingToken);
  4483. }
  4484. /**
  4485. * Helper static method to avoid exposing the constructor to end users.
  4486. *
  4487. * @internal
  4488. */
  4489. static _create(providerId, pendingToken) {
  4490. return new SAMLAuthCredential(providerId, pendingToken);
  4491. }
  4492. buildRequest() {
  4493. return {
  4494. requestUri: IDP_REQUEST_URI,
  4495. returnSecureToken: true,
  4496. pendingToken: this.pendingToken
  4497. };
  4498. }
  4499. }
  4500. /**
  4501. * @license
  4502. * Copyright 2020 Google LLC
  4503. *
  4504. * Licensed under the Apache License, Version 2.0 (the "License");
  4505. * you may not use this file except in compliance with the License.
  4506. * You may obtain a copy of the License at
  4507. *
  4508. * http://www.apache.org/licenses/LICENSE-2.0
  4509. *
  4510. * Unless required by applicable law or agreed to in writing, software
  4511. * distributed under the License is distributed on an "AS IS" BASIS,
  4512. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4513. * See the License for the specific language governing permissions and
  4514. * limitations under the License.
  4515. */
  4516. const SAML_PROVIDER_PREFIX = 'saml.';
  4517. /**
  4518. * An {@link AuthProvider} for SAML.
  4519. *
  4520. * @public
  4521. */
  4522. class SAMLAuthProvider extends FederatedAuthProvider {
  4523. /**
  4524. * Constructor. The providerId must start with "saml."
  4525. * @param providerId - SAML provider ID.
  4526. */
  4527. constructor(providerId) {
  4528. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4529. super(providerId);
  4530. }
  4531. /**
  4532. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  4533. * successful SAML flow completes.
  4534. *
  4535. * @remarks
  4536. *
  4537. * For example, to get an {@link AuthCredential}, you could write the
  4538. * following code:
  4539. *
  4540. * ```js
  4541. * const userCredential = await signInWithPopup(auth, samlProvider);
  4542. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  4543. * ```
  4544. *
  4545. * @param userCredential - The user credential.
  4546. */
  4547. static credentialFromResult(userCredential) {
  4548. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  4549. }
  4550. /**
  4551. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4552. * thrown during a sign-in, link, or reauthenticate operation.
  4553. *
  4554. * @param userCredential - The user credential.
  4555. */
  4556. static credentialFromError(error) {
  4557. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  4558. }
  4559. /**
  4560. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  4561. * @param json - A plain object or a JSON string
  4562. */
  4563. static credentialFromJSON(json) {
  4564. const credential = SAMLAuthCredential.fromJSON(json);
  4565. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4566. return credential;
  4567. }
  4568. static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4569. if (!tokenResponse) {
  4570. return null;
  4571. }
  4572. const { pendingToken, providerId } = tokenResponse;
  4573. if (!pendingToken || !providerId) {
  4574. return null;
  4575. }
  4576. try {
  4577. return SAMLAuthCredential._create(providerId, pendingToken);
  4578. }
  4579. catch (e) {
  4580. return null;
  4581. }
  4582. }
  4583. }
  4584. /**
  4585. * @license
  4586. * Copyright 2020 Google LLC
  4587. *
  4588. * Licensed under the Apache License, Version 2.0 (the "License");
  4589. * you may not use this file except in compliance with the License.
  4590. * You may obtain a copy of the License at
  4591. *
  4592. * http://www.apache.org/licenses/LICENSE-2.0
  4593. *
  4594. * Unless required by applicable law or agreed to in writing, software
  4595. * distributed under the License is distributed on an "AS IS" BASIS,
  4596. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4597. * See the License for the specific language governing permissions and
  4598. * limitations under the License.
  4599. */
  4600. /**
  4601. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  4602. *
  4603. * @example
  4604. * ```javascript
  4605. * // Sign in using a redirect.
  4606. * const provider = new TwitterAuthProvider();
  4607. * // Start a sign in process for an unauthenticated user.
  4608. * await signInWithRedirect(auth, provider);
  4609. * // This will trigger a full page redirect away from your app
  4610. *
  4611. * // After returning from the redirect when your app initializes you can obtain the result
  4612. * const result = await getRedirectResult(auth);
  4613. * if (result) {
  4614. * // This is the signed-in user
  4615. * const user = result.user;
  4616. * // This gives you a Twitter Access Token and Secret.
  4617. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4618. * const token = credential.accessToken;
  4619. * const secret = credential.secret;
  4620. * }
  4621. * ```
  4622. *
  4623. * @example
  4624. * ```javascript
  4625. * // Sign in using a popup.
  4626. * const provider = new TwitterAuthProvider();
  4627. * const result = await signInWithPopup(auth, provider);
  4628. *
  4629. * // The signed-in user info.
  4630. * const user = result.user;
  4631. * // This gives you a Twitter Access Token and Secret.
  4632. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4633. * const token = credential.accessToken;
  4634. * const secret = credential.secret;
  4635. * ```
  4636. *
  4637. * @public
  4638. */
  4639. class TwitterAuthProvider extends BaseOAuthProvider {
  4640. constructor() {
  4641. super("twitter.com" /* ProviderId.TWITTER */);
  4642. }
  4643. /**
  4644. * Creates a credential for Twitter.
  4645. *
  4646. * @param token - Twitter access token.
  4647. * @param secret - Twitter secret.
  4648. */
  4649. static credential(token, secret) {
  4650. return OAuthCredential._fromParams({
  4651. providerId: TwitterAuthProvider.PROVIDER_ID,
  4652. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  4653. oauthToken: token,
  4654. oauthTokenSecret: secret
  4655. });
  4656. }
  4657. /**
  4658. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4659. *
  4660. * @param userCredential - The user credential.
  4661. */
  4662. static credentialFromResult(userCredential) {
  4663. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  4664. }
  4665. /**
  4666. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4667. * thrown during a sign-in, link, or reauthenticate operation.
  4668. *
  4669. * @param userCredential - The user credential.
  4670. */
  4671. static credentialFromError(error) {
  4672. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4673. }
  4674. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4675. if (!tokenResponse) {
  4676. return null;
  4677. }
  4678. const { oauthAccessToken, oauthTokenSecret } = tokenResponse;
  4679. if (!oauthAccessToken || !oauthTokenSecret) {
  4680. return null;
  4681. }
  4682. try {
  4683. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  4684. }
  4685. catch (_a) {
  4686. return null;
  4687. }
  4688. }
  4689. }
  4690. /** Always set to {@link SignInMethod}.TWITTER. */
  4691. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  4692. /** Always set to {@link ProviderId}.TWITTER. */
  4693. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  4694. /**
  4695. * @license
  4696. * Copyright 2020 Google LLC
  4697. *
  4698. * Licensed under the Apache License, Version 2.0 (the "License");
  4699. * you may not use this file except in compliance with the License.
  4700. * You may obtain a copy of the License at
  4701. *
  4702. * http://www.apache.org/licenses/LICENSE-2.0
  4703. *
  4704. * Unless required by applicable law or agreed to in writing, software
  4705. * distributed under the License is distributed on an "AS IS" BASIS,
  4706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4707. * See the License for the specific language governing permissions and
  4708. * limitations under the License.
  4709. */
  4710. async function signUp(auth, request) {
  4711. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));
  4712. }
  4713. /**
  4714. * @license
  4715. * Copyright 2020 Google LLC
  4716. *
  4717. * Licensed under the Apache License, Version 2.0 (the "License");
  4718. * you may not use this file except in compliance with the License.
  4719. * You may obtain a copy of the License at
  4720. *
  4721. * http://www.apache.org/licenses/LICENSE-2.0
  4722. *
  4723. * Unless required by applicable law or agreed to in writing, software
  4724. * distributed under the License is distributed on an "AS IS" BASIS,
  4725. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4726. * See the License for the specific language governing permissions and
  4727. * limitations under the License.
  4728. */
  4729. class UserCredentialImpl {
  4730. constructor(params) {
  4731. this.user = params.user;
  4732. this.providerId = params.providerId;
  4733. this._tokenResponse = params._tokenResponse;
  4734. this.operationType = params.operationType;
  4735. }
  4736. static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {
  4737. const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);
  4738. const providerId = providerIdForResponse(idTokenResponse);
  4739. const userCred = new UserCredentialImpl({
  4740. user,
  4741. providerId,
  4742. _tokenResponse: idTokenResponse,
  4743. operationType
  4744. });
  4745. return userCred;
  4746. }
  4747. static async _forOperation(user, operationType, response) {
  4748. await user._updateTokensIfNecessary(response, /* reload */ true);
  4749. const providerId = providerIdForResponse(response);
  4750. return new UserCredentialImpl({
  4751. user,
  4752. providerId,
  4753. _tokenResponse: response,
  4754. operationType
  4755. });
  4756. }
  4757. }
  4758. function providerIdForResponse(response) {
  4759. if (response.providerId) {
  4760. return response.providerId;
  4761. }
  4762. if ('phoneNumber' in response) {
  4763. return "phone" /* ProviderId.PHONE */;
  4764. }
  4765. return null;
  4766. }
  4767. /**
  4768. * @license
  4769. * Copyright 2020 Google LLC
  4770. *
  4771. * Licensed under the Apache License, Version 2.0 (the "License");
  4772. * you may not use this file except in compliance with the License.
  4773. * You may obtain a copy of the License at
  4774. *
  4775. * http://www.apache.org/licenses/LICENSE-2.0
  4776. *
  4777. * Unless required by applicable law or agreed to in writing, software
  4778. * distributed under the License is distributed on an "AS IS" BASIS,
  4779. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4780. * See the License for the specific language governing permissions and
  4781. * limitations under the License.
  4782. */
  4783. /**
  4784. * Asynchronously signs in as an anonymous user.
  4785. *
  4786. * @remarks
  4787. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  4788. * new anonymous user identity will be created and returned.
  4789. *
  4790. * @param auth - The {@link Auth} instance.
  4791. *
  4792. * @public
  4793. */
  4794. async function signInAnonymously(auth) {
  4795. var _a;
  4796. const authInternal = _castAuth(auth);
  4797. await authInternal._initializationPromise;
  4798. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  4799. // If an anonymous user is already signed in, no need to sign them in again.
  4800. return new UserCredentialImpl({
  4801. user: authInternal.currentUser,
  4802. providerId: null,
  4803. operationType: "signIn" /* OperationType.SIGN_IN */
  4804. });
  4805. }
  4806. const response = await signUp(authInternal, {
  4807. returnSecureToken: true
  4808. });
  4809. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true);
  4810. await authInternal._updateCurrentUser(userCredential.user);
  4811. return userCredential;
  4812. }
  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. class MultiFactorError extends FirebaseError {
  4830. constructor(auth, error, operationType, user) {
  4831. var _a;
  4832. super(error.code, error.message);
  4833. this.operationType = operationType;
  4834. this.user = user;
  4835. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  4836. Object.setPrototypeOf(this, MultiFactorError.prototype);
  4837. this.customData = {
  4838. appName: auth.name,
  4839. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  4840. _serverResponse: error.customData._serverResponse,
  4841. operationType
  4842. };
  4843. }
  4844. static _fromErrorAndOperation(auth, error, operationType, user) {
  4845. return new MultiFactorError(auth, error, operationType, user);
  4846. }
  4847. }
  4848. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  4849. const idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  4850. ? credential._getReauthenticationResolver(auth)
  4851. : credential._getIdTokenResponse(auth);
  4852. return idTokenProvider.catch(error => {
  4853. if (error.code === `auth/${"multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */}`) {
  4854. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  4855. }
  4856. throw error;
  4857. });
  4858. }
  4859. /**
  4860. * @license
  4861. * Copyright 2020 Google LLC
  4862. *
  4863. * Licensed under the Apache License, Version 2.0 (the "License");
  4864. * you may not use this file except in compliance with the License.
  4865. * You may obtain a copy of the License at
  4866. *
  4867. * http://www.apache.org/licenses/LICENSE-2.0
  4868. *
  4869. * Unless required by applicable law or agreed to in writing, software
  4870. * distributed under the License is distributed on an "AS IS" BASIS,
  4871. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4872. * See the License for the specific language governing permissions and
  4873. * limitations under the License.
  4874. */
  4875. /**
  4876. * Takes a set of UserInfo provider data and converts it to a set of names
  4877. */
  4878. function providerDataAsNames(providerData) {
  4879. return new Set(providerData
  4880. .map(({ providerId }) => providerId)
  4881. .filter(pid => !!pid));
  4882. }
  4883. /**
  4884. * @license
  4885. * Copyright 2019 Google LLC
  4886. *
  4887. * Licensed under the Apache License, Version 2.0 (the "License");
  4888. * you may not use this file except in compliance with the License.
  4889. * You may obtain a copy of the License at
  4890. *
  4891. * http://www.apache.org/licenses/LICENSE-2.0
  4892. *
  4893. * Unless required by applicable law or agreed to in writing, software
  4894. * distributed under the License is distributed on an "AS IS" BASIS,
  4895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4896. * See the License for the specific language governing permissions and
  4897. * limitations under the License.
  4898. */
  4899. /**
  4900. * Unlinks a provider from a user account.
  4901. *
  4902. * @param user - The user.
  4903. * @param providerId - The provider to unlink.
  4904. *
  4905. * @public
  4906. */
  4907. async function unlink(user, providerId) {
  4908. const userInternal = getModularInstance(user);
  4909. await _assertLinkedStatus(true, userInternal, providerId);
  4910. const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {
  4911. idToken: await userInternal.getIdToken(),
  4912. deleteProvider: [providerId]
  4913. });
  4914. const providersLeft = providerDataAsNames(providerUserInfo || []);
  4915. userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));
  4916. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  4917. userInternal.phoneNumber = null;
  4918. }
  4919. await userInternal.auth._persistUserIfCurrent(userInternal);
  4920. return userInternal;
  4921. }
  4922. async function _link$1(user, credential, bypassAuthState = false) {
  4923. const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);
  4924. return UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response);
  4925. }
  4926. async function _assertLinkedStatus(expected, user, provider) {
  4927. await _reloadWithoutSaving(user);
  4928. const providerIds = providerDataAsNames(user.providerData);
  4929. const code = expected === false
  4930. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  4931. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  4932. _assert(providerIds.has(provider) === expected, user.auth, code);
  4933. }
  4934. /**
  4935. * @license
  4936. * Copyright 2019 Google LLC
  4937. *
  4938. * Licensed under the Apache License, Version 2.0 (the "License");
  4939. * you may not use this file except in compliance with the License.
  4940. * You may obtain a copy of the License at
  4941. *
  4942. * http://www.apache.org/licenses/LICENSE-2.0
  4943. *
  4944. * Unless required by applicable law or agreed to in writing, software
  4945. * distributed under the License is distributed on an "AS IS" BASIS,
  4946. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4947. * See the License for the specific language governing permissions and
  4948. * limitations under the License.
  4949. */
  4950. async function _reauthenticate(user, credential, bypassAuthState = false) {
  4951. const { auth } = user;
  4952. const operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  4953. try {
  4954. const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);
  4955. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4956. const parsed = _parseToken(response.idToken);
  4957. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4958. const { sub: localId } = parsed;
  4959. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4960. return UserCredentialImpl._forOperation(user, operationType, response);
  4961. }
  4962. catch (e) {
  4963. // Convert user deleted error into user mismatch
  4964. if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${"user-not-found" /* AuthErrorCode.USER_DELETED */}`) {
  4965. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4966. }
  4967. throw e;
  4968. }
  4969. }
  4970. /**
  4971. * @license
  4972. * Copyright 2020 Google LLC
  4973. *
  4974. * Licensed under the Apache License, Version 2.0 (the "License");
  4975. * you may not use this file except in compliance with the License.
  4976. * You may obtain a copy of the License at
  4977. *
  4978. * http://www.apache.org/licenses/LICENSE-2.0
  4979. *
  4980. * Unless required by applicable law or agreed to in writing, software
  4981. * distributed under the License is distributed on an "AS IS" BASIS,
  4982. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4983. * See the License for the specific language governing permissions and
  4984. * limitations under the License.
  4985. */
  4986. async function _signInWithCredential(auth, credential, bypassAuthState = false) {
  4987. const operationType = "signIn" /* OperationType.SIGN_IN */;
  4988. const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);
  4989. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);
  4990. if (!bypassAuthState) {
  4991. await auth._updateCurrentUser(userCredential.user);
  4992. }
  4993. return userCredential;
  4994. }
  4995. /**
  4996. * Asynchronously signs in with the given credentials.
  4997. *
  4998. * @remarks
  4999. * An {@link AuthProvider} can be used to generate the credential.
  5000. *
  5001. * @param auth - The {@link Auth} instance.
  5002. * @param credential - The auth credential.
  5003. *
  5004. * @public
  5005. */
  5006. async function signInWithCredential(auth, credential) {
  5007. return _signInWithCredential(_castAuth(auth), credential);
  5008. }
  5009. /**
  5010. * Links the user account with the given credentials.
  5011. *
  5012. * @remarks
  5013. * An {@link AuthProvider} can be used to generate the credential.
  5014. *
  5015. * @param user - The user.
  5016. * @param credential - The auth credential.
  5017. *
  5018. * @public
  5019. */
  5020. async function linkWithCredential(user, credential) {
  5021. const userInternal = getModularInstance(user);
  5022. await _assertLinkedStatus(false, userInternal, credential.providerId);
  5023. return _link$1(userInternal, credential);
  5024. }
  5025. /**
  5026. * Re-authenticates a user using a fresh credential.
  5027. *
  5028. * @remarks
  5029. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  5030. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error
  5031. * or a `TOKEN_EXPIRED` error.
  5032. *
  5033. * @param user - The user.
  5034. * @param credential - The auth credential.
  5035. *
  5036. * @public
  5037. */
  5038. async function reauthenticateWithCredential(user, credential) {
  5039. return _reauthenticate(getModularInstance(user), credential);
  5040. }
  5041. /**
  5042. * @license
  5043. * Copyright 2020 Google LLC
  5044. *
  5045. * Licensed under the Apache License, Version 2.0 (the "License");
  5046. * you may not use this file except in compliance with the License.
  5047. * You may obtain a copy of the License at
  5048. *
  5049. * http://www.apache.org/licenses/LICENSE-2.0
  5050. *
  5051. * Unless required by applicable law or agreed to in writing, software
  5052. * distributed under the License is distributed on an "AS IS" BASIS,
  5053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5054. * See the License for the specific language governing permissions and
  5055. * limitations under the License.
  5056. */
  5057. async function signInWithCustomToken$1(auth, request) {
  5058. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));
  5059. }
  5060. /**
  5061. * @license
  5062. * Copyright 2020 Google LLC
  5063. *
  5064. * Licensed under the Apache License, Version 2.0 (the "License");
  5065. * you may not use this file except in compliance with the License.
  5066. * You may obtain a copy of the License at
  5067. *
  5068. * http://www.apache.org/licenses/LICENSE-2.0
  5069. *
  5070. * Unless required by applicable law or agreed to in writing, software
  5071. * distributed under the License is distributed on an "AS IS" BASIS,
  5072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5073. * See the License for the specific language governing permissions and
  5074. * limitations under the License.
  5075. */
  5076. /**
  5077. * Asynchronously signs in using a custom token.
  5078. *
  5079. * @remarks
  5080. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  5081. * be generated by an auth backend using the
  5082. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  5083. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  5084. *
  5085. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  5086. *
  5087. * @param auth - The {@link Auth} instance.
  5088. * @param customToken - The custom token to sign in with.
  5089. *
  5090. * @public
  5091. */
  5092. async function signInWithCustomToken(auth, customToken) {
  5093. const authInternal = _castAuth(auth);
  5094. const response = await signInWithCustomToken$1(authInternal, {
  5095. token: customToken,
  5096. returnSecureToken: true
  5097. });
  5098. const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  5099. await authInternal._updateCurrentUser(cred.user);
  5100. return cred;
  5101. }
  5102. /**
  5103. * @license
  5104. * Copyright 2020 Google LLC
  5105. *
  5106. * Licensed under the Apache License, Version 2.0 (the "License");
  5107. * you may not use this file except in compliance with the License.
  5108. * You may obtain a copy of the License at
  5109. *
  5110. * http://www.apache.org/licenses/LICENSE-2.0
  5111. *
  5112. * Unless required by applicable law or agreed to in writing, software
  5113. * distributed under the License is distributed on an "AS IS" BASIS,
  5114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5115. * See the License for the specific language governing permissions and
  5116. * limitations under the License.
  5117. */
  5118. class MultiFactorInfoImpl {
  5119. constructor(factorId, response) {
  5120. this.factorId = factorId;
  5121. this.uid = response.mfaEnrollmentId;
  5122. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  5123. this.displayName = response.displayName;
  5124. }
  5125. static _fromServerResponse(auth, enrollment) {
  5126. if ('phoneInfo' in enrollment) {
  5127. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  5128. }
  5129. else if ('totpInfo' in enrollment) {
  5130. return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  5131. }
  5132. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5133. }
  5134. }
  5135. class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {
  5136. constructor(response) {
  5137. super("phone" /* FactorId.PHONE */, response);
  5138. this.phoneNumber = response.phoneInfo;
  5139. }
  5140. static _fromServerResponse(_auth, enrollment) {
  5141. return new PhoneMultiFactorInfoImpl(enrollment);
  5142. }
  5143. }
  5144. class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {
  5145. constructor(response) {
  5146. super("totp" /* FactorId.TOTP */, response);
  5147. }
  5148. static _fromServerResponse(_auth, enrollment) {
  5149. return new TotpMultiFactorInfoImpl(enrollment);
  5150. }
  5151. }
  5152. /**
  5153. * @license
  5154. * Copyright 2020 Google LLC
  5155. *
  5156. * Licensed under the Apache License, Version 2.0 (the "License");
  5157. * you may not use this file except in compliance with the License.
  5158. * You may obtain a copy of the License at
  5159. *
  5160. * http://www.apache.org/licenses/LICENSE-2.0
  5161. *
  5162. * Unless required by applicable law or agreed to in writing, software
  5163. * distributed under the License is distributed on an "AS IS" BASIS,
  5164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5165. * See the License for the specific language governing permissions and
  5166. * limitations under the License.
  5167. */
  5168. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  5169. var _a;
  5170. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  5171. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  5172. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  5173. request.continueUrl = actionCodeSettings.url;
  5174. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  5175. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  5176. if (actionCodeSettings.iOS) {
  5177. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  5178. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  5179. }
  5180. if (actionCodeSettings.android) {
  5181. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  5182. request.androidInstallApp = actionCodeSettings.android.installApp;
  5183. request.androidMinimumVersionCode =
  5184. actionCodeSettings.android.minimumVersion;
  5185. request.androidPackageName = actionCodeSettings.android.packageName;
  5186. }
  5187. }
  5188. /**
  5189. * @license
  5190. * Copyright 2020 Google LLC
  5191. *
  5192. * Licensed under the Apache License, Version 2.0 (the "License");
  5193. * you may not use this file except in compliance with the License.
  5194. * You may obtain a copy of the License at
  5195. *
  5196. * http://www.apache.org/licenses/LICENSE-2.0
  5197. *
  5198. * Unless required by applicable law or agreed to in writing, software
  5199. * distributed under the License is distributed on an "AS IS" BASIS,
  5200. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5201. * See the License for the specific language governing permissions and
  5202. * limitations under the License.
  5203. */
  5204. /**
  5205. * Sends a password reset email to the given email address.
  5206. *
  5207. * @remarks
  5208. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  5209. * the email sent to the user, along with the new password specified by the user.
  5210. *
  5211. * @example
  5212. * ```javascript
  5213. * const actionCodeSettings = {
  5214. * url: 'https://www.example.com/?email=user@example.com',
  5215. * iOS: {
  5216. * bundleId: 'com.example.ios'
  5217. * },
  5218. * android: {
  5219. * packageName: 'com.example.android',
  5220. * installApp: true,
  5221. * minimumVersion: '12'
  5222. * },
  5223. * handleCodeInApp: true
  5224. * };
  5225. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  5226. * // Obtain code from user.
  5227. * await confirmPasswordReset('user@example.com', code);
  5228. * ```
  5229. *
  5230. * @param auth - The {@link Auth} instance.
  5231. * @param email - The user's email address.
  5232. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5233. *
  5234. * @public
  5235. */
  5236. async function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  5237. var _a;
  5238. const authInternal = _castAuth(auth);
  5239. const request = {
  5240. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  5241. email,
  5242. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  5243. };
  5244. if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {
  5245. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true);
  5246. if (actionCodeSettings) {
  5247. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  5248. }
  5249. await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);
  5250. }
  5251. else {
  5252. if (actionCodeSettings) {
  5253. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  5254. }
  5255. await sendPasswordResetEmail$1(authInternal, request)
  5256. .catch(async (error) => {
  5257. if (error.code === `auth/${"missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {
  5258. console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');
  5259. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true);
  5260. if (actionCodeSettings) {
  5261. _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);
  5262. }
  5263. await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);
  5264. }
  5265. else {
  5266. return Promise.reject(error);
  5267. }
  5268. });
  5269. }
  5270. }
  5271. /**
  5272. * Completes the password reset process, given a confirmation code and new password.
  5273. *
  5274. * @param auth - The {@link Auth} instance.
  5275. * @param oobCode - A confirmation code sent to the user.
  5276. * @param newPassword - The new password.
  5277. *
  5278. * @public
  5279. */
  5280. async function confirmPasswordReset(auth, oobCode, newPassword) {
  5281. await resetPassword(getModularInstance(auth), {
  5282. oobCode,
  5283. newPassword
  5284. });
  5285. // Do not return the email.
  5286. }
  5287. /**
  5288. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  5289. *
  5290. * @param auth - The {@link Auth} instance.
  5291. * @param oobCode - A verification code sent to the user.
  5292. *
  5293. * @public
  5294. */
  5295. async function applyActionCode(auth, oobCode) {
  5296. await applyActionCode$1(getModularInstance(auth), { oobCode });
  5297. }
  5298. /**
  5299. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  5300. *
  5301. * @returns metadata about the code.
  5302. *
  5303. * @param auth - The {@link Auth} instance.
  5304. * @param oobCode - A verification code sent to the user.
  5305. *
  5306. * @public
  5307. */
  5308. async function checkActionCode(auth, oobCode) {
  5309. const authModular = getModularInstance(auth);
  5310. const response = await resetPassword(authModular, { oobCode });
  5311. // Email could be empty only if the request type is EMAIL_SIGNIN or
  5312. // VERIFY_AND_CHANGE_EMAIL.
  5313. // New email should not be empty if the request type is
  5314. // VERIFY_AND_CHANGE_EMAIL.
  5315. // Multi-factor info could not be empty if the request type is
  5316. // REVERT_SECOND_FACTOR_ADDITION.
  5317. const operation = response.requestType;
  5318. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5319. switch (operation) {
  5320. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  5321. break;
  5322. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  5323. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5324. break;
  5325. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  5326. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5327. // fall through
  5328. default:
  5329. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5330. }
  5331. // The multi-factor info for revert second factor addition
  5332. let multiFactorInfo = null;
  5333. if (response.mfaInfo) {
  5334. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  5335. }
  5336. return {
  5337. data: {
  5338. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5339. ? response.newEmail
  5340. : response.email) || null,
  5341. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5342. ? response.email
  5343. : response.newEmail) || null,
  5344. multiFactorInfo
  5345. },
  5346. operation
  5347. };
  5348. }
  5349. /**
  5350. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  5351. *
  5352. * @returns the user's email address if valid.
  5353. *
  5354. * @param auth - The {@link Auth} instance.
  5355. * @param code - A verification code sent to the user.
  5356. *
  5357. * @public
  5358. */
  5359. async function verifyPasswordResetCode(auth, code) {
  5360. const { data } = await checkActionCode(getModularInstance(auth), code);
  5361. // Email should always be present since a code was sent to it
  5362. return data.email;
  5363. }
  5364. /**
  5365. * Creates a new user account associated with the specified email address and password.
  5366. *
  5367. * @remarks
  5368. * On successful creation of the user account, this user will also be signed in to your application.
  5369. *
  5370. * User account creation can fail if the account already exists or the password is invalid.
  5371. *
  5372. * Note: The email address acts as a unique identifier for the user and enables an email-based
  5373. * password reset. This function will create a new user account and set the initial user password.
  5374. *
  5375. * @param auth - The {@link Auth} instance.
  5376. * @param email - The user's email address.
  5377. * @param password - The user's chosen password.
  5378. *
  5379. * @public
  5380. */
  5381. async function createUserWithEmailAndPassword(auth, email, password) {
  5382. var _a;
  5383. const authInternal = _castAuth(auth);
  5384. const request = {
  5385. returnSecureToken: true,
  5386. email,
  5387. password,
  5388. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  5389. };
  5390. let signUpResponse;
  5391. if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {
  5392. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */);
  5393. signUpResponse = signUp(authInternal, requestWithRecaptcha);
  5394. }
  5395. else {
  5396. signUpResponse = signUp(authInternal, request).catch(async (error) => {
  5397. if (error.code === `auth/${"missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {
  5398. console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');
  5399. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "signUpPassword" /* RecaptchaActionName.SIGN_UP_PASSWORD */);
  5400. return signUp(authInternal, requestWithRecaptcha);
  5401. }
  5402. else {
  5403. return Promise.reject(error);
  5404. }
  5405. });
  5406. }
  5407. const response = await signUpResponse.catch(error => {
  5408. return Promise.reject(error);
  5409. });
  5410. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  5411. await authInternal._updateCurrentUser(userCredential.user);
  5412. return userCredential;
  5413. }
  5414. /**
  5415. * Asynchronously signs in using an email and password.
  5416. *
  5417. * @remarks
  5418. * Fails with an error if the email address and password do not match.
  5419. *
  5420. * Note: The user's password is NOT the password used to access the user's email account. The
  5421. * email address serves as a unique identifier for the user, and the password is used to access
  5422. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  5423. *
  5424. * @param auth - The {@link Auth} instance.
  5425. * @param email - The users email address.
  5426. * @param password - The users password.
  5427. *
  5428. * @public
  5429. */
  5430. function signInWithEmailAndPassword(auth, email, password) {
  5431. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  5432. }
  5433. /**
  5434. * @license
  5435. * Copyright 2020 Google LLC
  5436. *
  5437. * Licensed under the Apache License, Version 2.0 (the "License");
  5438. * you may not use this file except in compliance with the License.
  5439. * You may obtain a copy of the License at
  5440. *
  5441. * http://www.apache.org/licenses/LICENSE-2.0
  5442. *
  5443. * Unless required by applicable law or agreed to in writing, software
  5444. * distributed under the License is distributed on an "AS IS" BASIS,
  5445. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5446. * See the License for the specific language governing permissions and
  5447. * limitations under the License.
  5448. */
  5449. /**
  5450. * Sends a sign-in email link to the user with the specified email.
  5451. *
  5452. * @remarks
  5453. * The sign-in operation has to always be completed in the app unlike other out of band email
  5454. * actions (password reset and email verifications). This is because, at the end of the flow,
  5455. * the user is expected to be signed in and their Auth state persisted within the app.
  5456. *
  5457. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  5458. * address and the email link supplied in the email sent to the user.
  5459. *
  5460. * @example
  5461. * ```javascript
  5462. * const actionCodeSettings = {
  5463. * url: 'https://www.example.com/?email=user@example.com',
  5464. * iOS: {
  5465. * bundleId: 'com.example.ios'
  5466. * },
  5467. * android: {
  5468. * packageName: 'com.example.android',
  5469. * installApp: true,
  5470. * minimumVersion: '12'
  5471. * },
  5472. * handleCodeInApp: true
  5473. * };
  5474. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5475. * // Obtain emailLink from the user.
  5476. * if(isSignInWithEmailLink(auth, emailLink)) {
  5477. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5478. * }
  5479. * ```
  5480. *
  5481. * @param authInternal - The {@link Auth} instance.
  5482. * @param email - The user's email address.
  5483. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5484. *
  5485. * @public
  5486. */
  5487. async function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  5488. var _a;
  5489. const authInternal = _castAuth(auth);
  5490. const request = {
  5491. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  5492. email,
  5493. clientType: "CLIENT_TYPE_WEB" /* RecaptchaClientType.WEB */
  5494. };
  5495. function setActionCodeSettings(request, actionCodeSettings) {
  5496. _assert(actionCodeSettings.handleCodeInApp, authInternal, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5497. if (actionCodeSettings) {
  5498. _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  5499. }
  5500. }
  5501. if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {
  5502. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true);
  5503. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  5504. await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);
  5505. }
  5506. else {
  5507. setActionCodeSettings(request, actionCodeSettings);
  5508. await sendSignInLinkToEmail$1(authInternal, request)
  5509. .catch(async (error) => {
  5510. if (error.code === `auth/${"missing-recaptcha-token" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {
  5511. console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');
  5512. const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, "getOobCode" /* RecaptchaActionName.GET_OOB_CODE */, true);
  5513. setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);
  5514. await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);
  5515. }
  5516. else {
  5517. return Promise.reject(error);
  5518. }
  5519. });
  5520. }
  5521. }
  5522. /**
  5523. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  5524. *
  5525. * @param auth - The {@link Auth} instance.
  5526. * @param emailLink - The link sent to the user's email address.
  5527. *
  5528. * @public
  5529. */
  5530. function isSignInWithEmailLink(auth, emailLink) {
  5531. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  5532. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  5533. }
  5534. /**
  5535. * Asynchronously signs in using an email and sign-in email link.
  5536. *
  5537. * @remarks
  5538. * If no link is passed, the link is inferred from the current URL.
  5539. *
  5540. * Fails with an error if the email address is invalid or OTP in email link expires.
  5541. *
  5542. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  5543. *
  5544. * @example
  5545. * ```javascript
  5546. * const actionCodeSettings = {
  5547. * url: 'https://www.example.com/?email=user@example.com',
  5548. * iOS: {
  5549. * bundleId: 'com.example.ios'
  5550. * },
  5551. * android: {
  5552. * packageName: 'com.example.android',
  5553. * installApp: true,
  5554. * minimumVersion: '12'
  5555. * },
  5556. * handleCodeInApp: true
  5557. * };
  5558. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5559. * // Obtain emailLink from the user.
  5560. * if(isSignInWithEmailLink(auth, emailLink)) {
  5561. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5562. * }
  5563. * ```
  5564. *
  5565. * @param auth - The {@link Auth} instance.
  5566. * @param email - The user's email address.
  5567. * @param emailLink - The link sent to the user's email address.
  5568. *
  5569. * @public
  5570. */
  5571. async function signInWithEmailLink(auth, email, emailLink) {
  5572. const authModular = getModularInstance(auth);
  5573. const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  5574. // Check if the tenant ID in the email link matches the tenant ID on Auth
  5575. // instance.
  5576. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  5577. return signInWithCredential(authModular, credential);
  5578. }
  5579. /**
  5580. * @license
  5581. * Copyright 2020 Google LLC
  5582. *
  5583. * Licensed under the Apache License, Version 2.0 (the "License");
  5584. * you may not use this file except in compliance with the License.
  5585. * You may obtain a copy of the License at
  5586. *
  5587. * http://www.apache.org/licenses/LICENSE-2.0
  5588. *
  5589. * Unless required by applicable law or agreed to in writing, software
  5590. * distributed under the License is distributed on an "AS IS" BASIS,
  5591. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5592. * See the License for the specific language governing permissions and
  5593. * limitations under the License.
  5594. */
  5595. async function createAuthUri(auth, request) {
  5596. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));
  5597. }
  5598. /**
  5599. * @license
  5600. * Copyright 2020 Google LLC
  5601. *
  5602. * Licensed under the Apache License, Version 2.0 (the "License");
  5603. * you may not use this file except in compliance with the License.
  5604. * You may obtain a copy of the License at
  5605. *
  5606. * http://www.apache.org/licenses/LICENSE-2.0
  5607. *
  5608. * Unless required by applicable law or agreed to in writing, software
  5609. * distributed under the License is distributed on an "AS IS" BASIS,
  5610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5611. * See the License for the specific language governing permissions and
  5612. * limitations under the License.
  5613. */
  5614. /**
  5615. * Gets the list of possible sign in methods for the given email address.
  5616. *
  5617. * @remarks
  5618. * This is useful to differentiate methods of sign-in for the same provider, eg.
  5619. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  5620. * {@link SignInMethod}.EMAIL_PASSWORD and
  5621. * {@link SignInMethod}.EMAIL_LINK.
  5622. *
  5623. * @param auth - The {@link Auth} instance.
  5624. * @param email - The user's email address.
  5625. *
  5626. * @public
  5627. */
  5628. async function fetchSignInMethodsForEmail(auth, email) {
  5629. // createAuthUri returns an error if continue URI is not http or https.
  5630. // For environments like Cordova, Chrome extensions, native frameworks, file
  5631. // systems, etc, use http://localhost as continue URL.
  5632. const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  5633. const request = {
  5634. identifier: email,
  5635. continueUri
  5636. };
  5637. const { signinMethods } = await createAuthUri(getModularInstance(auth), request);
  5638. return signinMethods || [];
  5639. }
  5640. /**
  5641. * Sends a verification email to a user.
  5642. *
  5643. * @remarks
  5644. * The verification process is completed by calling {@link applyActionCode}.
  5645. *
  5646. * @example
  5647. * ```javascript
  5648. * const actionCodeSettings = {
  5649. * url: 'https://www.example.com/?email=user@example.com',
  5650. * iOS: {
  5651. * bundleId: 'com.example.ios'
  5652. * },
  5653. * android: {
  5654. * packageName: 'com.example.android',
  5655. * installApp: true,
  5656. * minimumVersion: '12'
  5657. * },
  5658. * handleCodeInApp: true
  5659. * };
  5660. * await sendEmailVerification(user, actionCodeSettings);
  5661. * // Obtain code from the user.
  5662. * await applyActionCode(auth, code);
  5663. * ```
  5664. *
  5665. * @param user - The user.
  5666. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5667. *
  5668. * @public
  5669. */
  5670. async function sendEmailVerification(user, actionCodeSettings) {
  5671. const userInternal = getModularInstance(user);
  5672. const idToken = await user.getIdToken();
  5673. const request = {
  5674. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  5675. idToken
  5676. };
  5677. if (actionCodeSettings) {
  5678. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5679. }
  5680. const { email } = await sendEmailVerification$1(userInternal.auth, request);
  5681. if (email !== user.email) {
  5682. await user.reload();
  5683. }
  5684. }
  5685. /**
  5686. * Sends a verification email to a new email address.
  5687. *
  5688. * @remarks
  5689. * The user's email will be updated to the new one after being verified.
  5690. *
  5691. * If you have a custom email action handler, you can complete the verification process by calling
  5692. * {@link applyActionCode}.
  5693. *
  5694. * @example
  5695. * ```javascript
  5696. * const actionCodeSettings = {
  5697. * url: 'https://www.example.com/?email=user@example.com',
  5698. * iOS: {
  5699. * bundleId: 'com.example.ios'
  5700. * },
  5701. * android: {
  5702. * packageName: 'com.example.android',
  5703. * installApp: true,
  5704. * minimumVersion: '12'
  5705. * },
  5706. * handleCodeInApp: true
  5707. * };
  5708. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  5709. * // Obtain code from the user.
  5710. * await applyActionCode(auth, code);
  5711. * ```
  5712. *
  5713. * @param user - The user.
  5714. * @param newEmail - The new email address to be verified before update.
  5715. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5716. *
  5717. * @public
  5718. */
  5719. async function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  5720. const userInternal = getModularInstance(user);
  5721. const idToken = await user.getIdToken();
  5722. const request = {
  5723. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  5724. idToken,
  5725. newEmail
  5726. };
  5727. if (actionCodeSettings) {
  5728. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5729. }
  5730. const { email } = await verifyAndChangeEmail(userInternal.auth, request);
  5731. if (email !== user.email) {
  5732. // If the local copy of the email on user is outdated, reload the
  5733. // user.
  5734. await user.reload();
  5735. }
  5736. }
  5737. /**
  5738. * @license
  5739. * Copyright 2020 Google LLC
  5740. *
  5741. * Licensed under the Apache License, Version 2.0 (the "License");
  5742. * you may not use this file except in compliance with the License.
  5743. * You may obtain a copy of the License at
  5744. *
  5745. * http://www.apache.org/licenses/LICENSE-2.0
  5746. *
  5747. * Unless required by applicable law or agreed to in writing, software
  5748. * distributed under the License is distributed on an "AS IS" BASIS,
  5749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5750. * See the License for the specific language governing permissions and
  5751. * limitations under the License.
  5752. */
  5753. async function updateProfile$1(auth, request) {
  5754. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  5755. }
  5756. /**
  5757. * @license
  5758. * Copyright 2020 Google LLC
  5759. *
  5760. * Licensed under the Apache License, Version 2.0 (the "License");
  5761. * you may not use this file except in compliance with the License.
  5762. * You may obtain a copy of the License at
  5763. *
  5764. * http://www.apache.org/licenses/LICENSE-2.0
  5765. *
  5766. * Unless required by applicable law or agreed to in writing, software
  5767. * distributed under the License is distributed on an "AS IS" BASIS,
  5768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5769. * See the License for the specific language governing permissions and
  5770. * limitations under the License.
  5771. */
  5772. /**
  5773. * Updates a user's profile data.
  5774. *
  5775. * @param user - The user.
  5776. * @param profile - The profile's `displayName` and `photoURL` to update.
  5777. *
  5778. * @public
  5779. */
  5780. async function updateProfile(user, { displayName, photoURL: photoUrl }) {
  5781. if (displayName === undefined && photoUrl === undefined) {
  5782. return;
  5783. }
  5784. const userInternal = getModularInstance(user);
  5785. const idToken = await userInternal.getIdToken();
  5786. const profileRequest = {
  5787. idToken,
  5788. displayName,
  5789. photoUrl,
  5790. returnSecureToken: true
  5791. };
  5792. const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));
  5793. userInternal.displayName = response.displayName || null;
  5794. userInternal.photoURL = response.photoUrl || null;
  5795. // Update the password provider as well
  5796. const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === "password" /* ProviderId.PASSWORD */);
  5797. if (passwordProvider) {
  5798. passwordProvider.displayName = userInternal.displayName;
  5799. passwordProvider.photoURL = userInternal.photoURL;
  5800. }
  5801. await userInternal._updateTokensIfNecessary(response);
  5802. }
  5803. /**
  5804. * Updates the user's email address.
  5805. *
  5806. * @remarks
  5807. * An email will be sent to the original email address (if it was set) that allows to revoke the
  5808. * email address change, in order to protect them from account hijacking.
  5809. *
  5810. * Important: this is a security sensitive operation that requires the user to have recently signed
  5811. * in. If this requirement isn't met, ask the user to authenticate again and then call
  5812. * {@link reauthenticateWithCredential}.
  5813. *
  5814. * @param user - The user.
  5815. * @param newEmail - The new email address.
  5816. *
  5817. * @public
  5818. */
  5819. function updateEmail(user, newEmail) {
  5820. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  5821. }
  5822. /**
  5823. * Updates the user's password.
  5824. *
  5825. * @remarks
  5826. * Important: this is a security sensitive operation that requires the user to have recently signed
  5827. * in. If this requirement isn't met, ask the user to authenticate again and then call
  5828. * {@link reauthenticateWithCredential}.
  5829. *
  5830. * @param user - The user.
  5831. * @param newPassword - The new password.
  5832. *
  5833. * @public
  5834. */
  5835. function updatePassword(user, newPassword) {
  5836. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  5837. }
  5838. async function updateEmailOrPassword(user, email, password) {
  5839. const { auth } = user;
  5840. const idToken = await user.getIdToken();
  5841. const request = {
  5842. idToken,
  5843. returnSecureToken: true
  5844. };
  5845. if (email) {
  5846. request.email = email;
  5847. }
  5848. if (password) {
  5849. request.password = password;
  5850. }
  5851. const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));
  5852. await user._updateTokensIfNecessary(response, /* reload */ true);
  5853. }
  5854. /**
  5855. * @license
  5856. * Copyright 2019 Google LLC
  5857. *
  5858. * Licensed under the Apache License, Version 2.0 (the "License");
  5859. * you may not use this file except in compliance with the License.
  5860. * You may obtain a copy of the License at
  5861. *
  5862. * http://www.apache.org/licenses/LICENSE-2.0
  5863. *
  5864. * Unless required by applicable law or agreed to in writing, software
  5865. * distributed under the License is distributed on an "AS IS" BASIS,
  5866. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5867. * See the License for the specific language governing permissions and
  5868. * limitations under the License.
  5869. */
  5870. /**
  5871. * Parse the `AdditionalUserInfo` from the ID token response.
  5872. *
  5873. */
  5874. function _fromIdTokenResponse(idTokenResponse) {
  5875. var _a, _b;
  5876. if (!idTokenResponse) {
  5877. return null;
  5878. }
  5879. const { providerId } = idTokenResponse;
  5880. const profile = idTokenResponse.rawUserInfo
  5881. ? JSON.parse(idTokenResponse.rawUserInfo)
  5882. : {};
  5883. const isNewUser = idTokenResponse.isNewUser ||
  5884. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  5885. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  5886. const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  5887. if (signInProvider) {
  5888. const filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  5889. signInProvider !== "custom" /* ProviderId.CUSTOM */
  5890. ? signInProvider
  5891. : null;
  5892. // Uses generic class in accordance with the legacy SDK.
  5893. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  5894. }
  5895. }
  5896. if (!providerId) {
  5897. return null;
  5898. }
  5899. switch (providerId) {
  5900. case "facebook.com" /* ProviderId.FACEBOOK */:
  5901. return new FacebookAdditionalUserInfo(isNewUser, profile);
  5902. case "github.com" /* ProviderId.GITHUB */:
  5903. return new GithubAdditionalUserInfo(isNewUser, profile);
  5904. case "google.com" /* ProviderId.GOOGLE */:
  5905. return new GoogleAdditionalUserInfo(isNewUser, profile);
  5906. case "twitter.com" /* ProviderId.TWITTER */:
  5907. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  5908. case "custom" /* ProviderId.CUSTOM */:
  5909. case "anonymous" /* ProviderId.ANONYMOUS */:
  5910. return new GenericAdditionalUserInfo(isNewUser, null);
  5911. default:
  5912. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  5913. }
  5914. }
  5915. class GenericAdditionalUserInfo {
  5916. constructor(isNewUser, providerId, profile = {}) {
  5917. this.isNewUser = isNewUser;
  5918. this.providerId = providerId;
  5919. this.profile = profile;
  5920. }
  5921. }
  5922. class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {
  5923. constructor(isNewUser, providerId, profile, username) {
  5924. super(isNewUser, providerId, profile);
  5925. this.username = username;
  5926. }
  5927. }
  5928. class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {
  5929. constructor(isNewUser, profile) {
  5930. super(isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile);
  5931. }
  5932. }
  5933. class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5934. constructor(isNewUser, profile) {
  5935. super(isNewUser, "github.com" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);
  5936. }
  5937. }
  5938. class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {
  5939. constructor(isNewUser, profile) {
  5940. super(isNewUser, "google.com" /* ProviderId.GOOGLE */, profile);
  5941. }
  5942. }
  5943. class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5944. constructor(isNewUser, profile, screenName) {
  5945. super(isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName);
  5946. }
  5947. }
  5948. /**
  5949. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  5950. *
  5951. * @param userCredential - The user credential.
  5952. *
  5953. * @public
  5954. */
  5955. function getAdditionalUserInfo(userCredential) {
  5956. const { user, _tokenResponse } = userCredential;
  5957. if (user.isAnonymous && !_tokenResponse) {
  5958. // Handle the special case where signInAnonymously() gets called twice.
  5959. // No network call is made so there's nothing to actually fill this in
  5960. return {
  5961. providerId: null,
  5962. isNewUser: false,
  5963. profile: null
  5964. };
  5965. }
  5966. return _fromIdTokenResponse(_tokenResponse);
  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. // Non-optional auth methods.
  5985. /**
  5986. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  5987. * `Auth` session and applies this type of persistence for future sign-in requests, including
  5988. * sign-in with redirect requests.
  5989. *
  5990. * @remarks
  5991. * This makes it easy for a user signing in to specify whether their session should be
  5992. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  5993. * that are shared by other users or have sensitive data.
  5994. *
  5995. * @example
  5996. * ```javascript
  5997. * setPersistence(auth, browserSessionPersistence);
  5998. * ```
  5999. *
  6000. * @param auth - The {@link Auth} instance.
  6001. * @param persistence - The {@link Persistence} to use.
  6002. * @returns A `Promise` that resolves once the persistence change has completed
  6003. *
  6004. * @public
  6005. */
  6006. function setPersistence(auth, persistence) {
  6007. return getModularInstance(auth).setPersistence(persistence);
  6008. }
  6009. /**
  6010. * Loads the reCAPTCHA configuration into the `Auth` instance.
  6011. *
  6012. * @remarks
  6013. * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA
  6014. * verification flow should be triggered for each auth provider, into the
  6015. * current Auth session.
  6016. *
  6017. * If initializeRecaptchaConfig() is not invoked, the auth flow will always start
  6018. * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA
  6019. * verification, the SDK will transparently load the reCAPTCHA config and restart the
  6020. * auth flows.
  6021. *
  6022. * Thus, by calling this optional method, you will reduce the latency of future auth flows.
  6023. * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.
  6024. *
  6025. * @example
  6026. * ```javascript
  6027. * initializeRecaptchaConfig(auth);
  6028. * ```
  6029. *
  6030. * @param auth - The {@link Auth} instance.
  6031. *
  6032. * @public
  6033. */
  6034. function initializeRecaptchaConfig(auth) {
  6035. const authInternal = _castAuth(auth);
  6036. return authInternal.initializeRecaptchaConfig();
  6037. }
  6038. /**
  6039. * Adds an observer for changes to the signed-in user's ID token.
  6040. *
  6041. * @remarks
  6042. * This includes sign-in, sign-out, and token refresh events.
  6043. * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.
  6044. *
  6045. * @param auth - The {@link Auth} instance.
  6046. * @param nextOrObserver - callback triggered on change.
  6047. * @param error - Deprecated. This callback is never triggered. Errors
  6048. * on signing in/out can be caught in promises returned from
  6049. * sign-in/sign-out functions.
  6050. * @param completed - Deprecated. This callback is never triggered.
  6051. *
  6052. * @public
  6053. */
  6054. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  6055. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  6056. }
  6057. /**
  6058. * Adds a blocking callback that runs before an auth state change
  6059. * sets a new user.
  6060. *
  6061. * @param auth - The {@link Auth} instance.
  6062. * @param callback - callback triggered before new user value is set.
  6063. * If this throws, it blocks the user from being set.
  6064. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  6065. * callback throws, allowing you to undo any side effects.
  6066. */
  6067. function beforeAuthStateChanged(auth, callback, onAbort) {
  6068. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  6069. }
  6070. /**
  6071. * Adds an observer for changes to the user's sign-in state.
  6072. *
  6073. * @remarks
  6074. * To keep the old behavior, see {@link onIdTokenChanged}.
  6075. *
  6076. * @param auth - The {@link Auth} instance.
  6077. * @param nextOrObserver - callback triggered on change.
  6078. * @param error - Deprecated. This callback is never triggered. Errors
  6079. * on signing in/out can be caught in promises returned from
  6080. * sign-in/sign-out functions.
  6081. * @param completed - Deprecated. This callback is never triggered.
  6082. *
  6083. * @public
  6084. */
  6085. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  6086. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  6087. }
  6088. /**
  6089. * Sets the current language to the default device/browser preference.
  6090. *
  6091. * @param auth - The {@link Auth} instance.
  6092. *
  6093. * @public
  6094. */
  6095. function useDeviceLanguage(auth) {
  6096. getModularInstance(auth).useDeviceLanguage();
  6097. }
  6098. /**
  6099. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  6100. * {@link Auth} instance.
  6101. *
  6102. * @remarks
  6103. * A new instance copy of the user provided will be made and set as currentUser.
  6104. *
  6105. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  6106. * like other sign in methods.
  6107. *
  6108. * The operation fails with an error if the user to be updated belongs to a different Firebase
  6109. * project.
  6110. *
  6111. * @param auth - The {@link Auth} instance.
  6112. * @param user - The new {@link User}.
  6113. *
  6114. * @public
  6115. */
  6116. function updateCurrentUser(auth, user) {
  6117. return getModularInstance(auth).updateCurrentUser(user);
  6118. }
  6119. /**
  6120. * Signs out the current user.
  6121. *
  6122. * @param auth - The {@link Auth} instance.
  6123. *
  6124. * @public
  6125. */
  6126. function signOut(auth) {
  6127. return getModularInstance(auth).signOut();
  6128. }
  6129. /**
  6130. * Deletes and signs out the user.
  6131. *
  6132. * @remarks
  6133. * Important: this is a security-sensitive operation that requires the user to have recently
  6134. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  6135. * {@link reauthenticateWithCredential}.
  6136. *
  6137. * @param user - The user.
  6138. *
  6139. * @public
  6140. */
  6141. async function deleteUser(user) {
  6142. return getModularInstance(user).delete();
  6143. }
  6144. class MultiFactorSessionImpl {
  6145. constructor(type, credential, auth) {
  6146. this.type = type;
  6147. this.credential = credential;
  6148. this.auth = auth;
  6149. }
  6150. static _fromIdtoken(idToken, auth) {
  6151. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  6152. }
  6153. static _fromMfaPendingCredential(mfaPendingCredential) {
  6154. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  6155. }
  6156. toJSON() {
  6157. const key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  6158. ? 'idToken'
  6159. : 'pendingCredential';
  6160. return {
  6161. multiFactorSession: {
  6162. [key]: this.credential
  6163. }
  6164. };
  6165. }
  6166. static fromJSON(obj) {
  6167. var _a, _b;
  6168. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  6169. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  6170. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  6171. }
  6172. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  6173. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  6174. }
  6175. }
  6176. return null;
  6177. }
  6178. }
  6179. /**
  6180. * @license
  6181. * Copyright 2020 Google LLC
  6182. *
  6183. * Licensed under the Apache License, Version 2.0 (the "License");
  6184. * you may not use this file except in compliance with the License.
  6185. * You may obtain a copy of the License at
  6186. *
  6187. * http://www.apache.org/licenses/LICENSE-2.0
  6188. *
  6189. * Unless required by applicable law or agreed to in writing, software
  6190. * distributed under the License is distributed on an "AS IS" BASIS,
  6191. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6192. * See the License for the specific language governing permissions and
  6193. * limitations under the License.
  6194. */
  6195. class MultiFactorResolverImpl {
  6196. constructor(session, hints, signInResolver) {
  6197. this.session = session;
  6198. this.hints = hints;
  6199. this.signInResolver = signInResolver;
  6200. }
  6201. /** @internal */
  6202. static _fromError(authExtern, error) {
  6203. const auth = _castAuth(authExtern);
  6204. const serverResponse = error.customData._serverResponse;
  6205. const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));
  6206. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6207. const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  6208. return new MultiFactorResolverImpl(session, hints, async (assertion) => {
  6209. const mfaResponse = await assertion._process(auth, session);
  6210. // Clear out the unneeded fields from the old login response
  6211. delete serverResponse.mfaInfo;
  6212. delete serverResponse.mfaPendingCredential;
  6213. // Use in the new token & refresh token in the old response
  6214. const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  6215. // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case
  6216. switch (error.operationType) {
  6217. case "signIn" /* OperationType.SIGN_IN */:
  6218. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);
  6219. await auth._updateCurrentUser(userCredential.user);
  6220. return userCredential;
  6221. case "reauthenticate" /* OperationType.REAUTHENTICATE */:
  6222. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6223. return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);
  6224. default:
  6225. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6226. }
  6227. });
  6228. }
  6229. async resolveSignIn(assertionExtern) {
  6230. const assertion = assertionExtern;
  6231. return this.signInResolver(assertion);
  6232. }
  6233. }
  6234. /**
  6235. * Provides a {@link MultiFactorResolver} suitable for completion of a
  6236. * multi-factor flow.
  6237. *
  6238. * @param auth - The {@link Auth} instance.
  6239. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  6240. * reauthentication operation.
  6241. *
  6242. * @public
  6243. */
  6244. function getMultiFactorResolver(auth, error) {
  6245. var _a;
  6246. const authModular = getModularInstance(auth);
  6247. const errorInternal = error;
  6248. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6249. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6250. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  6251. }
  6252. /**
  6253. * @license
  6254. * Copyright 2020 Google LLC
  6255. *
  6256. * Licensed under the Apache License, Version 2.0 (the "License");
  6257. * you may not use this file except in compliance with the License.
  6258. * You may obtain a copy of the License at
  6259. *
  6260. * http://www.apache.org/licenses/LICENSE-2.0
  6261. *
  6262. * Unless required by applicable law or agreed to in writing, software
  6263. * distributed under the License is distributed on an "AS IS" BASIS,
  6264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6265. * See the License for the specific language governing permissions and
  6266. * limitations under the License.
  6267. */
  6268. function startEnrollPhoneMfa(auth, request) {
  6269. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6270. }
  6271. function finalizeEnrollPhoneMfa(auth, request) {
  6272. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6273. }
  6274. function startEnrollTotpMfa(auth, request) {
  6275. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6276. }
  6277. function finalizeEnrollTotpMfa(auth, request) {
  6278. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6279. }
  6280. function withdrawMfa(auth, request) {
  6281. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  6282. }
  6283. class MultiFactorUserImpl {
  6284. constructor(user) {
  6285. this.user = user;
  6286. this.enrolledFactors = [];
  6287. user._onReload(userInfo => {
  6288. if (userInfo.mfaInfo) {
  6289. this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));
  6290. }
  6291. });
  6292. }
  6293. static _fromUser(user) {
  6294. return new MultiFactorUserImpl(user);
  6295. }
  6296. async getSession() {
  6297. return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user.auth);
  6298. }
  6299. async enroll(assertionExtern, displayName) {
  6300. const assertion = assertionExtern;
  6301. const session = (await this.getSession());
  6302. const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));
  6303. // New tokens will be issued after enrollment of the new second factors.
  6304. // They need to be updated on the user.
  6305. await this.user._updateTokensIfNecessary(finalizeMfaResponse);
  6306. // The user needs to be reloaded to get the new multi-factor information
  6307. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  6308. // will be updated.
  6309. return this.user.reload();
  6310. }
  6311. async unenroll(infoOrUid) {
  6312. const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  6313. const idToken = await this.user.getIdToken();
  6314. try {
  6315. const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  6316. idToken,
  6317. mfaEnrollmentId
  6318. }));
  6319. // Remove the second factor from the user's list.
  6320. this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);
  6321. // Depending on whether the backend decided to revoke the user's session,
  6322. // the tokenResponse may be empty. If the tokens were not updated (and they
  6323. // are now invalid), reloading the user will discover this and invalidate
  6324. // the user's state accordingly.
  6325. await this.user._updateTokensIfNecessary(idTokenResponse);
  6326. await this.user.reload();
  6327. }
  6328. catch (e) {
  6329. throw e;
  6330. }
  6331. }
  6332. }
  6333. const multiFactorUserCache = new WeakMap();
  6334. /**
  6335. * The {@link MultiFactorUser} corresponding to the user.
  6336. *
  6337. * @remarks
  6338. * This is used to access all multi-factor properties and operations related to the user.
  6339. *
  6340. * @param user - The user.
  6341. *
  6342. * @public
  6343. */
  6344. function multiFactor(user) {
  6345. const userModular = getModularInstance(user);
  6346. if (!multiFactorUserCache.has(userModular)) {
  6347. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  6348. }
  6349. return multiFactorUserCache.get(userModular);
  6350. }
  6351. const STORAGE_AVAILABLE_KEY = '__sak';
  6352. /**
  6353. * @license
  6354. * Copyright 2019 Google LLC
  6355. *
  6356. * Licensed under the Apache License, Version 2.0 (the "License");
  6357. * you may not use this file except in compliance with the License.
  6358. * You may obtain a copy of the License at
  6359. *
  6360. * http://www.apache.org/licenses/LICENSE-2.0
  6361. *
  6362. * Unless required by applicable law or agreed to in writing, software
  6363. * distributed under the License is distributed on an "AS IS" BASIS,
  6364. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6365. * See the License for the specific language governing permissions and
  6366. * limitations under the License.
  6367. */
  6368. // There are two different browser persistence types: local and session.
  6369. // Both have the same implementation but use a different underlying storage
  6370. // object.
  6371. class BrowserPersistenceClass {
  6372. constructor(storageRetriever, type) {
  6373. this.storageRetriever = storageRetriever;
  6374. this.type = type;
  6375. }
  6376. _isAvailable() {
  6377. try {
  6378. if (!this.storage) {
  6379. return Promise.resolve(false);
  6380. }
  6381. this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
  6382. this.storage.removeItem(STORAGE_AVAILABLE_KEY);
  6383. return Promise.resolve(true);
  6384. }
  6385. catch (_a) {
  6386. return Promise.resolve(false);
  6387. }
  6388. }
  6389. _set(key, value) {
  6390. this.storage.setItem(key, JSON.stringify(value));
  6391. return Promise.resolve();
  6392. }
  6393. _get(key) {
  6394. const json = this.storage.getItem(key);
  6395. return Promise.resolve(json ? JSON.parse(json) : null);
  6396. }
  6397. _remove(key) {
  6398. this.storage.removeItem(key);
  6399. return Promise.resolve();
  6400. }
  6401. get storage() {
  6402. return this.storageRetriever();
  6403. }
  6404. }
  6405. /**
  6406. * @license
  6407. * Copyright 2020 Google LLC
  6408. *
  6409. * Licensed under the Apache License, Version 2.0 (the "License");
  6410. * you may not use this file except in compliance with the License.
  6411. * You may obtain a copy of the License at
  6412. *
  6413. * http://www.apache.org/licenses/LICENSE-2.0
  6414. *
  6415. * Unless required by applicable law or agreed to in writing, software
  6416. * distributed under the License is distributed on an "AS IS" BASIS,
  6417. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6418. * See the License for the specific language governing permissions and
  6419. * limitations under the License.
  6420. */
  6421. function _iframeCannotSyncWebStorage() {
  6422. const ua = getUA();
  6423. return _isSafari(ua) || _isIOS(ua);
  6424. }
  6425. // The polling period in case events are not supported
  6426. const _POLLING_INTERVAL_MS$1 = 1000;
  6427. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  6428. const IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  6429. class BrowserLocalPersistence extends BrowserPersistenceClass {
  6430. constructor() {
  6431. super(() => window.localStorage, "LOCAL" /* PersistenceType.LOCAL */);
  6432. this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);
  6433. this.listeners = {};
  6434. this.localCache = {};
  6435. // setTimeout return value is platform specific
  6436. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6437. this.pollTimer = null;
  6438. // Safari or iOS browser and embedded in an iframe.
  6439. this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
  6440. // Whether to use polling instead of depending on window events
  6441. this.fallbackToPolling = _isMobileBrowser();
  6442. this._shouldAllowMigration = true;
  6443. }
  6444. forAllChangedKeys(cb) {
  6445. // Check all keys with listeners on them.
  6446. for (const key of Object.keys(this.listeners)) {
  6447. // Get value from localStorage.
  6448. const newValue = this.storage.getItem(key);
  6449. const oldValue = this.localCache[key];
  6450. // If local map value does not match, trigger listener with storage event.
  6451. // Differentiate this simulated event from the real storage event.
  6452. if (newValue !== oldValue) {
  6453. cb(key, oldValue, newValue);
  6454. }
  6455. }
  6456. }
  6457. onStorageEvent(event, poll = false) {
  6458. // Key would be null in some situations, like when localStorage is cleared
  6459. if (!event.key) {
  6460. this.forAllChangedKeys((key, _oldValue, newValue) => {
  6461. this.notifyListeners(key, newValue);
  6462. });
  6463. return;
  6464. }
  6465. const key = event.key;
  6466. // Check the mechanism how this event was detected.
  6467. // The first event will dictate the mechanism to be used.
  6468. if (poll) {
  6469. // Environment detects storage changes via polling.
  6470. // Remove storage event listener to prevent possible event duplication.
  6471. this.detachListener();
  6472. }
  6473. else {
  6474. // Environment detects storage changes via storage event listener.
  6475. // Remove polling listener to prevent possible event duplication.
  6476. this.stopPolling();
  6477. }
  6478. // Safari embedded iframe. Storage event will trigger with the delta
  6479. // changes but no changes will be applied to the iframe localStorage.
  6480. if (this.safariLocalStorageNotSynced) {
  6481. // Get current iframe page value.
  6482. const storedValue = this.storage.getItem(key);
  6483. // Value not synchronized, synchronize manually.
  6484. if (event.newValue !== storedValue) {
  6485. if (event.newValue !== null) {
  6486. // Value changed from current value.
  6487. this.storage.setItem(key, event.newValue);
  6488. }
  6489. else {
  6490. // Current value deleted.
  6491. this.storage.removeItem(key);
  6492. }
  6493. }
  6494. else if (this.localCache[key] === event.newValue && !poll) {
  6495. // Already detected and processed, do not trigger listeners again.
  6496. return;
  6497. }
  6498. }
  6499. const triggerListeners = () => {
  6500. // Keep local map up to date in case storage event is triggered before
  6501. // poll.
  6502. const storedValue = this.storage.getItem(key);
  6503. if (!poll && this.localCache[key] === storedValue) {
  6504. // Real storage event which has already been detected, do nothing.
  6505. // This seems to trigger in some IE browsers for some reason.
  6506. return;
  6507. }
  6508. this.notifyListeners(key, storedValue);
  6509. };
  6510. const storedValue = this.storage.getItem(key);
  6511. if (_isIE10() &&
  6512. storedValue !== event.newValue &&
  6513. event.newValue !== event.oldValue) {
  6514. // IE 10 has this weird bug where a storage event would trigger with the
  6515. // correct key, oldValue and newValue but localStorage.getItem(key) does
  6516. // not yield the updated value until a few milliseconds. This ensures
  6517. // this recovers from that situation.
  6518. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  6519. }
  6520. else {
  6521. triggerListeners();
  6522. }
  6523. }
  6524. notifyListeners(key, value) {
  6525. this.localCache[key] = value;
  6526. const listeners = this.listeners[key];
  6527. if (listeners) {
  6528. for (const listener of Array.from(listeners)) {
  6529. listener(value ? JSON.parse(value) : value);
  6530. }
  6531. }
  6532. }
  6533. startPolling() {
  6534. this.stopPolling();
  6535. this.pollTimer = setInterval(() => {
  6536. this.forAllChangedKeys((key, oldValue, newValue) => {
  6537. this.onStorageEvent(new StorageEvent('storage', {
  6538. key,
  6539. oldValue,
  6540. newValue
  6541. }),
  6542. /* poll */ true);
  6543. });
  6544. }, _POLLING_INTERVAL_MS$1);
  6545. }
  6546. stopPolling() {
  6547. if (this.pollTimer) {
  6548. clearInterval(this.pollTimer);
  6549. this.pollTimer = null;
  6550. }
  6551. }
  6552. attachListener() {
  6553. window.addEventListener('storage', this.boundEventHandler);
  6554. }
  6555. detachListener() {
  6556. window.removeEventListener('storage', this.boundEventHandler);
  6557. }
  6558. _addListener(key, listener) {
  6559. if (Object.keys(this.listeners).length === 0) {
  6560. // Whether browser can detect storage event when it had already been pushed to the background.
  6561. // This may happen in some mobile browsers. A localStorage change in the foreground window
  6562. // will not be detected in the background window via the storage event.
  6563. // This was detected in iOS 7.x mobile browsers
  6564. if (this.fallbackToPolling) {
  6565. this.startPolling();
  6566. }
  6567. else {
  6568. this.attachListener();
  6569. }
  6570. }
  6571. if (!this.listeners[key]) {
  6572. this.listeners[key] = new Set();
  6573. // Populate the cache to avoid spuriously triggering on first poll.
  6574. this.localCache[key] = this.storage.getItem(key);
  6575. }
  6576. this.listeners[key].add(listener);
  6577. }
  6578. _removeListener(key, listener) {
  6579. if (this.listeners[key]) {
  6580. this.listeners[key].delete(listener);
  6581. if (this.listeners[key].size === 0) {
  6582. delete this.listeners[key];
  6583. }
  6584. }
  6585. if (Object.keys(this.listeners).length === 0) {
  6586. this.detachListener();
  6587. this.stopPolling();
  6588. }
  6589. }
  6590. // Update local cache on base operations:
  6591. async _set(key, value) {
  6592. await super._set(key, value);
  6593. this.localCache[key] = JSON.stringify(value);
  6594. }
  6595. async _get(key) {
  6596. const value = await super._get(key);
  6597. this.localCache[key] = JSON.stringify(value);
  6598. return value;
  6599. }
  6600. async _remove(key) {
  6601. await super._remove(key);
  6602. delete this.localCache[key];
  6603. }
  6604. }
  6605. BrowserLocalPersistence.type = 'LOCAL';
  6606. /**
  6607. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  6608. * for the underlying storage.
  6609. *
  6610. * @public
  6611. */
  6612. const browserLocalPersistence = BrowserLocalPersistence;
  6613. /**
  6614. * @license
  6615. * Copyright 2020 Google LLC
  6616. *
  6617. * Licensed under the Apache License, Version 2.0 (the "License");
  6618. * you may not use this file except in compliance with the License.
  6619. * You may obtain a copy of the License at
  6620. *
  6621. * http://www.apache.org/licenses/LICENSE-2.0
  6622. *
  6623. * Unless required by applicable law or agreed to in writing, software
  6624. * distributed under the License is distributed on an "AS IS" BASIS,
  6625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6626. * See the License for the specific language governing permissions and
  6627. * limitations under the License.
  6628. */
  6629. class BrowserSessionPersistence extends BrowserPersistenceClass {
  6630. constructor() {
  6631. super(() => window.sessionStorage, "SESSION" /* PersistenceType.SESSION */);
  6632. }
  6633. _addListener(_key, _listener) {
  6634. // Listeners are not supported for session storage since it cannot be shared across windows
  6635. return;
  6636. }
  6637. _removeListener(_key, _listener) {
  6638. // Listeners are not supported for session storage since it cannot be shared across windows
  6639. return;
  6640. }
  6641. }
  6642. BrowserSessionPersistence.type = 'SESSION';
  6643. /**
  6644. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  6645. * for the underlying storage.
  6646. *
  6647. * @public
  6648. */
  6649. const browserSessionPersistence = BrowserSessionPersistence;
  6650. /**
  6651. * @license
  6652. * Copyright 2019 Google LLC
  6653. *
  6654. * Licensed under the Apache License, Version 2.0 (the "License");
  6655. * you may not use this file except in compliance with the License.
  6656. * You may obtain a copy of the License at
  6657. *
  6658. * http://www.apache.org/licenses/LICENSE-2.0
  6659. *
  6660. * Unless required by applicable law or agreed to in writing, software
  6661. * distributed under the License is distributed on an "AS IS" BASIS,
  6662. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6663. * See the License for the specific language governing permissions and
  6664. * limitations under the License.
  6665. */
  6666. /**
  6667. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  6668. *
  6669. * @param promises - Array of promises to wait on.
  6670. */
  6671. function _allSettled(promises) {
  6672. return Promise.all(promises.map(async (promise) => {
  6673. try {
  6674. const value = await promise;
  6675. return {
  6676. fulfilled: true,
  6677. value
  6678. };
  6679. }
  6680. catch (reason) {
  6681. return {
  6682. fulfilled: false,
  6683. reason
  6684. };
  6685. }
  6686. }));
  6687. }
  6688. /**
  6689. * @license
  6690. * Copyright 2019 Google LLC
  6691. *
  6692. * Licensed under the Apache License, Version 2.0 (the "License");
  6693. * you may not use this file except in compliance with the License.
  6694. * You may obtain a copy of the License at
  6695. *
  6696. * http://www.apache.org/licenses/LICENSE-2.0
  6697. *
  6698. * Unless required by applicable law or agreed to in writing, software
  6699. * distributed under the License is distributed on an "AS IS" BASIS,
  6700. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6701. * See the License for the specific language governing permissions and
  6702. * limitations under the License.
  6703. */
  6704. /**
  6705. * Interface class for receiving messages.
  6706. *
  6707. */
  6708. class Receiver {
  6709. constructor(eventTarget) {
  6710. this.eventTarget = eventTarget;
  6711. this.handlersMap = {};
  6712. this.boundEventHandler = this.handleEvent.bind(this);
  6713. }
  6714. /**
  6715. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  6716. *
  6717. * @param eventTarget - An event target (such as window or self) through which the underlying
  6718. * messages will be received.
  6719. */
  6720. static _getInstance(eventTarget) {
  6721. // The results are stored in an array since objects can't be keys for other
  6722. // objects. In addition, setting a unique property on an event target as a
  6723. // hash map key may not be allowed due to CORS restrictions.
  6724. const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));
  6725. if (existingInstance) {
  6726. return existingInstance;
  6727. }
  6728. const newInstance = new Receiver(eventTarget);
  6729. this.receivers.push(newInstance);
  6730. return newInstance;
  6731. }
  6732. isListeningto(eventTarget) {
  6733. return this.eventTarget === eventTarget;
  6734. }
  6735. /**
  6736. * Fans out a MessageEvent to the appropriate listeners.
  6737. *
  6738. * @remarks
  6739. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  6740. * finished processing.
  6741. *
  6742. * @param event - The MessageEvent.
  6743. *
  6744. */
  6745. async handleEvent(event) {
  6746. const messageEvent = event;
  6747. const { eventId, eventType, data } = messageEvent.data;
  6748. const handlers = this.handlersMap[eventType];
  6749. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  6750. return;
  6751. }
  6752. messageEvent.ports[0].postMessage({
  6753. status: "ack" /* _Status.ACK */,
  6754. eventId,
  6755. eventType
  6756. });
  6757. const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));
  6758. const response = await _allSettled(promises);
  6759. messageEvent.ports[0].postMessage({
  6760. status: "done" /* _Status.DONE */,
  6761. eventId,
  6762. eventType,
  6763. response
  6764. });
  6765. }
  6766. /**
  6767. * Subscribe an event handler for a particular event.
  6768. *
  6769. * @param eventType - Event name to subscribe to.
  6770. * @param eventHandler - The event handler which should receive the events.
  6771. *
  6772. */
  6773. _subscribe(eventType, eventHandler) {
  6774. if (Object.keys(this.handlersMap).length === 0) {
  6775. this.eventTarget.addEventListener('message', this.boundEventHandler);
  6776. }
  6777. if (!this.handlersMap[eventType]) {
  6778. this.handlersMap[eventType] = new Set();
  6779. }
  6780. this.handlersMap[eventType].add(eventHandler);
  6781. }
  6782. /**
  6783. * Unsubscribe an event handler from a particular event.
  6784. *
  6785. * @param eventType - Event name to unsubscribe from.
  6786. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  6787. *
  6788. */
  6789. _unsubscribe(eventType, eventHandler) {
  6790. if (this.handlersMap[eventType] && eventHandler) {
  6791. this.handlersMap[eventType].delete(eventHandler);
  6792. }
  6793. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  6794. delete this.handlersMap[eventType];
  6795. }
  6796. if (Object.keys(this.handlersMap).length === 0) {
  6797. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  6798. }
  6799. }
  6800. }
  6801. Receiver.receivers = [];
  6802. /**
  6803. * @license
  6804. * Copyright 2020 Google LLC
  6805. *
  6806. * Licensed under the Apache License, Version 2.0 (the "License");
  6807. * you may not use this file except in compliance with the License.
  6808. * You may obtain a copy of the License at
  6809. *
  6810. * http://www.apache.org/licenses/LICENSE-2.0
  6811. *
  6812. * Unless required by applicable law or agreed to in writing, software
  6813. * distributed under the License is distributed on an "AS IS" BASIS,
  6814. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6815. * See the License for the specific language governing permissions and
  6816. * limitations under the License.
  6817. */
  6818. function _generateEventId(prefix = '', digits = 10) {
  6819. let random = '';
  6820. for (let i = 0; i < digits; i++) {
  6821. random += Math.floor(Math.random() * 10);
  6822. }
  6823. return prefix + random;
  6824. }
  6825. /**
  6826. * @license
  6827. * Copyright 2019 Google LLC
  6828. *
  6829. * Licensed under the Apache License, Version 2.0 (the "License");
  6830. * you may not use this file except in compliance with the License.
  6831. * You may obtain a copy of the License at
  6832. *
  6833. * http://www.apache.org/licenses/LICENSE-2.0
  6834. *
  6835. * Unless required by applicable law or agreed to in writing, software
  6836. * distributed under the License is distributed on an "AS IS" BASIS,
  6837. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6838. * See the License for the specific language governing permissions and
  6839. * limitations under the License.
  6840. */
  6841. /**
  6842. * Interface for sending messages and waiting for a completion response.
  6843. *
  6844. */
  6845. class Sender {
  6846. constructor(target) {
  6847. this.target = target;
  6848. this.handlers = new Set();
  6849. }
  6850. /**
  6851. * Unsubscribe the handler and remove it from our tracking Set.
  6852. *
  6853. * @param handler - The handler to unsubscribe.
  6854. */
  6855. removeMessageHandler(handler) {
  6856. if (handler.messageChannel) {
  6857. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  6858. handler.messageChannel.port1.close();
  6859. }
  6860. this.handlers.delete(handler);
  6861. }
  6862. /**
  6863. * Send a message to the Receiver located at {@link target}.
  6864. *
  6865. * @remarks
  6866. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  6867. * receiver has had a chance to fully process the event.
  6868. *
  6869. * @param eventType - Type of event to send.
  6870. * @param data - The payload of the event.
  6871. * @param timeout - Timeout for waiting on an ACK from the receiver.
  6872. *
  6873. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  6874. */
  6875. async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {
  6876. const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  6877. if (!messageChannel) {
  6878. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  6879. }
  6880. // Node timers and browser timers return fundamentally different types.
  6881. // We don't actually care what the value is but TS won't accept unknown and
  6882. // we can't cast properly in both environments.
  6883. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6884. let completionTimer;
  6885. let handler;
  6886. return new Promise((resolve, reject) => {
  6887. const eventId = _generateEventId('', 20);
  6888. messageChannel.port1.start();
  6889. const ackTimer = setTimeout(() => {
  6890. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  6891. }, timeout);
  6892. handler = {
  6893. messageChannel,
  6894. onMessage(event) {
  6895. const messageEvent = event;
  6896. if (messageEvent.data.eventId !== eventId) {
  6897. return;
  6898. }
  6899. switch (messageEvent.data.status) {
  6900. case "ack" /* _Status.ACK */:
  6901. // The receiver should ACK first.
  6902. clearTimeout(ackTimer);
  6903. completionTimer = setTimeout(() => {
  6904. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  6905. }, 3000 /* _TimeoutDuration.COMPLETION */);
  6906. break;
  6907. case "done" /* _Status.DONE */:
  6908. // Once the receiver's handlers are finished we will get the results.
  6909. clearTimeout(completionTimer);
  6910. resolve(messageEvent.data.response);
  6911. break;
  6912. default:
  6913. clearTimeout(ackTimer);
  6914. clearTimeout(completionTimer);
  6915. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  6916. break;
  6917. }
  6918. }
  6919. };
  6920. this.handlers.add(handler);
  6921. messageChannel.port1.addEventListener('message', handler.onMessage);
  6922. this.target.postMessage({
  6923. eventType,
  6924. eventId,
  6925. data
  6926. }, [messageChannel.port2]);
  6927. }).finally(() => {
  6928. if (handler) {
  6929. this.removeMessageHandler(handler);
  6930. }
  6931. });
  6932. }
  6933. }
  6934. /**
  6935. * @license
  6936. * Copyright 2020 Google LLC
  6937. *
  6938. * Licensed under the Apache License, Version 2.0 (the "License");
  6939. * you may not use this file except in compliance with the License.
  6940. * You may obtain a copy of the License at
  6941. *
  6942. * http://www.apache.org/licenses/LICENSE-2.0
  6943. *
  6944. * Unless required by applicable law or agreed to in writing, software
  6945. * distributed under the License is distributed on an "AS IS" BASIS,
  6946. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6947. * See the License for the specific language governing permissions and
  6948. * limitations under the License.
  6949. */
  6950. /**
  6951. * Lazy accessor for window, since the compat layer won't tree shake this out,
  6952. * we need to make sure not to mess with window unless we have to
  6953. */
  6954. function _window() {
  6955. return window;
  6956. }
  6957. function _setWindowLocation(url) {
  6958. _window().location.href = url;
  6959. }
  6960. /**
  6961. * @license
  6962. * Copyright 2020 Google LLC.
  6963. *
  6964. * Licensed under the Apache License, Version 2.0 (the "License");
  6965. * you may not use this file except in compliance with the License.
  6966. * You may obtain a copy of the License at
  6967. *
  6968. * http://www.apache.org/licenses/LICENSE-2.0
  6969. *
  6970. * Unless required by applicable law or agreed to in writing, software
  6971. * distributed under the License is distributed on an "AS IS" BASIS,
  6972. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6973. * See the License for the specific language governing permissions and
  6974. * limitations under the License.
  6975. */
  6976. function _isWorker() {
  6977. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  6978. typeof _window()['importScripts'] === 'function');
  6979. }
  6980. async function _getActiveServiceWorker() {
  6981. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  6982. return null;
  6983. }
  6984. try {
  6985. const registration = await navigator.serviceWorker.ready;
  6986. return registration.active;
  6987. }
  6988. catch (_a) {
  6989. return null;
  6990. }
  6991. }
  6992. function _getServiceWorkerController() {
  6993. var _a;
  6994. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  6995. }
  6996. function _getWorkerGlobalScope() {
  6997. return _isWorker() ? self : null;
  6998. }
  6999. /**
  7000. * @license
  7001. * Copyright 2019 Google LLC
  7002. *
  7003. * Licensed under the Apache License, Version 2.0 (the "License");
  7004. * you may not use this file except in compliance with the License.
  7005. * You may obtain a copy of the License at
  7006. *
  7007. * http://www.apache.org/licenses/LICENSE-2.0
  7008. *
  7009. * Unless required by applicable law or agreed to in writing, software
  7010. * distributed under the License is distributed on an "AS IS" BASIS,
  7011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7012. * See the License for the specific language governing permissions and
  7013. * limitations under the License.
  7014. */
  7015. const DB_NAME = 'firebaseLocalStorageDb';
  7016. const DB_VERSION = 1;
  7017. const DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  7018. const DB_DATA_KEYPATH = 'fbase_key';
  7019. /**
  7020. * Promise wrapper for IDBRequest
  7021. *
  7022. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  7023. *
  7024. */
  7025. class DBPromise {
  7026. constructor(request) {
  7027. this.request = request;
  7028. }
  7029. toPromise() {
  7030. return new Promise((resolve, reject) => {
  7031. this.request.addEventListener('success', () => {
  7032. resolve(this.request.result);
  7033. });
  7034. this.request.addEventListener('error', () => {
  7035. reject(this.request.error);
  7036. });
  7037. });
  7038. }
  7039. }
  7040. function getObjectStore(db, isReadWrite) {
  7041. return db
  7042. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  7043. .objectStore(DB_OBJECTSTORE_NAME);
  7044. }
  7045. function _deleteDatabase() {
  7046. const request = indexedDB.deleteDatabase(DB_NAME);
  7047. return new DBPromise(request).toPromise();
  7048. }
  7049. function _openDatabase() {
  7050. const request = indexedDB.open(DB_NAME, DB_VERSION);
  7051. return new Promise((resolve, reject) => {
  7052. request.addEventListener('error', () => {
  7053. reject(request.error);
  7054. });
  7055. request.addEventListener('upgradeneeded', () => {
  7056. const db = request.result;
  7057. try {
  7058. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  7059. }
  7060. catch (e) {
  7061. reject(e);
  7062. }
  7063. });
  7064. request.addEventListener('success', async () => {
  7065. const db = request.result;
  7066. // Strange bug that occurs in Firefox when multiple tabs are opened at the
  7067. // same time. The only way to recover seems to be deleting the database
  7068. // and re-initializing it.
  7069. // https://github.com/firebase/firebase-js-sdk/issues/634
  7070. if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {
  7071. // Need to close the database or else you get a `blocked` event
  7072. db.close();
  7073. await _deleteDatabase();
  7074. resolve(await _openDatabase());
  7075. }
  7076. else {
  7077. resolve(db);
  7078. }
  7079. });
  7080. });
  7081. }
  7082. async function _putObject(db, key, value) {
  7083. const request = getObjectStore(db, true).put({
  7084. [DB_DATA_KEYPATH]: key,
  7085. value
  7086. });
  7087. return new DBPromise(request).toPromise();
  7088. }
  7089. async function getObject(db, key) {
  7090. const request = getObjectStore(db, false).get(key);
  7091. const data = await new DBPromise(request).toPromise();
  7092. return data === undefined ? null : data.value;
  7093. }
  7094. function _deleteObject(db, key) {
  7095. const request = getObjectStore(db, true).delete(key);
  7096. return new DBPromise(request).toPromise();
  7097. }
  7098. const _POLLING_INTERVAL_MS = 800;
  7099. const _TRANSACTION_RETRY_COUNT = 3;
  7100. class IndexedDBLocalPersistence {
  7101. constructor() {
  7102. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  7103. this._shouldAllowMigration = true;
  7104. this.listeners = {};
  7105. this.localCache = {};
  7106. // setTimeout return value is platform specific
  7107. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7108. this.pollTimer = null;
  7109. this.pendingWrites = 0;
  7110. this.receiver = null;
  7111. this.sender = null;
  7112. this.serviceWorkerReceiverAvailable = false;
  7113. this.activeServiceWorker = null;
  7114. // Fire & forget the service worker registration as it may never resolve
  7115. this._workerInitializationPromise =
  7116. this.initializeServiceWorkerMessaging().then(() => { }, () => { });
  7117. }
  7118. async _openDb() {
  7119. if (this.db) {
  7120. return this.db;
  7121. }
  7122. this.db = await _openDatabase();
  7123. return this.db;
  7124. }
  7125. async _withRetries(op) {
  7126. let numAttempts = 0;
  7127. while (true) {
  7128. try {
  7129. const db = await this._openDb();
  7130. return await op(db);
  7131. }
  7132. catch (e) {
  7133. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  7134. throw e;
  7135. }
  7136. if (this.db) {
  7137. this.db.close();
  7138. this.db = undefined;
  7139. }
  7140. // TODO: consider adding exponential backoff
  7141. }
  7142. }
  7143. }
  7144. /**
  7145. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  7146. * postMessage interface to send these events to the worker ourselves.
  7147. */
  7148. async initializeServiceWorkerMessaging() {
  7149. return _isWorker() ? this.initializeReceiver() : this.initializeSender();
  7150. }
  7151. /**
  7152. * As the worker we should listen to events from the main window.
  7153. */
  7154. async initializeReceiver() {
  7155. this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
  7156. // Refresh from persistence if we receive a KeyChanged message.
  7157. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, async (_origin, data) => {
  7158. const keys = await this._poll();
  7159. return {
  7160. keyProcessed: keys.includes(data.key)
  7161. };
  7162. });
  7163. // Let the sender know that we are listening so they give us more timeout.
  7164. this.receiver._subscribe("ping" /* _EventType.PING */, async (_origin, _data) => {
  7165. return ["keyChanged" /* _EventType.KEY_CHANGED */];
  7166. });
  7167. }
  7168. /**
  7169. * As the main window, we should let the worker know when keys change (set and remove).
  7170. *
  7171. * @remarks
  7172. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  7173. * may not resolve.
  7174. */
  7175. async initializeSender() {
  7176. var _a, _b;
  7177. // Check to see if there's an active service worker.
  7178. this.activeServiceWorker = await _getActiveServiceWorker();
  7179. if (!this.activeServiceWorker) {
  7180. return;
  7181. }
  7182. this.sender = new Sender(this.activeServiceWorker);
  7183. // Ping the service worker to check what events they can handle.
  7184. const results = await this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);
  7185. if (!results) {
  7186. return;
  7187. }
  7188. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  7189. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  7190. this.serviceWorkerReceiverAvailable = true;
  7191. }
  7192. }
  7193. /**
  7194. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  7195. * worker will just trigger a full sync anyway.
  7196. *
  7197. * @remarks
  7198. * For now, we only support one service worker per page.
  7199. *
  7200. * @param key - Storage key which changed.
  7201. */
  7202. async notifyServiceWorker(key) {
  7203. if (!this.sender ||
  7204. !this.activeServiceWorker ||
  7205. _getServiceWorkerController() !== this.activeServiceWorker) {
  7206. return;
  7207. }
  7208. try {
  7209. await this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key },
  7210. // Use long timeout if receiver has previously responded to a ping from us.
  7211. this.serviceWorkerReceiverAvailable
  7212. ? 800 /* _TimeoutDuration.LONG_ACK */
  7213. : 50 /* _TimeoutDuration.ACK */);
  7214. }
  7215. catch (_a) {
  7216. // This is a best effort approach. Ignore errors.
  7217. }
  7218. }
  7219. async _isAvailable() {
  7220. try {
  7221. if (!indexedDB) {
  7222. return false;
  7223. }
  7224. const db = await _openDatabase();
  7225. await _putObject(db, STORAGE_AVAILABLE_KEY, '1');
  7226. await _deleteObject(db, STORAGE_AVAILABLE_KEY);
  7227. return true;
  7228. }
  7229. catch (_a) { }
  7230. return false;
  7231. }
  7232. async _withPendingWrite(write) {
  7233. this.pendingWrites++;
  7234. try {
  7235. await write();
  7236. }
  7237. finally {
  7238. this.pendingWrites--;
  7239. }
  7240. }
  7241. async _set(key, value) {
  7242. return this._withPendingWrite(async () => {
  7243. await this._withRetries((db) => _putObject(db, key, value));
  7244. this.localCache[key] = value;
  7245. return this.notifyServiceWorker(key);
  7246. });
  7247. }
  7248. async _get(key) {
  7249. const obj = (await this._withRetries((db) => getObject(db, key)));
  7250. this.localCache[key] = obj;
  7251. return obj;
  7252. }
  7253. async _remove(key) {
  7254. return this._withPendingWrite(async () => {
  7255. await this._withRetries((db) => _deleteObject(db, key));
  7256. delete this.localCache[key];
  7257. return this.notifyServiceWorker(key);
  7258. });
  7259. }
  7260. async _poll() {
  7261. // TODO: check if we need to fallback if getAll is not supported
  7262. const result = await this._withRetries((db) => {
  7263. const getAllRequest = getObjectStore(db, false).getAll();
  7264. return new DBPromise(getAllRequest).toPromise();
  7265. });
  7266. if (!result) {
  7267. return [];
  7268. }
  7269. // If we have pending writes in progress abort, we'll get picked up on the next poll
  7270. if (this.pendingWrites !== 0) {
  7271. return [];
  7272. }
  7273. const keys = [];
  7274. const keysInResult = new Set();
  7275. for (const { fbase_key: key, value } of result) {
  7276. keysInResult.add(key);
  7277. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  7278. this.notifyListeners(key, value);
  7279. keys.push(key);
  7280. }
  7281. }
  7282. for (const localKey of Object.keys(this.localCache)) {
  7283. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  7284. // Deleted
  7285. this.notifyListeners(localKey, null);
  7286. keys.push(localKey);
  7287. }
  7288. }
  7289. return keys;
  7290. }
  7291. notifyListeners(key, newValue) {
  7292. this.localCache[key] = newValue;
  7293. const listeners = this.listeners[key];
  7294. if (listeners) {
  7295. for (const listener of Array.from(listeners)) {
  7296. listener(newValue);
  7297. }
  7298. }
  7299. }
  7300. startPolling() {
  7301. this.stopPolling();
  7302. this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);
  7303. }
  7304. stopPolling() {
  7305. if (this.pollTimer) {
  7306. clearInterval(this.pollTimer);
  7307. this.pollTimer = null;
  7308. }
  7309. }
  7310. _addListener(key, listener) {
  7311. if (Object.keys(this.listeners).length === 0) {
  7312. this.startPolling();
  7313. }
  7314. if (!this.listeners[key]) {
  7315. this.listeners[key] = new Set();
  7316. // Populate the cache to avoid spuriously triggering on first poll.
  7317. void this._get(key); // This can happen in the background async and we can return immediately.
  7318. }
  7319. this.listeners[key].add(listener);
  7320. }
  7321. _removeListener(key, listener) {
  7322. if (this.listeners[key]) {
  7323. this.listeners[key].delete(listener);
  7324. if (this.listeners[key].size === 0) {
  7325. delete this.listeners[key];
  7326. }
  7327. }
  7328. if (Object.keys(this.listeners).length === 0) {
  7329. this.stopPolling();
  7330. }
  7331. }
  7332. }
  7333. IndexedDBLocalPersistence.type = 'LOCAL';
  7334. /**
  7335. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  7336. * for the underlying storage.
  7337. *
  7338. * @public
  7339. */
  7340. const indexedDBLocalPersistence = IndexedDBLocalPersistence;
  7341. /**
  7342. * @license
  7343. * Copyright 2020 Google LLC
  7344. *
  7345. * Licensed under the Apache License, Version 2.0 (the "License");
  7346. * you may not use this file except in compliance with the License.
  7347. * You may obtain a copy of the License at
  7348. *
  7349. * http://www.apache.org/licenses/LICENSE-2.0
  7350. *
  7351. * Unless required by applicable law or agreed to in writing, software
  7352. * distributed under the License is distributed on an "AS IS" BASIS,
  7353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7354. * See the License for the specific language governing permissions and
  7355. * limitations under the License.
  7356. */
  7357. function startSignInPhoneMfa(auth, request) {
  7358. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7359. }
  7360. function finalizeSignInPhoneMfa(auth, request) {
  7361. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7362. }
  7363. function finalizeSignInTotpMfa(auth, request) {
  7364. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7365. }
  7366. /**
  7367. * @license
  7368. * Copyright 2020 Google LLC
  7369. *
  7370. * Licensed under the Apache License, Version 2.0 (the "License");
  7371. * you may not use this file except in compliance with the License.
  7372. * You may obtain a copy of the License at
  7373. *
  7374. * http://www.apache.org/licenses/LICENSE-2.0
  7375. *
  7376. * Unless required by applicable law or agreed to in writing, software
  7377. * distributed under the License is distributed on an "AS IS" BASIS,
  7378. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7379. * See the License for the specific language governing permissions and
  7380. * limitations under the License.
  7381. */
  7382. const _SOLVE_TIME_MS = 500;
  7383. const _EXPIRATION_TIME_MS = 60000;
  7384. const _WIDGET_ID_START = 1000000000000;
  7385. class MockReCaptcha {
  7386. constructor(auth) {
  7387. this.auth = auth;
  7388. this.counter = _WIDGET_ID_START;
  7389. this._widgets = new Map();
  7390. }
  7391. render(container, parameters) {
  7392. const id = this.counter;
  7393. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  7394. this.counter++;
  7395. return id;
  7396. }
  7397. reset(optWidgetId) {
  7398. var _a;
  7399. const id = optWidgetId || _WIDGET_ID_START;
  7400. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  7401. this._widgets.delete(id);
  7402. }
  7403. getResponse(optWidgetId) {
  7404. var _a;
  7405. const id = optWidgetId || _WIDGET_ID_START;
  7406. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  7407. }
  7408. async execute(optWidgetId) {
  7409. var _a;
  7410. const id = optWidgetId || _WIDGET_ID_START;
  7411. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  7412. return '';
  7413. }
  7414. }
  7415. class MockWidget {
  7416. constructor(containerOrId, appName, params) {
  7417. this.params = params;
  7418. this.timerId = null;
  7419. this.deleted = false;
  7420. this.responseToken = null;
  7421. this.clickHandler = () => {
  7422. this.execute();
  7423. };
  7424. const container = typeof containerOrId === 'string'
  7425. ? document.getElementById(containerOrId)
  7426. : containerOrId;
  7427. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });
  7428. this.container = container;
  7429. this.isVisible = this.params.size !== 'invisible';
  7430. if (this.isVisible) {
  7431. this.execute();
  7432. }
  7433. else {
  7434. this.container.addEventListener('click', this.clickHandler);
  7435. }
  7436. }
  7437. getResponse() {
  7438. this.checkIfDeleted();
  7439. return this.responseToken;
  7440. }
  7441. delete() {
  7442. this.checkIfDeleted();
  7443. this.deleted = true;
  7444. if (this.timerId) {
  7445. clearTimeout(this.timerId);
  7446. this.timerId = null;
  7447. }
  7448. this.container.removeEventListener('click', this.clickHandler);
  7449. }
  7450. execute() {
  7451. this.checkIfDeleted();
  7452. if (this.timerId) {
  7453. return;
  7454. }
  7455. this.timerId = window.setTimeout(() => {
  7456. this.responseToken = generateRandomAlphaNumericString(50);
  7457. const { callback, 'expired-callback': expiredCallback } = this.params;
  7458. if (callback) {
  7459. try {
  7460. callback(this.responseToken);
  7461. }
  7462. catch (e) { }
  7463. }
  7464. this.timerId = window.setTimeout(() => {
  7465. this.timerId = null;
  7466. this.responseToken = null;
  7467. if (expiredCallback) {
  7468. try {
  7469. expiredCallback();
  7470. }
  7471. catch (e) { }
  7472. }
  7473. if (this.isVisible) {
  7474. this.execute();
  7475. }
  7476. }, _EXPIRATION_TIME_MS);
  7477. }, _SOLVE_TIME_MS);
  7478. }
  7479. checkIfDeleted() {
  7480. if (this.deleted) {
  7481. throw new Error('reCAPTCHA mock was already deleted!');
  7482. }
  7483. }
  7484. }
  7485. function generateRandomAlphaNumericString(len) {
  7486. const chars = [];
  7487. const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7488. for (let i = 0; i < len; i++) {
  7489. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  7490. }
  7491. return chars.join('');
  7492. }
  7493. /**
  7494. * @license
  7495. * Copyright 2020 Google LLC
  7496. *
  7497. * Licensed under the Apache License, Version 2.0 (the "License");
  7498. * you may not use this file except in compliance with the License.
  7499. * You may obtain a copy of the License at
  7500. *
  7501. * http://www.apache.org/licenses/LICENSE-2.0
  7502. *
  7503. * Unless required by applicable law or agreed to in writing, software
  7504. * distributed under the License is distributed on an "AS IS" BASIS,
  7505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7506. * See the License for the specific language governing permissions and
  7507. * limitations under the License.
  7508. */
  7509. // ReCaptcha will load using the same callback, so the callback function needs
  7510. // to be kept around
  7511. const _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  7512. const NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  7513. const RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  7514. /**
  7515. * Loader for the GReCaptcha library. There should only ever be one of this.
  7516. */
  7517. class ReCaptchaLoaderImpl {
  7518. constructor() {
  7519. var _a;
  7520. this.hostLanguage = '';
  7521. this.counter = 0;
  7522. /**
  7523. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  7524. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  7525. * `window.grecaptcha.render()` will not. Another load will add it.
  7526. */
  7527. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  7528. }
  7529. load(auth, hl = '') {
  7530. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7531. if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {
  7532. return Promise.resolve(_window().grecaptcha);
  7533. }
  7534. return new Promise((resolve, reject) => {
  7535. const networkTimeout = _window().setTimeout(() => {
  7536. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  7537. }, NETWORK_TIMEOUT_DELAY.get());
  7538. _window()[_JSLOAD_CALLBACK] = () => {
  7539. _window().clearTimeout(networkTimeout);
  7540. delete _window()[_JSLOAD_CALLBACK];
  7541. const recaptcha = _window().grecaptcha;
  7542. if (!recaptcha || !isV2(recaptcha)) {
  7543. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7544. return;
  7545. }
  7546. // Wrap the greptcha render function so that we know if the developer has
  7547. // called it separately
  7548. const render = recaptcha.render;
  7549. recaptcha.render = (container, params) => {
  7550. const widgetId = render(container, params);
  7551. this.counter++;
  7552. return widgetId;
  7553. };
  7554. this.hostLanguage = hl;
  7555. resolve(recaptcha);
  7556. };
  7557. const url = `${RECAPTCHA_BASE}?${querystring({
  7558. onload: _JSLOAD_CALLBACK,
  7559. render: 'explicit',
  7560. hl
  7561. })}`;
  7562. _loadJS(url).catch(() => {
  7563. clearTimeout(networkTimeout);
  7564. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7565. });
  7566. });
  7567. }
  7568. clearedOneInstance() {
  7569. this.counter--;
  7570. }
  7571. shouldResolveImmediately(hl) {
  7572. var _a;
  7573. // We can resolve immediately if:
  7574. // • grecaptcha is already defined AND (
  7575. // 1. the requested language codes are the same OR
  7576. // 2. there exists already a ReCaptcha on the page
  7577. // 3. the library was already loaded by the app
  7578. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  7579. // that are already in the page
  7580. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  7581. (hl === this.hostLanguage ||
  7582. this.counter > 0 ||
  7583. this.librarySeparatelyLoaded));
  7584. }
  7585. }
  7586. function isHostLanguageValid(hl) {
  7587. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  7588. }
  7589. class MockReCaptchaLoaderImpl {
  7590. async load(auth) {
  7591. return new MockReCaptcha(auth);
  7592. }
  7593. clearedOneInstance() { }
  7594. }
  7595. /**
  7596. * @license
  7597. * Copyright 2020 Google LLC
  7598. *
  7599. * Licensed under the Apache License, Version 2.0 (the "License");
  7600. * you may not use this file except in compliance with the License.
  7601. * You may obtain a copy of the License at
  7602. *
  7603. * http://www.apache.org/licenses/LICENSE-2.0
  7604. *
  7605. * Unless required by applicable law or agreed to in writing, software
  7606. * distributed under the License is distributed on an "AS IS" BASIS,
  7607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7608. * See the License for the specific language governing permissions and
  7609. * limitations under the License.
  7610. */
  7611. const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  7612. const DEFAULT_PARAMS = {
  7613. theme: 'light',
  7614. type: 'image'
  7615. };
  7616. /**
  7617. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  7618. *
  7619. * @public
  7620. */
  7621. class RecaptchaVerifier {
  7622. /**
  7623. *
  7624. * @param containerOrId - The reCAPTCHA container parameter.
  7625. *
  7626. * @remarks
  7627. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  7628. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  7629. * an element ID. The corresponding element must also must be in the DOM at the time of
  7630. * initialization.
  7631. *
  7632. * @param parameters - The optional reCAPTCHA parameters.
  7633. *
  7634. * @remarks
  7635. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  7636. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  7637. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  7638. * 'invisible'.
  7639. *
  7640. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  7641. */
  7642. constructor(containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS), authExtern) {
  7643. this.parameters = parameters;
  7644. /**
  7645. * The application verifier type.
  7646. *
  7647. * @remarks
  7648. * For a reCAPTCHA verifier, this is 'recaptcha'.
  7649. */
  7650. this.type = RECAPTCHA_VERIFIER_TYPE;
  7651. this.destroyed = false;
  7652. this.widgetId = null;
  7653. this.tokenChangeListeners = new Set();
  7654. this.renderPromise = null;
  7655. this.recaptcha = null;
  7656. this.auth = _castAuth(authExtern);
  7657. this.isInvisible = this.parameters.size === 'invisible';
  7658. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7659. const container = typeof containerOrId === 'string'
  7660. ? document.getElementById(containerOrId)
  7661. : containerOrId;
  7662. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7663. this.container = container;
  7664. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  7665. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  7666. ? new MockReCaptchaLoaderImpl()
  7667. : new ReCaptchaLoaderImpl();
  7668. this.validateStartingState();
  7669. // TODO: Figure out if sdk version is needed
  7670. }
  7671. /**
  7672. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  7673. *
  7674. * @returns A Promise for the reCAPTCHA token.
  7675. */
  7676. async verify() {
  7677. this.assertNotDestroyed();
  7678. const id = await this.render();
  7679. const recaptcha = this.getAssertedRecaptcha();
  7680. const response = recaptcha.getResponse(id);
  7681. if (response) {
  7682. return response;
  7683. }
  7684. return new Promise(resolve => {
  7685. const tokenChange = (token) => {
  7686. if (!token) {
  7687. return; // Ignore token expirations.
  7688. }
  7689. this.tokenChangeListeners.delete(tokenChange);
  7690. resolve(token);
  7691. };
  7692. this.tokenChangeListeners.add(tokenChange);
  7693. if (this.isInvisible) {
  7694. recaptcha.execute(id);
  7695. }
  7696. });
  7697. }
  7698. /**
  7699. * Renders the reCAPTCHA widget on the page.
  7700. *
  7701. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  7702. */
  7703. render() {
  7704. try {
  7705. this.assertNotDestroyed();
  7706. }
  7707. catch (e) {
  7708. // This method returns a promise. Since it's not async (we want to return the
  7709. // _same_ promise if rendering is still occurring), the API surface should
  7710. // reject with the error rather than just throw
  7711. return Promise.reject(e);
  7712. }
  7713. if (this.renderPromise) {
  7714. return this.renderPromise;
  7715. }
  7716. this.renderPromise = this.makeRenderPromise().catch(e => {
  7717. this.renderPromise = null;
  7718. throw e;
  7719. });
  7720. return this.renderPromise;
  7721. }
  7722. /** @internal */
  7723. _reset() {
  7724. this.assertNotDestroyed();
  7725. if (this.widgetId !== null) {
  7726. this.getAssertedRecaptcha().reset(this.widgetId);
  7727. }
  7728. }
  7729. /**
  7730. * Clears the reCAPTCHA widget from the page and destroys the instance.
  7731. */
  7732. clear() {
  7733. this.assertNotDestroyed();
  7734. this.destroyed = true;
  7735. this._recaptchaLoader.clearedOneInstance();
  7736. if (!this.isInvisible) {
  7737. this.container.childNodes.forEach(node => {
  7738. this.container.removeChild(node);
  7739. });
  7740. }
  7741. }
  7742. validateStartingState() {
  7743. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7744. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7745. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7746. }
  7747. makeTokenCallback(existing) {
  7748. return token => {
  7749. this.tokenChangeListeners.forEach(listener => listener(token));
  7750. if (typeof existing === 'function') {
  7751. existing(token);
  7752. }
  7753. else if (typeof existing === 'string') {
  7754. const globalFunc = _window()[existing];
  7755. if (typeof globalFunc === 'function') {
  7756. globalFunc(token);
  7757. }
  7758. }
  7759. };
  7760. }
  7761. assertNotDestroyed() {
  7762. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7763. }
  7764. async makeRenderPromise() {
  7765. await this.init();
  7766. if (!this.widgetId) {
  7767. let container = this.container;
  7768. if (!this.isInvisible) {
  7769. const guaranteedEmpty = document.createElement('div');
  7770. container.appendChild(guaranteedEmpty);
  7771. container = guaranteedEmpty;
  7772. }
  7773. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  7774. }
  7775. return this.widgetId;
  7776. }
  7777. async init() {
  7778. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7779. await domReady();
  7780. this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);
  7781. const siteKey = await getRecaptchaParams(this.auth);
  7782. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7783. this.parameters.sitekey = siteKey;
  7784. }
  7785. getAssertedRecaptcha() {
  7786. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7787. return this.recaptcha;
  7788. }
  7789. }
  7790. function domReady() {
  7791. let resolver = null;
  7792. return new Promise(resolve => {
  7793. if (document.readyState === 'complete') {
  7794. resolve();
  7795. return;
  7796. }
  7797. // Document not ready, wait for load before resolving.
  7798. // Save resolver, so we can remove listener in case it was externally
  7799. // cancelled.
  7800. resolver = () => resolve();
  7801. window.addEventListener('load', resolver);
  7802. }).catch(e => {
  7803. if (resolver) {
  7804. window.removeEventListener('load', resolver);
  7805. }
  7806. throw e;
  7807. });
  7808. }
  7809. /**
  7810. * @license
  7811. * Copyright 2020 Google LLC
  7812. *
  7813. * Licensed under the Apache License, Version 2.0 (the "License");
  7814. * you may not use this file except in compliance with the License.
  7815. * You may obtain a copy of the License at
  7816. *
  7817. * http://www.apache.org/licenses/LICENSE-2.0
  7818. *
  7819. * Unless required by applicable law or agreed to in writing, software
  7820. * distributed under the License is distributed on an "AS IS" BASIS,
  7821. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7822. * See the License for the specific language governing permissions and
  7823. * limitations under the License.
  7824. */
  7825. class ConfirmationResultImpl {
  7826. constructor(verificationId, onConfirmation) {
  7827. this.verificationId = verificationId;
  7828. this.onConfirmation = onConfirmation;
  7829. }
  7830. confirm(verificationCode) {
  7831. const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  7832. return this.onConfirmation(authCredential);
  7833. }
  7834. }
  7835. /**
  7836. * Asynchronously signs in using a phone number.
  7837. *
  7838. * @remarks
  7839. * This method sends a code via SMS to the given
  7840. * phone number, and returns a {@link ConfirmationResult}. After the user
  7841. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  7842. * with the code to sign the user in.
  7843. *
  7844. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  7845. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  7846. * This function can work on other platforms that do not support the
  7847. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  7848. * third-party {@link ApplicationVerifier} implementation.
  7849. *
  7850. * @example
  7851. * ```javascript
  7852. * // 'recaptcha-container' is the ID of an element in the DOM.
  7853. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  7854. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  7855. * // Obtain a verificationCode from the user.
  7856. * const credential = await confirmationResult.confirm(verificationCode);
  7857. * ```
  7858. *
  7859. * @param auth - The {@link Auth} instance.
  7860. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7861. * @param appVerifier - The {@link ApplicationVerifier}.
  7862. *
  7863. * @public
  7864. */
  7865. async function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  7866. const authInternal = _castAuth(auth);
  7867. const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));
  7868. return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));
  7869. }
  7870. /**
  7871. * Links the user account with the given phone number.
  7872. *
  7873. * @param user - The user.
  7874. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7875. * @param appVerifier - The {@link ApplicationVerifier}.
  7876. *
  7877. * @public
  7878. */
  7879. async function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  7880. const userInternal = getModularInstance(user);
  7881. await _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */);
  7882. const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  7883. return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));
  7884. }
  7885. /**
  7886. * Re-authenticates a user using a fresh phone credential.
  7887. *
  7888. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  7889. *
  7890. * @param user - The user.
  7891. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7892. * @param appVerifier - The {@link ApplicationVerifier}.
  7893. *
  7894. * @public
  7895. */
  7896. async function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  7897. const userInternal = getModularInstance(user);
  7898. const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  7899. return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));
  7900. }
  7901. /**
  7902. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  7903. *
  7904. */
  7905. async function _verifyPhoneNumber(auth, options, verifier) {
  7906. var _a;
  7907. const recaptchaToken = await verifier.verify();
  7908. try {
  7909. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7910. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7911. let phoneInfoOptions;
  7912. if (typeof options === 'string') {
  7913. phoneInfoOptions = {
  7914. phoneNumber: options
  7915. };
  7916. }
  7917. else {
  7918. phoneInfoOptions = options;
  7919. }
  7920. if ('session' in phoneInfoOptions) {
  7921. const session = phoneInfoOptions.session;
  7922. if ('phoneNumber' in phoneInfoOptions) {
  7923. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7924. const response = await startEnrollPhoneMfa(auth, {
  7925. idToken: session.credential,
  7926. phoneEnrollmentInfo: {
  7927. phoneNumber: phoneInfoOptions.phoneNumber,
  7928. recaptchaToken
  7929. }
  7930. });
  7931. return response.phoneSessionInfo.sessionInfo;
  7932. }
  7933. else {
  7934. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7935. const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  7936. phoneInfoOptions.multiFactorUid;
  7937. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  7938. const response = await startSignInPhoneMfa(auth, {
  7939. mfaPendingCredential: session.credential,
  7940. mfaEnrollmentId,
  7941. phoneSignInInfo: {
  7942. recaptchaToken
  7943. }
  7944. });
  7945. return response.phoneResponseInfo.sessionInfo;
  7946. }
  7947. }
  7948. else {
  7949. const { sessionInfo } = await sendPhoneVerificationCode(auth, {
  7950. phoneNumber: phoneInfoOptions.phoneNumber,
  7951. recaptchaToken
  7952. });
  7953. return sessionInfo;
  7954. }
  7955. }
  7956. finally {
  7957. verifier._reset();
  7958. }
  7959. }
  7960. /**
  7961. * Updates the user's phone number.
  7962. *
  7963. * @example
  7964. * ```
  7965. * // 'recaptcha-container' is the ID of an element in the DOM.
  7966. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  7967. * const provider = new PhoneAuthProvider(auth);
  7968. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  7969. * // Obtain the verificationCode from the user.
  7970. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  7971. * await updatePhoneNumber(user, phoneCredential);
  7972. * ```
  7973. *
  7974. * @param user - The user.
  7975. * @param credential - A credential authenticating the new phone number.
  7976. *
  7977. * @public
  7978. */
  7979. async function updatePhoneNumber(user, credential) {
  7980. await _link$1(getModularInstance(user), credential);
  7981. }
  7982. /**
  7983. * @license
  7984. * Copyright 2020 Google LLC
  7985. *
  7986. * Licensed under the Apache License, Version 2.0 (the "License");
  7987. * you may not use this file except in compliance with the License.
  7988. * You may obtain a copy of the License at
  7989. *
  7990. * http://www.apache.org/licenses/LICENSE-2.0
  7991. *
  7992. * Unless required by applicable law or agreed to in writing, software
  7993. * distributed under the License is distributed on an "AS IS" BASIS,
  7994. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7995. * See the License for the specific language governing permissions and
  7996. * limitations under the License.
  7997. */
  7998. /**
  7999. * Provider for generating an {@link PhoneAuthCredential}.
  8000. *
  8001. * @example
  8002. * ```javascript
  8003. * // 'recaptcha-container' is the ID of an element in the DOM.
  8004. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  8005. * const provider = new PhoneAuthProvider(auth);
  8006. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  8007. * // Obtain the verificationCode from the user.
  8008. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8009. * const userCredential = await signInWithCredential(auth, phoneCredential);
  8010. * ```
  8011. *
  8012. * @public
  8013. */
  8014. class PhoneAuthProvider {
  8015. /**
  8016. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  8017. *
  8018. */
  8019. constructor(auth) {
  8020. /** Always set to {@link ProviderId}.PHONE. */
  8021. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  8022. this.auth = _castAuth(auth);
  8023. }
  8024. /**
  8025. *
  8026. * Starts a phone number authentication flow by sending a verification code to the given phone
  8027. * number.
  8028. *
  8029. * @example
  8030. * ```javascript
  8031. * const provider = new PhoneAuthProvider(auth);
  8032. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  8033. * // Obtain verificationCode from the user.
  8034. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8035. * const userCredential = await signInWithCredential(auth, authCredential);
  8036. * ```
  8037. *
  8038. * @example
  8039. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  8040. * ```javascript
  8041. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  8042. * // Obtain verificationCode from the user.
  8043. * const userCredential = confirmationResult.confirm(verificationCode);
  8044. * ```
  8045. *
  8046. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  8047. * E.164 format (e.g. +16505550101).
  8048. * @param applicationVerifier - For abuse prevention, this method also requires a
  8049. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  8050. * {@link RecaptchaVerifier}.
  8051. *
  8052. * @returns A Promise for a verification ID that can be passed to
  8053. * {@link PhoneAuthProvider.credential} to identify this flow..
  8054. */
  8055. verifyPhoneNumber(phoneOptions, applicationVerifier) {
  8056. return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  8057. }
  8058. /**
  8059. * Creates a phone auth credential, given the verification ID from
  8060. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  8061. * mobile device.
  8062. *
  8063. * @example
  8064. * ```javascript
  8065. * const provider = new PhoneAuthProvider(auth);
  8066. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  8067. * // Obtain verificationCode from the user.
  8068. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8069. * const userCredential = signInWithCredential(auth, authCredential);
  8070. * ```
  8071. *
  8072. * @example
  8073. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  8074. * ```javascript
  8075. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  8076. * // Obtain verificationCode from the user.
  8077. * const userCredential = await confirmationResult.confirm(verificationCode);
  8078. * ```
  8079. *
  8080. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  8081. * @param verificationCode - The verification code sent to the user's mobile device.
  8082. *
  8083. * @returns The auth provider credential.
  8084. */
  8085. static credential(verificationId, verificationCode) {
  8086. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  8087. }
  8088. /**
  8089. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  8090. * @param userCredential - The user credential.
  8091. */
  8092. static credentialFromResult(userCredential) {
  8093. const credential = userCredential;
  8094. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  8095. }
  8096. /**
  8097. * Returns an {@link AuthCredential} when passed an error.
  8098. *
  8099. * @remarks
  8100. *
  8101. * This method works for errors like
  8102. * `auth/account-exists-with-different-credentials`. This is useful for
  8103. * recovering when attempting to set a user's phone number but the number
  8104. * in question is already tied to another account. For example, the following
  8105. * code tries to update the current user's phone number, and if that
  8106. * fails, links the user with the account associated with that number:
  8107. *
  8108. * ```js
  8109. * const provider = new PhoneAuthProvider(auth);
  8110. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  8111. * try {
  8112. * const code = ''; // Prompt the user for the verification code
  8113. * await updatePhoneNumber(
  8114. * auth.currentUser,
  8115. * PhoneAuthProvider.credential(verificationId, code));
  8116. * } catch (e) {
  8117. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  8118. * const cred = PhoneAuthProvider.credentialFromError(e);
  8119. * await linkWithCredential(auth.currentUser, cred);
  8120. * }
  8121. * }
  8122. *
  8123. * // At this point, auth.currentUser.phoneNumber === number.
  8124. * ```
  8125. *
  8126. * @param error - The error to generate a credential from.
  8127. */
  8128. static credentialFromError(error) {
  8129. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  8130. }
  8131. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  8132. if (!tokenResponse) {
  8133. return null;
  8134. }
  8135. const { phoneNumber, temporaryProof } = tokenResponse;
  8136. if (phoneNumber && temporaryProof) {
  8137. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  8138. }
  8139. return null;
  8140. }
  8141. }
  8142. /** Always set to {@link ProviderId}.PHONE. */
  8143. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  8144. /** Always set to {@link SignInMethod}.PHONE. */
  8145. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  8146. /**
  8147. * @license
  8148. * Copyright 2021 Google LLC
  8149. *
  8150. * Licensed under the Apache License, Version 2.0 (the "License");
  8151. * you may not use this file except in compliance with the License.
  8152. * You may obtain a copy of the License at
  8153. *
  8154. * http://www.apache.org/licenses/LICENSE-2.0
  8155. *
  8156. * Unless required by applicable law or agreed to in writing, software
  8157. * distributed under the License is distributed on an "AS IS" BASIS,
  8158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8159. * See the License for the specific language governing permissions and
  8160. * limitations under the License.
  8161. */
  8162. /**
  8163. * Chooses a popup/redirect resolver to use. This prefers the override (which
  8164. * is directly passed in), and falls back to the property set on the auth
  8165. * object. If neither are available, this function errors w/ an argument error.
  8166. */
  8167. function _withDefaultResolver(auth, resolverOverride) {
  8168. if (resolverOverride) {
  8169. return _getInstance(resolverOverride);
  8170. }
  8171. _assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8172. return auth._popupRedirectResolver;
  8173. }
  8174. /**
  8175. * @license
  8176. * Copyright 2019 Google LLC
  8177. *
  8178. * Licensed under the Apache License, Version 2.0 (the "License");
  8179. * you may not use this file except in compliance with the License.
  8180. * You may obtain a copy of the License at
  8181. *
  8182. * http://www.apache.org/licenses/LICENSE-2.0
  8183. *
  8184. * Unless required by applicable law or agreed to in writing, software
  8185. * distributed under the License is distributed on an "AS IS" BASIS,
  8186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8187. * See the License for the specific language governing permissions and
  8188. * limitations under the License.
  8189. */
  8190. class IdpCredential extends AuthCredential {
  8191. constructor(params) {
  8192. super("custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */);
  8193. this.params = params;
  8194. }
  8195. _getIdTokenResponse(auth) {
  8196. return signInWithIdp(auth, this._buildIdpRequest());
  8197. }
  8198. _linkToIdToken(auth, idToken) {
  8199. return signInWithIdp(auth, this._buildIdpRequest(idToken));
  8200. }
  8201. _getReauthenticationResolver(auth) {
  8202. return signInWithIdp(auth, this._buildIdpRequest());
  8203. }
  8204. _buildIdpRequest(idToken) {
  8205. const request = {
  8206. requestUri: this.params.requestUri,
  8207. sessionId: this.params.sessionId,
  8208. postBody: this.params.postBody,
  8209. tenantId: this.params.tenantId,
  8210. pendingToken: this.params.pendingToken,
  8211. returnSecureToken: true,
  8212. returnIdpCredential: true
  8213. };
  8214. if (idToken) {
  8215. request.idToken = idToken;
  8216. }
  8217. return request;
  8218. }
  8219. }
  8220. function _signIn(params) {
  8221. return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  8222. }
  8223. function _reauth(params) {
  8224. const { auth, user } = params;
  8225. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8226. return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  8227. }
  8228. async function _link(params) {
  8229. const { auth, user } = params;
  8230. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8231. return _link$1(user, new IdpCredential(params), params.bypassAuthState);
  8232. }
  8233. /**
  8234. * @license
  8235. * Copyright 2020 Google LLC
  8236. *
  8237. * Licensed under the Apache License, Version 2.0 (the "License");
  8238. * you may not use this file except in compliance with the License.
  8239. * You may obtain a copy of the License at
  8240. *
  8241. * http://www.apache.org/licenses/LICENSE-2.0
  8242. *
  8243. * Unless required by applicable law or agreed to in writing, software
  8244. * distributed under the License is distributed on an "AS IS" BASIS,
  8245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8246. * See the License for the specific language governing permissions and
  8247. * limitations under the License.
  8248. */
  8249. /**
  8250. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  8251. * events
  8252. */
  8253. class AbstractPopupRedirectOperation {
  8254. constructor(auth, filter, resolver, user, bypassAuthState = false) {
  8255. this.auth = auth;
  8256. this.resolver = resolver;
  8257. this.user = user;
  8258. this.bypassAuthState = bypassAuthState;
  8259. this.pendingPromise = null;
  8260. this.eventManager = null;
  8261. this.filter = Array.isArray(filter) ? filter : [filter];
  8262. }
  8263. execute() {
  8264. return new Promise(async (resolve, reject) => {
  8265. this.pendingPromise = { resolve, reject };
  8266. try {
  8267. this.eventManager = await this.resolver._initialize(this.auth);
  8268. await this.onExecution();
  8269. this.eventManager.registerConsumer(this);
  8270. }
  8271. catch (e) {
  8272. this.reject(e);
  8273. }
  8274. });
  8275. }
  8276. async onAuthEvent(event) {
  8277. const { urlResponse, sessionId, postBody, tenantId, error, type } = event;
  8278. if (error) {
  8279. this.reject(error);
  8280. return;
  8281. }
  8282. const params = {
  8283. auth: this.auth,
  8284. requestUri: urlResponse,
  8285. sessionId: sessionId,
  8286. tenantId: tenantId || undefined,
  8287. postBody: postBody || undefined,
  8288. user: this.user,
  8289. bypassAuthState: this.bypassAuthState
  8290. };
  8291. try {
  8292. this.resolve(await this.getIdpTask(type)(params));
  8293. }
  8294. catch (e) {
  8295. this.reject(e);
  8296. }
  8297. }
  8298. onError(error) {
  8299. this.reject(error);
  8300. }
  8301. getIdpTask(type) {
  8302. switch (type) {
  8303. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  8304. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  8305. return _signIn;
  8306. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  8307. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  8308. return _link;
  8309. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  8310. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  8311. return _reauth;
  8312. default:
  8313. _fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8314. }
  8315. }
  8316. resolve(cred) {
  8317. debugAssert(this.pendingPromise, 'Pending promise was never set');
  8318. this.pendingPromise.resolve(cred);
  8319. this.unregisterAndCleanUp();
  8320. }
  8321. reject(error) {
  8322. debugAssert(this.pendingPromise, 'Pending promise was never set');
  8323. this.pendingPromise.reject(error);
  8324. this.unregisterAndCleanUp();
  8325. }
  8326. unregisterAndCleanUp() {
  8327. if (this.eventManager) {
  8328. this.eventManager.unregisterConsumer(this);
  8329. }
  8330. this.pendingPromise = null;
  8331. this.cleanUp();
  8332. }
  8333. }
  8334. /**
  8335. * @license
  8336. * Copyright 2020 Google LLC
  8337. *
  8338. * Licensed under the Apache License, Version 2.0 (the "License");
  8339. * you may not use this file except in compliance with the License.
  8340. * You may obtain a copy of the License at
  8341. *
  8342. * http://www.apache.org/licenses/LICENSE-2.0
  8343. *
  8344. * Unless required by applicable law or agreed to in writing, software
  8345. * distributed under the License is distributed on an "AS IS" BASIS,
  8346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8347. * See the License for the specific language governing permissions and
  8348. * limitations under the License.
  8349. */
  8350. const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
  8351. /**
  8352. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  8353. *
  8354. * @remarks
  8355. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  8356. * unsuccessful, returns an error object containing additional information about the error.
  8357. *
  8358. * @example
  8359. * ```javascript
  8360. * // Sign in using a popup.
  8361. * const provider = new FacebookAuthProvider();
  8362. * const result = await signInWithPopup(auth, provider);
  8363. *
  8364. * // The signed-in user info.
  8365. * const user = result.user;
  8366. * // This gives you a Facebook Access Token.
  8367. * const credential = provider.credentialFromResult(auth, result);
  8368. * const token = credential.accessToken;
  8369. * ```
  8370. *
  8371. * @param auth - The {@link Auth} instance.
  8372. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8373. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8374. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8375. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8376. *
  8377. *
  8378. * @public
  8379. */
  8380. async function signInWithPopup(auth, provider, resolver) {
  8381. const authInternal = _castAuth(auth);
  8382. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  8383. const resolverInternal = _withDefaultResolver(authInternal, resolver);
  8384. const action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  8385. return action.executeNotNull();
  8386. }
  8387. /**
  8388. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  8389. * OAuth flow.
  8390. *
  8391. * @remarks
  8392. * If the reauthentication is successful, the returned result will contain the user and the
  8393. * provider's credential.
  8394. *
  8395. * @example
  8396. * ```javascript
  8397. * // Sign in using a popup.
  8398. * const provider = new FacebookAuthProvider();
  8399. * const result = await signInWithPopup(auth, provider);
  8400. * // Reauthenticate using a popup.
  8401. * await reauthenticateWithPopup(result.user, provider);
  8402. * ```
  8403. *
  8404. * @param user - The user.
  8405. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8406. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8407. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8408. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8409. *
  8410. * @public
  8411. */
  8412. async function reauthenticateWithPopup(user, provider, resolver) {
  8413. const userInternal = getModularInstance(user);
  8414. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8415. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8416. const action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  8417. return action.executeNotNull();
  8418. }
  8419. /**
  8420. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  8421. *
  8422. * @remarks
  8423. * If the linking is successful, the returned result will contain the user and the provider's credential.
  8424. *
  8425. *
  8426. * @example
  8427. * ```javascript
  8428. * // Sign in using some other provider.
  8429. * const result = await signInWithEmailAndPassword(auth, email, password);
  8430. * // Link using a popup.
  8431. * const provider = new FacebookAuthProvider();
  8432. * await linkWithPopup(result.user, provider);
  8433. * ```
  8434. *
  8435. * @param user - The user.
  8436. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8437. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8438. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8439. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8440. *
  8441. * @public
  8442. */
  8443. async function linkWithPopup(user, provider, resolver) {
  8444. const userInternal = getModularInstance(user);
  8445. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8446. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8447. const action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  8448. return action.executeNotNull();
  8449. }
  8450. /**
  8451. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  8452. * events
  8453. *
  8454. */
  8455. class PopupOperation extends AbstractPopupRedirectOperation {
  8456. constructor(auth, filter, provider, resolver, user) {
  8457. super(auth, filter, resolver, user);
  8458. this.provider = provider;
  8459. this.authWindow = null;
  8460. this.pollId = null;
  8461. if (PopupOperation.currentPopupAction) {
  8462. PopupOperation.currentPopupAction.cancel();
  8463. }
  8464. PopupOperation.currentPopupAction = this;
  8465. }
  8466. async executeNotNull() {
  8467. const result = await this.execute();
  8468. _assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8469. return result;
  8470. }
  8471. async onExecution() {
  8472. debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  8473. const eventId = _generateEventId();
  8474. this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  8475. eventId);
  8476. this.authWindow.associatedEvent = eventId;
  8477. // Check for web storage support and origin validation _after_ the popup is
  8478. // loaded. These operations are slow (~1 second or so) Rather than
  8479. // waiting on them before opening the window, optimistically open the popup
  8480. // and check for storage support at the same time. If storage support is
  8481. // not available, this will cause the whole thing to reject properly. It
  8482. // will also close the popup, but since the promise has already rejected,
  8483. // the popup closed by user poll will reject into the void.
  8484. this.resolver._originValidation(this.auth).catch(e => {
  8485. this.reject(e);
  8486. });
  8487. this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {
  8488. if (!isSupported) {
  8489. this.reject(_createError(this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  8490. }
  8491. });
  8492. // Handle user closure. Notice this does *not* use await
  8493. this.pollUserCancellation();
  8494. }
  8495. get eventId() {
  8496. var _a;
  8497. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  8498. }
  8499. cancel() {
  8500. this.reject(_createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  8501. }
  8502. cleanUp() {
  8503. if (this.authWindow) {
  8504. this.authWindow.close();
  8505. }
  8506. if (this.pollId) {
  8507. window.clearTimeout(this.pollId);
  8508. }
  8509. this.authWindow = null;
  8510. this.pollId = null;
  8511. PopupOperation.currentPopupAction = null;
  8512. }
  8513. pollUserCancellation() {
  8514. const poll = () => {
  8515. var _a, _b;
  8516. if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  8517. // Make sure that there is sufficient time for whatever action to
  8518. // complete. The window could have closed but the sign in network
  8519. // call could still be in flight. This is specifically true for
  8520. // Firefox or if the opener is in an iframe, in which case the oauth
  8521. // helper closes the popup.
  8522. this.pollId = window.setTimeout(() => {
  8523. this.pollId = null;
  8524. this.reject(_createError(this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  8525. }, 8000 /* _Timeout.AUTH_EVENT */);
  8526. return;
  8527. }
  8528. this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  8529. };
  8530. poll();
  8531. }
  8532. }
  8533. // Only one popup is ever shown at once. The lifecycle of the current popup
  8534. // can be managed / cancelled by the constructor.
  8535. PopupOperation.currentPopupAction = null;
  8536. /**
  8537. * @license
  8538. * Copyright 2020 Google LLC
  8539. *
  8540. * Licensed under the Apache License, Version 2.0 (the "License");
  8541. * you may not use this file except in compliance with the License.
  8542. * You may obtain a copy of the License at
  8543. *
  8544. * http://www.apache.org/licenses/LICENSE-2.0
  8545. *
  8546. * Unless required by applicable law or agreed to in writing, software
  8547. * distributed under the License is distributed on an "AS IS" BASIS,
  8548. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8549. * See the License for the specific language governing permissions and
  8550. * limitations under the License.
  8551. */
  8552. const PENDING_REDIRECT_KEY = 'pendingRedirect';
  8553. // We only get one redirect outcome for any one auth, so just store it
  8554. // in here.
  8555. const redirectOutcomeMap = new Map();
  8556. class RedirectAction extends AbstractPopupRedirectOperation {
  8557. constructor(auth, resolver, bypassAuthState = false) {
  8558. super(auth, [
  8559. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  8560. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  8561. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  8562. "unknown" /* AuthEventType.UNKNOWN */
  8563. ], resolver, undefined, bypassAuthState);
  8564. this.eventId = null;
  8565. }
  8566. /**
  8567. * Override the execute function; if we already have a redirect result, then
  8568. * just return it.
  8569. */
  8570. async execute() {
  8571. let readyOutcome = redirectOutcomeMap.get(this.auth._key());
  8572. if (!readyOutcome) {
  8573. try {
  8574. const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);
  8575. const result = hasPendingRedirect ? await super.execute() : null;
  8576. readyOutcome = () => Promise.resolve(result);
  8577. }
  8578. catch (e) {
  8579. readyOutcome = () => Promise.reject(e);
  8580. }
  8581. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  8582. }
  8583. // If we're not bypassing auth state, the ready outcome should be set to
  8584. // null.
  8585. if (!this.bypassAuthState) {
  8586. redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));
  8587. }
  8588. return readyOutcome();
  8589. }
  8590. async onAuthEvent(event) {
  8591. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  8592. return super.onAuthEvent(event);
  8593. }
  8594. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  8595. // This is a sentinel value indicating there's no pending redirect
  8596. this.resolve(null);
  8597. return;
  8598. }
  8599. if (event.eventId) {
  8600. const user = await this.auth._redirectUserForId(event.eventId);
  8601. if (user) {
  8602. this.user = user;
  8603. return super.onAuthEvent(event);
  8604. }
  8605. else {
  8606. this.resolve(null);
  8607. }
  8608. }
  8609. }
  8610. async onExecution() { }
  8611. cleanUp() { }
  8612. }
  8613. async function _getAndClearPendingRedirectStatus(resolver, auth) {
  8614. const key = pendingRedirectKey(auth);
  8615. const persistence = resolverPersistence(resolver);
  8616. if (!(await persistence._isAvailable())) {
  8617. return false;
  8618. }
  8619. const hasPendingRedirect = (await persistence._get(key)) === 'true';
  8620. await persistence._remove(key);
  8621. return hasPendingRedirect;
  8622. }
  8623. async function _setPendingRedirectStatus(resolver, auth) {
  8624. return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');
  8625. }
  8626. function _clearRedirectOutcomes() {
  8627. redirectOutcomeMap.clear();
  8628. }
  8629. function _overrideRedirectResult(auth, result) {
  8630. redirectOutcomeMap.set(auth._key(), result);
  8631. }
  8632. function resolverPersistence(resolver) {
  8633. return _getInstance(resolver._redirectPersistence);
  8634. }
  8635. function pendingRedirectKey(auth) {
  8636. return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  8637. }
  8638. /**
  8639. * @license
  8640. * Copyright 2020 Google LLC
  8641. *
  8642. * Licensed under the Apache License, Version 2.0 (the "License");
  8643. * you may not use this file except in compliance with the License.
  8644. * You may obtain a copy of the License at
  8645. *
  8646. * http://www.apache.org/licenses/LICENSE-2.0
  8647. *
  8648. * Unless required by applicable law or agreed to in writing, software
  8649. * distributed under the License is distributed on an "AS IS" BASIS,
  8650. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8651. * See the License for the specific language governing permissions and
  8652. * limitations under the License.
  8653. */
  8654. /**
  8655. * Authenticates a Firebase client using a full-page redirect flow.
  8656. *
  8657. * @remarks
  8658. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8659. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  8660. * | best practices} when using {@link signInWithRedirect}.
  8661. *
  8662. * @example
  8663. * ```javascript
  8664. * // Sign in using a redirect.
  8665. * const provider = new FacebookAuthProvider();
  8666. * // You can add additional scopes to the provider:
  8667. * provider.addScope('user_birthday');
  8668. * // Start a sign in process for an unauthenticated user.
  8669. * await signInWithRedirect(auth, provider);
  8670. * // This will trigger a full page redirect away from your app
  8671. *
  8672. * // After returning from the redirect when your app initializes you can obtain the result
  8673. * const result = await getRedirectResult(auth);
  8674. * if (result) {
  8675. * // This is the signed-in user
  8676. * const user = result.user;
  8677. * // This gives you a Facebook Access Token.
  8678. * const credential = provider.credentialFromResult(auth, result);
  8679. * const token = credential.accessToken;
  8680. * }
  8681. * // As this API can be used for sign-in, linking and reauthentication,
  8682. * // check the operationType to determine what triggered this redirect
  8683. * // operation.
  8684. * const operationType = result.operationType;
  8685. * ```
  8686. *
  8687. * @param auth - The {@link Auth} instance.
  8688. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8689. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8690. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8691. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8692. *
  8693. * @public
  8694. */
  8695. function signInWithRedirect(auth, provider, resolver) {
  8696. return _signInWithRedirect(auth, provider, resolver);
  8697. }
  8698. async function _signInWithRedirect(auth, provider, resolver) {
  8699. const authInternal = _castAuth(auth);
  8700. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  8701. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8702. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8703. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8704. await authInternal._initializationPromise;
  8705. const resolverInternal = _withDefaultResolver(authInternal, resolver);
  8706. await _setPendingRedirectStatus(resolverInternal, authInternal);
  8707. return resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);
  8708. }
  8709. /**
  8710. * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
  8711. * @remarks
  8712. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8713. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  8714. * | best practices} when using {@link reauthenticateWithRedirect}.
  8715. *
  8716. * @example
  8717. * ```javascript
  8718. * // Sign in using a redirect.
  8719. * const provider = new FacebookAuthProvider();
  8720. * const result = await signInWithRedirect(auth, provider);
  8721. * // This will trigger a full page redirect away from your app
  8722. *
  8723. * // After returning from the redirect when your app initializes you can obtain the result
  8724. * const result = await getRedirectResult(auth);
  8725. * // Reauthenticate using a redirect.
  8726. * await reauthenticateWithRedirect(result.user, provider);
  8727. * // This will again trigger a full page redirect away from your app
  8728. *
  8729. * // After returning from the redirect when your app initializes you can obtain the result
  8730. * const result = await getRedirectResult(auth);
  8731. * ```
  8732. *
  8733. * @param user - The user.
  8734. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8735. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8736. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8737. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8738. *
  8739. * @public
  8740. */
  8741. function reauthenticateWithRedirect(user, provider, resolver) {
  8742. return _reauthenticateWithRedirect(user, provider, resolver);
  8743. }
  8744. async function _reauthenticateWithRedirect(user, provider, resolver) {
  8745. const userInternal = getModularInstance(user);
  8746. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8747. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8748. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8749. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8750. await userInternal.auth._initializationPromise;
  8751. // Allow the resolver to error before persisting the redirect user
  8752. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8753. await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  8754. const eventId = await prepareUserForRedirect(userInternal);
  8755. return resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);
  8756. }
  8757. /**
  8758. * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
  8759. * @remarks
  8760. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8761. * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices
  8762. * | best practices} when using {@link linkWithRedirect}.
  8763. *
  8764. * @example
  8765. * ```javascript
  8766. * // Sign in using some other provider.
  8767. * const result = await signInWithEmailAndPassword(auth, email, password);
  8768. * // Link using a redirect.
  8769. * const provider = new FacebookAuthProvider();
  8770. * await linkWithRedirect(result.user, provider);
  8771. * // This will trigger a full page redirect away from your app
  8772. *
  8773. * // After returning from the redirect when your app initializes you can obtain the result
  8774. * const result = await getRedirectResult(auth);
  8775. * ```
  8776. *
  8777. * @param user - The user.
  8778. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8779. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8780. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8781. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8782. *
  8783. *
  8784. * @public
  8785. */
  8786. function linkWithRedirect(user, provider, resolver) {
  8787. return _linkWithRedirect(user, provider, resolver);
  8788. }
  8789. async function _linkWithRedirect(user, provider, resolver) {
  8790. const userInternal = getModularInstance(user);
  8791. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8792. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8793. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8794. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8795. await userInternal.auth._initializationPromise;
  8796. // Allow the resolver to error before persisting the redirect user
  8797. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8798. await _assertLinkedStatus(false, userInternal, provider.providerId);
  8799. await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  8800. const eventId = await prepareUserForRedirect(userInternal);
  8801. return resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);
  8802. }
  8803. /**
  8804. * Returns a {@link UserCredential} from the redirect-based sign-in flow.
  8805. *
  8806. * @remarks
  8807. * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
  8808. * error. If no redirect operation was called, returns `null`.
  8809. *
  8810. * @example
  8811. * ```javascript
  8812. * // Sign in using a redirect.
  8813. * const provider = new FacebookAuthProvider();
  8814. * // You can add additional scopes to the provider:
  8815. * provider.addScope('user_birthday');
  8816. * // Start a sign in process for an unauthenticated user.
  8817. * await signInWithRedirect(auth, provider);
  8818. * // This will trigger a full page redirect away from your app
  8819. *
  8820. * // After returning from the redirect when your app initializes you can obtain the result
  8821. * const result = await getRedirectResult(auth);
  8822. * if (result) {
  8823. * // This is the signed-in user
  8824. * const user = result.user;
  8825. * // This gives you a Facebook Access Token.
  8826. * const credential = provider.credentialFromResult(auth, result);
  8827. * const token = credential.accessToken;
  8828. * }
  8829. * // As this API can be used for sign-in, linking and reauthentication,
  8830. * // check the operationType to determine what triggered this redirect
  8831. * // operation.
  8832. * const operationType = result.operationType;
  8833. * ```
  8834. *
  8835. * @param auth - The {@link Auth} instance.
  8836. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8837. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8838. *
  8839. * @public
  8840. */
  8841. async function getRedirectResult(auth, resolver) {
  8842. await _castAuth(auth)._initializationPromise;
  8843. return _getRedirectResult(auth, resolver, false);
  8844. }
  8845. async function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {
  8846. const authInternal = _castAuth(auth);
  8847. const resolver = _withDefaultResolver(authInternal, resolverExtern);
  8848. const action = new RedirectAction(authInternal, resolver, bypassAuthState);
  8849. const result = await action.execute();
  8850. if (result && !bypassAuthState) {
  8851. delete result.user._redirectEventId;
  8852. await authInternal._persistUserIfCurrent(result.user);
  8853. await authInternal._setRedirectUser(null, resolverExtern);
  8854. }
  8855. return result;
  8856. }
  8857. async function prepareUserForRedirect(user) {
  8858. const eventId = _generateEventId(`${user.uid}:::`);
  8859. user._redirectEventId = eventId;
  8860. await user.auth._setRedirectUser(user);
  8861. await user.auth._persistUserIfCurrent(user);
  8862. return eventId;
  8863. }
  8864. /**
  8865. * @license
  8866. * Copyright 2020 Google LLC
  8867. *
  8868. * Licensed under the Apache License, Version 2.0 (the "License");
  8869. * you may not use this file except in compliance with the License.
  8870. * You may obtain a copy of the License at
  8871. *
  8872. * http://www.apache.org/licenses/LICENSE-2.0
  8873. *
  8874. * Unless required by applicable law or agreed to in writing, software
  8875. * distributed under the License is distributed on an "AS IS" BASIS,
  8876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8877. * See the License for the specific language governing permissions and
  8878. * limitations under the License.
  8879. */
  8880. // The amount of time to store the UIDs of seen events; this is
  8881. // set to 10 min by default
  8882. const EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  8883. class AuthEventManager {
  8884. constructor(auth) {
  8885. this.auth = auth;
  8886. this.cachedEventUids = new Set();
  8887. this.consumers = new Set();
  8888. this.queuedRedirectEvent = null;
  8889. this.hasHandledPotentialRedirect = false;
  8890. this.lastProcessedEventTime = Date.now();
  8891. }
  8892. registerConsumer(authEventConsumer) {
  8893. this.consumers.add(authEventConsumer);
  8894. if (this.queuedRedirectEvent &&
  8895. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  8896. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  8897. this.saveEventToCache(this.queuedRedirectEvent);
  8898. this.queuedRedirectEvent = null;
  8899. }
  8900. }
  8901. unregisterConsumer(authEventConsumer) {
  8902. this.consumers.delete(authEventConsumer);
  8903. }
  8904. onEvent(event) {
  8905. // Check if the event has already been handled
  8906. if (this.hasEventBeenHandled(event)) {
  8907. return false;
  8908. }
  8909. let handled = false;
  8910. this.consumers.forEach(consumer => {
  8911. if (this.isEventForConsumer(event, consumer)) {
  8912. handled = true;
  8913. this.sendToConsumer(event, consumer);
  8914. this.saveEventToCache(event);
  8915. }
  8916. });
  8917. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  8918. // If we've already seen a redirect before, or this is a popup event,
  8919. // bail now
  8920. return handled;
  8921. }
  8922. this.hasHandledPotentialRedirect = true;
  8923. // If the redirect wasn't handled, hang on to it
  8924. if (!handled) {
  8925. this.queuedRedirectEvent = event;
  8926. handled = true;
  8927. }
  8928. return handled;
  8929. }
  8930. sendToConsumer(event, consumer) {
  8931. var _a;
  8932. if (event.error && !isNullRedirectEvent(event)) {
  8933. const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  8934. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  8935. consumer.onError(_createError(this.auth, code));
  8936. }
  8937. else {
  8938. consumer.onAuthEvent(event);
  8939. }
  8940. }
  8941. isEventForConsumer(event, consumer) {
  8942. const eventIdMatches = consumer.eventId === null ||
  8943. (!!event.eventId && event.eventId === consumer.eventId);
  8944. return consumer.filter.includes(event.type) && eventIdMatches;
  8945. }
  8946. hasEventBeenHandled(event) {
  8947. if (Date.now() - this.lastProcessedEventTime >=
  8948. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  8949. this.cachedEventUids.clear();
  8950. }
  8951. return this.cachedEventUids.has(eventUid(event));
  8952. }
  8953. saveEventToCache(event) {
  8954. this.cachedEventUids.add(eventUid(event));
  8955. this.lastProcessedEventTime = Date.now();
  8956. }
  8957. }
  8958. function eventUid(e) {
  8959. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');
  8960. }
  8961. function isNullRedirectEvent({ type, error }) {
  8962. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  8963. (error === null || error === void 0 ? void 0 : error.code) === `auth/${"no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */}`);
  8964. }
  8965. function isRedirectEvent(event) {
  8966. switch (event.type) {
  8967. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  8968. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  8969. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  8970. return true;
  8971. case "unknown" /* AuthEventType.UNKNOWN */:
  8972. return isNullRedirectEvent(event);
  8973. default:
  8974. return false;
  8975. }
  8976. }
  8977. /**
  8978. * @license
  8979. * Copyright 2020 Google LLC
  8980. *
  8981. * Licensed under the Apache License, Version 2.0 (the "License");
  8982. * you may not use this file except in compliance with the License.
  8983. * You may obtain a copy of the License at
  8984. *
  8985. * http://www.apache.org/licenses/LICENSE-2.0
  8986. *
  8987. * Unless required by applicable law or agreed to in writing, software
  8988. * distributed under the License is distributed on an "AS IS" BASIS,
  8989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8990. * See the License for the specific language governing permissions and
  8991. * limitations under the License.
  8992. */
  8993. async function _getProjectConfig(auth, request = {}) {
  8994. return _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request);
  8995. }
  8996. /**
  8997. * @license
  8998. * Copyright 2020 Google LLC
  8999. *
  9000. * Licensed under the Apache License, Version 2.0 (the "License");
  9001. * you may not use this file except in compliance with the License.
  9002. * You may obtain a copy of the License at
  9003. *
  9004. * http://www.apache.org/licenses/LICENSE-2.0
  9005. *
  9006. * Unless required by applicable law or agreed to in writing, software
  9007. * distributed under the License is distributed on an "AS IS" BASIS,
  9008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9009. * See the License for the specific language governing permissions and
  9010. * limitations under the License.
  9011. */
  9012. const IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  9013. const HTTP_REGEX = /^https?/;
  9014. async function _validateOrigin(auth) {
  9015. // Skip origin validation if we are in an emulated environment
  9016. if (auth.config.emulator) {
  9017. return;
  9018. }
  9019. const { authorizedDomains } = await _getProjectConfig(auth);
  9020. for (const domain of authorizedDomains) {
  9021. try {
  9022. if (matchDomain(domain)) {
  9023. return;
  9024. }
  9025. }
  9026. catch (_a) {
  9027. // Do nothing if there's a URL error; just continue searching
  9028. }
  9029. }
  9030. // In the old SDK, this error also provides helpful messages.
  9031. _fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  9032. }
  9033. function matchDomain(expected) {
  9034. const currentUrl = _getCurrentUrl();
  9035. const { protocol, hostname } = new URL(currentUrl);
  9036. if (expected.startsWith('chrome-extension://')) {
  9037. const ceUrl = new URL(expected);
  9038. if (ceUrl.hostname === '' && hostname === '') {
  9039. // For some reason we're not parsing chrome URLs properly
  9040. return (protocol === 'chrome-extension:' &&
  9041. expected.replace('chrome-extension://', '') ===
  9042. currentUrl.replace('chrome-extension://', ''));
  9043. }
  9044. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  9045. }
  9046. if (!HTTP_REGEX.test(protocol)) {
  9047. return false;
  9048. }
  9049. if (IP_ADDRESS_REGEX.test(expected)) {
  9050. // The domain has to be exactly equal to the pattern, as an IP domain will
  9051. // only contain the IP, no extra character.
  9052. return hostname === expected;
  9053. }
  9054. // Dots in pattern should be escaped.
  9055. const escapedDomainPattern = expected.replace(/\./g, '\\.');
  9056. // Non ip address domains.
  9057. // domain.com = *.domain.com OR domain.com
  9058. const re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  9059. return re.test(hostname);
  9060. }
  9061. /**
  9062. * @license
  9063. * Copyright 2020 Google LLC.
  9064. *
  9065. * Licensed under the Apache License, Version 2.0 (the "License");
  9066. * you may not use this file except in compliance with the License.
  9067. * You may obtain a copy of the License at
  9068. *
  9069. * http://www.apache.org/licenses/LICENSE-2.0
  9070. *
  9071. * Unless required by applicable law or agreed to in writing, software
  9072. * distributed under the License is distributed on an "AS IS" BASIS,
  9073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9074. * See the License for the specific language governing permissions and
  9075. * limitations under the License.
  9076. */
  9077. const NETWORK_TIMEOUT = new Delay(30000, 60000);
  9078. /**
  9079. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  9080. * it will stop working after a retrial. This is a hack to fix this issue.
  9081. */
  9082. function resetUnloadedGapiModules() {
  9083. // Clear last failed gapi.load state to force next gapi.load to first
  9084. // load the failed gapi.iframes module.
  9085. // Get gapix.beacon context.
  9086. const beacon = _window().___jsl;
  9087. // Get current hint.
  9088. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  9089. // Get gapi hint.
  9090. for (const hint of Object.keys(beacon.H)) {
  9091. // Requested modules.
  9092. beacon.H[hint].r = beacon.H[hint].r || [];
  9093. // Loaded modules.
  9094. beacon.H[hint].L = beacon.H[hint].L || [];
  9095. // Set requested modules to a copy of the loaded modules.
  9096. beacon.H[hint].r = [...beacon.H[hint].L];
  9097. // Clear pending callbacks.
  9098. if (beacon.CP) {
  9099. for (let i = 0; i < beacon.CP.length; i++) {
  9100. // Remove all failed pending callbacks.
  9101. beacon.CP[i] = null;
  9102. }
  9103. }
  9104. }
  9105. }
  9106. }
  9107. function loadGapi(auth) {
  9108. return new Promise((resolve, reject) => {
  9109. var _a, _b, _c;
  9110. // Function to run when gapi.load is ready.
  9111. function loadGapiIframe() {
  9112. // The developer may have tried to previously run gapi.load and failed.
  9113. // Run this to fix that.
  9114. resetUnloadedGapiModules();
  9115. gapi.load('gapi.iframes', {
  9116. callback: () => {
  9117. resolve(gapi.iframes.getContext());
  9118. },
  9119. ontimeout: () => {
  9120. // The above reset may be sufficient, but having this reset after
  9121. // failure ensures that if the developer calls gapi.load after the
  9122. // connection is re-established and before another attempt to embed
  9123. // the iframe, it would work and would not be broken because of our
  9124. // failed attempt.
  9125. // Timeout when gapi.iframes.Iframe not loaded.
  9126. resetUnloadedGapiModules();
  9127. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  9128. },
  9129. timeout: NETWORK_TIMEOUT.get()
  9130. });
  9131. }
  9132. if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  9133. // If gapi.iframes.Iframe available, resolve.
  9134. resolve(gapi.iframes.getContext());
  9135. }
  9136. else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  9137. // Gapi loader ready, load gapi.iframes.
  9138. loadGapiIframe();
  9139. }
  9140. else {
  9141. // Create a new iframe callback when this is called so as not to overwrite
  9142. // any previous defined callback. This happens if this method is called
  9143. // multiple times in parallel and could result in the later callback
  9144. // overwriting the previous one. This would end up with a iframe
  9145. // timeout.
  9146. const cbName = _generateCallbackName('iframefcb');
  9147. // GApi loader not available, dynamically load platform.js.
  9148. _window()[cbName] = () => {
  9149. // GApi loader should be ready.
  9150. if (!!gapi.load) {
  9151. loadGapiIframe();
  9152. }
  9153. else {
  9154. // Gapi loader failed, throw error.
  9155. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  9156. }
  9157. };
  9158. // Load GApi loader.
  9159. return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)
  9160. .catch(e => reject(e));
  9161. }
  9162. }).catch(error => {
  9163. // Reset cached promise to allow for retrial.
  9164. cachedGApiLoader = null;
  9165. throw error;
  9166. });
  9167. }
  9168. let cachedGApiLoader = null;
  9169. function _loadGapi(auth) {
  9170. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  9171. return cachedGApiLoader;
  9172. }
  9173. /**
  9174. * @license
  9175. * Copyright 2020 Google LLC.
  9176. *
  9177. * Licensed under the Apache License, Version 2.0 (the "License");
  9178. * you may not use this file except in compliance with the License.
  9179. * You may obtain a copy of the License at
  9180. *
  9181. * http://www.apache.org/licenses/LICENSE-2.0
  9182. *
  9183. * Unless required by applicable law or agreed to in writing, software
  9184. * distributed under the License is distributed on an "AS IS" BASIS,
  9185. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9186. * See the License for the specific language governing permissions and
  9187. * limitations under the License.
  9188. */
  9189. const PING_TIMEOUT = new Delay(5000, 15000);
  9190. const IFRAME_PATH = '__/auth/iframe';
  9191. const EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  9192. const IFRAME_ATTRIBUTES = {
  9193. style: {
  9194. position: 'absolute',
  9195. top: '-100px',
  9196. width: '1px',
  9197. height: '1px'
  9198. },
  9199. 'aria-hidden': 'true',
  9200. tabindex: '-1'
  9201. };
  9202. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  9203. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  9204. const EID_FROM_APIHOST = new Map([
  9205. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  9206. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  9207. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  9208. ]);
  9209. function getIframeUrl(auth) {
  9210. const config = auth.config;
  9211. _assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  9212. const url = config.emulator
  9213. ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
  9214. : `https://${auth.config.authDomain}/${IFRAME_PATH}`;
  9215. const params = {
  9216. apiKey: config.apiKey,
  9217. appName: auth.name,
  9218. v: SDK_VERSION
  9219. };
  9220. const eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  9221. if (eid) {
  9222. params.eid = eid;
  9223. }
  9224. const frameworks = auth._getFrameworks();
  9225. if (frameworks.length) {
  9226. params.fw = frameworks.join(',');
  9227. }
  9228. return `${url}?${querystring(params).slice(1)}`;
  9229. }
  9230. async function _openIframe(auth) {
  9231. const context = await _loadGapi(auth);
  9232. const gapi = _window().gapi;
  9233. _assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9234. return context.open({
  9235. where: document.body,
  9236. url: getIframeUrl(auth),
  9237. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  9238. attributes: IFRAME_ATTRIBUTES,
  9239. dontclear: true
  9240. }, (iframe) => new Promise(async (resolve, reject) => {
  9241. await iframe.restyle({
  9242. // Prevent iframe from closing on mouse out.
  9243. setHideOnLeave: false
  9244. });
  9245. const networkError = _createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  9246. // Confirm iframe is correctly loaded.
  9247. // To fallback on failure, set a timeout.
  9248. const networkErrorTimer = _window().setTimeout(() => {
  9249. reject(networkError);
  9250. }, PING_TIMEOUT.get());
  9251. // Clear timer and resolve pending iframe ready promise.
  9252. function clearTimerAndResolve() {
  9253. _window().clearTimeout(networkErrorTimer);
  9254. resolve(iframe);
  9255. }
  9256. // This returns an IThenable. However the reject part does not call
  9257. // when the iframe is not loaded.
  9258. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {
  9259. reject(networkError);
  9260. });
  9261. }));
  9262. }
  9263. /**
  9264. * @license
  9265. * Copyright 2020 Google LLC.
  9266. *
  9267. * Licensed under the Apache License, Version 2.0 (the "License");
  9268. * you may not use this file except in compliance with the License.
  9269. * You may obtain a copy of the License at
  9270. *
  9271. * http://www.apache.org/licenses/LICENSE-2.0
  9272. *
  9273. * Unless required by applicable law or agreed to in writing, software
  9274. * distributed under the License is distributed on an "AS IS" BASIS,
  9275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9276. * See the License for the specific language governing permissions and
  9277. * limitations under the License.
  9278. */
  9279. const BASE_POPUP_OPTIONS = {
  9280. location: 'yes',
  9281. resizable: 'yes',
  9282. statusbar: 'yes',
  9283. toolbar: 'no'
  9284. };
  9285. const DEFAULT_WIDTH = 500;
  9286. const DEFAULT_HEIGHT = 600;
  9287. const TARGET_BLANK = '_blank';
  9288. const FIREFOX_EMPTY_URL = 'http://localhost';
  9289. class AuthPopup {
  9290. constructor(window) {
  9291. this.window = window;
  9292. this.associatedEvent = null;
  9293. }
  9294. close() {
  9295. if (this.window) {
  9296. try {
  9297. this.window.close();
  9298. }
  9299. catch (e) { }
  9300. }
  9301. }
  9302. }
  9303. function _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {
  9304. const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  9305. const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  9306. let target = '';
  9307. const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,
  9308. left });
  9309. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  9310. // specified, even though the popup is not necessarily blocked.
  9311. const ua = getUA().toLowerCase();
  9312. if (name) {
  9313. target = _isChromeIOS(ua) ? TARGET_BLANK : name;
  9314. }
  9315. if (_isFirefox(ua)) {
  9316. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  9317. url = url || FIREFOX_EMPTY_URL;
  9318. // Firefox disables by default scrolling on popup windows, which can create
  9319. // issues when the user has many Google accounts, for instance.
  9320. options.scrollbars = 'yes';
  9321. }
  9322. const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');
  9323. if (_isIOSStandalone(ua) && target !== '_self') {
  9324. openAsNewWindowIOS(url || '', target);
  9325. return new AuthPopup(null);
  9326. }
  9327. // about:blank getting sanitized causing browsers like IE/Edge to display
  9328. // brief error message before redirecting to handler.
  9329. const newWin = window.open(url || '', target, optionsString);
  9330. _assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  9331. // Flaky on IE edge, encapsulate with a try and catch.
  9332. try {
  9333. newWin.focus();
  9334. }
  9335. catch (e) { }
  9336. return new AuthPopup(newWin);
  9337. }
  9338. function openAsNewWindowIOS(url, target) {
  9339. const el = document.createElement('a');
  9340. el.href = url;
  9341. el.target = target;
  9342. const click = document.createEvent('MouseEvent');
  9343. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  9344. el.dispatchEvent(click);
  9345. }
  9346. /**
  9347. * @license
  9348. * Copyright 2021 Google LLC
  9349. *
  9350. * Licensed under the Apache License, Version 2.0 (the "License");
  9351. * you may not use this file except in compliance with the License.
  9352. * You may obtain a copy of the License at
  9353. *
  9354. * http://www.apache.org/licenses/LICENSE-2.0
  9355. *
  9356. * Unless required by applicable law or agreed to in writing, software
  9357. * distributed under the License is distributed on an "AS IS" BASIS,
  9358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9359. * See the License for the specific language governing permissions and
  9360. * limitations under the License.
  9361. */
  9362. /**
  9363. * URL for Authentication widget which will initiate the OAuth handshake
  9364. *
  9365. * @internal
  9366. */
  9367. const WIDGET_PATH = '__/auth/handler';
  9368. /**
  9369. * URL for emulated environment
  9370. *
  9371. * @internal
  9372. */
  9373. const EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  9374. /**
  9375. * Fragment name for the App Check token that gets passed to the widget
  9376. *
  9377. * @internal
  9378. */
  9379. const FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');
  9380. async function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  9381. _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  9382. _assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  9383. const params = {
  9384. apiKey: auth.config.apiKey,
  9385. appName: auth.name,
  9386. authType,
  9387. redirectUrl,
  9388. v: SDK_VERSION,
  9389. eventId
  9390. };
  9391. if (provider instanceof FederatedAuthProvider) {
  9392. provider.setDefaultLanguage(auth.languageCode);
  9393. params.providerId = provider.providerId || '';
  9394. if (!isEmpty(provider.getCustomParameters())) {
  9395. params.customParameters = JSON.stringify(provider.getCustomParameters());
  9396. }
  9397. // TODO set additionalParams from the provider as well?
  9398. for (const [key, value] of Object.entries(additionalParams || {})) {
  9399. params[key] = value;
  9400. }
  9401. }
  9402. if (provider instanceof BaseOAuthProvider) {
  9403. const scopes = provider.getScopes().filter(scope => scope !== '');
  9404. if (scopes.length > 0) {
  9405. params.scopes = scopes.join(',');
  9406. }
  9407. }
  9408. if (auth.tenantId) {
  9409. params.tid = auth.tenantId;
  9410. }
  9411. // TODO: maybe set eid as endipointId
  9412. // TODO: maybe set fw as Frameworks.join(",")
  9413. const paramsDict = params;
  9414. for (const key of Object.keys(paramsDict)) {
  9415. if (paramsDict[key] === undefined) {
  9416. delete paramsDict[key];
  9417. }
  9418. }
  9419. // Sets the App Check token to pass to the widget
  9420. const appCheckToken = await auth._getAppCheckToken();
  9421. const appCheckTokenFragment = appCheckToken
  9422. ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`
  9423. : '';
  9424. // Start at index 1 to skip the leading '&' in the query string
  9425. return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;
  9426. }
  9427. function getHandlerBase({ config }) {
  9428. if (!config.emulator) {
  9429. return `https://${config.authDomain}/${WIDGET_PATH}`;
  9430. }
  9431. return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
  9432. }
  9433. /**
  9434. * @license
  9435. * Copyright 2020 Google LLC
  9436. *
  9437. * Licensed under the Apache License, Version 2.0 (the "License");
  9438. * you may not use this file except in compliance with the License.
  9439. * You may obtain a copy of the License at
  9440. *
  9441. * http://www.apache.org/licenses/LICENSE-2.0
  9442. *
  9443. * Unless required by applicable law or agreed to in writing, software
  9444. * distributed under the License is distributed on an "AS IS" BASIS,
  9445. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9446. * See the License for the specific language governing permissions and
  9447. * limitations under the License.
  9448. */
  9449. /**
  9450. * The special web storage event
  9451. *
  9452. */
  9453. const WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  9454. class BrowserPopupRedirectResolver {
  9455. constructor() {
  9456. this.eventManagers = {};
  9457. this.iframes = {};
  9458. this.originValidationPromises = {};
  9459. this._redirectPersistence = browserSessionPersistence;
  9460. this._completeRedirectFn = _getRedirectResult;
  9461. this._overrideRedirectResult = _overrideRedirectResult;
  9462. }
  9463. // Wrapping in async even though we don't await anywhere in order
  9464. // to make sure errors are raised as promise rejections
  9465. async _openPopup(auth, provider, authType, eventId) {
  9466. var _a;
  9467. debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  9468. const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
  9469. return _open(auth, url, _generateEventId());
  9470. }
  9471. async _openRedirect(auth, provider, authType, eventId) {
  9472. await this._originValidation(auth);
  9473. const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
  9474. _setWindowLocation(url);
  9475. return new Promise(() => { });
  9476. }
  9477. _initialize(auth) {
  9478. const key = auth._key();
  9479. if (this.eventManagers[key]) {
  9480. const { manager, promise } = this.eventManagers[key];
  9481. if (manager) {
  9482. return Promise.resolve(manager);
  9483. }
  9484. else {
  9485. debugAssert(promise, 'If manager is not set, promise should be');
  9486. return promise;
  9487. }
  9488. }
  9489. const promise = this.initAndGetManager(auth);
  9490. this.eventManagers[key] = { promise };
  9491. // If the promise is rejected, the key should be removed so that the
  9492. // operation can be retried later.
  9493. promise.catch(() => {
  9494. delete this.eventManagers[key];
  9495. });
  9496. return promise;
  9497. }
  9498. async initAndGetManager(auth) {
  9499. const iframe = await _openIframe(auth);
  9500. const manager = new AuthEventManager(auth);
  9501. iframe.register('authEvent', (iframeEvent) => {
  9502. _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  9503. // TODO: Consider splitting redirect and popup events earlier on
  9504. const handled = manager.onEvent(iframeEvent.authEvent);
  9505. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  9506. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  9507. this.eventManagers[auth._key()] = { manager };
  9508. this.iframes[auth._key()] = iframe;
  9509. return manager;
  9510. }
  9511. _isIframeWebStorageSupported(auth, cb) {
  9512. const iframe = this.iframes[auth._key()];
  9513. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {
  9514. var _a;
  9515. const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  9516. if (isSupported !== undefined) {
  9517. cb(!!isSupported);
  9518. }
  9519. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9520. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  9521. }
  9522. _originValidation(auth) {
  9523. const key = auth._key();
  9524. if (!this.originValidationPromises[key]) {
  9525. this.originValidationPromises[key] = _validateOrigin(auth);
  9526. }
  9527. return this.originValidationPromises[key];
  9528. }
  9529. get _shouldInitProactively() {
  9530. // Mobile browsers and Safari need to optimistically initialize
  9531. return _isMobileBrowser() || _isSafari() || _isIOS();
  9532. }
  9533. }
  9534. /**
  9535. * An implementation of {@link PopupRedirectResolver} suitable for browser
  9536. * based applications.
  9537. *
  9538. * @public
  9539. */
  9540. const browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  9541. class MultiFactorAssertionImpl {
  9542. constructor(factorId) {
  9543. this.factorId = factorId;
  9544. }
  9545. _process(auth, session, displayName) {
  9546. switch (session.type) {
  9547. case "enroll" /* MultiFactorSessionType.ENROLL */:
  9548. return this._finalizeEnroll(auth, session.credential, displayName);
  9549. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  9550. return this._finalizeSignIn(auth, session.credential);
  9551. default:
  9552. return debugFail('unexpected MultiFactorSessionType');
  9553. }
  9554. }
  9555. }
  9556. /**
  9557. * {@inheritdoc PhoneMultiFactorAssertion}
  9558. *
  9559. * @public
  9560. */
  9561. class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {
  9562. constructor(credential) {
  9563. super("phone" /* FactorId.PHONE */);
  9564. this.credential = credential;
  9565. }
  9566. /** @internal */
  9567. static _fromCredential(credential) {
  9568. return new PhoneMultiFactorAssertionImpl(credential);
  9569. }
  9570. /** @internal */
  9571. _finalizeEnroll(auth, idToken, displayName) {
  9572. return finalizeEnrollPhoneMfa(auth, {
  9573. idToken,
  9574. displayName,
  9575. phoneVerificationInfo: this.credential._makeVerificationRequest()
  9576. });
  9577. }
  9578. /** @internal */
  9579. _finalizeSignIn(auth, mfaPendingCredential) {
  9580. return finalizeSignInPhoneMfa(auth, {
  9581. mfaPendingCredential,
  9582. phoneVerificationInfo: this.credential._makeVerificationRequest()
  9583. });
  9584. }
  9585. }
  9586. /**
  9587. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  9588. *
  9589. * @public
  9590. */
  9591. class PhoneMultiFactorGenerator {
  9592. constructor() { }
  9593. /**
  9594. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  9595. *
  9596. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  9597. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  9598. * {@link MultiFactorResolver.resolveSignIn}
  9599. */
  9600. static assertion(credential) {
  9601. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  9602. }
  9603. }
  9604. /**
  9605. * The identifier of the phone second factor: `phone`.
  9606. */
  9607. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  9608. /**
  9609. * Provider for generating a {@link TotpMultiFactorAssertion}.
  9610. *
  9611. * @public
  9612. */
  9613. class TotpMultiFactorGenerator {
  9614. /**
  9615. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of
  9616. * the TOTP (time-based one-time password) second factor.
  9617. * This assertion is used to complete enrollment in TOTP second factor.
  9618. *
  9619. * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.
  9620. * @param oneTimePassword One-time password from TOTP App.
  9621. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  9622. * {@link MultiFactorUser.enroll}.
  9623. */
  9624. static assertionForEnrollment(secret, oneTimePassword) {
  9625. return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);
  9626. }
  9627. /**
  9628. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.
  9629. * This assertion is used to complete signIn with TOTP as the second factor.
  9630. *
  9631. * @param enrollmentId identifies the enrolled TOTP second factor.
  9632. * @param oneTimePassword One-time password from TOTP App.
  9633. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  9634. * {@link MultiFactorResolver.resolveSignIn}.
  9635. */
  9636. static assertionForSignIn(enrollmentId, oneTimePassword) {
  9637. return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);
  9638. }
  9639. /**
  9640. * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.
  9641. * Creates a TOTP secret as part of enrolling a TOTP second factor.
  9642. * Used for generating a QR code URL or inputting into a TOTP app.
  9643. * This method uses the auth instance corresponding to the user in the multiFactorSession.
  9644. *
  9645. * @param session The {@link MultiFactorSession} that the user is part of.
  9646. * @returns A promise to {@link TotpSecret}.
  9647. */
  9648. static async generateSecret(session) {
  9649. const mfaSession = session;
  9650. _assert(typeof mfaSession.auth !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9651. const response = await startEnrollTotpMfa(mfaSession.auth, {
  9652. idToken: mfaSession.credential,
  9653. totpEnrollmentInfo: {}
  9654. });
  9655. return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.auth);
  9656. }
  9657. }
  9658. /**
  9659. * The identifier of the TOTP second factor: `totp`.
  9660. */
  9661. TotpMultiFactorGenerator.FACTOR_ID = "totp" /* FactorId.TOTP */;
  9662. class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {
  9663. constructor(otp, enrollmentId, secret) {
  9664. super("totp" /* FactorId.TOTP */);
  9665. this.otp = otp;
  9666. this.enrollmentId = enrollmentId;
  9667. this.secret = secret;
  9668. }
  9669. /** @internal */
  9670. static _fromSecret(secret, otp) {
  9671. return new TotpMultiFactorAssertionImpl(otp, undefined, secret);
  9672. }
  9673. /** @internal */
  9674. static _fromEnrollmentId(enrollmentId, otp) {
  9675. return new TotpMultiFactorAssertionImpl(otp, enrollmentId);
  9676. }
  9677. /** @internal */
  9678. async _finalizeEnroll(auth, idToken, displayName) {
  9679. _assert(typeof this.secret !== 'undefined', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9680. return finalizeEnrollTotpMfa(auth, {
  9681. idToken,
  9682. displayName,
  9683. totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)
  9684. });
  9685. }
  9686. /** @internal */
  9687. async _finalizeSignIn(auth, mfaPendingCredential) {
  9688. _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9689. const totpVerificationInfo = { verificationCode: this.otp };
  9690. return finalizeSignInTotpMfa(auth, {
  9691. mfaPendingCredential,
  9692. mfaEnrollmentId: this.enrollmentId,
  9693. totpVerificationInfo
  9694. });
  9695. }
  9696. }
  9697. /**
  9698. * Provider for generating a {@link TotpMultiFactorAssertion}.
  9699. *
  9700. * Stores the shared secret key and other parameters to generate time-based OTPs.
  9701. * Implements methods to retrieve the shared secret key and generate a QR code URL.
  9702. * @public
  9703. */
  9704. class TotpSecret {
  9705. // The public members are declared outside the constructor so the docs can be generated.
  9706. constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {
  9707. this.sessionInfo = sessionInfo;
  9708. this.auth = auth;
  9709. this.secretKey = secretKey;
  9710. this.hashingAlgorithm = hashingAlgorithm;
  9711. this.codeLength = codeLength;
  9712. this.codeIntervalSeconds = codeIntervalSeconds;
  9713. this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;
  9714. }
  9715. /** @internal */
  9716. static _fromStartTotpMfaEnrollmentResponse(response, auth) {
  9717. 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);
  9718. }
  9719. /** @internal */
  9720. _makeTotpVerificationInfo(otp) {
  9721. return { sessionInfo: this.sessionInfo, verificationCode: otp };
  9722. }
  9723. /**
  9724. * Returns a QR code URL as described in
  9725. * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
  9726. * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.
  9727. * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.
  9728. *
  9729. * @param accountName the name of the account/app along with a user identifier.
  9730. * @param issuer issuer of the TOTP (likely the app name).
  9731. * @returns A QR code URL string.
  9732. */
  9733. generateQrCodeUrl(accountName, issuer) {
  9734. var _a;
  9735. let useDefaults = false;
  9736. if (_isEmptyString(accountName) || _isEmptyString(issuer)) {
  9737. useDefaults = true;
  9738. }
  9739. if (useDefaults) {
  9740. if (_isEmptyString(accountName)) {
  9741. accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';
  9742. }
  9743. if (_isEmptyString(issuer)) {
  9744. issuer = this.auth.name;
  9745. }
  9746. }
  9747. return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;
  9748. }
  9749. }
  9750. /** @internal */
  9751. function _isEmptyString(input) {
  9752. return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;
  9753. }
  9754. var name = "@firebase/auth";
  9755. var version = "0.23.2";
  9756. /**
  9757. * @license
  9758. * Copyright 2020 Google LLC
  9759. *
  9760. * Licensed under the Apache License, Version 2.0 (the "License");
  9761. * you may not use this file except in compliance with the License.
  9762. * You may obtain a copy of the License at
  9763. *
  9764. * http://www.apache.org/licenses/LICENSE-2.0
  9765. *
  9766. * Unless required by applicable law or agreed to in writing, software
  9767. * distributed under the License is distributed on an "AS IS" BASIS,
  9768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9769. * See the License for the specific language governing permissions and
  9770. * limitations under the License.
  9771. */
  9772. class AuthInterop {
  9773. constructor(auth) {
  9774. this.auth = auth;
  9775. this.internalListeners = new Map();
  9776. }
  9777. getUid() {
  9778. var _a;
  9779. this.assertAuthConfigured();
  9780. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  9781. }
  9782. async getToken(forceRefresh) {
  9783. this.assertAuthConfigured();
  9784. await this.auth._initializationPromise;
  9785. if (!this.auth.currentUser) {
  9786. return null;
  9787. }
  9788. const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);
  9789. return { accessToken };
  9790. }
  9791. addAuthTokenListener(listener) {
  9792. this.assertAuthConfigured();
  9793. if (this.internalListeners.has(listener)) {
  9794. return;
  9795. }
  9796. const unsubscribe = this.auth.onIdTokenChanged(user => {
  9797. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  9798. });
  9799. this.internalListeners.set(listener, unsubscribe);
  9800. this.updateProactiveRefresh();
  9801. }
  9802. removeAuthTokenListener(listener) {
  9803. this.assertAuthConfigured();
  9804. const unsubscribe = this.internalListeners.get(listener);
  9805. if (!unsubscribe) {
  9806. return;
  9807. }
  9808. this.internalListeners.delete(listener);
  9809. unsubscribe();
  9810. this.updateProactiveRefresh();
  9811. }
  9812. assertAuthConfigured() {
  9813. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  9814. }
  9815. updateProactiveRefresh() {
  9816. if (this.internalListeners.size > 0) {
  9817. this.auth._startProactiveRefresh();
  9818. }
  9819. else {
  9820. this.auth._stopProactiveRefresh();
  9821. }
  9822. }
  9823. }
  9824. /**
  9825. * @license
  9826. * Copyright 2020 Google LLC
  9827. *
  9828. * Licensed under the Apache License, Version 2.0 (the "License");
  9829. * you may not use this file except in compliance with the License.
  9830. * You may obtain a copy of the License at
  9831. *
  9832. * http://www.apache.org/licenses/LICENSE-2.0
  9833. *
  9834. * Unless required by applicable law or agreed to in writing, software
  9835. * distributed under the License is distributed on an "AS IS" BASIS,
  9836. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9837. * See the License for the specific language governing permissions and
  9838. * limitations under the License.
  9839. */
  9840. function getVersionForPlatform(clientPlatform) {
  9841. switch (clientPlatform) {
  9842. case "Node" /* ClientPlatform.NODE */:
  9843. return 'node';
  9844. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  9845. return 'rn';
  9846. case "Worker" /* ClientPlatform.WORKER */:
  9847. return 'webworker';
  9848. case "Cordova" /* ClientPlatform.CORDOVA */:
  9849. return 'cordova';
  9850. default:
  9851. return undefined;
  9852. }
  9853. }
  9854. /** @internal */
  9855. function registerAuth(clientPlatform) {
  9856. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, (container, { options: deps }) => {
  9857. const app = container.getProvider('app').getImmediate();
  9858. const heartbeatServiceProvider = container.getProvider('heartbeat');
  9859. const appCheckServiceProvider = container.getProvider('app-check-internal');
  9860. const { apiKey, authDomain } = app.options;
  9861. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  9862. const config = {
  9863. apiKey,
  9864. authDomain,
  9865. clientPlatform,
  9866. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  9867. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  9868. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  9869. sdkClientVersion: _getClientVersion(clientPlatform)
  9870. };
  9871. const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);
  9872. _initializeAuthInstance(authInstance, deps);
  9873. return authInstance;
  9874. }, "PUBLIC" /* ComponentType.PUBLIC */)
  9875. /**
  9876. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  9877. * For why we do this, See go/firebase-next-auth-init
  9878. */
  9879. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  9880. /**
  9881. * Because all firebase products that depend on auth depend on auth-internal directly,
  9882. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  9883. */
  9884. .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {
  9885. const authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  9886. authInternalProvider.initialize();
  9887. }));
  9888. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, container => {
  9889. const auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  9890. return (auth => new AuthInterop(auth))(auth);
  9891. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  9892. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  9893. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  9894. registerVersion(name, version, 'esm2017');
  9895. }
  9896. /**
  9897. * @license
  9898. * Copyright 2021 Google LLC
  9899. *
  9900. * Licensed under the Apache License, Version 2.0 (the "License");
  9901. * you may not use this file except in compliance with the License.
  9902. * You may obtain a copy of the License at
  9903. *
  9904. * http://www.apache.org/licenses/LICENSE-2.0
  9905. *
  9906. * Unless required by applicable law or agreed to in writing, software
  9907. * distributed under the License is distributed on an "AS IS" BASIS,
  9908. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9909. * See the License for the specific language governing permissions and
  9910. * limitations under the License.
  9911. */
  9912. const DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  9913. const authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  9914. let lastPostedIdToken = null;
  9915. const mintCookieFactory = (url) => async (user) => {
  9916. const idTokenResult = user && (await user.getIdTokenResult());
  9917. const idTokenAge = idTokenResult &&
  9918. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  9919. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  9920. return;
  9921. }
  9922. // Specifically trip null => undefined when logged out, to delete any existing cookie
  9923. const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  9924. if (lastPostedIdToken === idToken) {
  9925. return;
  9926. }
  9927. lastPostedIdToken = idToken;
  9928. await fetch(url, {
  9929. method: idToken ? 'POST' : 'DELETE',
  9930. headers: idToken
  9931. ? {
  9932. 'Authorization': `Bearer ${idToken}`
  9933. }
  9934. : {}
  9935. });
  9936. };
  9937. /**
  9938. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  9939. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  9940. *
  9941. * @param app - The Firebase App.
  9942. *
  9943. * @public
  9944. */
  9945. function getAuth(app = getApp()) {
  9946. const provider = _getProvider(app, 'auth');
  9947. if (provider.isInitialized()) {
  9948. return provider.getImmediate();
  9949. }
  9950. const auth = initializeAuth(app, {
  9951. popupRedirectResolver: browserPopupRedirectResolver,
  9952. persistence: [
  9953. indexedDBLocalPersistence,
  9954. browserLocalPersistence,
  9955. browserSessionPersistence
  9956. ]
  9957. });
  9958. const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');
  9959. if (authTokenSyncUrl) {
  9960. const mintCookie = mintCookieFactory(authTokenSyncUrl);
  9961. beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));
  9962. onIdTokenChanged(auth, user => mintCookie(user));
  9963. }
  9964. const authEmulatorHost = getDefaultEmulatorHost('auth');
  9965. if (authEmulatorHost) {
  9966. connectAuthEmulator(auth, `http://${authEmulatorHost}`);
  9967. }
  9968. return auth;
  9969. }
  9970. registerAuth("Browser" /* ClientPlatform.BROWSER */);
  9971. 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, _assert as aA, AuthEventManager as aB, _getInstance as aC, _persistenceKeyName as aD, _getRedirectResult as aE, _overrideRedirectResult as aF, _clearRedirectOutcomes 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, debugAssert as as, _isIOS as at, _isAndroid as au, _fail as av, _getRedirectUrl as aw, _getProjectConfig as ax, _isIOS7Or8 as ay, _createError 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 };
  9972. //# sourceMappingURL=index-e3d5d3f4.js.map