Skip to content

Commit

Permalink
feat: more isolation for gun instance
Browse files Browse the repository at this point in the history
  • Loading branch information
davay42 committed Apr 24, 2023
1 parent 283469f commit cd0c2d4
Show file tree
Hide file tree
Showing 17 changed files with 177 additions and 55 deletions.
5 changes: 2 additions & 3 deletions app/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createApp } from "vue";

import * as Vue from 'vue'
import { gun } from '../src/composables'
import { useGun } from '../src/composables'

import * as components from '../src/all-components'
import { GunVuePlugin } from '../src/components'
Expand All @@ -18,11 +18,10 @@ export function createGunVueApp(
}
},
init = app => console.log('GunVue app initiated')) {

const gun = useGun();
const App = createApp(component)
App.use(GunVuePlugin)
init(App)
App.mount(tag)

return { Gun: gun, Vue, App }
}
1 change: 1 addition & 0 deletions composables/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"serve": "vite preview"
},
"dependencies": {
"ses": "^0.18.4",
"@vueuse/core": "10.0.2",
"@vueuse/integrations": "10.0.2",
"@vueuse/math": "10.0.2",
Expand Down
40 changes: 40 additions & 0 deletions docs/.vitepress/theme/youtube-iframe.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<template lang="pug">
.row.gap-12.px-4.justify-between(ref="target")
template(v-if="targetIsVisible || loaded")
.flex-1.flex.items-center.justify-center(v-for="video in list", :key="video", )
iframe.shadow-2xl.rounded-lg(
loading="lazy"
width="320",
height="200",
:src="`https://www.youtube.com/embed/${video}`",
title="YouTube video player",
frameborder="0",
allowfullscreen
)
</template>

<script setup>
import { ref, watch } from 'vue'
import { useElementVisibility } from '@vueuse/core'
const target = ref(null)
const loaded = ref(false)
const targetIsVisible = useElementVisibility(target)
watch(targetIsVisible, t => {
loaded.value = true
})
const props = defineProps({
list: {
type: Array,
default: []
}
});
</script>

<style scoped>
.row {
@apply bg-dark-200;
}
</style>
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/account/AccountBadge.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ watchEffect(() => {
name.value = d
})
gun.user().get('petnames').get(props.pub).on(async d => {
petname.value = await SEA.decrypt(d, user.pair())
petname.value = await user.decrypt(d)
})
});
Expand Down
2 changes: 1 addition & 1 deletion src/account/AccountPetname.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const editPetname = ref(false)
watch(() => props.pub, pub => {
user.db.get('petnames').get(pub).on(async d => {
petname.value = await SEA.decrypt(d, user.pair())
petname.value = await user.decrypt(d)
})
}, { immediate: true })
Expand Down
4 changes: 2 additions & 2 deletions src/account/useAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function useAccount(pubKey: MaybeRef<string>) {

if (user.is) {
gun.user().get('petnames').get(pub.value).on(async (d: string) => {
acc.petname = await SEA.decrypt(d, user.pair())
acc.petname = await user.decrypt(d)
})
}

Expand All @@ -105,6 +105,6 @@ export async function setPetname(pub: string, name: string) {
const { user } = useUser()
if (!user.is) return
const gun = useGun();
const enc = await SEA.encrypt(name, user.pair())
const enc = await user.encrypt(name)
gun.user().get('petnames').get(pub).put(enc)
}
2 changes: 0 additions & 2 deletions src/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ export function createGunVueApp(
App.use(GunVuePlugin)
init(App)
App.mount(tag)

return { Gun: gun, Vue, App }
}


Expand Down
10 changes: 3 additions & 7 deletions src/gun/useGun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
* @module Gun
* @group Database
*/


import type { GunOptions, IGunInstance } from 'gun'

import Gun from "gun/gun";
Expand All @@ -14,12 +16,6 @@ import "gun/lib/rindexed";
import "gun/lib/webrtc";


// // // polyfiils for Gun 0.2020.1236
// import { Buffer } from 'buffer'
// window.Buffer = Buffer
// window.setImmediate = setTimeout
// window.global = {}

import { relay } from './useRelay'
import { shallowReactive } from 'vue';

Expand All @@ -31,7 +27,7 @@ import { shallowReactive } from 'vue';
export let gun: IGunInstance;

/** Secondary Gun instance for key management */
export let gun2: IGunInstance;
let gun2: IGunInstance;

export const gunInstances = shallowReactive([])

Expand Down
16 changes: 10 additions & 6 deletions src/post/usePost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { computed, reactive, ref } from "vue";
import ms from "ms";

import { useGun, gun, currentRoom, useUser, removeEmptyKeys } from "../composables";
import { useGun, currentRoom, useUser, removeEmptyKeys } from "../composables";
import { useZip } from "../file/composables";
import { hashObj, hashText, safeHash } from "../crypto/composables";

Expand Down Expand Up @@ -116,6 +116,7 @@ export function usePost({ hash = "", loadMedia = true }: {
*/

export async function addPost(to, post) {
const gun = useGun();
const { user } = useUser();
const { icon, cover, content } = post;
post.icon = await saveToHash("icon", icon);
Expand Down Expand Up @@ -165,25 +166,28 @@ export async function downloadPost(post: PostContent) {
}

export async function loadFromHash(category: string, hash: string): Promise<string> {

if (
category &&
hash &&
typeof hash == "string" &&
hash.length == 44 &&
hash.slice(0, 5) != "data:"
) {
const gun = useGun();
return await gun.get('posts').get(`#${category}`).get(hash).then();
}
return hash;
}

async function saveToHash(category: string, text: string) {
if (category && text) {
const hash = await hashText(text);
gun.get('posts').get(`#${category}`).get(`${hash}`).put(text);
return hash;
const hash = await hashText(text)
const gun = useGun()
gun.get('posts').get(`#${category}`).get(`${hash}`).put(text)
return hash
} else {
return text;
return text
}
}

Expand All @@ -209,7 +213,7 @@ export async function parsePost(data: string): Promise<string> {
export function usePostTimestamp({ hash }: {
hash: string
}) {

const gun = useGun()
const timestamp = ref(0)

const msTime = computed(() => ms(Date.now() - timestamp.value || 1000))
Expand Down
4 changes: 2 additions & 2 deletions src/private/usePrivate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function usePrivateChat(pub: string): Chat {
text: message
}
const today = theDate.toLocaleDateString('en-CA')
const secret = await SEA.secret(chat.epub, user.pair())
const secret = await user.secret(chat.epub)
const work = await SEA.work(secret, undefined, undefined, { salt: today })
const enc = await SEA.encrypt(toSend, work)

Expand Down Expand Up @@ -68,7 +68,7 @@ export function usePrivateChat(pub: string): Chat {
that.map().on(async (d: string | number, k: string) => {
if (typeof d == 'number') return
if (d && d.startsWith('SEA')) {
const secret = await SEA.secret(chat.epub, user.pair())
const secret = await user.secret(chat.epub)
const work = await SEA.work(secret, undefined, undefined, { salt: today })
const dec = await SEA.decrypt(d, work)
if (!dec || typeof dec != 'object') return
Expand Down
7 changes: 5 additions & 2 deletions src/project/useProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { reactive, ref, computed } from 'vue'
import { gun, useGun2, useGun, genUUID } from '../gun/composables'
import { useGun2, useGun, genUUID } from '../gun/composables'
import { currentRoom } from '../room/composables'
import { useUser } from '../user/composables'
import { SEA } from 'gun'
Expand Down Expand Up @@ -58,6 +58,7 @@ export async function addProject() {
}

export function updateProjectField(title: string, field: string, value: string) {
const gun = useGun();
const proj = gun.user().get('projects').get(title)
proj.get(field).put(value, () => {
proj.get('updatedAt').put(Date.now())
Expand Down Expand Up @@ -139,7 +140,9 @@ export async function removeProject(path: string) {
})

} else if (currentRoom.hosts[user.pub]) {
const pair = await SEA.decrypt(currentRoom.hosts[user.pub].enc, user.pair())
const pair = await user.decrypt(currentRoom.hosts[user.pub].enc)

//@ts-ignore
gun2.user().auth(pair, () => {
gun2.user().get('projects').get(path).put(null)
})
Expand Down
2 changes: 1 addition & 1 deletion src/room/RoomActions.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const roomPub = computed(() => {
})
async function download(enc) {
const dec = await SEA.decrypt(enc, user.pair());
const dec = await user.decrypt(enc)
downloadFile(JSON.stringify(dec), 'application/json', `room-${room.profile?.name}.json`)
}
Expand Down
16 changes: 9 additions & 7 deletions src/room/useRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
*/

import {
SEA,
gun,
useGun,
generateCerts,
useUser,
Expand Down Expand Up @@ -127,7 +125,7 @@ export function useRoom(pub = currentRoom.pub) {
export function useRoomLogo(pub = currentRoom.pub) {

const logo = ref()

const gun = useGun();
gun.user(pub).get('profile').get('logo').on(hash => {
if (!hash) {
logo.value = null
Expand Down Expand Up @@ -220,14 +218,15 @@ export async function createRoom({ pair, name }: { pair: ISEAPair, name?: string
list: Object.keys(config?.features).map(f => ({ tag: f, personal: true })),
});

const enc = await SEA.encrypt(pair, user.pair());
const dec = await SEA.decrypt(enc, user.pair());
const enc = await user.encrypt(`${pair}`);
const dec = await user.decrypt(enc);

const gunConfig = {
relay: relay.peer,
features: config.features,
room: {
pub: dec.pub,
//@ts-ignore
pub: dec?.pub,
hosts: { [user.pub]: { enc, ...certs } },
features,
}
Expand Down Expand Up @@ -273,7 +272,8 @@ export async function createRoom({ pair, name }: { pair: ISEAPair, name?: string
}

export async function recreateRoom(enc: string, name?: string) {
const dec: ISEAPair = await SEA.decrypt(enc, user.pair());
//@ts-ignore
const dec: ISEAPair = await user.decrypt(enc);
createRoom({
pair: dec,
name
Expand Down Expand Up @@ -336,6 +336,7 @@ export async function addPersonal({
pub: string
cert: string
}) {
const gun = useGun();
if (!cert) cert = await gun.user(pub).get("features").get(tag).then();
if (!cert) {
cert = currentRoom.features?.[`${tag}`];
Expand All @@ -344,6 +345,7 @@ export async function addPersonal({
console.log("No certificate found");
return;
}

gun
.user(pub)
.get(`${tag}`)
Expand Down
Loading

0 comments on commit cd0c2d4

Please sign in to comment.