working on client-server communication
authorjordan lavatai <jordanlavatai@gmail.com>
Fri, 30 Jun 2017 22:24:07 +0000 (15:24 -0700)
committerjordan lavatai <jordanlavatai@gmail.com>
Fri, 30 Jun 2017 22:24:07 +0000 (15:24 -0700)
client.js
host.js
main.js
npm-debug.log [new file with mode: 0644]
skel.html
strapp.manifest [new file with mode: 0644]
www/Thumbs.db [new file with mode: 0644]

index 69ac81e..8989989 100644 (file)
--- a/client.js
+++ b/client.js
@@ -8,25 +8,28 @@ document.body = body
    Do this until...? Can be used for either reconnecting or waiting for answer*/
 function pollServerTimeout(url, data, resolve, reject) {
   console.log('Polling server with offer ' + data)
-  const request = XMLHttpRequest()
+  const request = new XMLHttpRequest()
   request.open('GET', url)
   request.setRequestHeader('Content-Type', 'application/json' )
+  request.setRequestHeader('X-Strapp-Type', 'o' )
   request.onreadystatechange = () => {
     if (request.status === 200) {
-      console.log('recieved answer from host ' + request.response)
+      console.log(request.response)
       resolve(request.response)
     }
     else if (request.status === 504) {
+      console.log('timed out, resending')
       pollServerTimeout(url, data, resolve, reject)
     }
     else {
-      reject('server errored out with ' + request.status)
+      reject('server unhandled response of status ' + request.status)
     }
   }
-  request.send(data)
+  console.log(data)
+  request.send('data in stufff and stuff in data')
 }
 
-/* TODO: Possible to pass resolve/reject to functions? */
+/* TODO: All this does is wrap a function in a promise */
 function pollServer(url, clientPubKey, func) {
   return new Promise((resolve, reject) => {
     func(url, clientPubKey, resolve, reject )
@@ -35,38 +38,60 @@ function pollServer(url, clientPubKey, func) {
 
 /* TODO: duplicate in both client.js and host.js */
 function getPublicKey() {
-  /* Check local storage for public key */
-  if (window.localStorage.getItem('public-key') === undefined) {
-    /* If doesn't exist, generate public and private key pair, store in
-    local storage */
-    crypto.subtle.generateKey({name:'RSA-OAEP', length: 192}, true, ['encrypt', 'decrypt'])
-      .then((keyPair) => {
-        /* TODO: Do we need to store the private key as well? */
-        window.localStorage.setItem('public-key', keyPair.type.public.toString())
-      })
-  }
-    console.log(window.localStorage.getItem('public-key'))
-    return window.localStorage.getItem('public-key')
+  return new Promise( (resolve, reject) => {
+    /* Check local storage for public key */
+    if (!window.localStorage.getItem('public-key')) {
+      console.log('public key is undefined')
+      /* If doesn't exist, generate public and private key pair, store in
+      local storage */
+      crypto.subtle.generateKey(
+        { name:'RSA-OAEP',
+          modulusLength: 2048,
+          publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+          hash: {name: "SHA-256"}
+        },
+        true,
+        ['encrypt', 'decrypt']
+        ).then((keyPair) => {
+          /* TODO: Do we need to store the private key as well? */
+          crypto.subtle.exportKey('jwk', keyPair.publicKey)
+          .then((exportedKey) => {
+            window.localStorage.setItem('publicKey', exportedKey)
+            console.log('public key is' + window.localStorage.getItem('publicKey'))
+            resolve(exportedKey)
+          })
+
+        })
+    }
+    else {
+      resolve(window.localStorage.getItem('publicKey'))
+    }
+  })
+
 }
 
 /* Create, set, and get client Offer. Poll server for host answer.
    Set host answer as client remoteDescription */
 const cpc = new RTCPeerConnection()
+console.log('creating offer')
 cpc.createOffer().then((offer) => {
-  console.log('creating offer which is ' + offer)
   return cpc.setLocalDescription(offer)
 }).then(() => {
   console.log('sessionDescriptionInit = ' + cpc.localDescription)
-  const cpk = getPublicKey()
-  let offer = {
-    cmd: '> sdp pubKey'
-    sdp: cpc.localDescription,
-    pubKey: cpk
-  }
-  /* Poll for answer */
-  return pollServer(window.location, offer, pollServerTimeout)
-}).then((answer) => {
-  console.log(answer)
-  /* TODO: State machine to parse answer */
-  cpc.setRemoteDescription(answer.sdp)
+  getPublicKey().then((cpk) => {
+    console.log('cpk is' + cpk)
+    let offer = {
+      cmd: '> sdp pubKey',
+      sdp: cpc.localDescription,
+      pubKey: cpk
+    }
+    /* Poll for answer */
+    return pollServer(window.location, offer, pollServerTimeout)
+  }).then((answer) => {
+    //console.log(answer)
+    /* TODO: State machine to parse answer */
+    cpc.setRemoteDescription(answer.sdp)
+  }).catch( (err) => {
+    console.log('error in sdp handshake: ' + err)
+  })
 })
diff --git a/host.js b/host.js
index f70732b..dd48d10 100644 (file)
--- a/host.js
+++ b/host.js
@@ -9,6 +9,7 @@ if ("WebSocket" in window) {
     }
     wsock.onmessage = (msg) => {
       /* Message is offer from client */
+      /* TODO: Determine which client ?? */
       console.log("Incoming connection " + msg)
 
       /* TODO: State machine to parse offer */
@@ -23,15 +24,16 @@ if ("WebSocket" in window) {
       }).then(() => {
         const hpk = getPublicKey()
         wsock.send({
-          cmd: '< sdp pubKey'
-          sdp: hpc.localDescription
+          cmd: '< sdp pubKey',
+          sdp: hpc.localDescription,
           pubKey: hpk
         })
         clients.push({
-          host-sdp: hpc.localDescription,
-          client-sdp: hpc.remoteDescription,
+          hostsdp: hpc.localDescription,
+          clientsdp: hpc.remoteDescription,
           clientPubKey: msg.pubKey
         })
+
       })
     }
   })
diff --git a/main.js b/main.js
index 4ada8bb..845e54b 100644 (file)
--- a/main.js
+++ b/main.js
@@ -25,8 +25,16 @@ const router = {
   httpd:      undefined,
   wsProtocol: opts['no-tls'] ? 'ws' : 'wss',
   respond:    (request,response) => {
+    let body = []
+    request.on('error', function(err) {
+      console.error(`error is ${err}`);
+    }).on('data', function(chunk) {
+      console.log(`chunk is ${chunk}`)
+      body.push(chunk);
+    }).on('end', function() {
+      console.log(`body is ${body}`)
+    })
     console.log('server handling request')
-    console.log(request)
     const serveFile = (fPath) => {
       fs.readFile(fPath, { encoding: 'utf8' }, (err, data) => {
         if (err || data == undefined) {
@@ -61,10 +69,12 @@ const router = {
     }
     /* TODO: Handle reconnecting host */
     else if (routeName in router.routes) {
+
       const route = router.routes[routeName]
-      console.log(request)
+
       /* Client is INIT GET */
-      if (request) {
+      if (request.headers['x-strapp-type'] !== 'o') {
+        console.log('client init GET')
         response.writeHead(200, { 'Content-Type': 'text/html' })
         response.write(`${router.skelPage[0]}${router.clientJS}${router.skelPage[1]}`)
         response.end()
@@ -72,7 +82,11 @@ const router = {
         //      (this happens when a client connects to an active route with no currently-online host)
       }
       else { /* Client sent offer, waiting for answer */
-
+        console.log('client offer/answer GET')
+        //route.socket.send(JSON.parse(body.join('')))
+        route.socket.on('message', (hostResponse) => {
+          console.log(hostResponse)
+        })
       }
 
     }
@@ -111,6 +125,7 @@ const router = {
   * @summary Boot up the router.  With TLS, we must wait for file reads to sync.
   */
   if (!opts['no-tls']) {
+    console.log('tls')
     let filesRead = 0
     let key = undefined
     let cert = undefined
diff --git a/npm-debug.log b/npm-debug.log
new file mode 100644 (file)
index 0000000..c971f8e
--- /dev/null
@@ -0,0 +1,99 @@
+0 info it worked if it ends with ok
+1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
+1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
+1 verbose cli   'install',
+1 verbose cli   'n',
+1 verbose cli   '-g' ]
+2 info using npm@3.10.10
+3 info using node@v6.11.0
+4 silly loadCurrentTree Starting
+5 silly install loadCurrentTree
+6 silly install readGlobalPackageData
+7 silly fetchPackageMetaData n
+8 silly fetchNamedPackageData n
+9 silly mapToRegistry name n
+10 silly mapToRegistry using default registry
+11 silly mapToRegistry registry https://registry.npmjs.org/
+12 silly mapToRegistry data Result {
+12 silly mapToRegistry   raw: 'n',
+12 silly mapToRegistry   scope: null,
+12 silly mapToRegistry   escapedName: 'n',
+12 silly mapToRegistry   name: 'n',
+12 silly mapToRegistry   rawSpec: '',
+12 silly mapToRegistry   spec: 'latest',
+12 silly mapToRegistry   type: 'tag' }
+13 silly mapToRegistry uri https://registry.npmjs.org/n
+14 verbose request uri https://registry.npmjs.org/n
+15 verbose request no auth needed
+16 info attempt registry request try #1 at 1:42:44 PM
+17 verbose request id 3f5b5b88b169934f
+18 verbose etag W/"59501789-10f80"
+19 verbose lastModified Sun, 25 Jun 2017 20:05:29 GMT
+20 http request GET https://registry.npmjs.org/n
+21 http 304 https://registry.npmjs.org/n
+22 verbose headers { date: 'Tue, 27 Jun 2017 20:42:43 GMT',
+22 verbose headers   via: '1.1 varnish',
+22 verbose headers   'cache-control': 'max-age=300',
+22 verbose headers   etag: 'W/"59501789-10f80"',
+22 verbose headers   age: '0',
+22 verbose headers   connection: 'keep-alive',
+22 verbose headers   'x-served-by': 'cache-lax8631-LAX',
+22 verbose headers   'x-cache': 'HIT',
+22 verbose headers   'x-cache-hits': '1',
+22 verbose headers   'x-timer': 'S1498596163.275721,VS0,VE158',
+22 verbose headers   vary: 'Accept-Encoding' }
+23 silly get cb [ 304,
+23 silly get   { date: 'Tue, 27 Jun 2017 20:42:43 GMT',
+23 silly get     via: '1.1 varnish',
+23 silly get     'cache-control': 'max-age=300',
+23 silly get     etag: 'W/"59501789-10f80"',
+23 silly get     age: '0',
+23 silly get     connection: 'keep-alive',
+23 silly get     'x-served-by': 'cache-lax8631-LAX',
+23 silly get     'x-cache': 'HIT',
+23 silly get     'x-cache-hits': '1',
+23 silly get     'x-timer': 'S1498596163.275721,VS0,VE158',
+23 silly get     vary: 'Accept-Encoding' } ]
+24 verbose etag https://registry.npmjs.org/n from cache
+25 verbose get saving n to C:\Users\Jordan\AppData\Roaming\npm-cache\registry.npmjs.org\n\.cache.json
+26 verbose correctMkdir C:\Users\Jordan\AppData\Roaming\npm-cache correctMkdir not in flight; initializing
+27 silly install normalizeTree
+28 silly loadCurrentTree Finishing
+29 silly loadIdealTree Starting
+30 silly install loadIdealTree
+31 silly cloneCurrentTree Starting
+32 silly install cloneCurrentTreeToIdealTree
+33 silly cloneCurrentTree Finishing
+34 silly loadShrinkwrap Starting
+35 silly install loadShrinkwrap
+36 silly loadShrinkwrap Finishing
+37 silly loadAllDepsIntoIdealTree Starting
+38 silly install loadAllDepsIntoIdealTree
+39 silly rollbackFailedOptional Starting
+40 silly rollbackFailedOptional Finishing
+41 silly runTopLevelLifecycles Finishing
+42 silly install printInstalled
+43 verbose stack Error: Unsupported platform for n@2.1.7: wanted {"name":"n","description":"Interactively Manage All Your Node Versions","version":"2.1.7","author":{"name":"TJ Holowaychuk","email":"tj@vision-media.ca"},"homepage":"https://github.com/tj/n","bugs":{"url":"https://github.com/tj/n/issues"},"contributors":[{"name":"Travis Webb","email":"me@traviswebb.com","url":"tjw.io"},{"name":"Nimit Kalra","email":"me@nimit.io","url":"http://nimit.io"},{"name":"Troy Connor","email":"troy0820@gmail.com","url":"https://github.com/troy0820"}],"keywords":["nvm","node","version","manager","switcher","node","binary","env"],"bin":{"n":"./bin/n"},"repository":{"type":"git","url":"git://github.com/tj/n.git"},"preferGlobal":true,"os":["!win32"],"engines":{"node":"*"},"license":"MIT","gitHead":"bcec70577549a9a11d89d10284f8890f0debf6d6","_id":"n@2.1.7","scripts":{},"_shasum":"13fe032a5bed0797983bddf27eb0606517c73c74","_from":"n","_npmVersion":"4.4.1","_nodeVersion":"7.7.3","_npmUser":{"name":"troy0820","email":"troy0820@gmail.com"},"dist":{"shasum":"13fe032a5bed0797983bddf27eb0606517c73c74","tarball":"https://registry.npmjs.org/n/-/n-2.1.7.tgz"},"maintainers":[{"name":"bat","email":"ben@benatkin.com"},{"name":"qw3rtman","email":"nimit@nimitkalra.com"},{"name":"tedgaydos","email":"tedgaydos@gmail.com"},{"name":"tjholowaychuk","email":"tj@vision-media.ca"},{"name":"tjwebb","email":"me@traviswebb.com"},{"name":"troy0820","email":"troy.connor@yahoo.com"}],"_npmOperationalInternal":{"host":"packages-12-west.internal.npmjs.com","tmp":"tmp/n-2.1.7.tgz_1490918508873_0.5233936926815659"},"directories":{},"_resolved":"https://registry.npmjs.org/n/-/n-2.1.7.tgz","_requested":{"raw":"n","scope":null,"escapedName":"n","name":"n","rawSpec":"","spec":"latest","type":"tag"},"_spec":"n","_where":"C:\\Users\\Jordan\\strapp","_args":[[{"raw":"n","scope":null,"escapedName":"n","name":"n","rawSpec":"","spec":"latest","type":"tag"},"C:\\Users\\Jordan\\strapp"]],"readme":"ERROR: No README data found!"} (current: {"os":"win32","cpu":"x64"})
+43 verbose stack     at checkPlatform (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-install-checks\index.js:45:14)
+43 verbose stack     at thenWarnEngineIssues (C:\Program Files\nodejs\node_modules\npm\lib\install\validate-args.js:41:5)
+43 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\iferr\index.js:13:50
+43 verbose stack     at checkEngine (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-install-checks\index.js:24:10)
+43 verbose stack     at module.exports.isInstallable (C:\Program Files\nodejs\node_modules\npm\lib\install\validate-args.js:38:3)
+43 verbose stack     at Array.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\bind-actor.js:15:8)
+43 verbose stack     at LOOP (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\chain.js:15:14)
+43 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\chain.js:18:7
+43 verbose stack     at checkSelf (C:\Program Files\nodejs\node_modules\npm\lib\install\validate-args.js:46:72)
+43 verbose stack     at Array.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\bind-actor.js:15:8)
+44 verbose pkgid n@2.1.7
+45 verbose cwd C:\Users\Jordan\strapp
+46 error Windows_NT 10.0.14393
+47 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "n" "-g"
+48 error node v6.11.0
+49 error npm  v3.10.10
+50 error code EBADPLATFORM
+51 error notsup Unsupported platform for n@2.1.7: wanted {"os":"!win32","arch":"any"} (current: {"os":"win32","arch":"x64"})
+52 error notsup Valid OS:    !win32
+52 error notsup Valid Arch:  any
+52 error notsup Actual OS:   win32
+52 error notsup Actual Arch: x64
+53 verbose exit [ 1, true ]
index 69198c3..55559f4 100644 (file)
--- a/skel.html
+++ b/skel.html
@@ -1,5 +1,5 @@
 <!DOCTYPE html>
-<html manigest="strapp.appcache">
+<html>
   <head>
     <meta charset="utf-8" />
     <title>Strapp.io</title>
@@ -7,7 +7,7 @@
     <link rel=icon href="./www/favicon-96x96.png">
     <!--STRAPP_MANIFEST-->
     <link rel=manifest href="./www/manifest.json">
-    <script src="https://github.com/PeculiarVentures/webcrypto-liner/blob/master/dist/webcrypto-liner.shim.js"></script>
+    <script type="text/plain" href="https://rawgit.com/PeculiarVentures/webcrypto-liner/master/dist/webcrypto-liner.shim.js"></script>
     <script type="text/javascript">
       <!--STRAPP_SRC-->
     </script>
diff --git a/strapp.manifest b/strapp.manifest
new file mode 100644 (file)
index 0000000..af16a0e
--- /dev/null
@@ -0,0 +1 @@
+CACHE MANIFEST
diff --git a/www/Thumbs.db b/www/Thumbs.db
new file mode 100644 (file)
index 0000000..fa4a059
Binary files /dev/null and b/www/Thumbs.db differ