mirror of
https://github.com/sonr-io/sonr.git
synced 2026-08-03 09:51:39 +00:00
feature/1114 implement account interface (#1167)
- **refactor: move session-related code to middleware package** - **refactor: update PKL build process and adjust related configurations** - **feat: integrate base.cosmos.v1 Genesis module** - **refactor: pass session context to modal rendering functions** - **refactor: move nebula package to app directory and update templ version** - **refactor: Move home section video view to dedicated directory** - **refactor: remove unused views file** - **refactor: move styles and UI components to global scope** - **refactor: Rename images.go to cdn.go** - **feat: Add Empty State Illustrations** - **refactor: Consolidate Vault Index Logic** - **fix: References to App.wasm and remove Vault Directory embedded CDN files** - **refactor: Move CDN types to Models** - **fix: Correct line numbers in templ error messages for arch_templ.go** - **refactor: use common types for peer roles** - **refactor: move common types and ORM to a shared package** - **fix: Config import dwn** - **refactor: move nebula directory to app** - **feat: Rebuild nebula** - **fix: correct file paths in panels templates** - **feat: Remove duplicate types** - **refactor: Move dwn to pkg/core** - **refactor: Binary Structure** - **feat: Introduce Crypto Pkg** - **fix: Broken Process Start** - **feat: Update pkg/* structure** - **feat: Refactor PKL Structure** - **build: update pkl build process** - **chore: Remove Empty Files** - **refactor: remove unused macaroon package** - **feat: Add WebAwesome Components** - **refactor: consolidate build and generation tasks into a single taskfile, remove redundant makefile targets** - **refactor: refactor server and move components to pkg/core/dwn** - **build: update go modules** - **refactor: move gateway logic into dedicated hway command** - **feat: Add KSS (Krawczyk-Song-Song) MPC cryptography module** - **feat: Implement MPC-based JWT signing and UCAN token generation** - **feat: add support for MPC-based JWT signing** - **feat: Implement MPC-based UCAN capabilities for smart accounts** - **feat: add address field to keyshareSource** - **feat: Add comprehensive MPC test suite for keyshares, UCAN tokens, and token attenuations** - **refactor: improve MPC keyshare management and signing process** - **feat: enhance MPC capability hierarchy documentation** - **refactor: rename GenerateKeyshares function to NewKeyshareSource for clarity** - **refactor: remove unused Ethereum address computation** - **feat: Add HasHandle and IsAuthenticated methods to HTTPContext** - **refactor: Add context.Context support to session HTTPContext** - **refactor: Resolve context interface conflicts in HTTPContext** - **feat: Add session ID context key and helper functions** - **feat: Update WebApp Page Rendering** - **refactor: Simplify context management by using single HTTPContext key** - **refactor: Simplify HTTPContext creation and context management in session middleware** - **refactor: refactor session middleware to use a single data structure** - **refactor: Simplify HTTPContext implementation and session data handling** - **refactor: Improve session context handling and prevent nil pointer errors** - **refactor: Improve session context handling with nil safety and type support** - **refactor: improve session data injection** - **feat: add full-screen modal component and update registration flow** - **chore: add .air.toml to .gitignore** - **feat: add Air to devbox and update dependencies**
This commit is contained in:
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/ipfs/kubo/client/rpc"
|
||||
|
||||
apiv1 "github.com/onsonr/sonr/api/vault/v1"
|
||||
dwngen "github.com/onsonr/sonr/pkg/motr/config"
|
||||
"github.com/onsonr/sonr/pkg/core/dwn"
|
||||
didkeeper "github.com/onsonr/sonr/x/did/keeper"
|
||||
"github.com/onsonr/sonr/x/vault/types"
|
||||
)
|
||||
@@ -100,13 +100,13 @@ func NewKeeper(
|
||||
}
|
||||
|
||||
// currentSchema returns the current schema
|
||||
func (k Keeper) currentSchema(ctx sdk.Context) (*dwngen.Schema, error) {
|
||||
func (k Keeper) currentSchema(ctx sdk.Context) (*dwn.Schema, error) {
|
||||
p, err := k.Params.Get(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
schema := p.Schema
|
||||
return &dwngen.Schema{
|
||||
return &dwn.Schema{
|
||||
Version: int(schema.Version),
|
||||
Account: schema.Account,
|
||||
Asset: schema.Asset,
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
sdk "github.com/cosmos/cosmos-sdk/types"
|
||||
"github.com/onsonr/crypto/mpc"
|
||||
|
||||
"github.com/onsonr/sonr/pkg/crypto/mpc"
|
||||
"github.com/onsonr/sonr/x/did/controller"
|
||||
"github.com/onsonr/sonr/x/vault/types"
|
||||
)
|
||||
@@ -65,7 +65,7 @@ func (k Querier) Allocate(goCtx context.Context, req *types.QueryAllocateRequest
|
||||
}
|
||||
|
||||
// 2. Generate MPC Keyshares for new Account
|
||||
shares, err := mpc.GenerateKeyshares()
|
||||
shares, err := mpc.NewKeyshareSource()
|
||||
if err != nil {
|
||||
ctx.Logger().Error(fmt.Sprintf("Error generating keyshares: %s", err.Error()))
|
||||
return nil, types.ErrInvalidSchema.Wrap(err.Error())
|
||||
@@ -79,14 +79,14 @@ func (k Querier) Allocate(goCtx context.Context, req *types.QueryAllocateRequest
|
||||
}
|
||||
|
||||
// 4. Create a new vault PWA for service-worker
|
||||
v, err := types.NewVault("", con.SonrAddress(), con.ChainID(), sch)
|
||||
v, err := types.SpawnVault("", con.SonrAddress(), con.ChainID(), sch)
|
||||
if err != nil {
|
||||
ctx.Logger().Error(fmt.Sprintf("Error creating vault: %s", err.Error()))
|
||||
return nil, types.ErrInvalidSchema.Wrap(err.Error())
|
||||
}
|
||||
|
||||
// 5. Add to IPFS and Return CID for User Claims in Gateway
|
||||
cid, err := k.ipfsClient.Unixfs().Add(context.Background(), v.FS)
|
||||
cid, err := k.ipfsClient.Unixfs().Add(context.Background(), v)
|
||||
if err != nil {
|
||||
ctx.Logger().Error(fmt.Sprintf("Error adding to IPFS: %s", err.Error()))
|
||||
return nil, types.ErrVaultAssembly.Wrap(err.Error())
|
||||
|
||||
+10
-9
@@ -3,7 +3,8 @@ package types
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/onsonr/sonr/pkg/motr/types/orm"
|
||||
"github.com/onsonr/sonr/pkg/common"
|
||||
orm "github.com/onsonr/sonr/pkg/common/models"
|
||||
)
|
||||
|
||||
// DefaultParams returns default module parameters.
|
||||
@@ -35,13 +36,13 @@ func (p Params) Validate() error {
|
||||
// DefaultSchema returns the default schema
|
||||
func DefaultSchema() *Schema {
|
||||
return &Schema{
|
||||
Version: orm.SchemaVersion,
|
||||
Account: orm.GetSchema(&orm.Account{}),
|
||||
Asset: orm.GetSchema(&orm.Asset{}),
|
||||
Chain: orm.GetSchema(&orm.Chain{}),
|
||||
Credential: orm.GetSchema(&orm.Credential{}),
|
||||
Grant: orm.GetSchema(&orm.Grant{}),
|
||||
Keyshare: orm.GetSchema(&orm.Keyshare{}),
|
||||
Profile: orm.GetSchema(&orm.Profile{}),
|
||||
Version: common.SchemaVersion,
|
||||
Account: common.GetSchema(&orm.Account{}),
|
||||
Asset: common.GetSchema(&orm.Asset{}),
|
||||
Chain: common.GetSchema(&orm.Chain{}),
|
||||
Credential: common.GetSchema(&orm.Credential{}),
|
||||
Grant: common.GetSchema(&orm.Grant{}),
|
||||
Keyshare: common.GetSchema(&orm.Keyshare{}),
|
||||
Profile: common.GetSchema(&orm.Profile{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"github.com/ipfs/boxo/files"
|
||||
|
||||
"github.com/onsonr/sonr/pkg/core/dwn"
|
||||
"github.com/onsonr/sonr/x/vault/types/static"
|
||||
)
|
||||
|
||||
const (
|
||||
kFileNameConfigJSON = "dwn.json"
|
||||
kFileNameIndexHTML = "index.html"
|
||||
kFileNameWorkerJS = "sw.js"
|
||||
)
|
||||
|
||||
type Vault = files.Directory
|
||||
|
||||
func SpawnVault(keyshareJSON string, adddress string, chainID string, schema *dwn.Schema) (Vault, error) {
|
||||
dwnCfg := &dwn.Config{
|
||||
MotrKeyshare: keyshareJSON,
|
||||
MotrAddress: adddress,
|
||||
IpfsGatewayUrl: "https://ipfs.sonr.land",
|
||||
SonrApiUrl: "https://api.sonr.land",
|
||||
SonrRpcUrl: "https://rpc.sonr.land",
|
||||
SonrChainId: chainID,
|
||||
VaultSchema: schema,
|
||||
}
|
||||
cnf, err := dwnCfg.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return setupVaultDirectory(cnf), nil
|
||||
}
|
||||
|
||||
// spawnVaultDirectory creates a new directory with the default files
|
||||
func setupVaultDirectory(cfgBz []byte) files.Directory {
|
||||
return files.NewMapDirectory(map[string]files.Node{
|
||||
kFileNameConfigJSON: files.NewBytesFile(cfgBz),
|
||||
kFileNameIndexHTML: files.NewBytesFile(static.IndexHTML),
|
||||
kFileNameWorkerJS: files.NewBytesFile(static.WorkerJS),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Sonr DWN</title>
|
||||
<script type="text/javascript">
|
||||
if ("serviceWorker" in navigator) {
|
||||
// Register the service worker
|
||||
window.addEventListener("load", function () {
|
||||
navigator.serviceWorker
|
||||
.register("/sw.js")
|
||||
.then(function (registration) {
|
||||
console.log(
|
||||
"Service Worker registered with scope:",
|
||||
registration.scope,
|
||||
);
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log("Service Worker registration failed:", error);
|
||||
});
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body
|
||||
class="flex items-center justify-center h-full bg-zinc-50 lg:p-24 md:16 p-4"
|
||||
>
|
||||
<main
|
||||
class="flex-row items-center justify-center mx-auto w-fit max-w-screen-sm gap-y-3"
|
||||
>
|
||||
<div hx-get="/#" swap="outerHTML">Loading...</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed index.html
|
||||
var IndexHTML []byte
|
||||
|
||||
//go:embed sw.js
|
||||
var WorkerJS []byte
|
||||
@@ -0,0 +1,258 @@
|
||||
// Cache names for different types of resources
|
||||
const CACHE_NAMES = {
|
||||
wasm: 'wasm-cache-v1',
|
||||
static: 'static-cache-v1',
|
||||
dynamic: 'dynamic-cache-v1'
|
||||
};
|
||||
|
||||
// Import required scripts
|
||||
importScripts(
|
||||
"https://cdn.jsdelivr.net/gh/golang/go@go1.22.5/misc/wasm/wasm_exec.js",
|
||||
"https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v1.1.0/sw.js",
|
||||
);
|
||||
|
||||
// Initialize WASM HTTP listener
|
||||
const wasmInstance = registerWasmHTTPListener("https://cdn.sonr.id/wasm/app.wasm");
|
||||
|
||||
// MessageChannel port for WASM communication
|
||||
let wasmPort;
|
||||
|
||||
// Request queue for offline operations
|
||||
let requestQueue = new Map();
|
||||
|
||||
// Setup message channel handler
|
||||
self.addEventListener('message', async (event) => {
|
||||
if (event.data.type === 'PORT_INITIALIZATION') {
|
||||
wasmPort = event.data.port;
|
||||
setupWasmCommunication();
|
||||
}
|
||||
});
|
||||
|
||||
function setupWasmCommunication() {
|
||||
wasmPort.onmessage = async (event) => {
|
||||
const { type, data } = event.data;
|
||||
|
||||
switch (type) {
|
||||
case 'WASM_REQUEST':
|
||||
handleWasmRequest(data);
|
||||
break;
|
||||
case 'SYNC_REQUEST':
|
||||
processSyncQueue();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Notify that WASM is ready
|
||||
wasmPort.postMessage({ type: 'WASM_READY' });
|
||||
}
|
||||
|
||||
// Enhanced install event
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(
|
||||
Promise.all([
|
||||
skipWaiting(),
|
||||
// Cache WASM binary and essential resources
|
||||
caches.open(CACHE_NAMES.wasm).then(cache =>
|
||||
cache.addAll([
|
||||
'https://cdn.sonr.id/wasm/app.wasm',
|
||||
'https://cdn.jsdelivr.net/gh/golang/go@go1.22.5/misc/wasm/wasm_exec.js'
|
||||
])
|
||||
)
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
// Enhanced activate event
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
Promise.all([
|
||||
clients.claim(),
|
||||
// Clean up old caches
|
||||
caches.keys().then(keys =>
|
||||
Promise.all(
|
||||
keys.map(key => {
|
||||
if (!Object.values(CACHE_NAMES).includes(key)) {
|
||||
return caches.delete(key);
|
||||
}
|
||||
})
|
||||
)
|
||||
)
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
// Intercept fetch events
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const request = event.request;
|
||||
|
||||
// Handle API requests differently from static resources
|
||||
if (request.url.includes('/api/')) {
|
||||
event.respondWith(handleApiRequest(request));
|
||||
} else {
|
||||
event.respondWith(handleStaticRequest(request));
|
||||
}
|
||||
});
|
||||
|
||||
async function handleApiRequest(request) {
|
||||
try {
|
||||
// Try to make the request
|
||||
const response = await fetch(request.clone());
|
||||
|
||||
// If successful, pass through WASM handler
|
||||
if (response.ok) {
|
||||
return await processWasmResponse(request, response);
|
||||
}
|
||||
|
||||
// If offline or failed, queue the request
|
||||
await queueRequest(request);
|
||||
|
||||
// Return cached response if available
|
||||
const cachedResponse = await caches.match(request);
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
// Return offline response
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Currently offline' }),
|
||||
{
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
await queueRequest(request);
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Request failed' }),
|
||||
{
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStaticRequest(request) {
|
||||
// Check cache first
|
||||
const cachedResponse = await caches.match(request);
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
|
||||
// Cache successful responses
|
||||
if (response.ok) {
|
||||
const cache = await caches.open(CACHE_NAMES.static);
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
// Return offline page for navigation requests
|
||||
if (request.mode === 'navigate') {
|
||||
return caches.match('/offline.html');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function processWasmResponse(request, response) {
|
||||
// Clone the response before processing
|
||||
const responseClone = response.clone();
|
||||
|
||||
try {
|
||||
// Process through WASM
|
||||
const processedResponse = await wasmInstance.processResponse(responseClone);
|
||||
|
||||
// Notify client through message channel
|
||||
if (wasmPort) {
|
||||
wasmPort.postMessage({
|
||||
type: 'RESPONSE',
|
||||
requestId: request.headers.get('X-Wasm-Request-ID'),
|
||||
response: processedResponse
|
||||
});
|
||||
}
|
||||
|
||||
return processedResponse;
|
||||
} catch (error) {
|
||||
console.error('WASM processing error:', error);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
async function queueRequest(request) {
|
||||
const serializedRequest = await serializeRequest(request);
|
||||
requestQueue.set(request.url, serializedRequest);
|
||||
|
||||
// Register for background sync
|
||||
try {
|
||||
await self.registration.sync.register('wasm-sync');
|
||||
} catch (error) {
|
||||
console.error('Sync registration failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function serializeRequest(request) {
|
||||
const headers = {};
|
||||
for (const [key, value] of request.headers.entries()) {
|
||||
headers[key] = value;
|
||||
}
|
||||
|
||||
return {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers,
|
||||
body: await request.text(),
|
||||
timestamp: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
// Handle background sync
|
||||
self.addEventListener('sync', (event) => {
|
||||
if (event.tag === 'wasm-sync') {
|
||||
event.waitUntil(processSyncQueue());
|
||||
}
|
||||
});
|
||||
|
||||
async function processSyncQueue() {
|
||||
const requests = Array.from(requestQueue.values());
|
||||
|
||||
for (const serializedRequest of requests) {
|
||||
try {
|
||||
const response = await fetch(new Request(serializedRequest.url, {
|
||||
method: serializedRequest.method,
|
||||
headers: serializedRequest.headers,
|
||||
body: serializedRequest.body
|
||||
}));
|
||||
|
||||
if (response.ok) {
|
||||
requestQueue.delete(serializedRequest.url);
|
||||
|
||||
// Notify client of successful sync
|
||||
if (wasmPort) {
|
||||
wasmPort.postMessage({
|
||||
type: 'SYNC_COMPLETE',
|
||||
url: serializedRequest.url
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Sync failed for request:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle payment requests
|
||||
self.addEventListener("canmakepayment", function (e) {
|
||||
e.respondWith(Promise.resolve(true));
|
||||
});
|
||||
|
||||
// Handle periodic sync if available
|
||||
self.addEventListener('periodicsync', (event) => {
|
||||
if (event.tag === 'wasm-sync') {
|
||||
event.waitUntil(processSyncQueue());
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"github.com/ipfs/boxo/files"
|
||||
|
||||
"github.com/onsonr/sonr/pkg/motr"
|
||||
"github.com/onsonr/sonr/pkg/motr/config"
|
||||
)
|
||||
|
||||
type Vault struct {
|
||||
FS files.Node
|
||||
}
|
||||
|
||||
func NewVault(keyshareJSON string, adddress string, chainID string, schema *config.Schema) (*Vault, error) {
|
||||
dwnCfg := &config.Config{
|
||||
MotrKeyshare: keyshareJSON,
|
||||
MotrAddress: adddress,
|
||||
IpfsGatewayUrl: "https://ipfs.sonr.land",
|
||||
SonrApiUrl: "https://api.sonr.land",
|
||||
SonrRpcUrl: "https://rpc.sonr.land",
|
||||
SonrChainId: chainID,
|
||||
VaultSchema: schema,
|
||||
}
|
||||
fileMap, err := motr.NewVaultDirectory(dwnCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Vault{
|
||||
FS: fileMap,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user