strophe.esm.js 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238
  1. import { btoa as btoa$1, atob as atob$1 } from 'abab';
  2. var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
  3. /*
  4. * This module provides uniform
  5. * Shims APIs and globals that are not present in all JS environments,
  6. * the most common example for Strophe being browser APIs like WebSocket
  7. * and DOM that don't exist under nodejs.
  8. *
  9. * Usually these will be supplied in nodejs by conditionally requiring a
  10. * NPM module that provides a compatible implementation.
  11. */
  12. /* global global */
  13. /**
  14. * WHATWG WebSockets API
  15. * https://www.w3.org/TR/websockets/
  16. *
  17. * Interface to use the web socket protocol
  18. *
  19. * Used implementations:
  20. * - supported browsers: built-in in WebSocket global
  21. * https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Browser_compatibility
  22. * - nodejs: use standard-compliant 'ws' module
  23. * https://www.npmjs.com/package/ws
  24. */
  25. function getWebSocketImplementation() {
  26. let WebSocketImplementation = global$1.WebSocket;
  27. if (typeof WebSocketImplementation === 'undefined') {
  28. try {
  29. WebSocketImplementation = require('ws');
  30. } catch (err) {
  31. throw new Error('You must install the "ws" package to use Strophe in nodejs.');
  32. }
  33. }
  34. return WebSocketImplementation;
  35. }
  36. const WebSocket = getWebSocketImplementation();
  37. /**
  38. * DOMParser
  39. * https://w3c.github.io/DOM-Parsing/#the-domparser-interface
  40. *
  41. * Interface to parse XML strings into Document objects
  42. *
  43. * Used implementations:
  44. * - supported browsers: built-in in DOMParser global
  45. * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility
  46. * - nodejs: use '@xmldom/xmldom' module
  47. * https://www.npmjs.com/package/@xmldom/xmldom
  48. */
  49. function getDOMParserImplementation() {
  50. let DOMParserImplementation = global$1.DOMParser;
  51. if (typeof DOMParserImplementation === 'undefined') {
  52. try {
  53. DOMParserImplementation = require('@xmldom/xmldom').DOMParser;
  54. } catch (err) {
  55. throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.');
  56. }
  57. }
  58. return DOMParserImplementation;
  59. }
  60. const DOMParser = getDOMParserImplementation();
  61. /**
  62. * Gets IE xml doc object. Used by getDummyXMLDocument shim.
  63. *
  64. * Returns:
  65. * A Microsoft XML DOM Object
  66. * See Also:
  67. * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
  68. */
  69. function _getIEXmlDom() {
  70. const docStrings = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
  71. for (let d = 0; d < docStrings.length; d++) {
  72. try {
  73. // eslint-disable-next-line no-undef
  74. const doc = new ActiveXObject(docStrings[d]);
  75. return doc;
  76. } catch (e) {// Try next one
  77. }
  78. }
  79. }
  80. /**
  81. * Creates a dummy XML DOM document to serve as an element and text node generator.
  82. *
  83. * Used implementations:
  84. * - IE < 10: avoid using createDocument() due to a memory leak, use ie-specific
  85. * workaround
  86. * - other supported browsers: use document's createDocument
  87. * - nodejs: use '@xmldom/xmldom'
  88. */
  89. function getDummyXMLDOMDocument() {
  90. // nodejs
  91. if (typeof document === 'undefined') {
  92. try {
  93. const DOMImplementation = require('@xmldom/xmldom').DOMImplementation;
  94. return new DOMImplementation().createDocument('jabber:client', 'strophe', null);
  95. } catch (err) {
  96. throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.');
  97. }
  98. } // IE < 10
  99. if (document.implementation.createDocument === undefined || document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
  100. const doc = _getIEXmlDom();
  101. doc.appendChild(doc.createElement('strophe'));
  102. return doc;
  103. } // All other supported browsers
  104. return document.implementation.createDocument('jabber:client', 'strophe', null);
  105. }
  106. /*
  107. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  108. * Digest Algorithm, as defined in RFC 1321.
  109. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
  110. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  111. * Distributed under the BSD License
  112. * See http://pajhome.org.uk/crypt/md5 for more info.
  113. */
  114. /*
  115. * Everything that isn't used by Strophe has been stripped here!
  116. */
  117. /*
  118. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  119. * to work around bugs in some JS interpreters.
  120. */
  121. const safe_add$1 = function (x, y) {
  122. const lsw = (x & 0xFFFF) + (y & 0xFFFF);
  123. const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  124. return msw << 16 | lsw & 0xFFFF;
  125. };
  126. /*
  127. * Bitwise rotate a 32-bit number to the left.
  128. */
  129. const bit_rol = function (num, cnt) {
  130. return num << cnt | num >>> 32 - cnt;
  131. };
  132. /*
  133. * Convert a string to an array of little-endian words
  134. */
  135. const str2binl = function (str) {
  136. if (typeof str !== "string") {
  137. throw new Error("str2binl was passed a non-string");
  138. }
  139. const bin = [];
  140. for (let i = 0; i < str.length * 8; i += 8) {
  141. bin[i >> 5] |= (str.charCodeAt(i / 8) & 255) << i % 32;
  142. }
  143. return bin;
  144. };
  145. /*
  146. * Convert an array of little-endian words to a string
  147. */
  148. const binl2str = function (bin) {
  149. let str = "";
  150. for (let i = 0; i < bin.length * 32; i += 8) {
  151. str += String.fromCharCode(bin[i >> 5] >>> i % 32 & 255);
  152. }
  153. return str;
  154. };
  155. /*
  156. * Convert an array of little-endian words to a hex string.
  157. */
  158. const binl2hex = function (binarray) {
  159. const hex_tab = "0123456789abcdef";
  160. let str = "";
  161. for (let i = 0; i < binarray.length * 4; i++) {
  162. str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 0xF);
  163. }
  164. return str;
  165. };
  166. /*
  167. * These functions implement the four basic operations the algorithm uses.
  168. */
  169. const md5_cmn = function (q, a, b, x, s, t) {
  170. return safe_add$1(bit_rol(safe_add$1(safe_add$1(a, q), safe_add$1(x, t)), s), b);
  171. };
  172. const md5_ff = function (a, b, c, d, x, s, t) {
  173. return md5_cmn(b & c | ~b & d, a, b, x, s, t);
  174. };
  175. const md5_gg = function (a, b, c, d, x, s, t) {
  176. return md5_cmn(b & d | c & ~d, a, b, x, s, t);
  177. };
  178. const md5_hh = function (a, b, c, d, x, s, t) {
  179. return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  180. };
  181. const md5_ii = function (a, b, c, d, x, s, t) {
  182. return md5_cmn(c ^ (b | ~d), a, b, x, s, t);
  183. };
  184. /*
  185. * Calculate the MD5 of an array of little-endian words, and a bit length
  186. */
  187. const core_md5 = function (x, len) {
  188. /* append padding */
  189. x[len >> 5] |= 0x80 << len % 32;
  190. x[(len + 64 >>> 9 << 4) + 14] = len;
  191. let a = 1732584193;
  192. let b = -271733879;
  193. let c = -1732584194;
  194. let d = 271733878;
  195. let olda, oldb, oldc, oldd;
  196. for (let i = 0; i < x.length; i += 16) {
  197. olda = a;
  198. oldb = b;
  199. oldc = c;
  200. oldd = d;
  201. a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
  202. d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
  203. c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
  204. b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
  205. a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
  206. d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
  207. c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
  208. b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
  209. a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
  210. d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
  211. c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
  212. b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
  213. a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
  214. d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
  215. c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
  216. b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
  217. a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
  218. d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
  219. c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
  220. b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
  221. a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
  222. d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
  223. c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
  224. b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
  225. a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
  226. d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
  227. c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
  228. b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
  229. a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
  230. d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
  231. c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
  232. b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
  233. a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
  234. d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
  235. c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
  236. b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
  237. a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
  238. d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
  239. c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
  240. b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
  241. a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
  242. d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
  243. c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
  244. b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
  245. a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
  246. d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
  247. c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
  248. b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
  249. a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
  250. d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
  251. c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
  252. b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
  253. a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
  254. d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
  255. c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
  256. b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
  257. a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
  258. d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
  259. c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
  260. b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
  261. a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
  262. d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
  263. c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
  264. b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
  265. a = safe_add$1(a, olda);
  266. b = safe_add$1(b, oldb);
  267. c = safe_add$1(c, oldc);
  268. d = safe_add$1(d, oldd);
  269. }
  270. return [a, b, c, d];
  271. };
  272. /*
  273. * These are the functions you'll usually want to call.
  274. * They take string arguments and return either hex or base-64 encoded
  275. * strings.
  276. */
  277. const MD5 = {
  278. hexdigest: function (s) {
  279. return binl2hex(core_md5(str2binl(s), s.length * 8));
  280. },
  281. hash: function (s) {
  282. return binl2str(core_md5(str2binl(s), s.length * 8));
  283. }
  284. };
  285. /** Class: Strophe.SASLMechanism
  286. *
  287. * Encapsulates an SASL authentication mechanism.
  288. *
  289. * User code may override the priority for each mechanism or disable it completely.
  290. * See <priority> for information about changing priority and <test> for informatian on
  291. * how to disable a mechanism.
  292. *
  293. * By default, all mechanisms are enabled and the priorities are
  294. *
  295. * SCRAM-SHA-1 - 60
  296. * PLAIN - 50
  297. * OAUTHBEARER - 40
  298. * X-OAUTH2 - 30
  299. * ANONYMOUS - 20
  300. * EXTERNAL - 10
  301. *
  302. * See: Strophe.Connection.addSupportedSASLMechanisms
  303. */
  304. class SASLMechanism {
  305. /**
  306. * PrivateConstructor: Strophe.SASLMechanism
  307. * SASL auth mechanism abstraction.
  308. *
  309. * Parameters:
  310. * (String) name - SASL Mechanism name.
  311. * (Boolean) isClientFirst - If client should send response first without challenge.
  312. * (Number) priority - Priority.
  313. *
  314. * Returns:
  315. * A new Strophe.SASLMechanism object.
  316. */
  317. constructor(name, isClientFirst, priority) {
  318. /** PrivateVariable: mechname
  319. * Mechanism name.
  320. */
  321. this.mechname = name;
  322. /** PrivateVariable: isClientFirst
  323. * If client sends response without initial server challenge.
  324. */
  325. this.isClientFirst = isClientFirst;
  326. /** Variable: priority
  327. * Determines which <SASLMechanism> is chosen for authentication (Higher is better).
  328. * Users may override this to prioritize mechanisms differently.
  329. *
  330. * Example: (This will cause Strophe to choose the mechanism that the server sent first)
  331. *
  332. * > Strophe.SASLPlain.priority = Strophe.SASLSHA1.priority;
  333. *
  334. * See <SASL mechanisms> for a list of available mechanisms.
  335. *
  336. */
  337. this.priority = priority;
  338. }
  339. /**
  340. * Function: test
  341. * Checks if mechanism able to run.
  342. * To disable a mechanism, make this return false;
  343. *
  344. * To disable plain authentication run
  345. * > Strophe.SASLPlain.test = function() {
  346. * > return false;
  347. * > }
  348. *
  349. * See <SASL mechanisms> for a list of available mechanisms.
  350. *
  351. * Parameters:
  352. * (Strophe.Connection) connection - Target Connection.
  353. *
  354. * Returns:
  355. * (Boolean) If mechanism was able to run.
  356. */
  357. test() {
  358. // eslint-disable-line class-methods-use-this
  359. return true;
  360. }
  361. /** PrivateFunction: onStart
  362. * Called before starting mechanism on some connection.
  363. *
  364. * Parameters:
  365. * (Strophe.Connection) connection - Target Connection.
  366. */
  367. onStart(connection) {
  368. this._connection = connection;
  369. }
  370. /** PrivateFunction: onChallenge
  371. * Called by protocol implementation on incoming challenge.
  372. *
  373. * By deafult, if the client is expected to send data first (isClientFirst === true),
  374. * this method is called with `challenge` as null on the first call,
  375. * unless `clientChallenge` is overridden in the relevant subclass.
  376. *
  377. * Parameters:
  378. * (Strophe.Connection) connection - Target Connection.
  379. * (String) challenge - current challenge to handle.
  380. *
  381. * Returns:
  382. * (String) Mechanism response.
  383. */
  384. onChallenge(connection, challenge) {
  385. // eslint-disable-line
  386. throw new Error("You should implement challenge handling!");
  387. }
  388. /** PrivateFunction: clientChallenge
  389. * Called by the protocol implementation if the client is expected to send
  390. * data first in the authentication exchange (i.e. isClientFirst === true).
  391. *
  392. * Parameters:
  393. * (Strophe.Connection) connection - Target Connection.
  394. *
  395. * Returns:
  396. * (String) Mechanism response.
  397. */
  398. clientChallenge(connection) {
  399. if (!this.isClientFirst) {
  400. throw new Error("clientChallenge should not be called if isClientFirst is false!");
  401. }
  402. return this.onChallenge(connection);
  403. }
  404. /** PrivateFunction: onFailure
  405. * Protocol informs mechanism implementation about SASL failure.
  406. */
  407. onFailure() {
  408. this._connection = null;
  409. }
  410. /** PrivateFunction: onSuccess
  411. * Protocol informs mechanism implementation about SASL success.
  412. */
  413. onSuccess() {
  414. this._connection = null;
  415. }
  416. }
  417. class SASLAnonymous extends SASLMechanism {
  418. /** PrivateConstructor: SASLAnonymous
  419. * SASL ANONYMOUS authentication.
  420. */
  421. constructor() {
  422. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'ANONYMOUS';
  423. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  424. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
  425. super(mechname, isClientFirst, priority);
  426. }
  427. test(connection) {
  428. // eslint-disable-line class-methods-use-this
  429. return connection.authcid === null;
  430. }
  431. }
  432. class SASLExternal extends SASLMechanism {
  433. /** PrivateConstructor: SASLExternal
  434. * SASL EXTERNAL authentication.
  435. *
  436. * The EXTERNAL mechanism allows a client to request the server to use
  437. * credentials established by means external to the mechanism to
  438. * authenticate the client. The external means may be, for instance,
  439. * TLS services.
  440. */
  441. constructor() {
  442. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EXTERNAL';
  443. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  444. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
  445. super(mechname, isClientFirst, priority);
  446. }
  447. onChallenge(connection) {
  448. // eslint-disable-line class-methods-use-this
  449. /** According to XEP-178, an authzid SHOULD NOT be presented when the
  450. * authcid contained or implied in the client certificate is the JID (i.e.
  451. * authzid) with which the user wants to log in as.
  452. *
  453. * To NOT send the authzid, the user should therefore set the authcid equal
  454. * to the JID when instantiating a new Strophe.Connection object.
  455. */
  456. return connection.authcid === connection.authzid ? '' : connection.authzid;
  457. }
  458. }
  459. const utils = {
  460. utf16to8: function (str) {
  461. var i, c;
  462. var out = "";
  463. var len = str.length;
  464. for (i = 0; i < len; i++) {
  465. c = str.charCodeAt(i);
  466. if (c >= 0x0000 && c <= 0x007F) {
  467. out += str.charAt(i);
  468. } else if (c > 0x07FF) {
  469. out += String.fromCharCode(0xE0 | c >> 12 & 0x0F);
  470. out += String.fromCharCode(0x80 | c >> 6 & 0x3F);
  471. out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
  472. } else {
  473. out += String.fromCharCode(0xC0 | c >> 6 & 0x1F);
  474. out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
  475. }
  476. }
  477. return out;
  478. },
  479. addCookies: function (cookies) {
  480. /* Parameters:
  481. * (Object) cookies - either a map of cookie names
  482. * to string values or to maps of cookie values.
  483. *
  484. * For example:
  485. * { "myCookie": "1234" }
  486. *
  487. * or:
  488. * { "myCookie": {
  489. * "value": "1234",
  490. * "domain": ".example.org",
  491. * "path": "/",
  492. * "expires": expirationDate
  493. * }
  494. * }
  495. *
  496. * These values get passed to Strophe.Connection via
  497. * options.cookies
  498. */
  499. cookies = cookies || {};
  500. for (const cookieName in cookies) {
  501. if (Object.prototype.hasOwnProperty.call(cookies, cookieName)) {
  502. let expires = '';
  503. let domain = '';
  504. let path = '';
  505. const cookieObj = cookies[cookieName];
  506. const isObj = typeof cookieObj === "object";
  507. const cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj));
  508. if (isObj) {
  509. expires = cookieObj.expires ? ";expires=" + cookieObj.expires : '';
  510. domain = cookieObj.domain ? ";domain=" + cookieObj.domain : '';
  511. path = cookieObj.path ? ";path=" + cookieObj.path : '';
  512. }
  513. document.cookie = cookieName + '=' + cookieValue + expires + domain + path;
  514. }
  515. }
  516. }
  517. };
  518. class SASLOAuthBearer extends SASLMechanism {
  519. /** PrivateConstructor: SASLOAuthBearer
  520. * SASL OAuth Bearer authentication.
  521. */
  522. constructor() {
  523. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'OAUTHBEARER';
  524. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  525. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
  526. super(mechname, isClientFirst, priority);
  527. }
  528. test(connection) {
  529. // eslint-disable-line class-methods-use-this
  530. return connection.pass !== null;
  531. }
  532. onChallenge(connection) {
  533. // eslint-disable-line class-methods-use-this
  534. let auth_str = 'n,';
  535. if (connection.authcid !== null) {
  536. auth_str = auth_str + 'a=' + connection.authzid;
  537. }
  538. auth_str = auth_str + ',';
  539. auth_str = auth_str + "\u0001";
  540. auth_str = auth_str + 'auth=Bearer ';
  541. auth_str = auth_str + connection.pass;
  542. auth_str = auth_str + "\u0001";
  543. auth_str = auth_str + "\u0001";
  544. return utils.utf16to8(auth_str);
  545. }
  546. }
  547. class SASLPlain extends SASLMechanism {
  548. /** PrivateConstructor: SASLPlain
  549. * SASL PLAIN authentication.
  550. */
  551. constructor() {
  552. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'PLAIN';
  553. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  554. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
  555. super(mechname, isClientFirst, priority);
  556. }
  557. test(connection) {
  558. // eslint-disable-line class-methods-use-this
  559. return connection.authcid !== null;
  560. }
  561. onChallenge(connection) {
  562. // eslint-disable-line class-methods-use-this
  563. const {
  564. authcid,
  565. authzid,
  566. domain,
  567. pass
  568. } = connection;
  569. if (!domain) {
  570. throw new Error("SASLPlain onChallenge: domain is not defined!");
  571. } // Only include authzid if it differs from authcid.
  572. // See: https://tools.ietf.org/html/rfc6120#section-6.3.8
  573. let auth_str = authzid !== `${authcid}@${domain}` ? authzid : '';
  574. auth_str = auth_str + "\u0000";
  575. auth_str = auth_str + authcid;
  576. auth_str = auth_str + "\u0000";
  577. auth_str = auth_str + pass;
  578. return utils.utf16to8(auth_str);
  579. }
  580. }
  581. /*
  582. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  583. * in FIPS PUB 180-1
  584. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  585. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  586. * Distributed under the BSD License
  587. * See http://pajhome.org.uk/crypt/md5 for details.
  588. */
  589. /* global define */
  590. /* Some functions and variables have been stripped for use with Strophe */
  591. /*
  592. * Calculate the SHA-1 of an array of big-endian words, and a bit length
  593. */
  594. function core_sha1(x, len) {
  595. /* append padding */
  596. x[len >> 5] |= 0x80 << 24 - len % 32;
  597. x[(len + 64 >> 9 << 4) + 15] = len;
  598. var w = new Array(80);
  599. var a = 1732584193;
  600. var b = -271733879;
  601. var c = -1732584194;
  602. var d = 271733878;
  603. var e = -1009589776;
  604. var i, j, t, olda, oldb, oldc, oldd, olde;
  605. for (i = 0; i < x.length; i += 16) {
  606. olda = a;
  607. oldb = b;
  608. oldc = c;
  609. oldd = d;
  610. olde = e;
  611. for (j = 0; j < 80; j++) {
  612. if (j < 16) {
  613. w[j] = x[i + j];
  614. } else {
  615. w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  616. }
  617. t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
  618. e = d;
  619. d = c;
  620. c = rol(b, 30);
  621. b = a;
  622. a = t;
  623. }
  624. a = safe_add(a, olda);
  625. b = safe_add(b, oldb);
  626. c = safe_add(c, oldc);
  627. d = safe_add(d, oldd);
  628. e = safe_add(e, olde);
  629. }
  630. return [a, b, c, d, e];
  631. }
  632. /*
  633. * Perform the appropriate triplet combination function for the current
  634. * iteration
  635. */
  636. function sha1_ft(t, b, c, d) {
  637. if (t < 20) {
  638. return b & c | ~b & d;
  639. }
  640. if (t < 40) {
  641. return b ^ c ^ d;
  642. }
  643. if (t < 60) {
  644. return b & c | b & d | c & d;
  645. }
  646. return b ^ c ^ d;
  647. }
  648. /*
  649. * Determine the appropriate additive constant for the current iteration
  650. */
  651. function sha1_kt(t) {
  652. return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
  653. }
  654. /*
  655. * Calculate the HMAC-SHA1 of a key and some data
  656. */
  657. function core_hmac_sha1(key, data) {
  658. var bkey = str2binb(key);
  659. if (bkey.length > 16) {
  660. bkey = core_sha1(bkey, key.length * 8);
  661. }
  662. var ipad = new Array(16),
  663. opad = new Array(16);
  664. for (var i = 0; i < 16; i++) {
  665. ipad[i] = bkey[i] ^ 0x36363636;
  666. opad[i] = bkey[i] ^ 0x5C5C5C5C;
  667. }
  668. var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
  669. return core_sha1(opad.concat(hash), 512 + 160);
  670. }
  671. /*
  672. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  673. * to work around bugs in some JS interpreters.
  674. */
  675. function safe_add(x, y) {
  676. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  677. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  678. return msw << 16 | lsw & 0xFFFF;
  679. }
  680. /*
  681. * Bitwise rotate a 32-bit number to the left.
  682. */
  683. function rol(num, cnt) {
  684. return num << cnt | num >>> 32 - cnt;
  685. }
  686. /*
  687. * Convert an 8-bit or 16-bit string to an array of big-endian words
  688. * In 8-bit function, characters >255 have their hi-byte silently ignored.
  689. */
  690. function str2binb(str) {
  691. var bin = [];
  692. var mask = 255;
  693. for (var i = 0; i < str.length * 8; i += 8) {
  694. bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << 24 - i % 32;
  695. }
  696. return bin;
  697. }
  698. /*
  699. * Convert an array of big-endian words to a base-64 string
  700. */
  701. function binb2b64(binarray) {
  702. var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  703. var str = "";
  704. var triplet, j;
  705. for (var i = 0; i < binarray.length * 4; i += 3) {
  706. triplet = (binarray[i >> 2] >> 8 * (3 - i % 4) & 0xFF) << 16 | (binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4) & 0xFF) << 8 | binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4) & 0xFF;
  707. for (j = 0; j < 4; j++) {
  708. if (i * 8 + j * 6 > binarray.length * 32) {
  709. str += "=";
  710. } else {
  711. str += tab.charAt(triplet >> 6 * (3 - j) & 0x3F);
  712. }
  713. }
  714. }
  715. return str;
  716. }
  717. /*
  718. * Convert an array of big-endian words to a string
  719. */
  720. function binb2str(bin) {
  721. var str = "";
  722. var mask = 255;
  723. for (var i = 0; i < bin.length * 32; i += 8) {
  724. str += String.fromCharCode(bin[i >> 5] >>> 24 - i % 32 & mask);
  725. }
  726. return str;
  727. }
  728. /*
  729. * These are the functions you'll usually want to call
  730. * They take string arguments and return either hex or base-64 encoded strings
  731. */
  732. const SHA1 = {
  733. b64_hmac_sha1: function (key, data) {
  734. return binb2b64(core_hmac_sha1(key, data));
  735. },
  736. b64_sha1: function (s) {
  737. return binb2b64(core_sha1(str2binb(s), s.length * 8));
  738. },
  739. binb2str: binb2str,
  740. core_hmac_sha1: core_hmac_sha1,
  741. str_hmac_sha1: function (key, data) {
  742. return binb2str(core_hmac_sha1(key, data));
  743. },
  744. str_sha1: function (s) {
  745. return binb2str(core_sha1(str2binb(s), s.length * 8));
  746. }
  747. };
  748. class SASLSHA1 extends SASLMechanism {
  749. /** PrivateConstructor: SASLSHA1
  750. * SASL SCRAM SHA 1 authentication.
  751. */
  752. constructor() {
  753. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'SCRAM-SHA-1';
  754. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  755. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;
  756. super(mechname, isClientFirst, priority);
  757. }
  758. test(connection) {
  759. // eslint-disable-line class-methods-use-this
  760. return connection.authcid !== null;
  761. }
  762. onChallenge(connection, challenge) {
  763. // eslint-disable-line class-methods-use-this
  764. let nonce, salt, iter, Hi, U, U_old, i, k;
  765. let responseText = "c=biws,";
  766. let authMessage = `${connection._sasl_data["client-first-message-bare"]},${challenge},`;
  767. const cnonce = connection._sasl_data.cnonce;
  768. const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  769. while (challenge.match(attribMatch)) {
  770. const matches = challenge.match(attribMatch);
  771. challenge = challenge.replace(matches[0], "");
  772. switch (matches[1]) {
  773. case "r":
  774. nonce = matches[2];
  775. break;
  776. case "s":
  777. salt = matches[2];
  778. break;
  779. case "i":
  780. iter = matches[2];
  781. break;
  782. }
  783. }
  784. if (nonce.slice(0, cnonce.length) !== cnonce) {
  785. connection._sasl_data = {};
  786. return connection._sasl_failure_cb();
  787. }
  788. responseText += "r=" + nonce;
  789. authMessage += responseText;
  790. salt = atob(salt);
  791. salt += "\x00\x00\x00\x01";
  792. const pass = utils.utf16to8(connection.pass);
  793. Hi = U_old = SHA1.core_hmac_sha1(pass, salt);
  794. for (i = 1; i < iter; i++) {
  795. U = SHA1.core_hmac_sha1(pass, SHA1.binb2str(U_old));
  796. for (k = 0; k < 5; k++) {
  797. Hi[k] ^= U[k];
  798. }
  799. U_old = U;
  800. }
  801. Hi = SHA1.binb2str(Hi);
  802. const clientKey = SHA1.core_hmac_sha1(Hi, "Client Key");
  803. const serverKey = SHA1.str_hmac_sha1(Hi, "Server Key");
  804. const clientSignature = SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)), authMessage);
  805. connection._sasl_data["server-signature"] = SHA1.b64_hmac_sha1(serverKey, authMessage);
  806. for (k = 0; k < 5; k++) {
  807. clientKey[k] ^= clientSignature[k];
  808. }
  809. responseText += ",p=" + btoa(SHA1.binb2str(clientKey));
  810. return responseText;
  811. }
  812. clientChallenge(connection, test_cnonce) {
  813. // eslint-disable-line class-methods-use-this
  814. const cnonce = test_cnonce || MD5.hexdigest("" + Math.random() * 1234567890);
  815. let auth_str = "n=" + utils.utf16to8(connection.authcid);
  816. auth_str += ",r=";
  817. auth_str += cnonce;
  818. connection._sasl_data.cnonce = cnonce;
  819. connection._sasl_data["client-first-message-bare"] = auth_str;
  820. auth_str = "n,," + auth_str;
  821. return auth_str;
  822. }
  823. }
  824. class SASLXOAuth2 extends SASLMechanism {
  825. /** PrivateConstructor: SASLXOAuth2
  826. * SASL X-OAuth2 authentication.
  827. */
  828. constructor() {
  829. let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'X-OAUTH2';
  830. let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  831. let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 30;
  832. super(mechname, isClientFirst, priority);
  833. }
  834. test(connection) {
  835. // eslint-disable-line class-methods-use-this
  836. return connection.pass !== null;
  837. }
  838. onChallenge(connection) {
  839. // eslint-disable-line class-methods-use-this
  840. let auth_str = '\u0000';
  841. if (connection.authcid !== null) {
  842. auth_str = auth_str + connection.authzid;
  843. }
  844. auth_str = auth_str + "\u0000";
  845. auth_str = auth_str + connection.pass;
  846. return utils.utf16to8(auth_str);
  847. }
  848. }
  849. /*
  850. This program is distributed under the terms of the MIT license.
  851. Please see the LICENSE file for details.
  852. Copyright 2006-2018, OGG, LLC
  853. */
  854. /** Function: $build
  855. * Create a Strophe.Builder.
  856. * This is an alias for 'new Strophe.Builder(name, attrs)'.
  857. *
  858. * Parameters:
  859. * (String) name - The root element name.
  860. * (Object) attrs - The attributes for the root element in object notation.
  861. *
  862. * Returns:
  863. * A new Strophe.Builder object.
  864. */
  865. function $build(name, attrs) {
  866. return new Strophe.Builder(name, attrs);
  867. }
  868. /** Function: $msg
  869. * Create a Strophe.Builder with a <message/> element as the root.
  870. *
  871. * Parameters:
  872. * (Object) attrs - The <message/> element attributes in object notation.
  873. *
  874. * Returns:
  875. * A new Strophe.Builder object.
  876. */
  877. function $msg(attrs) {
  878. return new Strophe.Builder("message", attrs);
  879. }
  880. /** Function: $iq
  881. * Create a Strophe.Builder with an <iq/> element as the root.
  882. *
  883. * Parameters:
  884. * (Object) attrs - The <iq/> element attributes in object notation.
  885. *
  886. * Returns:
  887. * A new Strophe.Builder object.
  888. */
  889. function $iq(attrs) {
  890. return new Strophe.Builder("iq", attrs);
  891. }
  892. /** Function: $pres
  893. * Create a Strophe.Builder with a <presence/> element as the root.
  894. *
  895. * Parameters:
  896. * (Object) attrs - The <presence/> element attributes in object notation.
  897. *
  898. * Returns:
  899. * A new Strophe.Builder object.
  900. */
  901. function $pres(attrs) {
  902. return new Strophe.Builder("presence", attrs);
  903. }
  904. /** Class: Strophe
  905. * An object container for all Strophe library functions.
  906. *
  907. * This class is just a container for all the objects and constants
  908. * used in the library. It is not meant to be instantiated, but to
  909. * provide a namespace for library objects, constants, and functions.
  910. */
  911. const Strophe = {
  912. /** Constant: VERSION */
  913. VERSION: "1.5.0",
  914. /** Constants: XMPP Namespace Constants
  915. * Common namespace constants from the XMPP RFCs and XEPs.
  916. *
  917. * NS.HTTPBIND - HTTP BIND namespace from XEP 124.
  918. * NS.BOSH - BOSH namespace from XEP 206.
  919. * NS.CLIENT - Main XMPP client namespace.
  920. * NS.AUTH - Legacy authentication namespace.
  921. * NS.ROSTER - Roster operations namespace.
  922. * NS.PROFILE - Profile namespace.
  923. * NS.DISCO_INFO - Service discovery info namespace from XEP 30.
  924. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
  925. * NS.MUC - Multi-User Chat namespace from XEP 45.
  926. * NS.SASL - XMPP SASL namespace from RFC 3920.
  927. * NS.STREAM - XMPP Streams namespace from RFC 3920.
  928. * NS.BIND - XMPP Binding namespace from RFC 3920 and RFC 6120.
  929. * NS.SESSION - XMPP Session namespace from RFC 3920.
  930. * NS.XHTML_IM - XHTML-IM namespace from XEP 71.
  931. * NS.XHTML - XHTML body namespace from XEP 71.
  932. */
  933. NS: {
  934. HTTPBIND: "http://jabber.org/protocol/httpbind",
  935. BOSH: "urn:xmpp:xbosh",
  936. CLIENT: "jabber:client",
  937. AUTH: "jabber:iq:auth",
  938. ROSTER: "jabber:iq:roster",
  939. PROFILE: "jabber:iq:profile",
  940. DISCO_INFO: "http://jabber.org/protocol/disco#info",
  941. DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
  942. MUC: "http://jabber.org/protocol/muc",
  943. SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
  944. STREAM: "http://etherx.jabber.org/streams",
  945. FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
  946. BIND: "urn:ietf:params:xml:ns:xmpp-bind",
  947. SESSION: "urn:ietf:params:xml:ns:xmpp-session",
  948. VERSION: "jabber:iq:version",
  949. STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
  950. XHTML_IM: "http://jabber.org/protocol/xhtml-im",
  951. XHTML: "http://www.w3.org/1999/xhtml"
  952. },
  953. /** Constants: XHTML_IM Namespace
  954. * contains allowed tags, tag attributes, and css properties.
  955. * Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
  956. * See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
  957. * allowed tags and their attributes.
  958. */
  959. XHTML: {
  960. tags: ['a', 'blockquote', 'br', 'cite', 'em', 'img', 'li', 'ol', 'p', 'span', 'strong', 'ul', 'body'],
  961. attributes: {
  962. 'a': ['href'],
  963. 'blockquote': ['style'],
  964. 'br': [],
  965. 'cite': ['style'],
  966. 'em': [],
  967. 'img': ['src', 'alt', 'style', 'height', 'width'],
  968. 'li': ['style'],
  969. 'ol': ['style'],
  970. 'p': ['style'],
  971. 'span': ['style'],
  972. 'strong': [],
  973. 'ul': ['style'],
  974. 'body': []
  975. },
  976. css: ['background-color', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'margin-left', 'margin-right', 'text-align', 'text-decoration'],
  977. /** Function: XHTML.validTag
  978. *
  979. * Utility method to determine whether a tag is allowed
  980. * in the XHTML_IM namespace.
  981. *
  982. * XHTML tag names are case sensitive and must be lower case.
  983. */
  984. validTag(tag) {
  985. for (let i = 0; i < Strophe.XHTML.tags.length; i++) {
  986. if (tag === Strophe.XHTML.tags[i]) {
  987. return true;
  988. }
  989. }
  990. return false;
  991. },
  992. /** Function: XHTML.validAttribute
  993. *
  994. * Utility method to determine whether an attribute is allowed
  995. * as recommended per XEP-0071
  996. *
  997. * XHTML attribute names are case sensitive and must be lower case.
  998. */
  999. validAttribute(tag, attribute) {
  1000. if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
  1001. for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
  1002. if (attribute === Strophe.XHTML.attributes[tag][i]) {
  1003. return true;
  1004. }
  1005. }
  1006. }
  1007. return false;
  1008. },
  1009. validCSS(style) {
  1010. for (let i = 0; i < Strophe.XHTML.css.length; i++) {
  1011. if (style === Strophe.XHTML.css[i]) {
  1012. return true;
  1013. }
  1014. }
  1015. return false;
  1016. }
  1017. },
  1018. /** Constants: Connection Status Constants
  1019. * Connection status constants for use by the connection handler
  1020. * callback.
  1021. *
  1022. * Status.ERROR - An error has occurred
  1023. * Status.CONNECTING - The connection is currently being made
  1024. * Status.CONNFAIL - The connection attempt failed
  1025. * Status.AUTHENTICATING - The connection is authenticating
  1026. * Status.AUTHFAIL - The authentication attempt failed
  1027. * Status.CONNECTED - The connection has succeeded
  1028. * Status.DISCONNECTED - The connection has been terminated
  1029. * Status.DISCONNECTING - The connection is currently being terminated
  1030. * Status.ATTACHED - The connection has been attached
  1031. * Status.REDIRECT - The connection has been redirected
  1032. * Status.CONNTIMEOUT - The connection has timed out
  1033. */
  1034. Status: {
  1035. ERROR: 0,
  1036. CONNECTING: 1,
  1037. CONNFAIL: 2,
  1038. AUTHENTICATING: 3,
  1039. AUTHFAIL: 4,
  1040. CONNECTED: 5,
  1041. DISCONNECTED: 6,
  1042. DISCONNECTING: 7,
  1043. ATTACHED: 8,
  1044. REDIRECT: 9,
  1045. CONNTIMEOUT: 10,
  1046. BINDREQUIRED: 11,
  1047. ATTACHFAIL: 12
  1048. },
  1049. ErrorCondition: {
  1050. BAD_FORMAT: "bad-format",
  1051. CONFLICT: "conflict",
  1052. MISSING_JID_NODE: "x-strophe-bad-non-anon-jid",
  1053. NO_AUTH_MECH: "no-auth-mech",
  1054. UNKNOWN_REASON: "unknown"
  1055. },
  1056. /** Constants: Log Level Constants
  1057. * Logging level indicators.
  1058. *
  1059. * LogLevel.DEBUG - Debug output
  1060. * LogLevel.INFO - Informational output
  1061. * LogLevel.WARN - Warnings
  1062. * LogLevel.ERROR - Errors
  1063. * LogLevel.FATAL - Fatal errors
  1064. */
  1065. LogLevel: {
  1066. DEBUG: 0,
  1067. INFO: 1,
  1068. WARN: 2,
  1069. ERROR: 3,
  1070. FATAL: 4
  1071. },
  1072. /** PrivateConstants: DOM Element Type Constants
  1073. * DOM element types.
  1074. *
  1075. * ElementType.NORMAL - Normal element.
  1076. * ElementType.TEXT - Text data element.
  1077. * ElementType.FRAGMENT - XHTML fragment element.
  1078. */
  1079. ElementType: {
  1080. NORMAL: 1,
  1081. TEXT: 3,
  1082. CDATA: 4,
  1083. FRAGMENT: 11
  1084. },
  1085. /** PrivateConstants: Timeout Values
  1086. * Timeout values for error states. These values are in seconds.
  1087. * These should not be changed unless you know exactly what you are
  1088. * doing.
  1089. *
  1090. * TIMEOUT - Timeout multiplier. A waiting request will be considered
  1091. * failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
  1092. * This defaults to 1.1, and with default wait, 66 seconds.
  1093. * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
  1094. * Strophe can detect early failure, it will consider the request
  1095. * failed if it doesn't return after
  1096. * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
  1097. * This defaults to 0.1, and with default wait, 6 seconds.
  1098. */
  1099. TIMEOUT: 1.1,
  1100. SECONDARY_TIMEOUT: 0.1,
  1101. /** Function: addNamespace
  1102. * This function is used to extend the current namespaces in
  1103. * Strophe.NS. It takes a key and a value with the key being the
  1104. * name of the new namespace, with its actual value.
  1105. * For example:
  1106. * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
  1107. *
  1108. * Parameters:
  1109. * (String) name - The name under which the namespace will be
  1110. * referenced under Strophe.NS
  1111. * (String) value - The actual namespace.
  1112. */
  1113. addNamespace(name, value) {
  1114. Strophe.NS[name] = value;
  1115. },
  1116. /** Function: forEachChild
  1117. * Map a function over some or all child elements of a given element.
  1118. *
  1119. * This is a small convenience function for mapping a function over
  1120. * some or all of the children of an element. If elemName is null, all
  1121. * children will be passed to the function, otherwise only children
  1122. * whose tag names match elemName will be passed.
  1123. *
  1124. * Parameters:
  1125. * (XMLElement) elem - The element to operate on.
  1126. * (String) elemName - The child element tag name filter.
  1127. * (Function) func - The function to apply to each child. This
  1128. * function should take a single argument, a DOM element.
  1129. */
  1130. forEachChild(elem, elemName, func) {
  1131. for (let i = 0; i < elem.childNodes.length; i++) {
  1132. const childNode = elem.childNodes[i];
  1133. if (childNode.nodeType === Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) {
  1134. func(childNode);
  1135. }
  1136. }
  1137. },
  1138. /** Function: isTagEqual
  1139. * Compare an element's tag name with a string.
  1140. *
  1141. * This function is case sensitive.
  1142. *
  1143. * Parameters:
  1144. * (XMLElement) el - A DOM element.
  1145. * (String) name - The element name.
  1146. *
  1147. * Returns:
  1148. * true if the element's tag name matches _el_, and false
  1149. * otherwise.
  1150. */
  1151. isTagEqual(el, name) {
  1152. return el.tagName === name;
  1153. },
  1154. /** PrivateVariable: _xmlGenerator
  1155. * _Private_ variable that caches a DOM document to
  1156. * generate elements.
  1157. */
  1158. _xmlGenerator: null,
  1159. /** Function: xmlGenerator
  1160. * Get the DOM document to generate elements.
  1161. *
  1162. * Returns:
  1163. * The currently used DOM document.
  1164. */
  1165. xmlGenerator() {
  1166. if (!Strophe._xmlGenerator) {
  1167. Strophe._xmlGenerator = getDummyXMLDOMDocument();
  1168. }
  1169. return Strophe._xmlGenerator;
  1170. },
  1171. /** Function: xmlElement
  1172. * Create an XML DOM element.
  1173. *
  1174. * This function creates an XML DOM element correctly across all
  1175. * implementations. Note that these are not HTML DOM elements, which
  1176. * aren't appropriate for XMPP stanzas.
  1177. *
  1178. * Parameters:
  1179. * (String) name - The name for the element.
  1180. * (Array|Object) attrs - An optional array or object containing
  1181. * key/value pairs to use as element attributes. The object should
  1182. * be in the format {'key': 'value'} or {key: 'value'}. The array
  1183. * should have the format [['key1', 'value1'], ['key2', 'value2']].
  1184. * (String) text - The text child data for the element.
  1185. *
  1186. * Returns:
  1187. * A new XML DOM element.
  1188. */
  1189. xmlElement(name) {
  1190. if (!name) {
  1191. return null;
  1192. }
  1193. const node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or
  1194. // there are more than two optional args
  1195. for (let a = 1; a < arguments.length; a++) {
  1196. const arg = arguments[a];
  1197. if (!arg) {
  1198. continue;
  1199. }
  1200. if (typeof arg === "string" || typeof arg === "number") {
  1201. node.appendChild(Strophe.xmlTextNode(arg));
  1202. } else if (typeof arg === "object" && typeof arg.sort === "function") {
  1203. for (let i = 0; i < arg.length; i++) {
  1204. const attr = arg[i];
  1205. if (typeof attr === "object" && typeof attr.sort === "function" && attr[1] !== undefined && attr[1] !== null) {
  1206. node.setAttribute(attr[0], attr[1]);
  1207. }
  1208. }
  1209. } else if (typeof arg === "object") {
  1210. for (const k in arg) {
  1211. if (Object.prototype.hasOwnProperty.call(arg, k) && arg[k] !== undefined && arg[k] !== null) {
  1212. node.setAttribute(k, arg[k]);
  1213. }
  1214. }
  1215. }
  1216. }
  1217. return node;
  1218. },
  1219. /* Function: xmlescape
  1220. * Excapes invalid xml characters.
  1221. *
  1222. * Parameters:
  1223. * (String) text - text to escape.
  1224. *
  1225. * Returns:
  1226. * Escaped text.
  1227. */
  1228. xmlescape(text) {
  1229. text = text.replace(/\&/g, "&amp;");
  1230. text = text.replace(/</g, "&lt;");
  1231. text = text.replace(/>/g, "&gt;");
  1232. text = text.replace(/'/g, "&apos;");
  1233. text = text.replace(/"/g, "&quot;");
  1234. return text;
  1235. },
  1236. /* Function: xmlunescape
  1237. * Unexcapes invalid xml characters.
  1238. *
  1239. * Parameters:
  1240. * (String) text - text to unescape.
  1241. *
  1242. * Returns:
  1243. * Unescaped text.
  1244. */
  1245. xmlunescape(text) {
  1246. text = text.replace(/\&amp;/g, "&");
  1247. text = text.replace(/&lt;/g, "<");
  1248. text = text.replace(/&gt;/g, ">");
  1249. text = text.replace(/&apos;/g, "'");
  1250. text = text.replace(/&quot;/g, "\"");
  1251. return text;
  1252. },
  1253. /** Function: xmlTextNode
  1254. * Creates an XML DOM text node.
  1255. *
  1256. * Provides a cross implementation version of document.createTextNode.
  1257. *
  1258. * Parameters:
  1259. * (String) text - The content of the text node.
  1260. *
  1261. * Returns:
  1262. * A new XML DOM text node.
  1263. */
  1264. xmlTextNode(text) {
  1265. return Strophe.xmlGenerator().createTextNode(text);
  1266. },
  1267. /** Function: xmlHtmlNode
  1268. * Creates an XML DOM html node.
  1269. *
  1270. * Parameters:
  1271. * (String) html - The content of the html node.
  1272. *
  1273. * Returns:
  1274. * A new XML DOM text node.
  1275. */
  1276. xmlHtmlNode(html) {
  1277. let node; //ensure text is escaped
  1278. if (DOMParser) {
  1279. const parser = new DOMParser();
  1280. node = parser.parseFromString(html, "text/xml");
  1281. } else {
  1282. node = new ActiveXObject("Microsoft.XMLDOM");
  1283. node.async = "false";
  1284. node.loadXML(html);
  1285. }
  1286. return node;
  1287. },
  1288. /** Function: getText
  1289. * Get the concatenation of all text children of an element.
  1290. *
  1291. * Parameters:
  1292. * (XMLElement) elem - A DOM element.
  1293. *
  1294. * Returns:
  1295. * A String with the concatenated text of all text element children.
  1296. */
  1297. getText(elem) {
  1298. if (!elem) {
  1299. return null;
  1300. }
  1301. let str = "";
  1302. if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) {
  1303. str += elem.nodeValue;
  1304. }
  1305. for (let i = 0; i < elem.childNodes.length; i++) {
  1306. if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) {
  1307. str += elem.childNodes[i].nodeValue;
  1308. }
  1309. }
  1310. return Strophe.xmlescape(str);
  1311. },
  1312. /** Function: copyElement
  1313. * Copy an XML DOM element.
  1314. *
  1315. * This function copies a DOM element and all its descendants and returns
  1316. * the new copy.
  1317. *
  1318. * Parameters:
  1319. * (XMLElement) elem - A DOM element.
  1320. *
  1321. * Returns:
  1322. * A new, copied DOM element tree.
  1323. */
  1324. copyElement(elem) {
  1325. let el;
  1326. if (elem.nodeType === Strophe.ElementType.NORMAL) {
  1327. el = Strophe.xmlElement(elem.tagName);
  1328. for (let i = 0; i < elem.attributes.length; i++) {
  1329. el.setAttribute(elem.attributes[i].nodeName, elem.attributes[i].value);
  1330. }
  1331. for (let i = 0; i < elem.childNodes.length; i++) {
  1332. el.appendChild(Strophe.copyElement(elem.childNodes[i]));
  1333. }
  1334. } else if (elem.nodeType === Strophe.ElementType.TEXT) {
  1335. el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
  1336. }
  1337. return el;
  1338. },
  1339. /** Function: createHtml
  1340. * Copy an HTML DOM element into an XML DOM.
  1341. *
  1342. * This function copies a DOM element and all its descendants and returns
  1343. * the new copy.
  1344. *
  1345. * Parameters:
  1346. * (HTMLElement) elem - A DOM element.
  1347. *
  1348. * Returns:
  1349. * A new, copied DOM element tree.
  1350. */
  1351. createHtml(elem) {
  1352. let el;
  1353. if (elem.nodeType === Strophe.ElementType.NORMAL) {
  1354. const tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.
  1355. if (Strophe.XHTML.validTag(tag)) {
  1356. try {
  1357. el = Strophe.xmlElement(tag);
  1358. for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
  1359. const attribute = Strophe.XHTML.attributes[tag][i];
  1360. let value = elem.getAttribute(attribute);
  1361. if (typeof value === 'undefined' || value === null || value === '' || value === false || value === 0) {
  1362. continue;
  1363. }
  1364. if (attribute === 'style' && typeof value === 'object' && typeof value.cssText !== 'undefined') {
  1365. value = value.cssText; // we're dealing with IE, need to get CSS out
  1366. } // filter out invalid css styles
  1367. if (attribute === 'style') {
  1368. const css = [];
  1369. const cssAttrs = value.split(';');
  1370. for (let j = 0; j < cssAttrs.length; j++) {
  1371. const attr = cssAttrs[j].split(':');
  1372. const cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
  1373. if (Strophe.XHTML.validCSS(cssName)) {
  1374. const cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
  1375. css.push(cssName + ': ' + cssValue);
  1376. }
  1377. }
  1378. if (css.length > 0) {
  1379. value = css.join('; ');
  1380. el.setAttribute(attribute, value);
  1381. }
  1382. } else {
  1383. el.setAttribute(attribute, value);
  1384. }
  1385. }
  1386. for (let i = 0; i < elem.childNodes.length; i++) {
  1387. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1388. }
  1389. } catch (e) {
  1390. // invalid elements
  1391. el = Strophe.xmlTextNode('');
  1392. }
  1393. } else {
  1394. el = Strophe.xmlGenerator().createDocumentFragment();
  1395. for (let i = 0; i < elem.childNodes.length; i++) {
  1396. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1397. }
  1398. }
  1399. } else if (elem.nodeType === Strophe.ElementType.FRAGMENT) {
  1400. el = Strophe.xmlGenerator().createDocumentFragment();
  1401. for (let i = 0; i < elem.childNodes.length; i++) {
  1402. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1403. }
  1404. } else if (elem.nodeType === Strophe.ElementType.TEXT) {
  1405. el = Strophe.xmlTextNode(elem.nodeValue);
  1406. }
  1407. return el;
  1408. },
  1409. /** Function: escapeNode
  1410. * Escape the node part (also called local part) of a JID.
  1411. *
  1412. * Parameters:
  1413. * (String) node - A node (or local part).
  1414. *
  1415. * Returns:
  1416. * An escaped node (or local part).
  1417. */
  1418. escapeNode(node) {
  1419. if (typeof node !== "string") {
  1420. return node;
  1421. }
  1422. return node.replace(/^\s+|\s+$/g, '').replace(/\\/g, "\\5c").replace(/ /g, "\\20").replace(/\"/g, "\\22").replace(/\&/g, "\\26").replace(/\'/g, "\\27").replace(/\//g, "\\2f").replace(/:/g, "\\3a").replace(/</g, "\\3c").replace(/>/g, "\\3e").replace(/@/g, "\\40");
  1423. },
  1424. /** Function: unescapeNode
  1425. * Unescape a node part (also called local part) of a JID.
  1426. *
  1427. * Parameters:
  1428. * (String) node - A node (or local part).
  1429. *
  1430. * Returns:
  1431. * An unescaped node (or local part).
  1432. */
  1433. unescapeNode(node) {
  1434. if (typeof node !== "string") {
  1435. return node;
  1436. }
  1437. return node.replace(/\\20/g, " ").replace(/\\22/g, '"').replace(/\\26/g, "&").replace(/\\27/g, "'").replace(/\\2f/g, "/").replace(/\\3a/g, ":").replace(/\\3c/g, "<").replace(/\\3e/g, ">").replace(/\\40/g, "@").replace(/\\5c/g, "\\");
  1438. },
  1439. /** Function: getNodeFromJid
  1440. * Get the node portion of a JID String.
  1441. *
  1442. * Parameters:
  1443. * (String) jid - A JID.
  1444. *
  1445. * Returns:
  1446. * A String containing the node.
  1447. */
  1448. getNodeFromJid(jid) {
  1449. if (jid.indexOf("@") < 0) {
  1450. return null;
  1451. }
  1452. return jid.split("@")[0];
  1453. },
  1454. /** Function: getDomainFromJid
  1455. * Get the domain portion of a JID String.
  1456. *
  1457. * Parameters:
  1458. * (String) jid - A JID.
  1459. *
  1460. * Returns:
  1461. * A String containing the domain.
  1462. */
  1463. getDomainFromJid(jid) {
  1464. const bare = Strophe.getBareJidFromJid(jid);
  1465. if (bare.indexOf("@") < 0) {
  1466. return bare;
  1467. } else {
  1468. const parts = bare.split("@");
  1469. parts.splice(0, 1);
  1470. return parts.join('@');
  1471. }
  1472. },
  1473. /** Function: getResourceFromJid
  1474. * Get the resource portion of a JID String.
  1475. *
  1476. * Parameters:
  1477. * (String) jid - A JID.
  1478. *
  1479. * Returns:
  1480. * A String containing the resource.
  1481. */
  1482. getResourceFromJid(jid) {
  1483. if (!jid) {
  1484. return null;
  1485. }
  1486. const s = jid.split("/");
  1487. if (s.length < 2) {
  1488. return null;
  1489. }
  1490. s.splice(0, 1);
  1491. return s.join('/');
  1492. },
  1493. /** Function: getBareJidFromJid
  1494. * Get the bare JID from a JID String.
  1495. *
  1496. * Parameters:
  1497. * (String) jid - A JID.
  1498. *
  1499. * Returns:
  1500. * A String containing the bare JID.
  1501. */
  1502. getBareJidFromJid(jid) {
  1503. return jid ? jid.split("/")[0] : null;
  1504. },
  1505. /** PrivateFunction: _handleError
  1506. * _Private_ function that properly logs an error to the console
  1507. */
  1508. _handleError(e) {
  1509. if (typeof e.stack !== "undefined") {
  1510. Strophe.fatal(e.stack);
  1511. }
  1512. if (e.sourceURL) {
  1513. Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message);
  1514. } else if (e.fileName) {
  1515. Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message);
  1516. } else {
  1517. Strophe.fatal("error: " + e.message);
  1518. }
  1519. },
  1520. /** Function: log
  1521. * User overrideable logging function.
  1522. *
  1523. * This function is called whenever the Strophe library calls any
  1524. * of the logging functions. The default implementation of this
  1525. * function logs only fatal errors. If client code wishes to handle the logging
  1526. * messages, it should override this with
  1527. * > Strophe.log = function (level, msg) {
  1528. * > (user code here)
  1529. * > };
  1530. *
  1531. * Please note that data sent and received over the wire is logged
  1532. * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
  1533. *
  1534. * The different levels and their meanings are
  1535. *
  1536. * DEBUG - Messages useful for debugging purposes.
  1537. * INFO - Informational messages. This is mostly information like
  1538. * 'disconnect was called' or 'SASL auth succeeded'.
  1539. * WARN - Warnings about potential problems. This is mostly used
  1540. * to report transient connection errors like request timeouts.
  1541. * ERROR - Some error occurred.
  1542. * FATAL - A non-recoverable fatal error occurred.
  1543. *
  1544. * Parameters:
  1545. * (Integer) level - The log level of the log message. This will
  1546. * be one of the values in Strophe.LogLevel.
  1547. * (String) msg - The log message.
  1548. */
  1549. log(level, msg) {
  1550. if (level === this.LogLevel.FATAL) {
  1551. var _console;
  1552. (_console = console) === null || _console === void 0 ? void 0 : _console.error(msg);
  1553. }
  1554. },
  1555. /** Function: debug
  1556. * Log a message at the Strophe.LogLevel.DEBUG level.
  1557. *
  1558. * Parameters:
  1559. * (String) msg - The log message.
  1560. */
  1561. debug(msg) {
  1562. this.log(this.LogLevel.DEBUG, msg);
  1563. },
  1564. /** Function: info
  1565. * Log a message at the Strophe.LogLevel.INFO level.
  1566. *
  1567. * Parameters:
  1568. * (String) msg - The log message.
  1569. */
  1570. info(msg) {
  1571. this.log(this.LogLevel.INFO, msg);
  1572. },
  1573. /** Function: warn
  1574. * Log a message at the Strophe.LogLevel.WARN level.
  1575. *
  1576. * Parameters:
  1577. * (String) msg - The log message.
  1578. */
  1579. warn(msg) {
  1580. this.log(this.LogLevel.WARN, msg);
  1581. },
  1582. /** Function: error
  1583. * Log a message at the Strophe.LogLevel.ERROR level.
  1584. *
  1585. * Parameters:
  1586. * (String) msg - The log message.
  1587. */
  1588. error(msg) {
  1589. this.log(this.LogLevel.ERROR, msg);
  1590. },
  1591. /** Function: fatal
  1592. * Log a message at the Strophe.LogLevel.FATAL level.
  1593. *
  1594. * Parameters:
  1595. * (String) msg - The log message.
  1596. */
  1597. fatal(msg) {
  1598. this.log(this.LogLevel.FATAL, msg);
  1599. },
  1600. /** Function: serialize
  1601. * Render a DOM element and all descendants to a String.
  1602. *
  1603. * Parameters:
  1604. * (XMLElement) elem - A DOM element.
  1605. *
  1606. * Returns:
  1607. * The serialized element tree as a String.
  1608. */
  1609. serialize(elem) {
  1610. if (!elem) {
  1611. return null;
  1612. }
  1613. if (typeof elem.tree === "function") {
  1614. elem = elem.tree();
  1615. }
  1616. const names = [...Array(elem.attributes.length).keys()].map(i => elem.attributes[i].nodeName);
  1617. names.sort();
  1618. let result = names.reduce((a, n) => `${a} ${n}="${Strophe.xmlescape(elem.attributes.getNamedItem(n).value)}"`, `<${elem.nodeName}`);
  1619. if (elem.childNodes.length > 0) {
  1620. result += ">";
  1621. for (let i = 0; i < elem.childNodes.length; i++) {
  1622. const child = elem.childNodes[i];
  1623. switch (child.nodeType) {
  1624. case Strophe.ElementType.NORMAL:
  1625. // normal element, so recurse
  1626. result += Strophe.serialize(child);
  1627. break;
  1628. case Strophe.ElementType.TEXT:
  1629. // text element to escape values
  1630. result += Strophe.xmlescape(child.nodeValue);
  1631. break;
  1632. case Strophe.ElementType.CDATA:
  1633. // cdata section so don't escape values
  1634. result += "<![CDATA[" + child.nodeValue + "]]>";
  1635. }
  1636. }
  1637. result += "</" + elem.nodeName + ">";
  1638. } else {
  1639. result += "/>";
  1640. }
  1641. return result;
  1642. },
  1643. /** PrivateVariable: _requestId
  1644. * _Private_ variable that keeps track of the request ids for
  1645. * connections.
  1646. */
  1647. _requestId: 0,
  1648. /** PrivateVariable: Strophe.connectionPlugins
  1649. * _Private_ variable Used to store plugin names that need
  1650. * initialization on Strophe.Connection construction.
  1651. */
  1652. _connectionPlugins: {},
  1653. /** Function: addConnectionPlugin
  1654. * Extends the Strophe.Connection object with the given plugin.
  1655. *
  1656. * Parameters:
  1657. * (String) name - The name of the extension.
  1658. * (Object) ptype - The plugin's prototype.
  1659. */
  1660. addConnectionPlugin(name, ptype) {
  1661. Strophe._connectionPlugins[name] = ptype;
  1662. }
  1663. };
  1664. /** Class: Strophe.Builder
  1665. * XML DOM builder.
  1666. *
  1667. * This object provides an interface similar to JQuery but for building
  1668. * DOM elements easily and rapidly. All the functions except for toString()
  1669. * and tree() return the object, so calls can be chained. Here's an
  1670. * example using the $iq() builder helper.
  1671. * > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
  1672. * > .c('query', {xmlns: 'strophe:example'})
  1673. * > .c('example')
  1674. * > .toString()
  1675. *
  1676. * The above generates this XML fragment
  1677. * > <iq to='you' from='me' type='get' id='1'>
  1678. * > <query xmlns='strophe:example'>
  1679. * > <example/>
  1680. * > </query>
  1681. * > </iq>
  1682. * The corresponding DOM manipulations to get a similar fragment would be
  1683. * a lot more tedious and probably involve several helper variables.
  1684. *
  1685. * Since adding children makes new operations operate on the child, up()
  1686. * is provided to traverse up the tree. To add two children, do
  1687. * > builder.c('child1', ...).up().c('child2', ...)
  1688. * The next operation on the Builder will be relative to the second child.
  1689. */
  1690. /** Constructor: Strophe.Builder
  1691. * Create a Strophe.Builder object.
  1692. *
  1693. * The attributes should be passed in object notation. For example
  1694. * > let b = new Builder('message', {to: 'you', from: 'me'});
  1695. * or
  1696. * > let b = new Builder('messsage', {'xml:lang': 'en'});
  1697. *
  1698. * Parameters:
  1699. * (String) name - The name of the root element.
  1700. * (Object) attrs - The attributes for the root element in object notation.
  1701. *
  1702. * Returns:
  1703. * A new Strophe.Builder.
  1704. */
  1705. Strophe.Builder = class Builder {
  1706. constructor(name, attrs) {
  1707. // Set correct namespace for jabber:client elements
  1708. if (name === "presence" || name === "message" || name === "iq") {
  1709. if (attrs && !attrs.xmlns) {
  1710. attrs.xmlns = Strophe.NS.CLIENT;
  1711. } else if (!attrs) {
  1712. attrs = {
  1713. xmlns: Strophe.NS.CLIENT
  1714. };
  1715. }
  1716. } // Holds the tree being built.
  1717. this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node.
  1718. this.node = this.nodeTree;
  1719. }
  1720. /** Function: tree
  1721. * Return the DOM tree.
  1722. *
  1723. * This function returns the current DOM tree as an element object. This
  1724. * is suitable for passing to functions like Strophe.Connection.send().
  1725. *
  1726. * Returns:
  1727. * The DOM tree as a element object.
  1728. */
  1729. tree() {
  1730. return this.nodeTree;
  1731. }
  1732. /** Function: toString
  1733. * Serialize the DOM tree to a String.
  1734. *
  1735. * This function returns a string serialization of the current DOM
  1736. * tree. It is often used internally to pass data to a
  1737. * Strophe.Request object.
  1738. *
  1739. * Returns:
  1740. * The serialized DOM tree in a String.
  1741. */
  1742. toString() {
  1743. return Strophe.serialize(this.nodeTree);
  1744. }
  1745. /** Function: up
  1746. * Make the current parent element the new current element.
  1747. *
  1748. * This function is often used after c() to traverse back up the tree.
  1749. * For example, to add two children to the same element
  1750. * > builder.c('child1', {}).up().c('child2', {});
  1751. *
  1752. * Returns:
  1753. * The Stophe.Builder object.
  1754. */
  1755. up() {
  1756. this.node = this.node.parentNode;
  1757. return this;
  1758. }
  1759. /** Function: root
  1760. * Make the root element the new current element.
  1761. *
  1762. * When at a deeply nested element in the tree, this function can be used
  1763. * to jump back to the root of the tree, instead of having to repeatedly
  1764. * call up().
  1765. *
  1766. * Returns:
  1767. * The Stophe.Builder object.
  1768. */
  1769. root() {
  1770. this.node = this.nodeTree;
  1771. return this;
  1772. }
  1773. /** Function: attrs
  1774. * Add or modify attributes of the current element.
  1775. *
  1776. * The attributes should be passed in object notation. This function
  1777. * does not move the current element pointer.
  1778. *
  1779. * Parameters:
  1780. * (Object) moreattrs - The attributes to add/modify in object notation.
  1781. *
  1782. * Returns:
  1783. * The Strophe.Builder object.
  1784. */
  1785. attrs(moreattrs) {
  1786. for (const k in moreattrs) {
  1787. if (Object.prototype.hasOwnProperty.call(moreattrs, k)) {
  1788. if (moreattrs[k] === undefined) {
  1789. this.node.removeAttribute(k);
  1790. } else {
  1791. this.node.setAttribute(k, moreattrs[k]);
  1792. }
  1793. }
  1794. }
  1795. return this;
  1796. }
  1797. /** Function: c
  1798. * Add a child to the current element and make it the new current
  1799. * element.
  1800. *
  1801. * This function moves the current element pointer to the child,
  1802. * unless text is provided. If you need to add another child, it
  1803. * is necessary to use up() to go back to the parent in the tree.
  1804. *
  1805. * Parameters:
  1806. * (String) name - The name of the child.
  1807. * (Object) attrs - The attributes of the child in object notation.
  1808. * (String) text - The text to add to the child.
  1809. *
  1810. * Returns:
  1811. * The Strophe.Builder object.
  1812. */
  1813. c(name, attrs, text) {
  1814. const child = Strophe.xmlElement(name, attrs, text);
  1815. this.node.appendChild(child);
  1816. if (typeof text !== "string" && typeof text !== "number") {
  1817. this.node = child;
  1818. }
  1819. return this;
  1820. }
  1821. /** Function: cnode
  1822. * Add a child to the current element and make it the new current
  1823. * element.
  1824. *
  1825. * This function is the same as c() except that instead of using a
  1826. * name and an attributes object to create the child it uses an
  1827. * existing DOM element object.
  1828. *
  1829. * Parameters:
  1830. * (XMLElement) elem - A DOM element.
  1831. *
  1832. * Returns:
  1833. * The Strophe.Builder object.
  1834. */
  1835. cnode(elem) {
  1836. let impNode;
  1837. const xmlGen = Strophe.xmlGenerator();
  1838. try {
  1839. impNode = xmlGen.importNode !== undefined;
  1840. } catch (e) {
  1841. impNode = false;
  1842. }
  1843. const newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem);
  1844. this.node.appendChild(newElem);
  1845. this.node = newElem;
  1846. return this;
  1847. }
  1848. /** Function: t
  1849. * Add a child text element.
  1850. *
  1851. * This *does not* make the child the new current element since there
  1852. * are no children of text elements.
  1853. *
  1854. * Parameters:
  1855. * (String) text - The text data to append to the current element.
  1856. *
  1857. * Returns:
  1858. * The Strophe.Builder object.
  1859. */
  1860. t(text) {
  1861. const child = Strophe.xmlTextNode(text);
  1862. this.node.appendChild(child);
  1863. return this;
  1864. }
  1865. /** Function: h
  1866. * Replace current element contents with the HTML passed in.
  1867. *
  1868. * This *does not* make the child the new current element
  1869. *
  1870. * Parameters:
  1871. * (String) html - The html to insert as contents of current element.
  1872. *
  1873. * Returns:
  1874. * The Strophe.Builder object.
  1875. */
  1876. h(html) {
  1877. const fragment = Strophe.xmlGenerator().createElement('body'); // force the browser to try and fix any invalid HTML tags
  1878. fragment.innerHTML = html; // copy cleaned html into an xml dom
  1879. const xhtml = Strophe.createHtml(fragment);
  1880. while (xhtml.childNodes.length > 0) {
  1881. this.node.appendChild(xhtml.childNodes[0]);
  1882. }
  1883. return this;
  1884. }
  1885. };
  1886. /** PrivateClass: Strophe.Handler
  1887. * _Private_ helper class for managing stanza handlers.
  1888. *
  1889. * A Strophe.Handler encapsulates a user provided callback function to be
  1890. * executed when matching stanzas are received by the connection.
  1891. * Handlers can be either one-off or persistant depending on their
  1892. * return value. Returning true will cause a Handler to remain active, and
  1893. * returning false will remove the Handler.
  1894. *
  1895. * Users will not use Strophe.Handler objects directly, but instead they
  1896. * will use Strophe.Connection.addHandler() and
  1897. * Strophe.Connection.deleteHandler().
  1898. */
  1899. /** PrivateConstructor: Strophe.Handler
  1900. * Create and initialize a new Strophe.Handler.
  1901. *
  1902. * Parameters:
  1903. * (Function) handler - A function to be executed when the handler is run.
  1904. * (String) ns - The namespace to match.
  1905. * (String) name - The element name to match.
  1906. * (String) type - The element type to match.
  1907. * (String) id - The element id attribute to match.
  1908. * (String) from - The element from attribute to match.
  1909. * (Object) options - Handler options
  1910. *
  1911. * Returns:
  1912. * A new Strophe.Handler object.
  1913. */
  1914. Strophe.Handler = function (handler, ns, name, type, id, from, options) {
  1915. this.handler = handler;
  1916. this.ns = ns;
  1917. this.name = name;
  1918. this.type = type;
  1919. this.id = id;
  1920. this.options = options || {
  1921. 'matchBareFromJid': false,
  1922. 'ignoreNamespaceFragment': false
  1923. }; // BBB: Maintain backward compatibility with old `matchBare` option
  1924. if (this.options.matchBare) {
  1925. Strophe.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.');
  1926. this.options.matchBareFromJid = this.options.matchBare;
  1927. delete this.options.matchBare;
  1928. }
  1929. if (this.options.matchBareFromJid) {
  1930. this.from = from ? Strophe.getBareJidFromJid(from) : null;
  1931. } else {
  1932. this.from = from;
  1933. } // whether the handler is a user handler or a system handler
  1934. this.user = true;
  1935. };
  1936. Strophe.Handler.prototype = {
  1937. /** PrivateFunction: getNamespace
  1938. * Returns the XML namespace attribute on an element.
  1939. * If `ignoreNamespaceFragment` was passed in for this handler, then the
  1940. * URL fragment will be stripped.
  1941. *
  1942. * Parameters:
  1943. * (XMLElement) elem - The XML element with the namespace.
  1944. *
  1945. * Returns:
  1946. * The namespace, with optionally the fragment stripped.
  1947. */
  1948. getNamespace(elem) {
  1949. let elNamespace = elem.getAttribute("xmlns");
  1950. if (elNamespace && this.options.ignoreNamespaceFragment) {
  1951. elNamespace = elNamespace.split('#')[0];
  1952. }
  1953. return elNamespace;
  1954. },
  1955. /** PrivateFunction: namespaceMatch
  1956. * Tests if a stanza matches the namespace set for this Strophe.Handler.
  1957. *
  1958. * Parameters:
  1959. * (XMLElement) elem - The XML element to test.
  1960. *
  1961. * Returns:
  1962. * true if the stanza matches and false otherwise.
  1963. */
  1964. namespaceMatch(elem) {
  1965. let nsMatch = false;
  1966. if (!this.ns) {
  1967. return true;
  1968. } else {
  1969. Strophe.forEachChild(elem, null, elem => {
  1970. if (this.getNamespace(elem) === this.ns) {
  1971. nsMatch = true;
  1972. }
  1973. });
  1974. return nsMatch || this.getNamespace(elem) === this.ns;
  1975. }
  1976. },
  1977. /** PrivateFunction: isMatch
  1978. * Tests if a stanza matches the Strophe.Handler.
  1979. *
  1980. * Parameters:
  1981. * (XMLElement) elem - The XML element to test.
  1982. *
  1983. * Returns:
  1984. * true if the stanza matches and false otherwise.
  1985. */
  1986. isMatch(elem) {
  1987. let from = elem.getAttribute('from');
  1988. if (this.options.matchBareFromJid) {
  1989. from = Strophe.getBareJidFromJid(from);
  1990. }
  1991. const elem_type = elem.getAttribute("type");
  1992. if (this.namespaceMatch(elem) && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) && (!this.id || elem.getAttribute("id") === this.id) && (!this.from || from === this.from)) {
  1993. return true;
  1994. }
  1995. return false;
  1996. },
  1997. /** PrivateFunction: run
  1998. * Run the callback on a matching stanza.
  1999. *
  2000. * Parameters:
  2001. * (XMLElement) elem - The DOM element that triggered the
  2002. * Strophe.Handler.
  2003. *
  2004. * Returns:
  2005. * A boolean indicating if the handler should remain active.
  2006. */
  2007. run(elem) {
  2008. let result = null;
  2009. try {
  2010. result = this.handler(elem);
  2011. } catch (e) {
  2012. Strophe._handleError(e);
  2013. throw e;
  2014. }
  2015. return result;
  2016. },
  2017. /** PrivateFunction: toString
  2018. * Get a String representation of the Strophe.Handler object.
  2019. *
  2020. * Returns:
  2021. * A String.
  2022. */
  2023. toString() {
  2024. return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}";
  2025. }
  2026. };
  2027. /** PrivateClass: Strophe.TimedHandler
  2028. * _Private_ helper class for managing timed handlers.
  2029. *
  2030. * A Strophe.TimedHandler encapsulates a user provided callback that
  2031. * should be called after a certain period of time or at regular
  2032. * intervals. The return value of the callback determines whether the
  2033. * Strophe.TimedHandler will continue to fire.
  2034. *
  2035. * Users will not use Strophe.TimedHandler objects directly, but instead
  2036. * they will use Strophe.Connection.addTimedHandler() and
  2037. * Strophe.Connection.deleteTimedHandler().
  2038. */
  2039. Strophe.TimedHandler = class TimedHandler {
  2040. /** PrivateConstructor: Strophe.TimedHandler
  2041. * Create and initialize a new Strophe.TimedHandler object.
  2042. *
  2043. * Parameters:
  2044. * (Integer) period - The number of milliseconds to wait before the
  2045. * handler is called.
  2046. * (Function) handler - The callback to run when the handler fires. This
  2047. * function should take no arguments.
  2048. *
  2049. * Returns:
  2050. * A new Strophe.TimedHandler object.
  2051. */
  2052. constructor(period, handler) {
  2053. this.period = period;
  2054. this.handler = handler;
  2055. this.lastCalled = new Date().getTime();
  2056. this.user = true;
  2057. }
  2058. /** PrivateFunction: run
  2059. * Run the callback for the Strophe.TimedHandler.
  2060. *
  2061. * Returns:
  2062. * true if the Strophe.TimedHandler should be called again, and false
  2063. * otherwise.
  2064. */
  2065. run() {
  2066. this.lastCalled = new Date().getTime();
  2067. return this.handler();
  2068. }
  2069. /** PrivateFunction: reset
  2070. * Reset the last called time for the Strophe.TimedHandler.
  2071. */
  2072. reset() {
  2073. this.lastCalled = new Date().getTime();
  2074. }
  2075. /** PrivateFunction: toString
  2076. * Get a string representation of the Strophe.TimedHandler object.
  2077. *
  2078. * Returns:
  2079. * The string representation.
  2080. */
  2081. toString() {
  2082. return "{TimedHandler: " + this.handler + "(" + this.period + ")}";
  2083. }
  2084. };
  2085. /** Class: Strophe.Connection
  2086. * XMPP Connection manager.
  2087. *
  2088. * This class is the main part of Strophe. It manages a BOSH or websocket
  2089. * connection to an XMPP server and dispatches events to the user callbacks
  2090. * as data arrives. It supports SASL PLAIN, SASL SCRAM-SHA-1
  2091. * and legacy authentication.
  2092. *
  2093. * After creating a Strophe.Connection object, the user will typically
  2094. * call connect() with a user supplied callback to handle connection level
  2095. * events like authentication failure, disconnection, or connection
  2096. * complete.
  2097. *
  2098. * The user will also have several event handlers defined by using
  2099. * addHandler() and addTimedHandler(). These will allow the user code to
  2100. * respond to interesting stanzas or do something periodically with the
  2101. * connection. These handlers will be active once authentication is
  2102. * finished.
  2103. *
  2104. * To send data to the connection, use send().
  2105. */
  2106. /** Constructor: Strophe.Connection
  2107. * Create and initialize a Strophe.Connection object.
  2108. *
  2109. * The transport-protocol for this connection will be chosen automatically
  2110. * based on the given service parameter. URLs starting with "ws://" or
  2111. * "wss://" will use WebSockets, URLs starting with "http://", "https://"
  2112. * or without a protocol will use BOSH.
  2113. *
  2114. * To make Strophe connect to the current host you can leave out the protocol
  2115. * and host part and just pass the path, e.g.
  2116. *
  2117. * > let conn = new Strophe.Connection("/http-bind/");
  2118. *
  2119. * Options common to both Websocket and BOSH:
  2120. * ------------------------------------------
  2121. *
  2122. * cookies:
  2123. *
  2124. * The *cookies* option allows you to pass in cookies to be added to the
  2125. * document. These cookies will then be included in the BOSH XMLHttpRequest
  2126. * or in the websocket connection.
  2127. *
  2128. * The passed in value must be a map of cookie names and string values.
  2129. *
  2130. * > { "myCookie": {
  2131. * > "value": "1234",
  2132. * > "domain": ".example.org",
  2133. * > "path": "/",
  2134. * > "expires": expirationDate
  2135. * > }
  2136. * > }
  2137. *
  2138. * Note that cookies can't be set in this way for other domains (i.e. cross-domain).
  2139. * Those cookies need to be set under those domains, for example they can be
  2140. * set server-side by making a XHR call to that domain to ask it to set any
  2141. * necessary cookies.
  2142. *
  2143. * mechanisms:
  2144. *
  2145. * The *mechanisms* option allows you to specify the SASL mechanisms that this
  2146. * instance of Strophe.Connection (and therefore your XMPP client) will
  2147. * support.
  2148. *
  2149. * The value must be an array of objects with Strophe.SASLMechanism
  2150. * prototypes.
  2151. *
  2152. * If nothing is specified, then the following mechanisms (and their
  2153. * priorities) are registered:
  2154. *
  2155. * SCRAM-SHA-1 - 60
  2156. * PLAIN - 50
  2157. * OAUTHBEARER - 40
  2158. * X-OAUTH2 - 30
  2159. * ANONYMOUS - 20
  2160. * EXTERNAL - 10
  2161. *
  2162. * explicitResourceBinding:
  2163. *
  2164. * If `explicitResourceBinding` is set to a truthy value, then the XMPP client
  2165. * needs to explicitly call `Strophe.Connection.prototype.bind` once the XMPP
  2166. * server has advertised the "urn:ietf:params:xml:ns:xmpp-bind" feature.
  2167. *
  2168. * Making this step explicit allows client authors to first finish other
  2169. * stream related tasks, such as setting up an XEP-0198 Stream Management
  2170. * session, before binding the JID resource for this session.
  2171. *
  2172. * WebSocket options:
  2173. * ------------------
  2174. *
  2175. * protocol:
  2176. *
  2177. * If you want to connect to the current host with a WebSocket connection you
  2178. * can tell Strophe to use WebSockets through a "protocol" attribute in the
  2179. * optional options parameter. Valid values are "ws" for WebSocket and "wss"
  2180. * for Secure WebSocket.
  2181. * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
  2182. *
  2183. * > let conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
  2184. *
  2185. * Note that relative URLs _NOT_ starting with a "/" will also include the path
  2186. * of the current site.
  2187. *
  2188. * Also because downgrading security is not permitted by browsers, when using
  2189. * relative URLs both BOSH and WebSocket connections will use their secure
  2190. * variants if the current connection to the site is also secure (https).
  2191. *
  2192. * worker:
  2193. *
  2194. * Set this option to URL from where the shared worker script should be loaded.
  2195. *
  2196. * To run the websocket connection inside a shared worker.
  2197. * This allows you to share a single websocket-based connection between
  2198. * multiple Strophe.Connection instances, for example one per browser tab.
  2199. *
  2200. * The script to use is the one in `src/shared-connection-worker.js`.
  2201. *
  2202. * BOSH options:
  2203. * -------------
  2204. *
  2205. * By adding "sync" to the options, you can control if requests will
  2206. * be made synchronously or not. The default behaviour is asynchronous.
  2207. * If you want to make requests synchronous, make "sync" evaluate to true.
  2208. * > let conn = new Strophe.Connection("/http-bind/", {sync: true});
  2209. *
  2210. * You can also toggle this on an already established connection.
  2211. * > conn.options.sync = true;
  2212. *
  2213. * The *customHeaders* option can be used to provide custom HTTP headers to be
  2214. * included in the XMLHttpRequests made.
  2215. *
  2216. * The *keepalive* option can be used to instruct Strophe to maintain the
  2217. * current BOSH session across interruptions such as webpage reloads.
  2218. *
  2219. * It will do this by caching the sessions tokens in sessionStorage, and when
  2220. * "restore" is called it will check whether there are cached tokens with
  2221. * which it can resume an existing session.
  2222. *
  2223. * The *withCredentials* option should receive a Boolean value and is used to
  2224. * indicate wether cookies should be included in ajax requests (by default
  2225. * they're not).
  2226. * Set this value to true if you are connecting to a BOSH service
  2227. * and for some reason need to send cookies to it.
  2228. * In order for this to work cross-domain, the server must also enable
  2229. * credentials by setting the Access-Control-Allow-Credentials response header
  2230. * to "true". For most usecases however this setting should be false (which
  2231. * is the default).
  2232. * Additionally, when using Access-Control-Allow-Credentials, the
  2233. * Access-Control-Allow-Origin header can't be set to the wildcard "*", but
  2234. * instead must be restricted to actual domains.
  2235. *
  2236. * The *contentType* option can be set to change the default Content-Type
  2237. * of "text/xml; charset=utf-8", which can be useful to reduce the amount of
  2238. * CORS preflight requests that are sent to the server.
  2239. *
  2240. * Parameters:
  2241. * (String) service - The BOSH or WebSocket service URL.
  2242. * (Object) options - A hash of configuration options
  2243. *
  2244. * Returns:
  2245. * A new Strophe.Connection object.
  2246. */
  2247. Strophe.Connection = class Connection {
  2248. constructor(service, options) {
  2249. // The service URL
  2250. this.service = service; // Configuration options
  2251. this.options = options || {};
  2252. this.setProtocol();
  2253. /* The connected JID. */
  2254. this.jid = "";
  2255. /* the JIDs domain */
  2256. this.domain = null;
  2257. /* stream:features */
  2258. this.features = null; // SASL
  2259. this._sasl_data = {};
  2260. this.do_bind = false;
  2261. this.do_session = false;
  2262. this.mechanisms = {}; // handler lists
  2263. this.timedHandlers = [];
  2264. this.handlers = [];
  2265. this.removeTimeds = [];
  2266. this.removeHandlers = [];
  2267. this.addTimeds = [];
  2268. this.addHandlers = [];
  2269. this.protocolErrorHandlers = {
  2270. 'HTTP': {},
  2271. 'websocket': {}
  2272. };
  2273. this._idleTimeout = null;
  2274. this._disconnectTimeout = null;
  2275. this.authenticated = false;
  2276. this.connected = false;
  2277. this.disconnecting = false;
  2278. this.do_authentication = true;
  2279. this.paused = false;
  2280. this.restored = false;
  2281. this._data = [];
  2282. this._uniqueId = 0;
  2283. this._sasl_success_handler = null;
  2284. this._sasl_failure_handler = null;
  2285. this._sasl_challenge_handler = null; // Max retries before disconnecting
  2286. this.maxRetries = 5; // Call onIdle callback every 1/10th of a second
  2287. this._idleTimeout = setTimeout(() => this._onIdle(), 100);
  2288. utils.addCookies(this.options.cookies);
  2289. this.registerSASLMechanisms(this.options.mechanisms); // A client must always respond to incoming IQ "set" and "get" stanzas.
  2290. // See https://datatracker.ietf.org/doc/html/rfc6120#section-8.2.3
  2291. //
  2292. // This is a fallback handler which gets called when no other handler
  2293. // was called for a received IQ "set" or "get".
  2294. this.iqFallbackHandler = new Strophe.Handler(iq => this.send($iq({
  2295. type: 'error',
  2296. id: iq.getAttribute('id')
  2297. }).c('error', {
  2298. 'type': 'cancel'
  2299. }).c('service-unavailable', {
  2300. 'xmlns': Strophe.NS.STANZAS
  2301. })), null, 'iq', ['get', 'set']); // initialize plugins
  2302. for (const k in Strophe._connectionPlugins) {
  2303. if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
  2304. const F = function () {};
  2305. F.prototype = Strophe._connectionPlugins[k];
  2306. this[k] = new F();
  2307. this[k].init(this);
  2308. }
  2309. }
  2310. }
  2311. /** Function: setProtocol
  2312. * Select protocal based on this.options or this.service
  2313. */
  2314. setProtocol() {
  2315. const proto = this.options.protocol || "";
  2316. if (this.options.worker) {
  2317. this._proto = new Strophe.WorkerWebsocket(this);
  2318. } else if (this.service.indexOf("ws:") === 0 || this.service.indexOf("wss:") === 0 || proto.indexOf("ws") === 0) {
  2319. this._proto = new Strophe.Websocket(this);
  2320. } else {
  2321. this._proto = new Strophe.Bosh(this);
  2322. }
  2323. }
  2324. /** Function: reset
  2325. * Reset the connection.
  2326. *
  2327. * This function should be called after a connection is disconnected
  2328. * before that connection is reused.
  2329. */
  2330. reset() {
  2331. this._proto._reset(); // SASL
  2332. this.do_session = false;
  2333. this.do_bind = false; // handler lists
  2334. this.timedHandlers = [];
  2335. this.handlers = [];
  2336. this.removeTimeds = [];
  2337. this.removeHandlers = [];
  2338. this.addTimeds = [];
  2339. this.addHandlers = [];
  2340. this.authenticated = false;
  2341. this.connected = false;
  2342. this.disconnecting = false;
  2343. this.restored = false;
  2344. this._data = [];
  2345. this._requests = [];
  2346. this._uniqueId = 0;
  2347. }
  2348. /** Function: pause
  2349. * Pause the request manager.
  2350. *
  2351. * This will prevent Strophe from sending any more requests to the
  2352. * server. This is very useful for temporarily pausing
  2353. * BOSH-Connections while a lot of send() calls are happening quickly.
  2354. * This causes Strophe to send the data in a single request, saving
  2355. * many request trips.
  2356. */
  2357. pause() {
  2358. this.paused = true;
  2359. }
  2360. /** Function: resume
  2361. * Resume the request manager.
  2362. *
  2363. * This resumes after pause() has been called.
  2364. */
  2365. resume() {
  2366. this.paused = false;
  2367. }
  2368. /** Function: getUniqueId
  2369. * Generate a unique ID for use in <iq/> elements.
  2370. *
  2371. * All <iq/> stanzas are required to have unique id attributes. This
  2372. * function makes creating these easy. Each connection instance has
  2373. * a counter which starts from zero, and the value of this counter
  2374. * plus a colon followed by the suffix becomes the unique id. If no
  2375. * suffix is supplied, the counter is used as the unique id.
  2376. *
  2377. * Suffixes are used to make debugging easier when reading the stream
  2378. * data, and their use is recommended. The counter resets to 0 for
  2379. * every new connection for the same reason. For connections to the
  2380. * same server that authenticate the same way, all the ids should be
  2381. * the same, which makes it easy to see changes. This is useful for
  2382. * automated testing as well.
  2383. *
  2384. * Parameters:
  2385. * (String) suffix - A optional suffix to append to the id.
  2386. *
  2387. * Returns:
  2388. * A unique string to be used for the id attribute.
  2389. */
  2390. getUniqueId(suffix) {
  2391. // eslint-disable-line class-methods-use-this
  2392. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2393. const r = Math.random() * 16 | 0,
  2394. v = c === 'x' ? r : r & 0x3 | 0x8;
  2395. return v.toString(16);
  2396. });
  2397. if (typeof suffix === "string" || typeof suffix === "number") {
  2398. return uuid + ":" + suffix;
  2399. } else {
  2400. return uuid + "";
  2401. }
  2402. }
  2403. /** Function: addProtocolErrorHandler
  2404. * Register a handler function for when a protocol (websocker or HTTP)
  2405. * error occurs.
  2406. *
  2407. * NOTE: Currently only HTTP errors for BOSH requests are handled.
  2408. * Patches that handle websocket errors would be very welcome.
  2409. *
  2410. * Parameters:
  2411. * (String) protocol - 'HTTP' or 'websocket'
  2412. * (Integer) status_code - Error status code (e.g 500, 400 or 404)
  2413. * (Function) callback - Function that will fire on Http error
  2414. *
  2415. * Example:
  2416. * function onError(err_code){
  2417. * //do stuff
  2418. * }
  2419. *
  2420. * let conn = Strophe.connect('http://example.com/http-bind');
  2421. * conn.addProtocolErrorHandler('HTTP', 500, onError);
  2422. * // Triggers HTTP 500 error and onError handler will be called
  2423. * conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);
  2424. */
  2425. addProtocolErrorHandler(protocol, status_code, callback) {
  2426. this.protocolErrorHandlers[protocol][status_code] = callback;
  2427. }
  2428. /** Function: connect
  2429. * Starts the connection process.
  2430. *
  2431. * As the connection process proceeds, the user supplied callback will
  2432. * be triggered multiple times with status updates. The callback
  2433. * should take two arguments - the status code and the error condition.
  2434. *
  2435. * The status code will be one of the values in the Strophe.Status
  2436. * constants. The error condition will be one of the conditions
  2437. * defined in RFC 3920 or the condition 'strophe-parsererror'.
  2438. *
  2439. * The Parameters _wait_, _hold_ and _route_ are optional and only relevant
  2440. * for BOSH connections. Please see XEP 124 for a more detailed explanation
  2441. * of the optional parameters.
  2442. *
  2443. * Parameters:
  2444. * (String) jid - The user's JID. This may be a bare JID,
  2445. * or a full JID. If a node is not supplied, SASL OAUTHBEARER or
  2446. * SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will
  2447. * process the provided password value as an access token).
  2448. * (String) pass - The user's password.
  2449. * (Function) callback - The connect callback function.
  2450. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2451. * time the server will wait before returning an empty result for
  2452. * a request. The default setting of 60 seconds is recommended.
  2453. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2454. * number of connections the server will hold at one time. This
  2455. * should almost always be set to 1 (the default).
  2456. * (String) route - The optional route value.
  2457. * (String) authcid - The optional alternative authentication identity
  2458. * (username) if intending to impersonate another user.
  2459. * When using the SASL-EXTERNAL authentication mechanism, for example
  2460. * with client certificates, then the authcid value is used to
  2461. * determine whether an authorization JID (authzid) should be sent to
  2462. * the server. The authzid should NOT be sent to the server if the
  2463. * authzid and authcid are the same. So to prevent it from being sent
  2464. * (for example when the JID is already contained in the client
  2465. * certificate), set authcid to that same JID. See XEP-178 for more
  2466. * details.
  2467. * (Integer) disconnection_timeout - The optional disconnection timeout
  2468. * in milliseconds before _doDisconnect will be called.
  2469. */
  2470. connect(jid, pass, callback, wait, hold, route, authcid) {
  2471. let disconnection_timeout = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 3000;
  2472. this.jid = jid;
  2473. /** Variable: authzid
  2474. * Authorization identity.
  2475. */
  2476. this.authzid = Strophe.getBareJidFromJid(this.jid);
  2477. /** Variable: authcid
  2478. * Authentication identity (User name).
  2479. */
  2480. this.authcid = authcid || Strophe.getNodeFromJid(this.jid);
  2481. /** Variable: pass
  2482. * Authentication identity (User password).
  2483. */
  2484. this.pass = pass;
  2485. this.connect_callback = callback;
  2486. this.disconnecting = false;
  2487. this.connected = false;
  2488. this.authenticated = false;
  2489. this.restored = false;
  2490. this.disconnection_timeout = disconnection_timeout; // parse jid for domain
  2491. this.domain = Strophe.getDomainFromJid(this.jid);
  2492. this._changeConnectStatus(Strophe.Status.CONNECTING, null);
  2493. this._proto._connect(wait, hold, route);
  2494. }
  2495. /** Function: attach
  2496. * Attach to an already created and authenticated BOSH session.
  2497. *
  2498. * This function is provided to allow Strophe to attach to BOSH
  2499. * sessions which have been created externally, perhaps by a Web
  2500. * application. This is often used to support auto-login type features
  2501. * without putting user credentials into the page.
  2502. *
  2503. * Parameters:
  2504. * (String) jid - The full JID that is bound by the session.
  2505. * (String) sid - The SID of the BOSH session.
  2506. * (String) rid - The current RID of the BOSH session. This RID
  2507. * will be used by the next request.
  2508. * (Function) callback The connect callback function.
  2509. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2510. * time the server will wait before returning an empty result for
  2511. * a request. The default setting of 60 seconds is recommended.
  2512. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  2513. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2514. * number of connections the server will hold at one time. This
  2515. * should almost always be set to 1 (the default).
  2516. * (Integer) wind - The optional HTTBIND window value. This is the
  2517. * allowed range of request ids that are valid. The default is 5.
  2518. */
  2519. attach(jid, sid, rid, callback, wait, hold, wind) {
  2520. if (this._proto._attach) {
  2521. return this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
  2522. } else {
  2523. const error = new Error('The "attach" method is not available for your connection protocol');
  2524. error.name = 'StropheSessionError';
  2525. throw error;
  2526. }
  2527. }
  2528. /** Function: restore
  2529. * Attempt to restore a cached BOSH session.
  2530. *
  2531. * This function is only useful in conjunction with providing the
  2532. * "keepalive":true option when instantiating a new Strophe.Connection.
  2533. *
  2534. * When "keepalive" is set to true, Strophe will cache the BOSH tokens
  2535. * RID (Request ID) and SID (Session ID) and then when this function is
  2536. * called, it will attempt to restore the session from those cached
  2537. * tokens.
  2538. *
  2539. * This function must therefore be called instead of connect or attach.
  2540. *
  2541. * For an example on how to use it, please see examples/restore.js
  2542. *
  2543. * Parameters:
  2544. * (String) jid - The user's JID. This may be a bare JID or a full JID.
  2545. * (Function) callback - The connect callback function.
  2546. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2547. * time the server will wait before returning an empty result for
  2548. * a request. The default setting of 60 seconds is recommended.
  2549. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2550. * number of connections the server will hold at one time. This
  2551. * should almost always be set to 1 (the default).
  2552. * (Integer) wind - The optional HTTBIND window value. This is the
  2553. * allowed range of request ids that are valid. The default is 5.
  2554. */
  2555. restore(jid, callback, wait, hold, wind) {
  2556. if (this._sessionCachingSupported()) {
  2557. this._proto._restore(jid, callback, wait, hold, wind);
  2558. } else {
  2559. const error = new Error('The "restore" method can only be used with a BOSH connection.');
  2560. error.name = 'StropheSessionError';
  2561. throw error;
  2562. }
  2563. }
  2564. /** PrivateFunction: _sessionCachingSupported
  2565. * Checks whether sessionStorage and JSON are supported and whether we're
  2566. * using BOSH.
  2567. */
  2568. _sessionCachingSupported() {
  2569. if (this._proto instanceof Strophe.Bosh) {
  2570. if (!JSON) {
  2571. return false;
  2572. }
  2573. try {
  2574. sessionStorage.setItem('_strophe_', '_strophe_');
  2575. sessionStorage.removeItem('_strophe_');
  2576. } catch (e) {
  2577. return false;
  2578. }
  2579. return true;
  2580. }
  2581. return false;
  2582. }
  2583. /** Function: xmlInput
  2584. * User overrideable function that receives XML data coming into the
  2585. * connection.
  2586. *
  2587. * The default function does nothing. User code can override this with
  2588. * > Strophe.Connection.xmlInput = function (elem) {
  2589. * > (user code)
  2590. * > };
  2591. *
  2592. * Due to limitations of current Browsers' XML-Parsers the opening and closing
  2593. * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
  2594. *
  2595. * BOSH-Connections will have all stanzas wrapped in a <body> tag. See
  2596. * <Strophe.Bosh.strip> if you want to strip this tag.
  2597. *
  2598. * Parameters:
  2599. * (XMLElement) elem - The XML data received by the connection.
  2600. */
  2601. xmlInput(elem) {
  2602. // eslint-disable-line
  2603. return;
  2604. }
  2605. /** Function: xmlOutput
  2606. * User overrideable function that receives XML data sent to the
  2607. * connection.
  2608. *
  2609. * The default function does nothing. User code can override this with
  2610. * > Strophe.Connection.xmlOutput = function (elem) {
  2611. * > (user code)
  2612. * > };
  2613. *
  2614. * Due to limitations of current Browsers' XML-Parsers the opening and closing
  2615. * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
  2616. *
  2617. * BOSH-Connections will have all stanzas wrapped in a <body> tag. See
  2618. * <Strophe.Bosh.strip> if you want to strip this tag.
  2619. *
  2620. * Parameters:
  2621. * (XMLElement) elem - The XMLdata sent by the connection.
  2622. */
  2623. xmlOutput(elem) {
  2624. // eslint-disable-line
  2625. return;
  2626. }
  2627. /** Function: rawInput
  2628. * User overrideable function that receives raw data coming into the
  2629. * connection.
  2630. *
  2631. * The default function does nothing. User code can override this with
  2632. * > Strophe.Connection.rawInput = function (data) {
  2633. * > (user code)
  2634. * > };
  2635. *
  2636. * Parameters:
  2637. * (String) data - The data received by the connection.
  2638. */
  2639. rawInput(data) {
  2640. // eslint-disable-line
  2641. return;
  2642. }
  2643. /** Function: rawOutput
  2644. * User overrideable function that receives raw data sent to the
  2645. * connection.
  2646. *
  2647. * The default function does nothing. User code can override this with
  2648. * > Strophe.Connection.rawOutput = function (data) {
  2649. * > (user code)
  2650. * > };
  2651. *
  2652. * Parameters:
  2653. * (String) data - The data sent by the connection.
  2654. */
  2655. rawOutput(data) {
  2656. // eslint-disable-line
  2657. return;
  2658. }
  2659. /** Function: nextValidRid
  2660. * User overrideable function that receives the new valid rid.
  2661. *
  2662. * The default function does nothing. User code can override this with
  2663. * > Strophe.Connection.nextValidRid = function (rid) {
  2664. * > (user code)
  2665. * > };
  2666. *
  2667. * Parameters:
  2668. * (Number) rid - The next valid rid
  2669. */
  2670. nextValidRid(rid) {
  2671. // eslint-disable-line
  2672. return;
  2673. }
  2674. /** Function: send
  2675. * Send a stanza.
  2676. *
  2677. * This function is called to push data onto the send queue to
  2678. * go out over the wire. Whenever a request is sent to the BOSH
  2679. * server, all pending data is sent and the queue is flushed.
  2680. *
  2681. * Parameters:
  2682. * (XMLElement |
  2683. * [XMLElement] |
  2684. * Strophe.Builder) elem - The stanza to send.
  2685. */
  2686. send(elem) {
  2687. if (elem === null) {
  2688. return;
  2689. }
  2690. if (typeof elem.sort === "function") {
  2691. for (let i = 0; i < elem.length; i++) {
  2692. this._queueData(elem[i]);
  2693. }
  2694. } else if (typeof elem.tree === "function") {
  2695. this._queueData(elem.tree());
  2696. } else {
  2697. this._queueData(elem);
  2698. }
  2699. this._proto._send();
  2700. }
  2701. /** Function: flush
  2702. * Immediately send any pending outgoing data.
  2703. *
  2704. * Normally send() queues outgoing data until the next idle period
  2705. * (100ms), which optimizes network use in the common cases when
  2706. * several send()s are called in succession. flush() can be used to
  2707. * immediately send all pending data.
  2708. */
  2709. flush() {
  2710. // cancel the pending idle period and run the idle function
  2711. // immediately
  2712. clearTimeout(this._idleTimeout);
  2713. this._onIdle();
  2714. }
  2715. /** Function: sendPresence
  2716. * Helper function to send presence stanzas. The main benefit is for
  2717. * sending presence stanzas for which you expect a responding presence
  2718. * stanza with the same id (for example when leaving a chat room).
  2719. *
  2720. * Parameters:
  2721. * (XMLElement) elem - The stanza to send.
  2722. * (Function) callback - The callback function for a successful request.
  2723. * (Function) errback - The callback function for a failed or timed
  2724. * out request. On timeout, the stanza will be null.
  2725. * (Integer) timeout - The time specified in milliseconds for a
  2726. * timeout to occur.
  2727. *
  2728. * Returns:
  2729. * The id used to send the presence.
  2730. */
  2731. sendPresence(elem, callback, errback, timeout) {
  2732. let timeoutHandler = null;
  2733. if (typeof elem.tree === "function") {
  2734. elem = elem.tree();
  2735. }
  2736. let id = elem.getAttribute('id');
  2737. if (!id) {
  2738. // inject id if not found
  2739. id = this.getUniqueId("sendPresence");
  2740. elem.setAttribute("id", id);
  2741. }
  2742. if (typeof callback === "function" || typeof errback === "function") {
  2743. const handler = this.addHandler(stanza => {
  2744. // remove timeout handler if there is one
  2745. if (timeoutHandler) {
  2746. this.deleteTimedHandler(timeoutHandler);
  2747. }
  2748. if (stanza.getAttribute('type') === 'error') {
  2749. if (errback) {
  2750. errback(stanza);
  2751. }
  2752. } else if (callback) {
  2753. callback(stanza);
  2754. }
  2755. }, null, 'presence', null, id); // if timeout specified, set up a timeout handler.
  2756. if (timeout) {
  2757. timeoutHandler = this.addTimedHandler(timeout, () => {
  2758. // get rid of normal handler
  2759. this.deleteHandler(handler); // call errback on timeout with null stanza
  2760. if (errback) {
  2761. errback(null);
  2762. }
  2763. return false;
  2764. });
  2765. }
  2766. }
  2767. this.send(elem);
  2768. return id;
  2769. }
  2770. /** Function: sendIQ
  2771. * Helper function to send IQ stanzas.
  2772. *
  2773. * Parameters:
  2774. * (XMLElement) elem - The stanza to send.
  2775. * (Function) callback - The callback function for a successful request.
  2776. * (Function) errback - The callback function for a failed or timed
  2777. * out request. On timeout, the stanza will be null.
  2778. * (Integer) timeout - The time specified in milliseconds for a
  2779. * timeout to occur.
  2780. *
  2781. * Returns:
  2782. * The id used to send the IQ.
  2783. */
  2784. sendIQ(elem, callback, errback, timeout) {
  2785. let timeoutHandler = null;
  2786. if (typeof elem.tree === "function") {
  2787. elem = elem.tree();
  2788. }
  2789. let id = elem.getAttribute('id');
  2790. if (!id) {
  2791. // inject id if not found
  2792. id = this.getUniqueId("sendIQ");
  2793. elem.setAttribute("id", id);
  2794. }
  2795. if (typeof callback === "function" || typeof errback === "function") {
  2796. const handler = this.addHandler(stanza => {
  2797. // remove timeout handler if there is one
  2798. if (timeoutHandler) {
  2799. this.deleteTimedHandler(timeoutHandler);
  2800. }
  2801. const iqtype = stanza.getAttribute('type');
  2802. if (iqtype === 'result') {
  2803. if (callback) {
  2804. callback(stanza);
  2805. }
  2806. } else if (iqtype === 'error') {
  2807. if (errback) {
  2808. errback(stanza);
  2809. }
  2810. } else {
  2811. const error = new Error(`Got bad IQ type of ${iqtype}`);
  2812. error.name = "StropheError";
  2813. throw error;
  2814. }
  2815. }, null, 'iq', ['error', 'result'], id); // if timeout specified, set up a timeout handler.
  2816. if (timeout) {
  2817. timeoutHandler = this.addTimedHandler(timeout, () => {
  2818. // get rid of normal handler
  2819. this.deleteHandler(handler); // call errback on timeout with null stanza
  2820. if (errback) {
  2821. errback(null);
  2822. }
  2823. return false;
  2824. });
  2825. }
  2826. }
  2827. this.send(elem);
  2828. return id;
  2829. }
  2830. /** PrivateFunction: _queueData
  2831. * Queue outgoing data for later sending. Also ensures that the data
  2832. * is a DOMElement.
  2833. */
  2834. _queueData(element) {
  2835. if (element === null || !element.tagName || !element.childNodes) {
  2836. const error = new Error("Cannot queue non-DOMElement.");
  2837. error.name = "StropheError";
  2838. throw error;
  2839. }
  2840. this._data.push(element);
  2841. }
  2842. /** PrivateFunction: _sendRestart
  2843. * Send an xmpp:restart stanza.
  2844. */
  2845. _sendRestart() {
  2846. this._data.push("restart");
  2847. this._proto._sendRestart();
  2848. this._idleTimeout = setTimeout(() => this._onIdle(), 100);
  2849. }
  2850. /** Function: addTimedHandler
  2851. * Add a timed handler to the connection.
  2852. *
  2853. * This function adds a timed handler. The provided handler will
  2854. * be called every period milliseconds until it returns false,
  2855. * the connection is terminated, or the handler is removed. Handlers
  2856. * that wish to continue being invoked should return true.
  2857. *
  2858. * Because of method binding it is necessary to save the result of
  2859. * this function if you wish to remove a handler with
  2860. * deleteTimedHandler().
  2861. *
  2862. * Note that user handlers are not active until authentication is
  2863. * successful.
  2864. *
  2865. * Parameters:
  2866. * (Integer) period - The period of the handler.
  2867. * (Function) handler - The callback function.
  2868. *
  2869. * Returns:
  2870. * A reference to the handler that can be used to remove it.
  2871. */
  2872. addTimedHandler(period, handler) {
  2873. const thand = new Strophe.TimedHandler(period, handler);
  2874. this.addTimeds.push(thand);
  2875. return thand;
  2876. }
  2877. /** Function: deleteTimedHandler
  2878. * Delete a timed handler for a connection.
  2879. *
  2880. * This function removes a timed handler from the connection. The
  2881. * handRef parameter is *not* the function passed to addTimedHandler(),
  2882. * but is the reference returned from addTimedHandler().
  2883. *
  2884. * Parameters:
  2885. * (Strophe.TimedHandler) handRef - The handler reference.
  2886. */
  2887. deleteTimedHandler(handRef) {
  2888. // this must be done in the Idle loop so that we don't change
  2889. // the handlers during iteration
  2890. this.removeTimeds.push(handRef);
  2891. }
  2892. /** Function: addHandler
  2893. * Add a stanza handler for the connection.
  2894. *
  2895. * This function adds a stanza handler to the connection. The
  2896. * handler callback will be called for any stanza that matches
  2897. * the parameters. Note that if multiple parameters are supplied,
  2898. * they must all match for the handler to be invoked.
  2899. *
  2900. * The handler will receive the stanza that triggered it as its argument.
  2901. * *The handler should return true if it is to be invoked again;
  2902. * returning false will remove the handler after it returns.*
  2903. *
  2904. * As a convenience, the ns parameters applies to the top level element
  2905. * and also any of its immediate children. This is primarily to make
  2906. * matching /iq/query elements easy.
  2907. *
  2908. * Options
  2909. * ~~~~~~~
  2910. * With the options argument, you can specify boolean flags that affect how
  2911. * matches are being done.
  2912. *
  2913. * Currently two flags exist:
  2914. *
  2915. * - matchBareFromJid:
  2916. * When set to true, the from parameter and the
  2917. * from attribute on the stanza will be matched as bare JIDs instead
  2918. * of full JIDs. To use this, pass {matchBareFromJid: true} as the
  2919. * value of options. The default value for matchBareFromJid is false.
  2920. *
  2921. * - ignoreNamespaceFragment:
  2922. * When set to true, a fragment specified on the stanza's namespace
  2923. * URL will be ignored when it's matched with the one configured for
  2924. * the handler.
  2925. *
  2926. * This means that if you register like this:
  2927. * > connection.addHandler(
  2928. * > handler,
  2929. * > 'http://jabber.org/protocol/muc',
  2930. * > null, null, null, null,
  2931. * > {'ignoreNamespaceFragment': true}
  2932. * > );
  2933. *
  2934. * Then a stanza with XML namespace of
  2935. * 'http://jabber.org/protocol/muc#user' will also be matched. If
  2936. * 'ignoreNamespaceFragment' is false, then only stanzas with
  2937. * 'http://jabber.org/protocol/muc' will be matched.
  2938. *
  2939. * Deleting the handler
  2940. * ~~~~~~~~~~~~~~~~~~~~
  2941. * The return value should be saved if you wish to remove the handler
  2942. * with deleteHandler().
  2943. *
  2944. * Parameters:
  2945. * (Function) handler - The user callback.
  2946. * (String) ns - The namespace to match.
  2947. * (String) name - The stanza name to match.
  2948. * (String|Array) type - The stanza type (or types if an array) to match.
  2949. * (String) id - The stanza id attribute to match.
  2950. * (String) from - The stanza from attribute to match.
  2951. * (String) options - The handler options
  2952. *
  2953. * Returns:
  2954. * A reference to the handler that can be used to remove it.
  2955. */
  2956. addHandler(handler, ns, name, type, id, from, options) {
  2957. const hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
  2958. this.addHandlers.push(hand);
  2959. return hand;
  2960. }
  2961. /** Function: deleteHandler
  2962. * Delete a stanza handler for a connection.
  2963. *
  2964. * This function removes a stanza handler from the connection. The
  2965. * handRef parameter is *not* the function passed to addHandler(),
  2966. * but is the reference returned from addHandler().
  2967. *
  2968. * Parameters:
  2969. * (Strophe.Handler) handRef - The handler reference.
  2970. */
  2971. deleteHandler(handRef) {
  2972. // this must be done in the Idle loop so that we don't change
  2973. // the handlers during iteration
  2974. this.removeHandlers.push(handRef); // If a handler is being deleted while it is being added,
  2975. // prevent it from getting added
  2976. const i = this.addHandlers.indexOf(handRef);
  2977. if (i >= 0) {
  2978. this.addHandlers.splice(i, 1);
  2979. }
  2980. }
  2981. /** Function: registerSASLMechanisms
  2982. *
  2983. * Register the SASL mechanisms which will be supported by this instance of
  2984. * Strophe.Connection (i.e. which this XMPP client will support).
  2985. *
  2986. * Parameters:
  2987. * (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes
  2988. *
  2989. */
  2990. registerSASLMechanisms(mechanisms) {
  2991. this.mechanisms = {};
  2992. mechanisms = mechanisms || [Strophe.SASLAnonymous, Strophe.SASLExternal, Strophe.SASLOAuthBearer, Strophe.SASLXOAuth2, Strophe.SASLPlain, Strophe.SASLSHA1];
  2993. mechanisms.forEach(m => this.registerSASLMechanism(m));
  2994. }
  2995. /** Function: registerSASLMechanism
  2996. *
  2997. * Register a single SASL mechanism, to be supported by this client.
  2998. *
  2999. * Parameters:
  3000. * (Object) mechanism - Object with a Strophe.SASLMechanism prototype
  3001. *
  3002. */
  3003. registerSASLMechanism(Mechanism) {
  3004. const mechanism = new Mechanism();
  3005. this.mechanisms[mechanism.mechname] = mechanism;
  3006. }
  3007. /** Function: disconnect
  3008. * Start the graceful disconnection process.
  3009. *
  3010. * This function starts the disconnection process. This process starts
  3011. * by sending unavailable presence and sending BOSH body of type
  3012. * terminate. A timeout handler makes sure that disconnection happens
  3013. * even if the BOSH server does not respond.
  3014. * If the Connection object isn't connected, at least tries to abort all pending requests
  3015. * so the connection object won't generate successful requests (which were already opened).
  3016. *
  3017. * The user supplied connection callback will be notified of the
  3018. * progress as this process happens.
  3019. *
  3020. * Parameters:
  3021. * (String) reason - The reason the disconnect is occuring.
  3022. */
  3023. disconnect(reason) {
  3024. this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
  3025. if (reason) {
  3026. Strophe.warn("Disconnect was called because: " + reason);
  3027. } else {
  3028. Strophe.info("Disconnect was called");
  3029. }
  3030. if (this.connected) {
  3031. let pres = false;
  3032. this.disconnecting = true;
  3033. if (this.authenticated) {
  3034. pres = $pres({
  3035. 'xmlns': Strophe.NS.CLIENT,
  3036. 'type': 'unavailable'
  3037. });
  3038. } // setup timeout handler
  3039. this._disconnectTimeout = this._addSysTimedHandler(this.disconnection_timeout, this._onDisconnectTimeout.bind(this));
  3040. this._proto._disconnect(pres);
  3041. } else {
  3042. Strophe.warn("Disconnect was called before Strophe connected to the server");
  3043. this._proto._abortAllRequests();
  3044. this._doDisconnect();
  3045. }
  3046. }
  3047. /** PrivateFunction: _changeConnectStatus
  3048. * _Private_ helper function that makes sure plugins and the user's
  3049. * callback are notified of connection status changes.
  3050. *
  3051. * Parameters:
  3052. * (Integer) status - the new connection status, one of the values
  3053. * in Strophe.Status
  3054. * (String) condition - the error condition or null
  3055. * (XMLElement) elem - The triggering stanza.
  3056. */
  3057. _changeConnectStatus(status, condition, elem) {
  3058. // notify all plugins listening for status changes
  3059. for (const k in Strophe._connectionPlugins) {
  3060. if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
  3061. const plugin = this[k];
  3062. if (plugin.statusChanged) {
  3063. try {
  3064. plugin.statusChanged(status, condition);
  3065. } catch (err) {
  3066. Strophe.error(`${k} plugin caused an exception changing status: ${err}`);
  3067. }
  3068. }
  3069. }
  3070. } // notify the user's callback
  3071. if (this.connect_callback) {
  3072. try {
  3073. this.connect_callback(status, condition, elem);
  3074. } catch (e) {
  3075. Strophe._handleError(e);
  3076. Strophe.error(`User connection callback caused an exception: ${e}`);
  3077. }
  3078. }
  3079. }
  3080. /** PrivateFunction: _doDisconnect
  3081. * _Private_ function to disconnect.
  3082. *
  3083. * This is the last piece of the disconnection logic. This resets the
  3084. * connection and alerts the user's connection callback.
  3085. */
  3086. _doDisconnect(condition) {
  3087. if (typeof this._idleTimeout === "number") {
  3088. clearTimeout(this._idleTimeout);
  3089. } // Cancel Disconnect Timeout
  3090. if (this._disconnectTimeout !== null) {
  3091. this.deleteTimedHandler(this._disconnectTimeout);
  3092. this._disconnectTimeout = null;
  3093. }
  3094. Strophe.debug("_doDisconnect was called");
  3095. this._proto._doDisconnect();
  3096. this.authenticated = false;
  3097. this.disconnecting = false;
  3098. this.restored = false; // delete handlers
  3099. this.handlers = [];
  3100. this.timedHandlers = [];
  3101. this.removeTimeds = [];
  3102. this.removeHandlers = [];
  3103. this.addTimeds = [];
  3104. this.addHandlers = []; // tell the parent we disconnected
  3105. this._changeConnectStatus(Strophe.Status.DISCONNECTED, condition);
  3106. this.connected = false;
  3107. }
  3108. /** PrivateFunction: _dataRecv
  3109. * _Private_ handler to processes incoming data from the the connection.
  3110. *
  3111. * Except for _connect_cb handling the initial connection request,
  3112. * this function handles the incoming data for all requests. This
  3113. * function also fires stanza handlers that match each incoming
  3114. * stanza.
  3115. *
  3116. * Parameters:
  3117. * (Strophe.Request) req - The request that has data ready.
  3118. * (string) req - The stanza a raw string (optiona).
  3119. */
  3120. _dataRecv(req, raw) {
  3121. const elem = this._proto._reqToData(req);
  3122. if (elem === null) {
  3123. return;
  3124. }
  3125. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  3126. if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
  3127. this.xmlInput(elem.childNodes[0]);
  3128. } else {
  3129. this.xmlInput(elem);
  3130. }
  3131. }
  3132. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  3133. if (raw) {
  3134. this.rawInput(raw);
  3135. } else {
  3136. this.rawInput(Strophe.serialize(elem));
  3137. }
  3138. } // remove handlers scheduled for deletion
  3139. while (this.removeHandlers.length > 0) {
  3140. const hand = this.removeHandlers.pop();
  3141. const i = this.handlers.indexOf(hand);
  3142. if (i >= 0) {
  3143. this.handlers.splice(i, 1);
  3144. }
  3145. } // add handlers scheduled for addition
  3146. while (this.addHandlers.length > 0) {
  3147. this.handlers.push(this.addHandlers.pop());
  3148. } // handle graceful disconnect
  3149. if (this.disconnecting && this._proto._emptyQueue()) {
  3150. this._doDisconnect();
  3151. return;
  3152. }
  3153. const type = elem.getAttribute("type");
  3154. if (type !== null && type === "terminate") {
  3155. // Don't process stanzas that come in after disconnect
  3156. if (this.disconnecting) {
  3157. return;
  3158. } // an error occurred
  3159. let cond = elem.getAttribute("condition");
  3160. const conflict = elem.getElementsByTagName("conflict");
  3161. if (cond !== null) {
  3162. if (cond === "remote-stream-error" && conflict.length > 0) {
  3163. cond = "conflict";
  3164. }
  3165. this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  3166. } else {
  3167. this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.UNKOWN_REASON);
  3168. }
  3169. this._doDisconnect(cond);
  3170. return;
  3171. } // send each incoming stanza through the handler chain
  3172. Strophe.forEachChild(elem, null, child => {
  3173. const matches = [];
  3174. this.handlers = this.handlers.reduce((handlers, handler) => {
  3175. try {
  3176. if (handler.isMatch(child) && (this.authenticated || !handler.user)) {
  3177. if (handler.run(child)) {
  3178. handlers.push(handler);
  3179. }
  3180. matches.push(handler);
  3181. } else {
  3182. handlers.push(handler);
  3183. }
  3184. } catch (e) {
  3185. // if the handler throws an exception, we consider it as false
  3186. Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message);
  3187. }
  3188. return handlers;
  3189. }, []); // If no handler was fired for an incoming IQ with type="set",
  3190. // then we return an IQ error stanza with service-unavailable.
  3191. if (!matches.length && this.iqFallbackHandler.isMatch(child)) {
  3192. this.iqFallbackHandler.run(child);
  3193. }
  3194. });
  3195. }
  3196. /** PrivateFunction: _connect_cb
  3197. * _Private_ handler for initial connection request.
  3198. *
  3199. * This handler is used to process the initial connection request
  3200. * response from the BOSH server. It is used to set up authentication
  3201. * handlers and start the authentication process.
  3202. *
  3203. * SASL authentication will be attempted if available, otherwise
  3204. * the code will fall back to legacy authentication.
  3205. *
  3206. * Parameters:
  3207. * (Strophe.Request) req - The current request.
  3208. * (Function) _callback - low level (xmpp) connect callback function.
  3209. * Useful for plugins with their own xmpp connect callback (when they
  3210. * want to do something special).
  3211. */
  3212. _connect_cb(req, _callback, raw) {
  3213. Strophe.debug("_connect_cb was called");
  3214. this.connected = true;
  3215. let bodyWrap;
  3216. try {
  3217. bodyWrap = this._proto._reqToData(req);
  3218. } catch (e) {
  3219. if (e.name !== Strophe.ErrorCondition.BAD_FORMAT) {
  3220. throw e;
  3221. }
  3222. this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.BAD_FORMAT);
  3223. this._doDisconnect(Strophe.ErrorCondition.BAD_FORMAT);
  3224. }
  3225. if (!bodyWrap) {
  3226. return;
  3227. }
  3228. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  3229. if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
  3230. this.xmlInput(bodyWrap.childNodes[0]);
  3231. } else {
  3232. this.xmlInput(bodyWrap);
  3233. }
  3234. }
  3235. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  3236. if (raw) {
  3237. this.rawInput(raw);
  3238. } else {
  3239. this.rawInput(Strophe.serialize(bodyWrap));
  3240. }
  3241. }
  3242. const conncheck = this._proto._connect_cb(bodyWrap);
  3243. if (conncheck === Strophe.Status.CONNFAIL) {
  3244. return;
  3245. } // Check for the stream:features tag
  3246. let hasFeatures;
  3247. if (bodyWrap.getElementsByTagNameNS) {
  3248. hasFeatures = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "features").length > 0;
  3249. } else {
  3250. hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0 || bodyWrap.getElementsByTagName("features").length > 0;
  3251. }
  3252. if (!hasFeatures) {
  3253. this._proto._no_auth_received(_callback);
  3254. return;
  3255. }
  3256. const matched = Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m => this.mechanisms[m.textContent]).filter(m => m);
  3257. if (matched.length === 0) {
  3258. if (bodyWrap.getElementsByTagName("auth").length === 0) {
  3259. // There are no matching SASL mechanisms and also no legacy
  3260. // auth available.
  3261. this._proto._no_auth_received(_callback);
  3262. return;
  3263. }
  3264. }
  3265. if (this.do_authentication !== false) {
  3266. this.authenticate(matched);
  3267. }
  3268. }
  3269. /** Function: sortMechanismsByPriority
  3270. *
  3271. * Sorts an array of objects with prototype SASLMechanism according to
  3272. * their priorities.
  3273. *
  3274. * Parameters:
  3275. * (Array) mechanisms - Array of SASL mechanisms.
  3276. *
  3277. */
  3278. sortMechanismsByPriority(mechanisms) {
  3279. // eslint-disable-line class-methods-use-this
  3280. // Sorting mechanisms according to priority.
  3281. for (let i = 0; i < mechanisms.length - 1; ++i) {
  3282. let higher = i;
  3283. for (let j = i + 1; j < mechanisms.length; ++j) {
  3284. if (mechanisms[j].priority > mechanisms[higher].priority) {
  3285. higher = j;
  3286. }
  3287. }
  3288. if (higher !== i) {
  3289. const swap = mechanisms[i];
  3290. mechanisms[i] = mechanisms[higher];
  3291. mechanisms[higher] = swap;
  3292. }
  3293. }
  3294. return mechanisms;
  3295. }
  3296. /** Function: authenticate
  3297. * Set up authentication
  3298. *
  3299. * Continues the initial connection request by setting up authentication
  3300. * handlers and starting the authentication process.
  3301. *
  3302. * SASL authentication will be attempted if available, otherwise
  3303. * the code will fall back to legacy authentication.
  3304. *
  3305. * Parameters:
  3306. * (Array) matched - Array of SASL mechanisms supported.
  3307. *
  3308. */
  3309. authenticate(matched) {
  3310. if (!this._attemptSASLAuth(matched)) {
  3311. this._attemptLegacyAuth();
  3312. }
  3313. }
  3314. /** PrivateFunction: _attemptSASLAuth
  3315. *
  3316. * Iterate through an array of SASL mechanisms and attempt authentication
  3317. * with the highest priority (enabled) mechanism.
  3318. *
  3319. * Parameters:
  3320. * (Array) mechanisms - Array of SASL mechanisms.
  3321. *
  3322. * Returns:
  3323. * (Boolean) mechanism_found - true or false, depending on whether a
  3324. * valid SASL mechanism was found with which authentication could be
  3325. * started.
  3326. */
  3327. _attemptSASLAuth(mechanisms) {
  3328. mechanisms = this.sortMechanismsByPriority(mechanisms || []);
  3329. let mechanism_found = false;
  3330. for (let i = 0; i < mechanisms.length; ++i) {
  3331. if (!mechanisms[i].test(this)) {
  3332. continue;
  3333. }
  3334. this._sasl_success_handler = this._addSysHandler(this._sasl_success_cb.bind(this), null, "success", null, null);
  3335. this._sasl_failure_handler = this._addSysHandler(this._sasl_failure_cb.bind(this), null, "failure", null, null);
  3336. this._sasl_challenge_handler = this._addSysHandler(this._sasl_challenge_cb.bind(this), null, "challenge", null, null);
  3337. this._sasl_mechanism = mechanisms[i];
  3338. this._sasl_mechanism.onStart(this);
  3339. const request_auth_exchange = $build("auth", {
  3340. 'xmlns': Strophe.NS.SASL,
  3341. 'mechanism': this._sasl_mechanism.mechname
  3342. });
  3343. if (this._sasl_mechanism.isClientFirst) {
  3344. const response = this._sasl_mechanism.clientChallenge(this);
  3345. request_auth_exchange.t(btoa$1(response));
  3346. }
  3347. this.send(request_auth_exchange.tree());
  3348. mechanism_found = true;
  3349. break;
  3350. }
  3351. return mechanism_found;
  3352. }
  3353. /** PrivateFunction: _sasl_challenge_cb
  3354. * _Private_ handler for the SASL challenge
  3355. *
  3356. */
  3357. _sasl_challenge_cb(elem) {
  3358. const challenge = atob$1(Strophe.getText(elem));
  3359. const response = this._sasl_mechanism.onChallenge(this, challenge);
  3360. const stanza = $build('response', {
  3361. 'xmlns': Strophe.NS.SASL
  3362. });
  3363. if (response !== "") {
  3364. stanza.t(btoa$1(response));
  3365. }
  3366. this.send(stanza.tree());
  3367. return true;
  3368. }
  3369. /** PrivateFunction: _attemptLegacyAuth
  3370. *
  3371. * Attempt legacy (i.e. non-SASL) authentication.
  3372. */
  3373. _attemptLegacyAuth() {
  3374. if (Strophe.getNodeFromJid(this.jid) === null) {
  3375. // we don't have a node, which is required for non-anonymous
  3376. // client connections
  3377. this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.MISSING_JID_NODE);
  3378. this.disconnect(Strophe.ErrorCondition.MISSING_JID_NODE);
  3379. } else {
  3380. // Fall back to legacy authentication
  3381. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3382. this._addSysHandler(this._onLegacyAuthIQResult.bind(this), null, null, null, "_auth_1");
  3383. this.send($iq({
  3384. 'type': "get",
  3385. 'to': this.domain,
  3386. 'id': "_auth_1"
  3387. }).c("query", {
  3388. xmlns: Strophe.NS.AUTH
  3389. }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
  3390. }
  3391. }
  3392. /** PrivateFunction: _onLegacyAuthIQResult
  3393. * _Private_ handler for legacy authentication.
  3394. *
  3395. * This handler is called in response to the initial <iq type='get'/>
  3396. * for legacy authentication. It builds an authentication <iq/> and
  3397. * sends it, creating a handler (calling back to _auth2_cb()) to
  3398. * handle the result
  3399. *
  3400. * Parameters:
  3401. * (XMLElement) elem - The stanza that triggered the callback.
  3402. *
  3403. * Returns:
  3404. * false to remove the handler.
  3405. */
  3406. _onLegacyAuthIQResult(elem) {
  3407. // eslint-disable-line no-unused-vars
  3408. // build plaintext auth iq
  3409. const iq = $iq({
  3410. type: "set",
  3411. id: "_auth_2"
  3412. }).c('query', {
  3413. xmlns: Strophe.NS.AUTH
  3414. }).c('username', {}).t(Strophe.getNodeFromJid(this.jid)).up().c('password').t(this.pass);
  3415. if (!Strophe.getResourceFromJid(this.jid)) {
  3416. // since the user has not supplied a resource, we pick
  3417. // a default one here. unlike other auth methods, the server
  3418. // cannot do this for us.
  3419. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
  3420. }
  3421. iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
  3422. this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2");
  3423. this.send(iq.tree());
  3424. return false;
  3425. }
  3426. /** PrivateFunction: _sasl_success_cb
  3427. * _Private_ handler for succesful SASL authentication.
  3428. *
  3429. * Parameters:
  3430. * (XMLElement) elem - The matching stanza.
  3431. *
  3432. * Returns:
  3433. * false to remove the handler.
  3434. */
  3435. _sasl_success_cb(elem) {
  3436. if (this._sasl_data["server-signature"]) {
  3437. let serverSignature;
  3438. const success = atob$1(Strophe.getText(elem));
  3439. const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  3440. const matches = success.match(attribMatch);
  3441. if (matches[1] === "v") {
  3442. serverSignature = matches[2];
  3443. }
  3444. if (serverSignature !== this._sasl_data["server-signature"]) {
  3445. // remove old handlers
  3446. this.deleteHandler(this._sasl_failure_handler);
  3447. this._sasl_failure_handler = null;
  3448. if (this._sasl_challenge_handler) {
  3449. this.deleteHandler(this._sasl_challenge_handler);
  3450. this._sasl_challenge_handler = null;
  3451. }
  3452. this._sasl_data = {};
  3453. return this._sasl_failure_cb(null);
  3454. }
  3455. }
  3456. Strophe.info("SASL authentication succeeded.");
  3457. if (this._sasl_mechanism) {
  3458. this._sasl_mechanism.onSuccess();
  3459. } // remove old handlers
  3460. this.deleteHandler(this._sasl_failure_handler);
  3461. this._sasl_failure_handler = null;
  3462. if (this._sasl_challenge_handler) {
  3463. this.deleteHandler(this._sasl_challenge_handler);
  3464. this._sasl_challenge_handler = null;
  3465. }
  3466. const streamfeature_handlers = [];
  3467. const wrapper = (handlers, elem) => {
  3468. while (handlers.length) {
  3469. this.deleteHandler(handlers.pop());
  3470. }
  3471. this._onStreamFeaturesAfterSASL(elem);
  3472. return false;
  3473. };
  3474. streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), null, "stream:features", null, null));
  3475. streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), Strophe.NS.STREAM, "features", null, null)); // we must send an xmpp:restart now
  3476. this._sendRestart();
  3477. return false;
  3478. }
  3479. /** PrivateFunction: _onStreamFeaturesAfterSASL
  3480. * Parameters:
  3481. * (XMLElement) elem - The matching stanza.
  3482. *
  3483. * Returns:
  3484. * false to remove the handler.
  3485. */
  3486. _onStreamFeaturesAfterSASL(elem) {
  3487. // save stream:features for future usage
  3488. this.features = elem;
  3489. for (let i = 0; i < elem.childNodes.length; i++) {
  3490. const child = elem.childNodes[i];
  3491. if (child.nodeName === 'bind') {
  3492. this.do_bind = true;
  3493. }
  3494. if (child.nodeName === 'session') {
  3495. this.do_session = true;
  3496. }
  3497. }
  3498. if (!this.do_bind) {
  3499. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3500. return false;
  3501. } else if (!this.options.explicitResourceBinding) {
  3502. this.bind();
  3503. } else {
  3504. this._changeConnectStatus(Strophe.Status.BINDREQUIRED, null);
  3505. }
  3506. return false;
  3507. }
  3508. /** Function: bind
  3509. *
  3510. * Sends an IQ to the XMPP server to bind a JID resource for this session.
  3511. *
  3512. * https://tools.ietf.org/html/rfc6120#section-7.5
  3513. *
  3514. * If `explicitResourceBinding` was set to a truthy value in the options
  3515. * passed to the Strophe.Connection constructor, then this function needs
  3516. * to be called explicitly by the client author.
  3517. *
  3518. * Otherwise it'll be called automatically as soon as the XMPP server
  3519. * advertises the "urn:ietf:params:xml:ns:xmpp-bind" stream feature.
  3520. */
  3521. bind() {
  3522. if (!this.do_bind) {
  3523. Strophe.log(Strophe.LogLevel.INFO, `Strophe.Connection.prototype.bind called but "do_bind" is false`);
  3524. return;
  3525. }
  3526. this._addSysHandler(this._onResourceBindResultIQ.bind(this), null, null, null, "_bind_auth_2");
  3527. const resource = Strophe.getResourceFromJid(this.jid);
  3528. if (resource) {
  3529. this.send($iq({
  3530. type: "set",
  3531. id: "_bind_auth_2"
  3532. }).c('bind', {
  3533. xmlns: Strophe.NS.BIND
  3534. }).c('resource', {}).t(resource).tree());
  3535. } else {
  3536. this.send($iq({
  3537. type: "set",
  3538. id: "_bind_auth_2"
  3539. }).c('bind', {
  3540. xmlns: Strophe.NS.BIND
  3541. }).tree());
  3542. }
  3543. }
  3544. /** PrivateFunction: _onResourceBindIQ
  3545. * _Private_ handler for binding result and session start.
  3546. *
  3547. * Parameters:
  3548. * (XMLElement) elem - The matching stanza.
  3549. *
  3550. * Returns:
  3551. * false to remove the handler.
  3552. */
  3553. _onResourceBindResultIQ(elem) {
  3554. if (elem.getAttribute("type") === "error") {
  3555. Strophe.warn("Resource binding failed.");
  3556. const conflict = elem.getElementsByTagName("conflict");
  3557. let condition;
  3558. if (conflict.length > 0) {
  3559. condition = Strophe.ErrorCondition.CONFLICT;
  3560. }
  3561. this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition, elem);
  3562. return false;
  3563. } // TODO - need to grab errors
  3564. const bind = elem.getElementsByTagName("bind");
  3565. if (bind.length > 0) {
  3566. const jidNode = bind[0].getElementsByTagName("jid");
  3567. if (jidNode.length > 0) {
  3568. this.authenticated = true;
  3569. this.jid = Strophe.getText(jidNode[0]);
  3570. if (this.do_session) {
  3571. this._establishSession();
  3572. } else {
  3573. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3574. }
  3575. }
  3576. } else {
  3577. Strophe.warn("Resource binding failed.");
  3578. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
  3579. return false;
  3580. }
  3581. }
  3582. /** PrivateFunction: _establishSession
  3583. * Send IQ request to establish a session with the XMPP server.
  3584. *
  3585. * See https://xmpp.org/rfcs/rfc3921.html#session
  3586. *
  3587. * Note: The protocol for session establishment has been determined as
  3588. * unnecessary and removed in RFC-6121.
  3589. */
  3590. _establishSession() {
  3591. if (!this.do_session) {
  3592. throw new Error(`Strophe.Connection.prototype._establishSession ` + `called but apparently ${Strophe.NS.SESSION} wasn't advertised by the server`);
  3593. }
  3594. this._addSysHandler(this._onSessionResultIQ.bind(this), null, null, null, "_session_auth_2");
  3595. this.send($iq({
  3596. type: "set",
  3597. id: "_session_auth_2"
  3598. }).c('session', {
  3599. xmlns: Strophe.NS.SESSION
  3600. }).tree());
  3601. }
  3602. /** PrivateFunction: _onSessionResultIQ
  3603. * _Private_ handler for the server's IQ response to a client's session
  3604. * request.
  3605. *
  3606. * This sets Connection.authenticated to true on success, which
  3607. * starts the processing of user handlers.
  3608. *
  3609. * See https://xmpp.org/rfcs/rfc3921.html#session
  3610. *
  3611. * Note: The protocol for session establishment has been determined as
  3612. * unnecessary and removed in RFC-6121.
  3613. *
  3614. * Parameters:
  3615. * (XMLElement) elem - The matching stanza.
  3616. *
  3617. * Returns:
  3618. * false to remove the handler.
  3619. */
  3620. _onSessionResultIQ(elem) {
  3621. if (elem.getAttribute("type") === "result") {
  3622. this.authenticated = true;
  3623. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3624. } else if (elem.getAttribute("type") === "error") {
  3625. this.authenticated = false;
  3626. Strophe.warn("Session creation failed.");
  3627. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
  3628. return false;
  3629. }
  3630. return false;
  3631. }
  3632. /** PrivateFunction: _sasl_failure_cb
  3633. * _Private_ handler for SASL authentication failure.
  3634. *
  3635. * Parameters:
  3636. * (XMLElement) elem - The matching stanza.
  3637. *
  3638. * Returns:
  3639. * false to remove the handler.
  3640. */
  3641. _sasl_failure_cb(elem) {
  3642. // delete unneeded handlers
  3643. if (this._sasl_success_handler) {
  3644. this.deleteHandler(this._sasl_success_handler);
  3645. this._sasl_success_handler = null;
  3646. }
  3647. if (this._sasl_challenge_handler) {
  3648. this.deleteHandler(this._sasl_challenge_handler);
  3649. this._sasl_challenge_handler = null;
  3650. }
  3651. if (this._sasl_mechanism) this._sasl_mechanism.onFailure();
  3652. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
  3653. return false;
  3654. }
  3655. /** PrivateFunction: _auth2_cb
  3656. * _Private_ handler to finish legacy authentication.
  3657. *
  3658. * This handler is called when the result from the jabber:iq:auth
  3659. * <iq/> stanza is returned.
  3660. *
  3661. * Parameters:
  3662. * (XMLElement) elem - The stanza that triggered the callback.
  3663. *
  3664. * Returns:
  3665. * false to remove the handler.
  3666. */
  3667. _auth2_cb(elem) {
  3668. if (elem.getAttribute("type") === "result") {
  3669. this.authenticated = true;
  3670. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3671. } else if (elem.getAttribute("type") === "error") {
  3672. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);
  3673. this.disconnect('authentication failed');
  3674. }
  3675. return false;
  3676. }
  3677. /** PrivateFunction: _addSysTimedHandler
  3678. * _Private_ function to add a system level timed handler.
  3679. *
  3680. * This function is used to add a Strophe.TimedHandler for the
  3681. * library code. System timed handlers are allowed to run before
  3682. * authentication is complete.
  3683. *
  3684. * Parameters:
  3685. * (Integer) period - The period of the handler.
  3686. * (Function) handler - The callback function.
  3687. */
  3688. _addSysTimedHandler(period, handler) {
  3689. const thand = new Strophe.TimedHandler(period, handler);
  3690. thand.user = false;
  3691. this.addTimeds.push(thand);
  3692. return thand;
  3693. }
  3694. /** PrivateFunction: _addSysHandler
  3695. * _Private_ function to add a system level stanza handler.
  3696. *
  3697. * This function is used to add a Strophe.Handler for the
  3698. * library code. System stanza handlers are allowed to run before
  3699. * authentication is complete.
  3700. *
  3701. * Parameters:
  3702. * (Function) handler - The callback function.
  3703. * (String) ns - The namespace to match.
  3704. * (String) name - The stanza name to match.
  3705. * (String) type - The stanza type attribute to match.
  3706. * (String) id - The stanza id attribute to match.
  3707. */
  3708. _addSysHandler(handler, ns, name, type, id) {
  3709. const hand = new Strophe.Handler(handler, ns, name, type, id);
  3710. hand.user = false;
  3711. this.addHandlers.push(hand);
  3712. return hand;
  3713. }
  3714. /** PrivateFunction: _onDisconnectTimeout
  3715. * _Private_ timeout handler for handling non-graceful disconnection.
  3716. *
  3717. * If the graceful disconnect process does not complete within the
  3718. * time allotted, this handler finishes the disconnect anyway.
  3719. *
  3720. * Returns:
  3721. * false to remove the handler.
  3722. */
  3723. _onDisconnectTimeout() {
  3724. Strophe.debug("_onDisconnectTimeout was called");
  3725. this._changeConnectStatus(Strophe.Status.CONNTIMEOUT, null);
  3726. this._proto._onDisconnectTimeout(); // actually disconnect
  3727. this._doDisconnect();
  3728. return false;
  3729. }
  3730. /** PrivateFunction: _onIdle
  3731. * _Private_ handler to process events during idle cycle.
  3732. *
  3733. * This handler is called every 100ms to fire timed handlers that
  3734. * are ready and keep poll requests going.
  3735. */
  3736. _onIdle() {
  3737. // add timed handlers scheduled for addition
  3738. // NOTE: we add before remove in the case a timed handler is
  3739. // added and then deleted before the next _onIdle() call.
  3740. while (this.addTimeds.length > 0) {
  3741. this.timedHandlers.push(this.addTimeds.pop());
  3742. } // remove timed handlers that have been scheduled for deletion
  3743. while (this.removeTimeds.length > 0) {
  3744. const thand = this.removeTimeds.pop();
  3745. const i = this.timedHandlers.indexOf(thand);
  3746. if (i >= 0) {
  3747. this.timedHandlers.splice(i, 1);
  3748. }
  3749. } // call ready timed handlers
  3750. const now = new Date().getTime();
  3751. const newList = [];
  3752. for (let i = 0; i < this.timedHandlers.length; i++) {
  3753. const thand = this.timedHandlers[i];
  3754. if (this.authenticated || !thand.user) {
  3755. const since = thand.lastCalled + thand.period;
  3756. if (since - now <= 0) {
  3757. if (thand.run()) {
  3758. newList.push(thand);
  3759. }
  3760. } else {
  3761. newList.push(thand);
  3762. }
  3763. }
  3764. }
  3765. this.timedHandlers = newList;
  3766. clearTimeout(this._idleTimeout);
  3767. this._proto._onIdle(); // reactivate the timer only if connected
  3768. if (this.connected) {
  3769. this._idleTimeout = setTimeout(() => this._onIdle(), 100);
  3770. }
  3771. }
  3772. };
  3773. Strophe.SASLMechanism = SASLMechanism;
  3774. /** Constants: SASL mechanisms
  3775. * Available authentication mechanisms
  3776. *
  3777. * Strophe.SASLAnonymous - SASL ANONYMOUS authentication.
  3778. * Strophe.SASLPlain - SASL PLAIN authentication.
  3779. * Strophe.SASLSHA1 - SASL SCRAM-SHA-1 authentication
  3780. * Strophe.SASLOAuthBearer - SASL OAuth Bearer authentication
  3781. * Strophe.SASLExternal - SASL EXTERNAL authentication
  3782. * Strophe.SASLXOAuth2 - SASL X-OAuth2 authentication
  3783. */
  3784. Strophe.SASLAnonymous = SASLAnonymous;
  3785. Strophe.SASLPlain = SASLPlain;
  3786. Strophe.SASLSHA1 = SASLSHA1;
  3787. Strophe.SASLOAuthBearer = SASLOAuthBearer;
  3788. Strophe.SASLExternal = SASLExternal;
  3789. Strophe.SASLXOAuth2 = SASLXOAuth2;
  3790. var core = {
  3791. 'Strophe': Strophe,
  3792. '$build': $build,
  3793. '$iq': $iq,
  3794. '$msg': $msg,
  3795. '$pres': $pres,
  3796. 'SHA1': SHA1,
  3797. 'MD5': MD5,
  3798. 'b64_hmac_sha1': SHA1.b64_hmac_sha1,
  3799. 'b64_sha1': SHA1.b64_sha1,
  3800. 'str_hmac_sha1': SHA1.str_hmac_sha1,
  3801. 'str_sha1': SHA1.str_sha1
  3802. };
  3803. /*
  3804. This program is distributed under the terms of the MIT license.
  3805. Please see the LICENSE file for details.
  3806. Copyright 2006-2008, OGG, LLC
  3807. */
  3808. /** PrivateClass: Strophe.Request
  3809. * _Private_ helper class that provides a cross implementation abstraction
  3810. * for a BOSH related XMLHttpRequest.
  3811. *
  3812. * The Strophe.Request class is used internally to encapsulate BOSH request
  3813. * information. It is not meant to be used from user's code.
  3814. */
  3815. Strophe.Request = class Request {
  3816. /** PrivateConstructor: Strophe.Request
  3817. * Create and initialize a new Strophe.Request object.
  3818. *
  3819. * Parameters:
  3820. * (XMLElement) elem - The XML data to be sent in the request.
  3821. * (Function) func - The function that will be called when the
  3822. * XMLHttpRequest readyState changes.
  3823. * (Integer) rid - The BOSH rid attribute associated with this request.
  3824. * (Integer) sends - The number of times this same request has been sent.
  3825. */
  3826. constructor(elem, func, rid, sends) {
  3827. this.id = ++Strophe._requestId;
  3828. this.xmlData = elem;
  3829. this.data = Strophe.serialize(elem); // save original function in case we need to make a new request
  3830. // from this one.
  3831. this.origFunc = func;
  3832. this.func = func;
  3833. this.rid = rid;
  3834. this.date = NaN;
  3835. this.sends = sends || 0;
  3836. this.abort = false;
  3837. this.dead = null;
  3838. this.age = function () {
  3839. if (!this.date) {
  3840. return 0;
  3841. }
  3842. const now = new Date();
  3843. return (now - this.date) / 1000;
  3844. };
  3845. this.timeDead = function () {
  3846. if (!this.dead) {
  3847. return 0;
  3848. }
  3849. const now = new Date();
  3850. return (now - this.dead) / 1000;
  3851. };
  3852. this.xhr = this._newXHR();
  3853. }
  3854. /** PrivateFunction: getResponse
  3855. * Get a response from the underlying XMLHttpRequest.
  3856. *
  3857. * This function attempts to get a response from the request and checks
  3858. * for errors.
  3859. *
  3860. * Throws:
  3861. * "parsererror" - A parser error occured.
  3862. * "bad-format" - The entity has sent XML that cannot be processed.
  3863. *
  3864. * Returns:
  3865. * The DOM element tree of the response.
  3866. */
  3867. getResponse() {
  3868. let node = null;
  3869. if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
  3870. node = this.xhr.responseXML.documentElement;
  3871. if (node.tagName === "parsererror") {
  3872. Strophe.error("invalid response received");
  3873. Strophe.error("responseText: " + this.xhr.responseText);
  3874. Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML));
  3875. throw new Error("parsererror");
  3876. }
  3877. } else if (this.xhr.responseText) {
  3878. // In React Native, we may get responseText but no responseXML. We can try to parse it manually.
  3879. Strophe.debug("Got responseText but no responseXML; attempting to parse it with DOMParser...");
  3880. node = new DOMParser().parseFromString(this.xhr.responseText, 'application/xml').documentElement;
  3881. if (!node) {
  3882. throw new Error('Parsing produced null node');
  3883. } else if (node.querySelector('parsererror')) {
  3884. Strophe.error("invalid response received: " + node.querySelector('parsererror').textContent);
  3885. Strophe.error("responseText: " + this.xhr.responseText);
  3886. const error = new Error();
  3887. error.name = Strophe.ErrorCondition.BAD_FORMAT;
  3888. throw error;
  3889. }
  3890. }
  3891. return node;
  3892. }
  3893. /** PrivateFunction: _newXHR
  3894. * _Private_ helper function to create XMLHttpRequests.
  3895. *
  3896. * This function creates XMLHttpRequests across all implementations.
  3897. *
  3898. * Returns:
  3899. * A new XMLHttpRequest.
  3900. */
  3901. _newXHR() {
  3902. let xhr = null;
  3903. if (window.XMLHttpRequest) {
  3904. xhr = new XMLHttpRequest();
  3905. if (xhr.overrideMimeType) {
  3906. xhr.overrideMimeType("text/xml; charset=utf-8");
  3907. }
  3908. } else if (window.ActiveXObject) {
  3909. xhr = new ActiveXObject("Microsoft.XMLHTTP");
  3910. } // use Function.bind() to prepend ourselves as an argument
  3911. xhr.onreadystatechange = this.func.bind(null, this);
  3912. return xhr;
  3913. }
  3914. };
  3915. /** Class: Strophe.Bosh
  3916. * _Private_ helper class that handles BOSH Connections
  3917. *
  3918. * The Strophe.Bosh class is used internally by Strophe.Connection
  3919. * to encapsulate BOSH sessions. It is not meant to be used from user's code.
  3920. */
  3921. /** File: bosh.js
  3922. * A JavaScript library to enable BOSH in Strophejs.
  3923. *
  3924. * this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
  3925. * to emulate a persistent, stateful, two-way connection to an XMPP server.
  3926. * More information on BOSH can be found in XEP 124.
  3927. */
  3928. /** PrivateConstructor: Strophe.Bosh
  3929. * Create and initialize a Strophe.Bosh object.
  3930. *
  3931. * Parameters:
  3932. * (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
  3933. *
  3934. * Returns:
  3935. * A new Strophe.Bosh object.
  3936. */
  3937. Strophe.Bosh = class Bosh {
  3938. constructor(connection) {
  3939. this._conn = connection;
  3940. /* request id for body tags */
  3941. this.rid = Math.floor(Math.random() * 4294967295);
  3942. /* The current session ID. */
  3943. this.sid = null; // default BOSH values
  3944. this.hold = 1;
  3945. this.wait = 60;
  3946. this.window = 5;
  3947. this.errors = 0;
  3948. this.inactivity = null;
  3949. this.lastResponseHeaders = null;
  3950. this._requests = [];
  3951. }
  3952. /** PrivateFunction: _buildBody
  3953. * _Private_ helper function to generate the <body/> wrapper for BOSH.
  3954. *
  3955. * Returns:
  3956. * A Strophe.Builder with a <body/> element.
  3957. */
  3958. _buildBody() {
  3959. const bodyWrap = $build('body', {
  3960. 'rid': this.rid++,
  3961. 'xmlns': Strophe.NS.HTTPBIND
  3962. });
  3963. if (this.sid !== null) {
  3964. bodyWrap.attrs({
  3965. 'sid': this.sid
  3966. });
  3967. }
  3968. if (this._conn.options.keepalive && this._conn._sessionCachingSupported()) {
  3969. this._cacheSession();
  3970. }
  3971. return bodyWrap;
  3972. }
  3973. /** PrivateFunction: _reset
  3974. * Reset the connection.
  3975. *
  3976. * This function is called by the reset function of the Strophe Connection
  3977. */
  3978. _reset() {
  3979. this.rid = Math.floor(Math.random() * 4294967295);
  3980. this.sid = null;
  3981. this.errors = 0;
  3982. if (this._conn._sessionCachingSupported()) {
  3983. window.sessionStorage.removeItem('strophe-bosh-session');
  3984. }
  3985. this._conn.nextValidRid(this.rid);
  3986. }
  3987. /** PrivateFunction: _connect
  3988. * _Private_ function that initializes the BOSH connection.
  3989. *
  3990. * Creates and sends the Request that initializes the BOSH connection.
  3991. */
  3992. _connect(wait, hold, route) {
  3993. this.wait = wait || this.wait;
  3994. this.hold = hold || this.hold;
  3995. this.errors = 0;
  3996. const body = this._buildBody().attrs({
  3997. "to": this._conn.domain,
  3998. "xml:lang": "en",
  3999. "wait": this.wait,
  4000. "hold": this.hold,
  4001. "content": "text/xml; charset=utf-8",
  4002. "ver": "1.6",
  4003. "xmpp:version": "1.0",
  4004. "xmlns:xmpp": Strophe.NS.BOSH
  4005. });
  4006. if (route) {
  4007. body.attrs({
  4008. 'route': route
  4009. });
  4010. }
  4011. const _connect_cb = this._conn._connect_cb;
  4012. this._requests.push(new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, _connect_cb.bind(this._conn)), body.tree().getAttribute("rid")));
  4013. this._throttledRequestHandler();
  4014. }
  4015. /** PrivateFunction: _attach
  4016. * Attach to an already created and authenticated BOSH session.
  4017. *
  4018. * This function is provided to allow Strophe to attach to BOSH
  4019. * sessions which have been created externally, perhaps by a Web
  4020. * application. This is often used to support auto-login type features
  4021. * without putting user credentials into the page.
  4022. *
  4023. * Parameters:
  4024. * (String) jid - The full JID that is bound by the session.
  4025. * (String) sid - The SID of the BOSH session.
  4026. * (String) rid - The current RID of the BOSH session. This RID
  4027. * will be used by the next request.
  4028. * (Function) callback The connect callback function.
  4029. * (Integer) wait - The optional HTTPBIND wait value. This is the
  4030. * time the server will wait before returning an empty result for
  4031. * a request. The default setting of 60 seconds is recommended.
  4032. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  4033. * (Integer) hold - The optional HTTPBIND hold value. This is the
  4034. * number of connections the server will hold at one time. This
  4035. * should almost always be set to 1 (the default).
  4036. * (Integer) wind - The optional HTTBIND window value. This is the
  4037. * allowed range of request ids that are valid. The default is 5.
  4038. */
  4039. _attach(jid, sid, rid, callback, wait, hold, wind) {
  4040. this._conn.jid = jid;
  4041. this.sid = sid;
  4042. this.rid = rid;
  4043. this._conn.connect_callback = callback;
  4044. this._conn.domain = Strophe.getDomainFromJid(this._conn.jid);
  4045. this._conn.authenticated = true;
  4046. this._conn.connected = true;
  4047. this.wait = wait || this.wait;
  4048. this.hold = hold || this.hold;
  4049. this.window = wind || this.window;
  4050. this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null);
  4051. }
  4052. /** PrivateFunction: _restore
  4053. * Attempt to restore a cached BOSH session
  4054. *
  4055. * Parameters:
  4056. * (String) jid - The full JID that is bound by the session.
  4057. * This parameter is optional but recommended, specifically in cases
  4058. * where prebinded BOSH sessions are used where it's important to know
  4059. * that the right session is being restored.
  4060. * (Function) callback The connect callback function.
  4061. * (Integer) wait - The optional HTTPBIND wait value. This is the
  4062. * time the server will wait before returning an empty result for
  4063. * a request. The default setting of 60 seconds is recommended.
  4064. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  4065. * (Integer) hold - The optional HTTPBIND hold value. This is the
  4066. * number of connections the server will hold at one time. This
  4067. * should almost always be set to 1 (the default).
  4068. * (Integer) wind - The optional HTTBIND window value. This is the
  4069. * allowed range of request ids that are valid. The default is 5.
  4070. */
  4071. _restore(jid, callback, wait, hold, wind) {
  4072. const session = JSON.parse(window.sessionStorage.getItem('strophe-bosh-session'));
  4073. if (typeof session !== "undefined" && session !== null && session.rid && session.sid && session.jid && (typeof jid === "undefined" || jid === null || Strophe.getBareJidFromJid(session.jid) === Strophe.getBareJidFromJid(jid) || // If authcid is null, then it's an anonymous login, so
  4074. // we compare only the domains:
  4075. Strophe.getNodeFromJid(jid) === null && Strophe.getDomainFromJid(session.jid) === jid)) {
  4076. this._conn.restored = true;
  4077. this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
  4078. } else {
  4079. const error = new Error("_restore: no restoreable session.");
  4080. error.name = "StropheSessionError";
  4081. throw error;
  4082. }
  4083. }
  4084. /** PrivateFunction: _cacheSession
  4085. * _Private_ handler for the beforeunload event.
  4086. *
  4087. * This handler is used to process the Bosh-part of the initial request.
  4088. * Parameters:
  4089. * (Strophe.Request) bodyWrap - The received stanza.
  4090. */
  4091. _cacheSession() {
  4092. if (this._conn.authenticated) {
  4093. if (this._conn.jid && this.rid && this.sid) {
  4094. window.sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
  4095. 'jid': this._conn.jid,
  4096. 'rid': this.rid,
  4097. 'sid': this.sid
  4098. }));
  4099. }
  4100. } else {
  4101. window.sessionStorage.removeItem('strophe-bosh-session');
  4102. }
  4103. }
  4104. /** PrivateFunction: _connect_cb
  4105. * _Private_ handler for initial connection request.
  4106. *
  4107. * This handler is used to process the Bosh-part of the initial request.
  4108. * Parameters:
  4109. * (Strophe.Request) bodyWrap - The received stanza.
  4110. */
  4111. _connect_cb(bodyWrap) {
  4112. const typ = bodyWrap.getAttribute("type");
  4113. if (typ !== null && typ === "terminate") {
  4114. // an error occurred
  4115. let cond = bodyWrap.getAttribute("condition");
  4116. Strophe.error("BOSH-Connection failed: " + cond);
  4117. const conflict = bodyWrap.getElementsByTagName("conflict");
  4118. if (cond !== null) {
  4119. if (cond === "remote-stream-error" && conflict.length > 0) {
  4120. cond = "conflict";
  4121. }
  4122. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  4123. } else {
  4124. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
  4125. }
  4126. this._conn._doDisconnect(cond);
  4127. return Strophe.Status.CONNFAIL;
  4128. } // check to make sure we don't overwrite these if _connect_cb is
  4129. // called multiple times in the case of missing stream:features
  4130. if (!this.sid) {
  4131. this.sid = bodyWrap.getAttribute("sid");
  4132. }
  4133. const wind = bodyWrap.getAttribute('requests');
  4134. if (wind) {
  4135. this.window = parseInt(wind, 10);
  4136. }
  4137. const hold = bodyWrap.getAttribute('hold');
  4138. if (hold) {
  4139. this.hold = parseInt(hold, 10);
  4140. }
  4141. const wait = bodyWrap.getAttribute('wait');
  4142. if (wait) {
  4143. this.wait = parseInt(wait, 10);
  4144. }
  4145. const inactivity = bodyWrap.getAttribute('inactivity');
  4146. if (inactivity) {
  4147. this.inactivity = parseInt(inactivity, 10);
  4148. }
  4149. }
  4150. /** PrivateFunction: _disconnect
  4151. * _Private_ part of Connection.disconnect for Bosh
  4152. *
  4153. * Parameters:
  4154. * (Request) pres - This stanza will be sent before disconnecting.
  4155. */
  4156. _disconnect(pres) {
  4157. this._sendTerminate(pres);
  4158. }
  4159. /** PrivateFunction: _doDisconnect
  4160. * _Private_ function to disconnect.
  4161. *
  4162. * Resets the SID and RID.
  4163. */
  4164. _doDisconnect() {
  4165. this.sid = null;
  4166. this.rid = Math.floor(Math.random() * 4294967295);
  4167. if (this._conn._sessionCachingSupported()) {
  4168. window.sessionStorage.removeItem('strophe-bosh-session');
  4169. }
  4170. this._conn.nextValidRid(this.rid);
  4171. }
  4172. /** PrivateFunction: _emptyQueue
  4173. * _Private_ function to check if the Request queue is empty.
  4174. *
  4175. * Returns:
  4176. * True, if there are no Requests queued, False otherwise.
  4177. */
  4178. _emptyQueue() {
  4179. return this._requests.length === 0;
  4180. }
  4181. /** PrivateFunction: _callProtocolErrorHandlers
  4182. * _Private_ function to call error handlers registered for HTTP errors.
  4183. *
  4184. * Parameters:
  4185. * (Strophe.Request) req - The request that is changing readyState.
  4186. */
  4187. _callProtocolErrorHandlers(req) {
  4188. const reqStatus = Bosh._getRequestStatus(req);
  4189. const err_callback = this._conn.protocolErrorHandlers.HTTP[reqStatus];
  4190. if (err_callback) {
  4191. err_callback.call(this, reqStatus);
  4192. }
  4193. }
  4194. /** PrivateFunction: _hitError
  4195. * _Private_ function to handle the error count.
  4196. *
  4197. * Requests are resent automatically until their error count reaches
  4198. * 5. Each time an error is encountered, this function is called to
  4199. * increment the count and disconnect if the count is too high.
  4200. *
  4201. * Parameters:
  4202. * (Integer) reqStatus - The request status.
  4203. */
  4204. _hitError(reqStatus) {
  4205. this.errors++;
  4206. Strophe.warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors);
  4207. if (this.errors > 4) {
  4208. this._conn._onDisconnectTimeout();
  4209. }
  4210. }
  4211. /** PrivateFunction: _no_auth_received
  4212. *
  4213. * Called on stream start/restart when no stream:features
  4214. * has been received and sends a blank poll request.
  4215. */
  4216. _no_auth_received(callback) {
  4217. Strophe.warn("Server did not yet offer a supported authentication " + "mechanism. Sending a blank poll request.");
  4218. if (callback) {
  4219. callback = callback.bind(this._conn);
  4220. } else {
  4221. callback = this._conn._connect_cb.bind(this._conn);
  4222. }
  4223. const body = this._buildBody();
  4224. this._requests.push(new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, callback), body.tree().getAttribute("rid")));
  4225. this._throttledRequestHandler();
  4226. }
  4227. /** PrivateFunction: _onDisconnectTimeout
  4228. * _Private_ timeout handler for handling non-graceful disconnection.
  4229. *
  4230. * Cancels all remaining Requests and clears the queue.
  4231. */
  4232. _onDisconnectTimeout() {
  4233. this._abortAllRequests();
  4234. }
  4235. /** PrivateFunction: _abortAllRequests
  4236. * _Private_ helper function that makes sure all pending requests are aborted.
  4237. */
  4238. _abortAllRequests() {
  4239. while (this._requests.length > 0) {
  4240. const req = this._requests.pop();
  4241. req.abort = true;
  4242. req.xhr.abort();
  4243. req.xhr.onreadystatechange = function () {};
  4244. }
  4245. }
  4246. /** PrivateFunction: _onIdle
  4247. * _Private_ handler called by Strophe.Connection._onIdle
  4248. *
  4249. * Sends all queued Requests or polls with empty Request if there are none.
  4250. */
  4251. _onIdle() {
  4252. const data = this._conn._data; // if no requests are in progress, poll
  4253. if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) {
  4254. Strophe.debug("no requests during idle cycle, sending blank request");
  4255. data.push(null);
  4256. }
  4257. if (this._conn.paused) {
  4258. return;
  4259. }
  4260. if (this._requests.length < 2 && data.length > 0) {
  4261. const body = this._buildBody();
  4262. for (let i = 0; i < data.length; i++) {
  4263. if (data[i] !== null) {
  4264. if (data[i] === "restart") {
  4265. body.attrs({
  4266. "to": this._conn.domain,
  4267. "xml:lang": "en",
  4268. "xmpp:restart": "true",
  4269. "xmlns:xmpp": Strophe.NS.BOSH
  4270. });
  4271. } else {
  4272. body.cnode(data[i]).up();
  4273. }
  4274. }
  4275. }
  4276. delete this._conn._data;
  4277. this._conn._data = [];
  4278. this._requests.push(new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid")));
  4279. this._throttledRequestHandler();
  4280. }
  4281. if (this._requests.length > 0) {
  4282. const time_elapsed = this._requests[0].age();
  4283. if (this._requests[0].dead !== null) {
  4284. if (this._requests[0].timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
  4285. this._throttledRequestHandler();
  4286. }
  4287. }
  4288. if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
  4289. Strophe.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) + " seconds since last activity");
  4290. this._throttledRequestHandler();
  4291. }
  4292. }
  4293. }
  4294. /** PrivateFunction: _getRequestStatus
  4295. *
  4296. * Returns the HTTP status code from a Strophe.Request
  4297. *
  4298. * Parameters:
  4299. * (Strophe.Request) req - The Strophe.Request instance.
  4300. * (Integer) def - The default value that should be returned if no
  4301. * status value was found.
  4302. */
  4303. static _getRequestStatus(req, def) {
  4304. let reqStatus;
  4305. if (req.xhr.readyState === 4) {
  4306. try {
  4307. reqStatus = req.xhr.status;
  4308. } catch (e) {
  4309. // ignore errors from undefined status attribute. Works
  4310. // around a browser bug
  4311. Strophe.error("Caught an error while retrieving a request's status, " + "reqStatus: " + reqStatus);
  4312. }
  4313. }
  4314. if (typeof reqStatus === "undefined") {
  4315. reqStatus = typeof def === 'number' ? def : 0;
  4316. }
  4317. return reqStatus;
  4318. }
  4319. /** PrivateFunction: _onRequestStateChange
  4320. * _Private_ handler for Strophe.Request state changes.
  4321. *
  4322. * This function is called when the XMLHttpRequest readyState changes.
  4323. * It contains a lot of error handling logic for the many ways that
  4324. * requests can fail, and calls the request callback when requests
  4325. * succeed.
  4326. *
  4327. * Parameters:
  4328. * (Function) func - The handler for the request.
  4329. * (Strophe.Request) req - The request that is changing readyState.
  4330. */
  4331. _onRequestStateChange(func, req) {
  4332. Strophe.debug("request id " + req.id + "." + req.sends + " state changed to " + req.xhr.readyState);
  4333. if (req.abort) {
  4334. req.abort = false;
  4335. return;
  4336. }
  4337. if (req.xhr.readyState !== 4) {
  4338. // The request is not yet complete
  4339. return;
  4340. }
  4341. const reqStatus = Bosh._getRequestStatus(req);
  4342. this.lastResponseHeaders = req.xhr.getAllResponseHeaders();
  4343. if (this._conn.disconnecting && reqStatus >= 400) {
  4344. this._hitError(reqStatus);
  4345. this._callProtocolErrorHandlers(req);
  4346. return;
  4347. }
  4348. const reqIs0 = this._requests[0] === req;
  4349. const reqIs1 = this._requests[1] === req;
  4350. const valid_request = reqStatus > 0 && reqStatus < 500;
  4351. const too_many_retries = req.sends > this._conn.maxRetries;
  4352. if (valid_request || too_many_retries) {
  4353. // remove from internal queue
  4354. this._removeRequest(req);
  4355. Strophe.debug("request id " + req.id + " should now be removed");
  4356. }
  4357. if (reqStatus === 200) {
  4358. // request succeeded
  4359. // if request 1 finished, or request 0 finished and request
  4360. // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
  4361. // restart the other - both will be in the first spot, as the
  4362. // completed request has been removed from the queue already
  4363. if (reqIs1 || reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
  4364. this._restartRequest(0);
  4365. }
  4366. this._conn.nextValidRid(Number(req.rid) + 1);
  4367. Strophe.debug("request id " + req.id + "." + req.sends + " got 200");
  4368. func(req); // call handler
  4369. this.errors = 0;
  4370. } else if (reqStatus === 0 || reqStatus >= 400 && reqStatus < 600 || reqStatus >= 12000) {
  4371. // request failed
  4372. Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened");
  4373. this._hitError(reqStatus);
  4374. this._callProtocolErrorHandlers(req);
  4375. if (reqStatus >= 400 && reqStatus < 500) {
  4376. this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null);
  4377. this._conn._doDisconnect();
  4378. }
  4379. } else {
  4380. Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened");
  4381. }
  4382. if (!valid_request && !too_many_retries) {
  4383. this._throttledRequestHandler();
  4384. } else if (too_many_retries && !this._conn.connected) {
  4385. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "giving-up");
  4386. }
  4387. }
  4388. /** PrivateFunction: _processRequest
  4389. * _Private_ function to process a request in the queue.
  4390. *
  4391. * This function takes requests off the queue and sends them and
  4392. * restarts dead requests.
  4393. *
  4394. * Parameters:
  4395. * (Integer) i - The index of the request in the queue.
  4396. */
  4397. _processRequest(i) {
  4398. let req = this._requests[i];
  4399. const reqStatus = Bosh._getRequestStatus(req, -1); // make sure we limit the number of retries
  4400. if (req.sends > this._conn.maxRetries) {
  4401. this._conn._onDisconnectTimeout();
  4402. return;
  4403. }
  4404. const time_elapsed = req.age();
  4405. const primary_timeout = !isNaN(time_elapsed) && time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait);
  4406. const secondary_timeout = req.dead !== null && req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait);
  4407. const server_error = req.xhr.readyState === 4 && (reqStatus < 1 || reqStatus >= 500);
  4408. if (primary_timeout || secondary_timeout || server_error) {
  4409. if (secondary_timeout) {
  4410. Strophe.error(`Request ${this._requests[i].id} timed out (secondary), restarting`);
  4411. }
  4412. req.abort = true;
  4413. req.xhr.abort(); // setting to null fails on IE6, so set to empty function
  4414. req.xhr.onreadystatechange = function () {};
  4415. this._requests[i] = new Strophe.Request(req.xmlData, req.origFunc, req.rid, req.sends);
  4416. req = this._requests[i];
  4417. }
  4418. if (req.xhr.readyState === 0) {
  4419. Strophe.debug("request id " + req.id + "." + req.sends + " posting");
  4420. try {
  4421. const content_type = this._conn.options.contentType || "text/xml; charset=utf-8";
  4422. req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);
  4423. if (typeof req.xhr.setRequestHeader !== 'undefined') {
  4424. // IE9 doesn't have setRequestHeader
  4425. req.xhr.setRequestHeader("Content-Type", content_type);
  4426. }
  4427. if (this._conn.options.withCredentials) {
  4428. req.xhr.withCredentials = true;
  4429. }
  4430. } catch (e2) {
  4431. Strophe.error("XHR open failed: " + e2.toString());
  4432. if (!this._conn.connected) {
  4433. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "bad-service");
  4434. }
  4435. this._conn.disconnect();
  4436. return;
  4437. } // Fires the XHR request -- may be invoked immediately
  4438. // or on a gradually expanding retry window for reconnects
  4439. const sendFunc = () => {
  4440. req.date = new Date();
  4441. if (this._conn.options.customHeaders) {
  4442. const headers = this._conn.options.customHeaders;
  4443. for (const header in headers) {
  4444. if (Object.prototype.hasOwnProperty.call(headers, header)) {
  4445. req.xhr.setRequestHeader(header, headers[header]);
  4446. }
  4447. }
  4448. }
  4449. req.xhr.send(req.data);
  4450. }; // Implement progressive backoff for reconnects --
  4451. // First retry (send === 1) should also be instantaneous
  4452. if (req.sends > 1) {
  4453. // Using a cube of the retry number creates a nicely
  4454. // expanding retry window
  4455. const backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000;
  4456. setTimeout(function () {
  4457. // XXX: setTimeout should be called only with function expressions (23974bc1)
  4458. sendFunc();
  4459. }, backoff);
  4460. } else {
  4461. sendFunc();
  4462. }
  4463. req.sends++;
  4464. if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
  4465. if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
  4466. this._conn.xmlOutput(req.xmlData.childNodes[0]);
  4467. } else {
  4468. this._conn.xmlOutput(req.xmlData);
  4469. }
  4470. }
  4471. if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
  4472. this._conn.rawOutput(req.data);
  4473. }
  4474. } else {
  4475. Strophe.debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState);
  4476. }
  4477. }
  4478. /** PrivateFunction: _removeRequest
  4479. * _Private_ function to remove a request from the queue.
  4480. *
  4481. * Parameters:
  4482. * (Strophe.Request) req - The request to remove.
  4483. */
  4484. _removeRequest(req) {
  4485. Strophe.debug("removing request");
  4486. for (let i = this._requests.length - 1; i >= 0; i--) {
  4487. if (req === this._requests[i]) {
  4488. this._requests.splice(i, 1);
  4489. }
  4490. } // IE6 fails on setting to null, so set to empty function
  4491. req.xhr.onreadystatechange = function () {};
  4492. this._throttledRequestHandler();
  4493. }
  4494. /** PrivateFunction: _restartRequest
  4495. * _Private_ function to restart a request that is presumed dead.
  4496. *
  4497. * Parameters:
  4498. * (Integer) i - The index of the request in the queue.
  4499. */
  4500. _restartRequest(i) {
  4501. const req = this._requests[i];
  4502. if (req.dead === null) {
  4503. req.dead = new Date();
  4504. }
  4505. this._processRequest(i);
  4506. }
  4507. /** PrivateFunction: _reqToData
  4508. * _Private_ function to get a stanza out of a request.
  4509. *
  4510. * Tries to extract a stanza out of a Request Object.
  4511. * When this fails the current connection will be disconnected.
  4512. *
  4513. * Parameters:
  4514. * (Object) req - The Request.
  4515. *
  4516. * Returns:
  4517. * The stanza that was passed.
  4518. */
  4519. _reqToData(req) {
  4520. try {
  4521. return req.getResponse();
  4522. } catch (e) {
  4523. if (e.message !== "parsererror") {
  4524. throw e;
  4525. }
  4526. this._conn.disconnect("strophe-parsererror");
  4527. }
  4528. }
  4529. /** PrivateFunction: _sendTerminate
  4530. * _Private_ function to send initial disconnect sequence.
  4531. *
  4532. * This is the first step in a graceful disconnect. It sends
  4533. * the BOSH server a terminate body and includes an unavailable
  4534. * presence if authentication has completed.
  4535. */
  4536. _sendTerminate(pres) {
  4537. Strophe.debug("_sendTerminate was called");
  4538. const body = this._buildBody().attrs({
  4539. type: "terminate"
  4540. });
  4541. if (pres) {
  4542. body.cnode(pres.tree());
  4543. }
  4544. const req = new Strophe.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid"));
  4545. this._requests.push(req);
  4546. this._throttledRequestHandler();
  4547. }
  4548. /** PrivateFunction: _send
  4549. * _Private_ part of the Connection.send function for BOSH
  4550. *
  4551. * Just triggers the RequestHandler to send the messages that are in the queue
  4552. */
  4553. _send() {
  4554. clearTimeout(this._conn._idleTimeout);
  4555. this._throttledRequestHandler();
  4556. this._conn._idleTimeout = setTimeout(() => this._conn._onIdle(), 100);
  4557. }
  4558. /** PrivateFunction: _sendRestart
  4559. *
  4560. * Send an xmpp:restart stanza.
  4561. */
  4562. _sendRestart() {
  4563. this._throttledRequestHandler();
  4564. clearTimeout(this._conn._idleTimeout);
  4565. }
  4566. /** PrivateFunction: _throttledRequestHandler
  4567. * _Private_ function to throttle requests to the connection window.
  4568. *
  4569. * This function makes sure we don't send requests so fast that the
  4570. * request ids overflow the connection window in the case that one
  4571. * request died.
  4572. */
  4573. _throttledRequestHandler() {
  4574. if (!this._requests) {
  4575. Strophe.debug("_throttledRequestHandler called with " + "undefined requests");
  4576. } else {
  4577. Strophe.debug("_throttledRequestHandler called with " + this._requests.length + " requests");
  4578. }
  4579. if (!this._requests || this._requests.length === 0) {
  4580. return;
  4581. }
  4582. if (this._requests.length > 0) {
  4583. this._processRequest(0);
  4584. }
  4585. if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) {
  4586. this._processRequest(1);
  4587. }
  4588. }
  4589. };
  4590. /** Variable: strip
  4591. *
  4592. * BOSH-Connections will have all stanzas wrapped in a <body> tag when
  4593. * passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>.
  4594. * To strip this tag, User code can set <Strophe.Bosh.strip> to "body":
  4595. *
  4596. * > Strophe.Bosh.prototype.strip = "body";
  4597. *
  4598. * This will enable stripping of the body tag in both
  4599. * <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>.
  4600. */
  4601. Strophe.Bosh.prototype.strip = null;
  4602. /*
  4603. This program is distributed under the terms of the MIT license.
  4604. Please see the LICENSE file for details.
  4605. Copyright 2006-2008, OGG, LLC
  4606. */
  4607. /** Class: Strophe.WebSocket
  4608. * _Private_ helper class that handles WebSocket Connections
  4609. *
  4610. * The Strophe.WebSocket class is used internally by Strophe.Connection
  4611. * to encapsulate WebSocket sessions. It is not meant to be used from user's code.
  4612. */
  4613. /** File: websocket.js
  4614. * A JavaScript library to enable XMPP over Websocket in Strophejs.
  4615. *
  4616. * This file implements XMPP over WebSockets for Strophejs.
  4617. * If a Connection is established with a Websocket url (ws://...)
  4618. * Strophe will use WebSockets.
  4619. * For more information on XMPP-over-WebSocket see RFC 7395:
  4620. * http://tools.ietf.org/html/rfc7395
  4621. *
  4622. * WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
  4623. */
  4624. Strophe.Websocket = class Websocket {
  4625. /** PrivateConstructor: Strophe.Websocket
  4626. * Create and initialize a Strophe.WebSocket object.
  4627. * Currently only sets the connection Object.
  4628. *
  4629. * Parameters:
  4630. * (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
  4631. *
  4632. * Returns:
  4633. * A new Strophe.WebSocket object.
  4634. */
  4635. constructor(connection) {
  4636. this._conn = connection;
  4637. this.strip = "wrapper";
  4638. const service = connection.service;
  4639. if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
  4640. // If the service is not an absolute URL, assume it is a path and put the absolute
  4641. // URL together from options, current URL and the path.
  4642. let new_service = "";
  4643. if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
  4644. new_service += "ws";
  4645. } else {
  4646. new_service += "wss";
  4647. }
  4648. new_service += "://" + window.location.host;
  4649. if (service.indexOf("/") !== 0) {
  4650. new_service += window.location.pathname + service;
  4651. } else {
  4652. new_service += service;
  4653. }
  4654. connection.service = new_service;
  4655. }
  4656. }
  4657. /** PrivateFunction: _buildStream
  4658. * _Private_ helper function to generate the <stream> start tag for WebSockets
  4659. *
  4660. * Returns:
  4661. * A Strophe.Builder with a <stream> element.
  4662. */
  4663. _buildStream() {
  4664. return $build("open", {
  4665. "xmlns": Strophe.NS.FRAMING,
  4666. "to": this._conn.domain,
  4667. "version": '1.0'
  4668. });
  4669. }
  4670. /** PrivateFunction: _checkStreamError
  4671. * _Private_ checks a message for stream:error
  4672. *
  4673. * Parameters:
  4674. * (Strophe.Request) bodyWrap - The received stanza.
  4675. * connectstatus - The ConnectStatus that will be set on error.
  4676. * Returns:
  4677. * true if there was a streamerror, false otherwise.
  4678. */
  4679. _checkStreamError(bodyWrap, connectstatus) {
  4680. let errors;
  4681. if (bodyWrap.getElementsByTagNameNS) {
  4682. errors = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "error");
  4683. } else {
  4684. errors = bodyWrap.getElementsByTagName("stream:error");
  4685. }
  4686. if (errors.length === 0) {
  4687. return false;
  4688. }
  4689. const error = errors[0];
  4690. let condition = "";
  4691. let text = "";
  4692. const ns = "urn:ietf:params:xml:ns:xmpp-streams";
  4693. for (let i = 0; i < error.childNodes.length; i++) {
  4694. const e = error.childNodes[i];
  4695. if (e.getAttribute("xmlns") !== ns) {
  4696. break;
  4697. }
  4698. if (e.nodeName === "text") {
  4699. text = e.textContent;
  4700. } else {
  4701. condition = e.nodeName;
  4702. }
  4703. }
  4704. let errorString = "WebSocket stream error: ";
  4705. if (condition) {
  4706. errorString += condition;
  4707. } else {
  4708. errorString += "unknown";
  4709. }
  4710. if (text) {
  4711. errorString += " - " + text;
  4712. }
  4713. Strophe.error(errorString); // close the connection on stream_error
  4714. this._conn._changeConnectStatus(connectstatus, condition);
  4715. this._conn._doDisconnect();
  4716. return true;
  4717. }
  4718. /** PrivateFunction: _reset
  4719. * Reset the connection.
  4720. *
  4721. * This function is called by the reset function of the Strophe Connection.
  4722. * Is not needed by WebSockets.
  4723. */
  4724. _reset() {
  4725. // eslint-disable-line class-methods-use-this
  4726. return;
  4727. }
  4728. /** PrivateFunction: _connect
  4729. * _Private_ function called by Strophe.Connection.connect
  4730. *
  4731. * Creates a WebSocket for a connection and assigns Callbacks to it.
  4732. * Does nothing if there already is a WebSocket.
  4733. */
  4734. _connect() {
  4735. // Ensure that there is no open WebSocket from a previous Connection.
  4736. this._closeSocket();
  4737. this.socket = new WebSocket(this._conn.service, "xmpp");
  4738. this.socket.onopen = () => this._onOpen();
  4739. this.socket.onerror = e => this._onError(e);
  4740. this.socket.onclose = e => this._onClose(e); // Gets replaced with this._onMessage once _onInitialMessage is called
  4741. this.socket.onmessage = message => this._onInitialMessage(message);
  4742. }
  4743. /** PrivateFunction: _connect_cb
  4744. * _Private_ function called by Strophe.Connection._connect_cb
  4745. *
  4746. * checks for stream:error
  4747. *
  4748. * Parameters:
  4749. * (Strophe.Request) bodyWrap - The received stanza.
  4750. */
  4751. _connect_cb(bodyWrap) {
  4752. const error = this._checkStreamError(bodyWrap, Strophe.Status.CONNFAIL);
  4753. if (error) {
  4754. return Strophe.Status.CONNFAIL;
  4755. }
  4756. }
  4757. /** PrivateFunction: _handleStreamStart
  4758. * _Private_ function that checks the opening <open /> tag for errors.
  4759. *
  4760. * Disconnects if there is an error and returns false, true otherwise.
  4761. *
  4762. * Parameters:
  4763. * (Node) message - Stanza containing the <open /> tag.
  4764. */
  4765. _handleStreamStart(message) {
  4766. let error = false; // Check for errors in the <open /> tag
  4767. const ns = message.getAttribute("xmlns");
  4768. if (typeof ns !== "string") {
  4769. error = "Missing xmlns in <open />";
  4770. } else if (ns !== Strophe.NS.FRAMING) {
  4771. error = "Wrong xmlns in <open />: " + ns;
  4772. }
  4773. const ver = message.getAttribute("version");
  4774. if (typeof ver !== "string") {
  4775. error = "Missing version in <open />";
  4776. } else if (ver !== "1.0") {
  4777. error = "Wrong version in <open />: " + ver;
  4778. }
  4779. if (error) {
  4780. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error);
  4781. this._conn._doDisconnect();
  4782. return false;
  4783. }
  4784. return true;
  4785. }
  4786. /** PrivateFunction: _onInitialMessage
  4787. * _Private_ function that handles the first connection messages.
  4788. *
  4789. * On receiving an opening stream tag this callback replaces itself with the real
  4790. * message handler. On receiving a stream error the connection is terminated.
  4791. */
  4792. _onInitialMessage(message) {
  4793. if (message.data.indexOf("<open ") === 0 || message.data.indexOf("<?xml") === 0) {
  4794. // Strip the XML Declaration, if there is one
  4795. const data = message.data.replace(/^(<\?.*?\?>\s*)*/, "");
  4796. if (data === '') return;
  4797. const streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement;
  4798. this._conn.xmlInput(streamStart);
  4799. this._conn.rawInput(message.data); //_handleStreamSteart will check for XML errors and disconnect on error
  4800. if (this._handleStreamStart(streamStart)) {
  4801. //_connect_cb will check for stream:error and disconnect on error
  4802. this._connect_cb(streamStart);
  4803. }
  4804. } else if (message.data.indexOf("<close ") === 0) {
  4805. // <close xmlns="urn:ietf:params:xml:ns:xmpp-framing />
  4806. // Parse the raw string to an XML element
  4807. const parsedMessage = new DOMParser().parseFromString(message.data, "text/xml").documentElement; // Report this input to the raw and xml handlers
  4808. this._conn.xmlInput(parsedMessage);
  4809. this._conn.rawInput(message.data);
  4810. const see_uri = parsedMessage.getAttribute("see-other-uri");
  4811. if (see_uri) {
  4812. const service = this._conn.service; // Valid scenarios: WSS->WSS, WS->ANY
  4813. const isSecureRedirect = service.indexOf("wss:") >= 0 && see_uri.indexOf("wss:") >= 0 || service.indexOf("ws:") >= 0;
  4814. if (isSecureRedirect) {
  4815. this._conn._changeConnectStatus(Strophe.Status.REDIRECT, "Received see-other-uri, resetting connection");
  4816. this._conn.reset();
  4817. this._conn.service = see_uri;
  4818. this._connect();
  4819. }
  4820. } else {
  4821. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream");
  4822. this._conn._doDisconnect();
  4823. }
  4824. } else {
  4825. this._replaceMessageHandler();
  4826. const string = this._streamWrap(message.data);
  4827. const elem = new DOMParser().parseFromString(string, "text/xml").documentElement;
  4828. this._conn._connect_cb(elem, null, message.data);
  4829. }
  4830. }
  4831. /** PrivateFunction: _replaceMessageHandler
  4832. *
  4833. * Called by _onInitialMessage in order to replace itself with the general message handler.
  4834. * This method is overridden by Strophe.WorkerWebsocket, which manages a
  4835. * websocket connection via a service worker and doesn't have direct access
  4836. * to the socket.
  4837. */
  4838. _replaceMessageHandler() {
  4839. this.socket.onmessage = m => this._onMessage(m);
  4840. }
  4841. /** PrivateFunction: _disconnect
  4842. * _Private_ function called by Strophe.Connection.disconnect
  4843. *
  4844. * Disconnects and sends a last stanza if one is given
  4845. *
  4846. * Parameters:
  4847. * (Request) pres - This stanza will be sent before disconnecting.
  4848. */
  4849. _disconnect(pres) {
  4850. if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
  4851. if (pres) {
  4852. this._conn.send(pres);
  4853. }
  4854. const close = $build("close", {
  4855. "xmlns": Strophe.NS.FRAMING
  4856. });
  4857. this._conn.xmlOutput(close.tree());
  4858. const closeString = Strophe.serialize(close);
  4859. this._conn.rawOutput(closeString);
  4860. try {
  4861. this.socket.send(closeString);
  4862. } catch (e) {
  4863. Strophe.warn("Couldn't send <close /> tag.");
  4864. }
  4865. }
  4866. setTimeout(() => this._conn._doDisconnect, 0);
  4867. }
  4868. /** PrivateFunction: _doDisconnect
  4869. * _Private_ function to disconnect.
  4870. *
  4871. * Just closes the Socket for WebSockets
  4872. */
  4873. _doDisconnect() {
  4874. Strophe.debug("WebSockets _doDisconnect was called");
  4875. this._closeSocket();
  4876. }
  4877. /** PrivateFunction _streamWrap
  4878. * _Private_ helper function to wrap a stanza in a <stream> tag.
  4879. * This is used so Strophe can process stanzas from WebSockets like BOSH
  4880. */
  4881. _streamWrap(stanza) {
  4882. // eslint-disable-line class-methods-use-this
  4883. return "<wrapper>" + stanza + '</wrapper>';
  4884. }
  4885. /** PrivateFunction: _closeSocket
  4886. * _Private_ function to close the WebSocket.
  4887. *
  4888. * Closes the socket if it is still open and deletes it
  4889. */
  4890. _closeSocket() {
  4891. if (this.socket) {
  4892. try {
  4893. this.socket.onclose = null;
  4894. this.socket.onerror = null;
  4895. this.socket.onmessage = null;
  4896. this.socket.close();
  4897. } catch (e) {
  4898. Strophe.debug(e.message);
  4899. }
  4900. }
  4901. this.socket = null;
  4902. }
  4903. /** PrivateFunction: _emptyQueue
  4904. * _Private_ function to check if the message queue is empty.
  4905. *
  4906. * Returns:
  4907. * True, because WebSocket messages are send immediately after queueing.
  4908. */
  4909. _emptyQueue() {
  4910. // eslint-disable-line class-methods-use-this
  4911. return true;
  4912. }
  4913. /** PrivateFunction: _onClose
  4914. * _Private_ function to handle websockets closing.
  4915. */
  4916. _onClose(e) {
  4917. if (this._conn.connected && !this._conn.disconnecting) {
  4918. Strophe.error("Websocket closed unexpectedly");
  4919. this._conn._doDisconnect();
  4920. } else if (e && e.code === 1006 && !this._conn.connected && this.socket) {
  4921. // in case the onError callback was not called (Safari 10 does not
  4922. // call onerror when the initial connection fails) we need to
  4923. // dispatch a CONNFAIL status update to be consistent with the
  4924. // behavior on other browsers.
  4925. Strophe.error("Websocket closed unexcectedly");
  4926. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
  4927. this._conn._doDisconnect();
  4928. } else {
  4929. Strophe.debug("Websocket closed");
  4930. }
  4931. }
  4932. /** PrivateFunction: _no_auth_received
  4933. *
  4934. * Called on stream start/restart when no stream:features
  4935. * has been received.
  4936. */
  4937. _no_auth_received(callback) {
  4938. Strophe.error("Server did not offer a supported authentication mechanism");
  4939. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.NO_AUTH_MECH);
  4940. if (callback) {
  4941. callback.call(this._conn);
  4942. }
  4943. this._conn._doDisconnect();
  4944. }
  4945. /** PrivateFunction: _onDisconnectTimeout
  4946. * _Private_ timeout handler for handling non-graceful disconnection.
  4947. *
  4948. * This does nothing for WebSockets
  4949. */
  4950. _onDisconnectTimeout() {} // eslint-disable-line class-methods-use-this
  4951. /** PrivateFunction: _abortAllRequests
  4952. * _Private_ helper function that makes sure all pending requests are aborted.
  4953. */
  4954. _abortAllRequests() {} // eslint-disable-line class-methods-use-this
  4955. /** PrivateFunction: _onError
  4956. * _Private_ function to handle websockets errors.
  4957. *
  4958. * Parameters:
  4959. * (Object) error - The websocket error.
  4960. */
  4961. _onError(error) {
  4962. Strophe.error("Websocket error " + JSON.stringify(error));
  4963. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
  4964. this._disconnect();
  4965. }
  4966. /** PrivateFunction: _onIdle
  4967. * _Private_ function called by Strophe.Connection._onIdle
  4968. *
  4969. * sends all queued stanzas
  4970. */
  4971. _onIdle() {
  4972. const data = this._conn._data;
  4973. if (data.length > 0 && !this._conn.paused) {
  4974. for (let i = 0; i < data.length; i++) {
  4975. if (data[i] !== null) {
  4976. let stanza;
  4977. if (data[i] === "restart") {
  4978. stanza = this._buildStream().tree();
  4979. } else {
  4980. stanza = data[i];
  4981. }
  4982. const rawStanza = Strophe.serialize(stanza);
  4983. this._conn.xmlOutput(stanza);
  4984. this._conn.rawOutput(rawStanza);
  4985. this.socket.send(rawStanza);
  4986. }
  4987. }
  4988. this._conn._data = [];
  4989. }
  4990. }
  4991. /** PrivateFunction: _onMessage
  4992. * _Private_ function to handle websockets messages.
  4993. *
  4994. * This function parses each of the messages as if they are full documents.
  4995. * [TODO : We may actually want to use a SAX Push parser].
  4996. *
  4997. * Since all XMPP traffic starts with
  4998. * <stream:stream version='1.0'
  4999. * xml:lang='en'
  5000. * xmlns='jabber:client'
  5001. * xmlns:stream='http://etherx.jabber.org/streams'
  5002. * id='3697395463'
  5003. * from='SERVER'>
  5004. *
  5005. * The first stanza will always fail to be parsed.
  5006. *
  5007. * Additionally, the seconds stanza will always be <stream:features> with
  5008. * the stream NS defined in the previous stanza, so we need to 'force'
  5009. * the inclusion of the NS in this stanza.
  5010. *
  5011. * Parameters:
  5012. * (string) message - The websocket message.
  5013. */
  5014. _onMessage(message) {
  5015. let elem; // check for closing stream
  5016. const close = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';
  5017. if (message.data === close) {
  5018. this._conn.rawInput(close);
  5019. this._conn.xmlInput(message);
  5020. if (!this._conn.disconnecting) {
  5021. this._conn._doDisconnect();
  5022. }
  5023. return;
  5024. } else if (message.data.search("<open ") === 0) {
  5025. // This handles stream restarts
  5026. elem = new DOMParser().parseFromString(message.data, "text/xml").documentElement;
  5027. if (!this._handleStreamStart(elem)) {
  5028. return;
  5029. }
  5030. } else {
  5031. const data = this._streamWrap(message.data);
  5032. elem = new DOMParser().parseFromString(data, "text/xml").documentElement;
  5033. }
  5034. if (this._checkStreamError(elem, Strophe.Status.ERROR)) {
  5035. return;
  5036. } //handle unavailable presence stanza before disconnecting
  5037. if (this._conn.disconnecting && elem.firstChild.nodeName === "presence" && elem.firstChild.getAttribute("type") === "unavailable") {
  5038. this._conn.xmlInput(elem);
  5039. this._conn.rawInput(Strophe.serialize(elem)); // if we are already disconnecting we will ignore the unavailable stanza and
  5040. // wait for the </stream:stream> tag before we close the connection
  5041. return;
  5042. }
  5043. this._conn._dataRecv(elem, message.data);
  5044. }
  5045. /** PrivateFunction: _onOpen
  5046. * _Private_ function to handle websockets connection setup.
  5047. *
  5048. * The opening stream tag is sent here.
  5049. */
  5050. _onOpen() {
  5051. Strophe.debug("Websocket open");
  5052. const start = this._buildStream();
  5053. this._conn.xmlOutput(start.tree());
  5054. const startString = Strophe.serialize(start);
  5055. this._conn.rawOutput(startString);
  5056. this.socket.send(startString);
  5057. }
  5058. /** PrivateFunction: _reqToData
  5059. * _Private_ function to get a stanza out of a request.
  5060. *
  5061. * WebSockets don't use requests, so the passed argument is just returned.
  5062. *
  5063. * Parameters:
  5064. * (Object) stanza - The stanza.
  5065. *
  5066. * Returns:
  5067. * The stanza that was passed.
  5068. */
  5069. _reqToData(stanza) {
  5070. // eslint-disable-line class-methods-use-this
  5071. return stanza;
  5072. }
  5073. /** PrivateFunction: _send
  5074. * _Private_ part of the Connection.send function for WebSocket
  5075. *
  5076. * Just flushes the messages that are in the queue
  5077. */
  5078. _send() {
  5079. this._conn.flush();
  5080. }
  5081. /** PrivateFunction: _sendRestart
  5082. *
  5083. * Send an xmpp:restart stanza.
  5084. */
  5085. _sendRestart() {
  5086. clearTimeout(this._conn._idleTimeout);
  5087. this._conn._onIdle.bind(this._conn)();
  5088. }
  5089. };
  5090. /*
  5091. This program is distributed under the terms of the MIT license.
  5092. Please see the LICENSE file for details.
  5093. Copyright 2020, JC Brand
  5094. */
  5095. const lmap = {};
  5096. lmap['debug'] = Strophe.LogLevel.DEBUG;
  5097. lmap['info'] = Strophe.LogLevel.INFO;
  5098. lmap['warn'] = Strophe.LogLevel.WARN;
  5099. lmap['error'] = Strophe.LogLevel.ERROR;
  5100. lmap['fatal'] = Strophe.LogLevel.FATAL;
  5101. /** Class: Strophe.WorkerWebsocket
  5102. * _Private_ helper class that handles a websocket connection inside a shared worker.
  5103. */
  5104. Strophe.WorkerWebsocket = class WorkerWebsocket extends Strophe.Websocket {
  5105. /** PrivateConstructor: Strophe.WorkerWebsocket
  5106. * Create and initialize a Strophe.WorkerWebsocket object.
  5107. *
  5108. * Parameters:
  5109. * (Strophe.Connection) connection - The Strophe.Connection
  5110. *
  5111. * Returns:
  5112. * A new Strophe.WorkerWebsocket object.
  5113. */
  5114. constructor(connection) {
  5115. super(connection);
  5116. this._conn = connection;
  5117. this.worker = new SharedWorker(this._conn.options.worker, 'Strophe XMPP Connection');
  5118. this.worker.onerror = e => {
  5119. var _console;
  5120. (_console = console) === null || _console === void 0 ? void 0 : _console.error(e);
  5121. Strophe.log(Strophe.LogLevel.ERROR, `Shared Worker Error: ${e}`);
  5122. };
  5123. }
  5124. get socket() {
  5125. return {
  5126. 'send': str => this.worker.port.postMessage(['send', str])
  5127. };
  5128. }
  5129. _connect() {
  5130. this._messageHandler = m => this._onInitialMessage(m);
  5131. this.worker.port.start();
  5132. this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
  5133. this.worker.port.postMessage(['_connect', this._conn.service, this._conn.jid]);
  5134. }
  5135. _attach(callback) {
  5136. this._messageHandler = m => this._onMessage(m);
  5137. this._conn.connect_callback = callback;
  5138. this.worker.port.start();
  5139. this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
  5140. this.worker.port.postMessage(['_attach', this._conn.service]);
  5141. }
  5142. _attachCallback(status, jid) {
  5143. if (status === Strophe.Status.ATTACHED) {
  5144. this._conn.jid = jid;
  5145. this._conn.authenticated = true;
  5146. this._conn.connected = true;
  5147. this._conn.restored = true;
  5148. this._conn._changeConnectStatus(Strophe.Status.ATTACHED);
  5149. } else if (status === Strophe.Status.ATTACHFAIL) {
  5150. this._conn.authenticated = false;
  5151. this._conn.connected = false;
  5152. this._conn.restored = false;
  5153. this._conn._changeConnectStatus(Strophe.Status.ATTACHFAIL);
  5154. }
  5155. }
  5156. _disconnect(readyState, pres) {
  5157. pres && this._conn.send(pres);
  5158. const close = $build("close", {
  5159. "xmlns": Strophe.NS.FRAMING
  5160. });
  5161. this._conn.xmlOutput(close.tree());
  5162. const closeString = Strophe.serialize(close);
  5163. this._conn.rawOutput(closeString);
  5164. this.worker.port.postMessage(['send', closeString]);
  5165. this._conn._doDisconnect();
  5166. }
  5167. _onClose(e) {
  5168. if (this._conn.connected && !this._conn.disconnecting) {
  5169. Strophe.error("Websocket closed unexpectedly");
  5170. this._conn._doDisconnect();
  5171. } else if (e && e.code === 1006 && !this._conn.connected) {
  5172. // in case the onError callback was not called (Safari 10 does not
  5173. // call onerror when the initial connection fails) we need to
  5174. // dispatch a CONNFAIL status update to be consistent with the
  5175. // behavior on other browsers.
  5176. Strophe.error("Websocket closed unexcectedly");
  5177. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");
  5178. this._conn._doDisconnect();
  5179. } else {
  5180. Strophe.debug("Websocket closed");
  5181. }
  5182. }
  5183. _closeSocket() {
  5184. this.worker.port.postMessage(['_closeSocket']);
  5185. }
  5186. /** PrivateFunction: _replaceMessageHandler
  5187. *
  5188. * Called by _onInitialMessage in order to replace itself with the general message handler.
  5189. * This method is overridden by Strophe.WorkerWebsocket, which manages a
  5190. * websocket connection via a service worker and doesn't have direct access
  5191. * to the socket.
  5192. */
  5193. _replaceMessageHandler() {
  5194. this._messageHandler = m => this._onMessage(m);
  5195. }
  5196. /** PrivateFunction: _onWorkerMessage
  5197. * _Private_ function that handles messages received from the service worker
  5198. */
  5199. _onWorkerMessage(ev) {
  5200. const {
  5201. data
  5202. } = ev;
  5203. const method_name = data[0];
  5204. if (method_name === '_onMessage') {
  5205. this._messageHandler(data[1]);
  5206. } else if (method_name in this) {
  5207. try {
  5208. this[method_name].apply(this, ev.data.slice(1));
  5209. } catch (e) {
  5210. Strophe.log(Strophe.LogLevel.ERROR, e);
  5211. }
  5212. } else if (method_name === 'log') {
  5213. const level = data[1];
  5214. const msg = data[2];
  5215. Strophe.log(lmap[level], msg);
  5216. } else {
  5217. Strophe.log(Strophe.LogLevel.ERROR, `Found unhandled service worker message: ${data}`);
  5218. }
  5219. }
  5220. };
  5221. global$1.$build = core.$build;
  5222. global$1.$iq = core.$iq;
  5223. global$1.$msg = core.$msg;
  5224. global$1.$pres = core.$pres;
  5225. global$1.Strophe = core.Strophe;
  5226. const {
  5227. b64_sha1
  5228. } = SHA1;
  5229. export { $build, $iq, $msg, $pres, Strophe, b64_sha1 };