Skip to content
This repository has been archived by the owner on Sep 18, 2020. It is now read-only.

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Ray committed Jul 10, 2019
1 parent 29cecdd commit f636a03
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 32 deletions.
77 changes: 57 additions & 20 deletions src/lib/masq.js
Expand Up @@ -86,8 +86,8 @@ const requiredParametersProfile = [
* Open or create a hyperdb instance
* @param {string} name The indexeddb store name
*/
const openOrCreateDB = (name) => {
return createPromisifiedHyperDB(name)
const openOrCreateDB = (name, key = null) => {
return createPromisifiedHyperDB(name, key)
}

const dispatchMasqError = (errorCode) => {
Expand Down Expand Up @@ -152,8 +152,10 @@ class Masq {
apps.forEach(app => {
const dbName = `app-${profileId}-${app.id}`
const db = openOrCreateDB(dbName)
this.appsDBs[dbName] = db
db.on('ready', () => this._startReplicate(db))
db.on('ready', () => {
this.appsDBs[db.key.toString('hex')] = db
this._startReplicate(db)
})
})

const profile = await this.getAndDecrypt('/profile')
Expand All @@ -164,10 +166,13 @@ class Masq {
if (!device) {
const { name, os } = DetectBrowser.detect()
await this.addDevice({
name: `${capitalize(name)} - ${os}`
name: `${capitalize(name)} - ${os}`,
apps: []
})
}

this._watchAndAuthorizeApps()

return profile
}

Expand Down Expand Up @@ -359,7 +364,10 @@ class Masq {
removeApp (app) {
checkObject(app, requiredParametersApp)
const dbName = `app-${this.profileId}-${app.id}`
const discoveryKey = this.appsDBs[dbName].discoveryKey.toString('hex')
console.log('okok1')
const discoveryKey = this.appsDBs[app.key].discoveryKey.toString('hex')
console.log('okok2')
// missing key
const sw = this.swarms[discoveryKey]
sw.close()
window.indexedDB.deleteDatabase(dbName)
Expand All @@ -376,7 +384,8 @@ class Masq {
await this.encryptAndPut(`/devices/${id}`, {
id,
...device,
localKey: this.profileDB.local.key.toString('hex')
localKey: this.profileDB.local.key.toString('hex'),
apps: []
})
}

Expand Down Expand Up @@ -583,6 +592,7 @@ class Masq {
const db = await this._createDBAndSyncApp(dbName)
// this.dbName must be filled only during the userApp register protocol
this.dbName = dbName
const key = db.key.toString('hex')

const dbKey = db.key.toString('hex')
const userAppDbId = id
Expand All @@ -594,18 +604,18 @@ class Masq {
const data = { msg: 'masqAccessGranted', key: dbKey, userAppDbId, userAppDEK, username, profileImage, userAppNonce }
const encryptedMsg = await encrypt(this.key, data, 'base64')
peer.send(JSON.stringify(encryptedMsg))
await this.receiveRequestWriteAccess(peer, dbName)
await this.receiveRequestWriteAccess(peer, key)
}

async receiveRequestWriteAccess (peer, dbName) {
async receiveRequestWriteAccess (peer, key) {
return new Promise(async (resolve, reject) => {
peer.once('data', async (data) => {
const json = await decrypt(this.key, JSON.parse(data), 'base64')

if (json.msg === 'requestWriteAccess') {
this.setState(STATES.REQUEST_WRITE_ACCESS_MATERIAL)
try {
await this._grantWriteAccess(peer, json, dbName)
await this._grantWriteAccess(peer, json, key)
await this._closeUserAppConnection()
resolve()
} catch (e) {
Expand All @@ -619,10 +629,10 @@ class Masq {
})
}

async _grantWriteAccess (peer, json, dbName) {
async _grantWriteAccess (peer, json, key) {
const userAppKey = Buffer.from(json.key, 'hex')
try {
await this.appsDBs[dbName].authorizeAsync(userAppKey)
await this.appsDBs[key].authorizeAsync(userAppKey)
} catch (err) {
throw new MasqError(MasqError.AUTHORIZE_DB_KEY_FAILED)
}
Expand All @@ -632,17 +642,44 @@ class Masq {
peer.send(JSON.stringify(encryptedMsg))
}

_createDBAndSyncApp (dbName) {
_watchAndAuthorizeApps () {
watch(this.profileDB, this.nonce, '/devices', async () => {
const allDevices = await this.getDevices()
const otherDevices = allDevices.filter(d => {
return d.localKey !== this.profileDB.local.key.toString('hex')
})

for (let otherDevice of otherDevices) {
for (let app of otherDevice.apps) {
if (!this.appsDBs[app.key]) {
continue
}

const keyBuf = Buffer.from(app.localKey, 'hex')

if (await this.appsDBs[app.key].authorizedAsync(keyBuf)) {
// console.log('ALREADY authorized')
} else {
// console.log('NOT authorized')
await this.appsDBs[app.key].authorizeAsync(keyBuf)
}
}
}
})
}

_createDBAndSyncApp (dbName, hex = null) {
return new Promise((resolve, reject) => {
const db = openOrCreateDB(dbName)
this.appsDBs[dbName] = db
const db = openOrCreateDB(dbName, hex)
db.on('ready', async () => {
this.appsDBs[db.key.toString('hex')] = db
const device = await this.getDevice()
await this.updateDevice({
...device,
apps: [{
apps: [...device.apps, {
id: dbName,
localKey: db.local.key
key: db.key.toString('hex'),
localKey: db.local.key.toString('hex')
}]
})
this._startReplicate(db)
Expand Down Expand Up @@ -787,9 +824,9 @@ class Masq {
this.hubs = {}
}

_stopReplicate (dbName) {
const discoveryKey = this.appsDBs[dbName].discoveryKey.toString('hex')
this.appsDBs[dbName] = null
_stopReplicate (key) {
const discoveryKey = this.appsDBs[key].discoveryKey.toString('hex')
this.appsDBs[key] = null
this.hubs[discoveryKey] = null
this.swarms[discoveryKey].close()
this.swarms[discoveryKey] = null
Expand Down
28 changes: 21 additions & 7 deletions src/lib/sync-profile.js
Expand Up @@ -111,14 +111,28 @@ class SyncProfile {
await sendEncryptedJSON({ msg: 'writeAccessGranted' }, this.key, this.peer)
}

async pullApps (masq) {
async pullApps (masq, prefix = '') {
console.log('pullApps')
// const apps = await masq.getApps()

// this.db = await createPromisifiedHyperDB('profile-' + id, key)
// await dbReady(this.db)
// Start to replicate the profile
// this.masq._startReplicate(this.db)
const device = await masq.getDevice()
const allDevices = await masq.getDevices()
// console.log('pullApps', allDevices)
const otherDevices = allDevices.filter(d => {
return d.localKey !== masq.profileDB.local.key.toString('hex')
})
// console.log('otherDevices', otherDevices)

for (let otherDevice of otherDevices) {
// d.apps, copy key, and add own localKey
// console.log('pullApps device apps', otherDevice.apps)
const newApps = otherDevice.apps.filter(({ key }) => {
return !(device.apps.find(app => app.key === key))
})

console.log('newApps', newApps)
for (let newApp of newApps) {
await masq._createDBAndSyncApp(newApp.id + prefix, newApp.key)
}
}
}
}

Expand Down
50 changes: 45 additions & 5 deletions test/sync-profile.test.js
Expand Up @@ -19,6 +19,7 @@ const waitForSync = async (db1, db2) => {
if (err) { throw err }
db2.version((err, currentVersion) => {
if (err) { throw err }
console.log(currentVersion.toString('hex'), latestVersion.toString('hex'))
if (currentVersion.toString('hex') === latestVersion.toString('hex')) {
return resolve()
}
Expand Down Expand Up @@ -139,12 +140,51 @@ describe('sync-profile', function () {
expect(devices[1].localKey).to.have.lengthOf(64)
expect(devices[0].localKey).to.not.equal(devices[1].localKey)

// expect(devices[1].apps).to.have.lengthOf(1)
let device1 = await masq.getDevice()
expect(device1.apps).to.have.lengthOf(1)
expect(device1.apps[0].id).to.exist
expect(device1.apps[0].key).to.have.lengthOf(64)
expect(device1.apps[0].localKey).to.have.lengthOf(64)
expect(device1.apps[0].localKey).to.equal(device1.apps[0].key)

// await masq.addApp({ name: 'new app', description: 'test', appId: 'id' })
})
expect(masq.appsDBs[device1.apps[0].key]).to.exist
expect(masq.appsDBs[device1.apps[0].key]._authorized).to.have.lengthOf(1)

await sp2.pullApps(masq2, '-copy')

let device2 = await masq2.getDevice()
expect(device2.apps).to.have.lengthOf(1)
expect(device2.apps[0].id).to.exist
expect(device2.apps[0].key).to.have.lengthOf(64)
expect(device2.apps[0].localKey).to.have.lengthOf(64)
expect(device2.apps[0].localKey).to.not.equal(device2.apps[0].key)

expect(masq2.appsDBs[device2.apps[0].key]).to.exist

await new Promise((resolve) => {
setTimeout(resolve, 5000)
})

const appKey = device1.apps[0].key
expect(masq.appsDBs[appKey]._authorized).to.have.lengthOf(2)
expect(masq2.appsDBs[appKey]._authorized).to.have.lengthOf(2)

// await masq2.addApp({
// name: 'another app added on second device',
// description: 'description of the app',
// appId: 'id2'
// })

// it('should pull apps', async () => {
await masq2._createDBAndSyncApp('app2')
await waitForSync(masq2.profileDB, masq.profileDB)

// })
await sp1.pullApps(masq, '-copy')
device1 = await masq.getDevice()
device2 = await masq2.getDevice()
expect(device1.apps).to.have.lengthOf(2)
expect(device2.apps).to.have.lengthOf(2)

expect(masq.appsDBs[appKey]._authorized).to.have.lengthOf(2)
expect(masq2.appsDBs[appKey]._authorized).to.have.lengthOf(2)
})
})

0 comments on commit f636a03

Please sign in to comment.