webpeerjs 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/webpeerjs.js CHANGED
@@ -92,6 +92,9 @@ class webpeerjs{
92
92
  //message tracker avoid double
93
93
  #msgIdtracker
94
94
 
95
+ //inbound message time tracker
96
+ #msgTimeTracker
97
+
95
98
  //map of peer exchange data
96
99
  #peerexchangedata
97
100
 
@@ -102,16 +105,23 @@ class webpeerjs{
102
105
  //arr to track on connect event
103
106
  #onConnectQueue
104
107
 
108
+ //callback to websocket dialable
109
+ #onWebsocketFn
110
+
111
+ //time tracker for sending message
112
+ #sendMessageTimeTracker
113
+
105
114
  id
106
115
  status
107
116
  IPFS
108
117
  address
109
118
  peers
110
119
 
111
- constructor(libp2p,dbstore,onMetrics){
120
+ constructor(libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn){
112
121
 
113
122
  this.#libp2p = libp2p
114
123
  this.#dbstore = dbstore
124
+ this.#onWebsocketFn = onWebsocketFn
115
125
  this.#dbstoreData = new Map()
116
126
  this.#discoveredPeers = new Map()
117
127
  this.#webPeersId = []
@@ -129,11 +139,13 @@ class webpeerjs{
129
139
  this.#trackDisconnect = new Map()
130
140
  this.#dialQueue = []
131
141
  this.#isDialEnabled = true
132
- this.#msgIdtracker = []
142
+ this.#msgIdtracker = new Map()
133
143
  this.#peerexchangedata = new Map()
134
144
  this.#lastTimeConnectToNetwork = new Date().getTime()
135
145
  this.#lastTimeReceiveData = new Date().getTime()
136
146
  this.#onConnectQueue = []
147
+ this.#msgTimeTracker = new Map()
148
+ this.#sendMessageTimeTracker = 0
137
149
 
138
150
  this.peers = (function(f) {
139
151
  return f
@@ -382,10 +394,17 @@ class webpeerjs{
382
394
  }
383
395
 
384
396
  //inbound message
397
+ //use #msgIdtracker to prevent double message
398
+ //use #msgTimeTracker to limit inbound message 1msg/s
385
399
  if(message){
386
400
  const msgID = msgId+id
387
- if(!this.#msgIdtracker.includes(msgID)){
388
- this.#msgIdtracker.push(msgID)
401
+ let oldmsgtime = 0
402
+ let newmsgtime = new Date().getTime()
403
+ if(this.#msgTimeTracker.has(id))oldmsgtime = this.#msgTimeTracker.get(id)
404
+ const msgtimelimit = 1000
405
+ if(!this.#msgIdtracker.has(msgID) && newmsgtime-oldmsgtime>msgtimelimit){
406
+ this.#msgIdtracker.set(msgID,newmsgtime)
407
+ this.#msgTimeTracker.set(id,newmsgtime)
389
408
  this.#rooms[room].onMessage(message,id)
390
409
  }
391
410
  }
@@ -581,15 +600,16 @@ class webpeerjs{
581
600
  //const multiaddrs = peer.addresses.map(({ multiaddr }) => multiaddr)
582
601
  //console.log(`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`)
583
602
  const id = peer.id.toString()
584
- const mddrs = []
585
- peer.addresses.forEach((addr)=>{
586
- const maddr = addr.multiaddr.toString()+'/p2p/'+id
587
- if(maddr.includes('webtransport') && maddr.includes('certhash')){
588
- mddrs.push(maddr)
603
+ const addrs = []
604
+ peer.addresses.forEach((address)=>{
605
+ const addr = address.multiaddr.toString()+'/p2p/'+id
606
+ if(addr.includes('webtransport') && addr.includes('certhash')){
607
+ addrs.push(addr)
589
608
  }
590
609
  })
591
- //this.#ListenAddressChange(mddrs)
592
- this.address = mddrs
610
+ if(!config.CONFIG_RUN_ON_TRANSIENT_CONNECTION)addrs.reverse()
611
+ //this.#ListenAddressChange(addrs)
612
+ this.address = addrs
593
613
  this.#ping()
594
614
  this.#peerDiscoveryHybrid()
595
615
  })
@@ -668,7 +688,8 @@ class webpeerjs{
668
688
 
669
689
  onMetrics((data)=>{
670
690
  const signal = metrics(data)
671
- this.#isDialEnabled = signal
691
+ this.#isDialEnabled = signal.isDialEnabled
692
+ onDialFn(signal.isAutoDialEnabled)
672
693
 
673
694
  })
674
695
 
@@ -689,6 +710,7 @@ class webpeerjs{
689
710
  this.#peerDiscoveryHybrid()
690
711
  this.#trackHybridPeersConnection()
691
712
  this.#trackWebpeerConnection()
713
+ this.#garbageCollectionMsgIdTracker()
692
714
  },10e3)
693
715
 
694
716
 
@@ -768,6 +790,11 @@ class webpeerjs{
768
790
  onMessage : () => {},
769
791
  listenMessage : f => (this.#rooms[room] = {...this.#rooms[room], onMessage: f}),
770
792
  sendMessage : async (message) => {
793
+ const now = (new Date()).getTime()
794
+ if(now-this.#sendMessageTimeTracker < 1000){
795
+ throw mkErr('can not send more than 1 message/s')
796
+ }
797
+ this.#sendMessageTimeTracker = now
771
798
  const msgId = (new Date()).getTime()
772
799
  const data = JSON.stringify({prefix:config.CONFIG_PREFIX,room,message,id:this.#libp2p.peerId.toString(),msgId})
773
800
  const arr = uint8ArrayFromString(data)
@@ -803,12 +830,25 @@ class webpeerjs{
803
830
  mddrs.push(mddr)
804
831
  this.#dialMultiaddress(mddrs)
805
832
  }
833
+
834
+ plugin(callback){
835
+ callback(this)
836
+ }
806
837
 
807
838
 
808
839
  /*
809
840
  PRIVATE FUNCTION
810
841
  */
811
842
 
843
+ #garbageCollectionMsgIdTracker(){
844
+ const limit = 60*1000
845
+ for(const msg of this.#msgIdtracker){
846
+ if(msg[1] > limit){
847
+ this.#msgIdtracker.delete(msg[0])
848
+ }
849
+ }
850
+ }
851
+
812
852
  //track hybrid peer connection and try to dial if not connected at least 1
813
853
  #trackHybridPeersConnection(){
814
854
  let isConnectedToHybridPeers = false
@@ -1656,7 +1696,7 @@ class webpeerjs{
1656
1696
 
1657
1697
  //dial based on known bootsrap peers address using Websocket expected
1658
1698
  #dialKnownBootstrap(){
1659
-
1699
+ //console.log('#dialKnownBootstrap()')
1660
1700
  if(!navigator.onLine)return
1661
1701
  if(!this.#isDialEnabled)return
1662
1702
 
@@ -1676,6 +1716,7 @@ class webpeerjs{
1676
1716
 
1677
1717
  this.#dialedKnownBootstrap.set(id,addrs)
1678
1718
  this.#isDialWebsocket = true
1719
+ this.#onWebsocketFn(true)
1679
1720
  if(!this.#isConnected(id)){
1680
1721
  this.#dialMultiaddress(mddrs)
1681
1722
  }
@@ -1685,7 +1726,7 @@ class webpeerjs{
1685
1726
 
1686
1727
  //dial based on known bootstrap DNS
1687
1728
  async #dialKnownDNS(){
1688
-
1729
+ //console.log('#dialKnownDNS()')
1689
1730
  if(!navigator.onLine)return
1690
1731
  if(!this.#isDialEnabled)return
1691
1732
 
@@ -1718,6 +1759,7 @@ class webpeerjs{
1718
1759
 
1719
1760
  this.#dialedKnownBootstrap.set(id,addrs)
1720
1761
  this.#isDialWebsocket = true
1762
+ this.#onWebsocketFn(true)
1721
1763
  if(!this.#isConnected(id)){
1722
1764
  this.#dialMultiaddress(mddrs)
1723
1765
  }
@@ -1728,7 +1770,7 @@ class webpeerjs{
1728
1770
 
1729
1771
  //dial based on known bootstrap DNS using DNS resolver only
1730
1772
  async #dialKnownDNSonly(){
1731
-
1773
+ console.log('#dialKnownDNSonly()')
1732
1774
  if(!navigator.onLine)return
1733
1775
  if(!this.#isDialEnabled)return
1734
1776
 
@@ -1765,6 +1807,7 @@ class webpeerjs{
1765
1807
 
1766
1808
 
1767
1809
  this.#isDialWebsocket = true
1810
+ this.#onWebsocketFn(true)
1768
1811
  this.#dialedKnownBootstrap.set(id,addrs)
1769
1812
 
1770
1813
  this.#dialedKnownBootstrap.set(id,addrs)
@@ -1832,6 +1875,21 @@ class webpeerjs{
1832
1875
 
1833
1876
  let onMetricsFn = () => {}
1834
1877
  const onMetrics = f => (onMetricsFn = f)
1878
+
1879
+ let isWebsocket = false
1880
+ let onWebsocketFn = () => {}
1881
+ const onWebsocket = f => (onWebsocketFn = f)
1882
+ onWebsocket((data)=>{
1883
+ isWebsocket = data
1884
+ })
1885
+
1886
+ let isDial = true
1887
+ let onDialFn = () => {}
1888
+ const onDial = f => (onDialFn = f)
1889
+ onDial((data)=>{
1890
+ //if(isDial!=data)console.warn('isDial',data)
1891
+ isDial = data
1892
+ })
1835
1893
 
1836
1894
  let listenaddress = []
1837
1895
 
@@ -1839,6 +1897,9 @@ class webpeerjs{
1839
1897
  listenaddress.push('/webrtc')
1840
1898
  }
1841
1899
 
1900
+ const stunurls = config.CONFIG_WEBRTC_STUN_URLS
1901
+ const stunurlsbackup = config.CONFIG_WEBRTC_STUN_URLS_BACKUP
1902
+
1842
1903
  const turnurls = atob(config.CONFIG_WEBRTC_TURN_HOST)
1843
1904
  const turnusername = atob(config.CONFIG_WEBRTC_TURN_USER)
1844
1905
  const turncredential = atob(config.CONFIG_WEBRTC_TURN_PWD)
@@ -1847,93 +1908,113 @@ class webpeerjs{
1847
1908
  const turnusernamebackup = atob(config.CONFIG_WEBRTC_TURN_USER_BACKUP)
1848
1909
  const turncredentialbackup = atob(config.CONFIG_WEBRTC_TURN_PWD_BACKUP)
1849
1910
 
1850
- const ice = await new Promise((resolve)=>{
1851
-
1852
- let stun = false
1853
- let turn = false
1854
-
1855
- const timeout = setTimeout(()=>{
1856
- let ice = []
1857
- if(stun){
1858
- ice.push(stun)
1859
- }else{
1860
- const backup = {
1861
- urls: config.CONFIG_WEBRTC_STUN_URLS_BACKUP
1862
- }
1863
- ice.push(backup)
1864
- }
1865
- if(turn){
1866
- ice.push(turn)
1867
- }else{
1868
- const backup = {
1869
- urls: turnurlsbackup,
1870
- username: turnusernamebackup,
1871
- credential: turncredentialbackup
1872
- }
1873
- ice.push(backup)
1874
- }
1875
- resolve(ice)
1876
- },5000)
1877
-
1878
- function check(){
1879
- if(stun && turn){
1911
+ async function checkice(stunurls,turnurls,turnusername,turncredential,time){
1912
+ return new Promise((resolve)=>{
1913
+
1914
+ let stun = false
1915
+ let turn = false
1916
+
1917
+ const timeout = setTimeout(()=>{
1880
1918
  let ice = []
1881
1919
  ice.push(stun)
1882
1920
  ice.push(turn)
1883
- clearTimeout(timeout)
1884
1921
  resolve(ice)
1922
+ },time)
1923
+
1924
+ function check(){
1925
+ if(stun && turn){
1926
+ let ice = []
1927
+ ice.push(stun)
1928
+ ice.push(turn)
1929
+ clearTimeout(timeout)
1930
+ resolve(ice)
1931
+ }
1885
1932
  }
1886
- }
1887
-
1888
- //test ice servers
1889
-
1890
- const iceServers = [
1891
- {
1892
- urls: config.CONFIG_WEBRTC_STUN_URLS
1893
- },
1894
- {
1895
- urls: turnurls,
1896
- username: turnusername,
1897
- credential: turncredential
1898
- }
1899
- ];
1933
+
1934
+ //test ice servers
1935
+
1936
+ const iceServers = [
1937
+ {
1938
+ urls: stunurls
1939
+ },
1940
+ {
1941
+ urls: turnurls,
1942
+ username: turnusername,
1943
+ credential: turncredential
1944
+ }
1945
+ ];
1900
1946
 
1901
- const pc = new RTCPeerConnection({
1902
- iceServers
1903
- });
1947
+ const pc = new RTCPeerConnection({
1948
+ iceServers
1949
+ });
1904
1950
 
1905
- pc.onicecandidate = (e) => {
1906
- if (!e.candidate) return;
1951
+ pc.onicecandidate = (e) => {
1952
+ if (!e.candidate) return;
1907
1953
 
1908
- //console.log(e.candidate.candidate);
1954
+ //console.log(e.candidate.candidate);
1909
1955
 
1910
- // stun works
1911
- if(e.candidate.type == "srflx"){
1912
- //console.log('publicip',e.candidate.address);
1913
- stun = {
1914
- urls: config.CONFIG_WEBRTC_STUN_URLS
1915
- }
1916
- check()
1917
- }
1956
+ // stun works
1957
+ if(e.candidate.type == "srflx"){
1958
+ //console.log('publicip',e.candidate.address);
1959
+ stun = {
1960
+ urls: stunurls
1961
+ }
1962
+ check()
1963
+ }
1918
1964
 
1919
- // turn works
1920
- if(e.candidate.type == "relay"){
1921
- turn = {
1922
- urls: turnurls,
1923
- username: turnusername,
1924
- credential: turncredential
1925
- }
1926
- check()
1927
- }
1928
- };
1965
+ // turn works
1966
+ if(e.candidate.type == "relay"){
1967
+ turn = {
1968
+ urls: turnurls,
1969
+ username: turnusername,
1970
+ credential: turncredential
1971
+ }
1972
+ check()
1973
+ }
1974
+ };
1929
1975
 
1930
- pc.onicecandidateerror = (e) => {
1931
- console.debug(e);
1932
- };
1976
+ pc.onicecandidateerror = (e) => {
1977
+ console.debug(e);
1978
+ };
1933
1979
 
1934
- pc.createDataChannel('webpeerjs');
1935
- pc.createOffer().then(offer => pc.setLocalDescription(offer));
1936
- })
1980
+ pc.createDataChannel('webpeerjs');
1981
+ pc.createOffer().then(offer => pc.setLocalDescription(offer));
1982
+ })
1983
+ }
1984
+
1985
+ let ice = await checkice(stunurls,turnurls,turnusername,turncredential,5000)
1986
+
1987
+ //console.log(ice)
1988
+
1989
+ //recheck ice
1990
+ if(!ice[0] && !ice[1]){
1991
+ ice = await checkice(stunurlsbackup,turnurlsbackup,turnusernamebackup,turncredentialbackup,5000)
1992
+ }else if (ice[0] && !ice[1]){
1993
+ ice = await checkice(stunurls,turnurlsbackup,turnusernamebackup,turncredentialbackup,5000)
1994
+ }else if (!ice[0] && ice[1]){
1995
+ ice = await checkice(stunurlsbackup,turnurls,turnusername,turncredential,5000)
1996
+ }
1997
+
1998
+ //console.log(ice)
1999
+
2000
+ //final ice remove false value
2001
+ ice.forEach(function(value, index) {
2002
+ if(!value){
2003
+ this.splice(index, 1)
2004
+ }
2005
+ }, ice);
2006
+
2007
+ //console.log(ice)
2008
+
2009
+ let configuration = {}
2010
+
2011
+ if(arguments.length > 0){
2012
+ configuration = arguments[0]
2013
+ }else{
2014
+ configuration.rtcConfiguration = {
2015
+ iceServers: ice,
2016
+ }
2017
+ }
1937
2018
 
1938
2019
  //create libp2p instance
1939
2020
  const libp2p = await createLibp2p({
@@ -1944,9 +2025,7 @@ class webpeerjs{
1944
2025
  webTransport(),
1945
2026
  webSockets(),
1946
2027
  webRTC({
1947
- rtcConfiguration: {
1948
- iceServers: ice,
1949
- },
2028
+ rtcConfiguration: configuration.rtcConfiguration,
1950
2029
  }),
1951
2030
  circuitRelayTransport({
1952
2031
  discoverRelays: config.CONFIG_DISCOVER_RELAYS,
@@ -1979,24 +2058,26 @@ class webpeerjs{
1979
2058
  ],
1980
2059
  connectionGater: {
1981
2060
  filterMultiaddrForPeer: async (peer, multiaddrTest) => {
1982
- const multiaddrString = multiaddrTest.toString();
2061
+ const multiaddrString = multiaddrTest.toString()
1983
2062
  if (
1984
2063
  multiaddrString.includes("/ip4/127.0.0.1") ||
1985
2064
  multiaddrString.includes("/ip6/")
1986
2065
  ) {
1987
- return false;
2066
+ return false
1988
2067
  }
1989
- return true;
2068
+ if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return isWebsocket
2069
+ return isDial
1990
2070
  },
1991
2071
  denyDialMultiaddr: async (multiaddrTest) => {
1992
- const multiaddrString = multiaddrTest.toString();
2072
+ const multiaddrString = multiaddrTest.toString()
1993
2073
  if (
1994
2074
  multiaddrString.includes("/ip4/127.0.0.1") ||
1995
2075
  multiaddrString.includes("/ip6/")
1996
2076
  ) {
1997
- return true;
2077
+ return true
1998
2078
  }
1999
- return false;
2079
+ if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return !isWebsocket
2080
+ return !isDial
2000
2081
  },
2001
2082
  },
2002
2083
  peerDiscovery: [
@@ -2042,7 +2123,7 @@ class webpeerjs{
2042
2123
 
2043
2124
 
2044
2125
  //return webpeerjs class
2045
- return new webpeerjs(libp2p,dbstore,onMetrics)
2126
+ return new webpeerjs(libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn)
2046
2127
  }
2047
2128
  }
2048
2129