Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor DID Connect and add App DIDs and Permissions #37

Merged
merged 3 commits into from
Apr 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
556 changes: 382 additions & 174 deletions examples/test-dashboard/desktop-agent.html

Large diffs are not rendered by default.

26 changes: 24 additions & 2 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tbd54566975/web5",
"version": "0.4.0",
"version": "0.5.0",
"description": "SDK for accessing the features and capabilities of Web5",
"type": "module",
"main": "./dist/cjs/index.js",
Expand Down Expand Up @@ -49,6 +49,7 @@
"license": "Apache-2.0",
"devDependencies": {
"chai": "4.3.7",
"chai-as-promised": "^7.1.1",
"esbuild": "0.16.17",
"eslint": "8.36.0",
"karma": "6.4.1",
Expand All @@ -73,4 +74,4 @@
"ed2curve": "0.3.0",
"tweetnacl": "1.0.3"
}
}
}
173 changes: 6 additions & 167 deletions src/Web5.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
import nacl from 'tweetnacl';

import { Web5DID } from './did/Web5DID.js';
import { Web5DWN } from './dwn/Web5DWN.js';
import { LocalStorage } from './storage/LocalStorage.js';
import { AppTransport } from './transport/AppTransport.js';
import { HTTPTransport } from './transport/HTTPTransport.js';
import {
decodePin,
isUnsignedMessage,
parseJSON,
parseURL,
triggerProtocolHandler,
} from './utils.js';
import { isUnsignedMessage, parseURL } from './utils.js';

class Web5 extends EventTarget {
#dwn;
#did;
#transports;

#keys = null;
#connection = null;

constructor(options = { }) {
super();

Expand All @@ -47,10 +35,10 @@ class Web5 extends EventTarget {

/**
* @param {string} target The DID to send the message to.
* @param {Object} request - Object containing the request parameters.
* @param {object} request - Object containing the request parameters.
* @param {string} request.author - The DID of the author of the message.
* @param {*} request.data - The message data (if any).
* @param {Object} request.message - The DWeb message.
* @param {object} request.message - The DWeb message.
* @returns Promise
*/
async send(target, request) {
Expand All @@ -76,7 +64,7 @@ class Web5 extends EventTarget {

if (resolvedTarget?.connected) {
return this.#send([resolvedTarget.endpoint], { author, data, message, target });
} else if (resolvedTarget) {
} else if (resolvedTarget?.didDocument) {
// Resolve the DWN endpoint(s) of the target and send using the endpoint's transport protocol (e.g., HTTP).
const dwnServices = await this.#did.getServices(target, { cache: true, type: 'DecentralizedWebNode' });
const dwnNodes = dwnServices[0]?.serviceEndpoint?.nodes;
Expand All @@ -89,155 +77,6 @@ class Web5 extends EventTarget {
return { status: { code: 422, detail: 'Target DID could not be resolved' } };
}

async connect(options = { }) {
const storage = options?.storage ?? new LocalStorage();
const connectionLocation = options?.connectionLocation ?? 'web5-connection';
const keysLocation = options?.keysLocation ?? 'web5-keys';

if (this.#connection) {
return;
}

this.#connection = await storage.get(connectionLocation);
if (this.#connection) {
// Register DID on reconnection
await this.#did.register({
connected: true,
did: this.#connection.did,
endpoint: `http://localhost:${this.#connection.port}/dwn`,
});

this.dispatchEvent(new CustomEvent('connection', { detail: this.#connection }));
return;
}

if (options?.silent) {
return;
}

if (!this.#keys) {
const keys = await storage.get(keysLocation);
if (keys) {
this.#keys = {
encoded: keys,
decoded: {
publicKey: this.#dwn.SDK.Encoder.base64UrlToBytes(keys.publicKey),
secretKey: this.#dwn.SDK.Encoder.base64UrlToBytes(keys.secretKey),
},
};
} else {
const keys = nacl.box.keyPair();
this.#keys = {
encoded: {
publicKey: this.#dwn.SDK.Encoder.bytesToBase64Url(keys.publicKey),
secretKey: this.#dwn.SDK.Encoder.bytesToBase64Url(keys.secretKey),
},
decoded: keys,
};
await storage.set(keysLocation, this.#keys.encoded);
}
}

const encodedOrigin = this.#dwn.SDK.Encoder.stringToBase64Url(location.origin);
triggerProtocolHandler(`web5://connect/${this.#keys.encoded.publicKey}/${encodedOrigin}`);

function destroySocket(socket) {
socket.close();
socket.removeEventListener('open', handleOpen);
socket.removeEventListener('error', handleError);
socket.removeEventListener('message', handleMessage);
}

const removeSocket = (socket) => {
destroySocket(socket);
sockets.delete(socket);

if (!sockets.size) {
this.dispatchEvent(new CustomEvent('error'));
}
};

function handleOpen(event) {
const socket = event.target;

socket.addEventListener('message', handleMessage);
}

function handleError(event) {
const socket = event.target;

removeSocket(socket);
}

const handleMessage = async (event) => {
const socket = event.target;

const json = parseJSON(event.data);

switch (json?.type) {
case 'connected':
if (!json.data) {
removeSocket(socket);
return;
}

this.#connection = json.data;
await storage.set(connectionLocation, this.#connection);

// Register DID on initial connection
await this.#did.register({
connected: true,
did: this.#connection.did,
endpoint: `http://localhost:${this.#connection.port}/dwn`,
});

this.dispatchEvent(new CustomEvent('connection', { detail: this.#connection }));
break;

case 'requested':
if (!json.data) {
removeSocket(socket);
return;
}

try {
await decodePin(json.data, this.#keys.decoded.secretKey);
} catch {
removeSocket(socket);
return;
}

this.dispatchEvent(new CustomEvent('open', { detail: json.data }));
return;

case 'blocked':
case 'denied':
case 'closed':
this.dispatchEvent(new CustomEvent('close'));
break;

case 'unknown':
return;

default:
removeSocket(socket);
return;
}

sockets.forEach(destroySocket);
sockets.clear();
};

const sockets = new Set();
for (let port = 55_500; port <= 55_600; ++port) {
const socket = new WebSocket(`ws://localhost:${port}/connections/${this.#keys.encoded.publicKey}`);
sockets.add(socket);

socket.addEventListener('open', handleOpen);
socket.addEventListener('error', handleError);
}
}

async #createSignedMessage(resolvedAuthor, message, data) {
const authorizationSignatureInput = this.#dwn.SDK.Jws.createSignatureInput({
keyId: resolvedAuthor.did + '#key-1',
Expand All @@ -264,10 +103,10 @@ class Web5 extends EventTarget {
* Service Endpoint URIs in the nodes array in index order, so this function makes that approach easy.
*
* @param {string[]} endpoints - An array of one or more endpoints to send the message to.
* @param {Object} request - Object containing the request parameters.
* @param {object} request - Object containing the request parameters.
* @param {string} request.author - The DID of the author of the message.
* @param {*} request.data - The message data (if any).
* @param {Object} request.message - The DWeb message.
* @param {object} request.message - The DWeb message.
* @param {string} request.target - The DID to send the message to.
* @returns Promise
*/
Expand Down
Loading