Home

Awesome

DWN Server <!-- omit in toc -->

Exposes a multi-tenanted DWN (aka Decentralized Web Node) through a JSON-RPC API over http: and ws:

Supported DBs

See more in Storage Options

Running online environment

Interested in contributing instantly? You can make your updates directly without cloning in the running CodeSandbox environment.

Button to click and edit the code in CodeSandbox

Installation

npm install @web5/dwn-server

Package usage

import { DwnServer } from '@web5/dwn-server';

const server = new DwnServer();

server.start();

Running the server

Running via docker

docker run -p 3000:3000 -v myvolume:/dwn-server/data ghcr.io/tbd54566975/dwn-server:main

This can run on services like AWS, GCP, VPS, home server (with ngrok or cloudflare), fly.io, render.com etc. Ideally the volume is persistent so that data is kept (or has to be synced back from another DWN instance).

Running a specific version

Running the command above will run the latest version at the time the image is pulled. If you need to run a specific version (and in many cases this is recommended) you can see the list published images here

To run a specific image: docker pull ghcr.io/tbd54566975/dwn-server@sha256:870e0f0f12016e6607060a81ea31458443f7439522fab2688d7a6706ab366c58

Running Locally for Development

git clone https://github.com/TBD54566975/dwn-server.git
cd dwn-server
npm install
npm run server

Building a docker image locally

A docker image is continuously published from this repository, but if you want to build it locally run: docker build -t dwn-server .

JSON-RPC API

JSON-RPC is a lightweight remote procedure call (RPC) protocol that uses JSON as a data format for exchanging information between a client and a server over a network. JSON-RPC is language-independent and transport-agnostic which makes it usable in a variety of contexts (e.g. browser, server-side)

With JSON-RPC, a client sends a request message to a server over a network, and the server responds with a response message.

The request message consists of:

The response message contains:

Available Methods

dwn.processMessage

Used to send DWeb Messages to the server.

Params
PropertyRequired (Y/N)Description
targetYThe DID that the message is intended for
messageYThe DWeb Message
encodedDataNData associated to the message (e.g. data associated to a RecordsWrite)
Example Request Message
{
  "jsonrpc": "2.0",
  "id": "b23f9e31-4966-4972-8048-af3eed43cb41",
  "method": "dwn.processMessage",
  "params": {
    "message": {
      "recordId": "bafyreidtix6ghjmsbg7eitexsmwzvjxc7aelagsqasybmql7zrms34ju6i",
      "descriptor": {
        "interface": "Records",
        "method": "Write",
        "dataCid": "bafkreidnfo6aux5qbg3wwzy5hvwexnoyhk3q3v47znka2afa6mf2rffkbi",
        "dataSize": 32,
        "dateCreated": "2023-04-30T22:49:37.713976Z",
        "dateModified": "2023-04-30T22:49:37.713976Z",
        "dataFormat": "application/json"
      },
      "authorization": {
        "payload": "eyJyZWNvcmRJZCI6ImJhZnlyZWlkdGl4Nmdoam1zYmc3ZWl0ZXhzbXd6dmp4YzdhZWxhZ3NxYXN5Ym1xbDd6cm1zMzRqdTZpIiwiZGVzY3JpcHRvckNpZCI6ImJhZnlyZWlheTVwNWZ1bzJhc2hqZXRvbzR1M3p1b282dW02cGlzNHl5NnUzaHE1emxsdmZhN2ZubXY0In0",
        "signatures": [
          {
            "protected": "eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDprZXk6ejZNa3UxaDRMZGtoWFczSG5uQktBTnhnVWFRMTYyY3ZXbVJ1emNiZDJZZThWc3RaI2RpZDprZXk6ejZNa3UxaDRMZGtoWFczSG5uQktBTnhnVWFRMTYyY3ZXbVJ1emNiZDJZZThWc3RaI3o2TWt1MWg0TGRraFhXM0hubkJLQU54Z1VhUTE2MmN2V21SdXpjYmQyWWU4VnN0WiJ9",
            "signature": "cy_RtWjjVK2mmKkI_35qiv54_1Pp_f7SjAx0z75PBL4th-fgfjuLZmF-V3czCWwFYMMnN0W4zl3LJ2jEf_t9DQ"
          }
        ]
      }
    },
    "target": "did:key:z6Mku1h4LdkhXW3HnnBKANxgUaQ162cvWmRuzcbd2Ye8VstZ",
    "encodedData": "ub3-FwUsSs4GgZWqt5eXSH41RKlwCx41y3dgio9Di74"
  }
}
Example Success Response
{
  "jsonrpc": "2.0",
  "id": "18eb421f-4750-4e31-a062-412b71139546",
  "result": {
    "reply": {
      "status": {
        "code": 202,
        "detail": "Accepted"
      }
    }
  }
}
Example Error Response
{
  "jsonrpc": "2.0",
  "id": "1c7f6ed8-eaaf-447c-aaf3-b9e61f3f59af",
  "error": {
    "code": -50400,
    "message": "Unexpected token ';', \";;;;@!#@!$$#!@%\" is not valid JSON"
  }
}
Transporting large amounts of data

RecordsWrite data can be of any size. If needed, large amounts of data can be streamed to the server over http by:

:bulb: Examples can be found in the examples directory.

Receiving large amounts of data

RecordsWrite data can be of any size. RecordsWrite messages returned as the result of a RecordsQuery will include encodedData if the RecordsWrite data is under 9.77KB. Data larger than this will need to be fetched using RecordsRead which can be done over http. The response to a RecordsRead includes:

Examples can be found in the examples directory.

:bulb: TODO: Add examples in examples directory

Hosting your own DWN-server

By default, when you call web5.connect() there will be some bootstrap DWN nodes included which allow people to reach you via your DID.

You may want to run a DWN server just for you, or as a public service for you and your friends and family. DWNs can be as simple as a docker image or a node process running somewhere.

DWN-servers can run anywhere you can run node.js or docker. http and websocket need to be available to the DWN server. See below for some suggestions.

Running on render.com

You can run an instance on the render.com service:

Running with ngrok

You can run a DWN-server on your local machine or home server and expose it to the internet using ngrok.

First, install ngrok

Then run:

docker run -p 3000:3000 -v myvolume:/dwn-server/data ghcr.io/tbd54566975/dwn-server:main

## in another terminal:
ngrok http 3000

Note the resulting publicly addressable https url for your DWN instance.

Running with cloudflared

Cloudflare has a tunnel service that you can use to expose your DWN server to the internet, if you run it on a server at home. With cloudflared installed, run the following commands:

git clone https://github.com/TBD54566975/dwn-server.git
cd dwn-server
npm install
npm run server

## in another terminal:

cloudflared tunnel --url http://localhost:3000

Running on GCP

... check back soon ... (enterprising people I am sure can work it out)

npm scripts

ScriptDescription
npm run build:esmcompiles typescript into ESM JS
npm run build:cjscompiles typescript into CommonJS
npm run buildcompiles typescript into ESM JS & CommonJS
npm run cleandeletes compiled JS
npm run lintruns linter
npm run lint:fixruns linter and fixes auto-fixable problems
npm run testruns tests
npm run serverstarts server
npm run prepareprepares husky for pre-commit hooks (auto-runs with npm install)

Configuration

Configuration can be set using environment variables

Env VarDescriptionDefault
DS_PORTPort that the server listens on3000
DS_MAX_RECORD_DATA_SIZEMaximum size for RecordsWrite data. use b, kb, mb, gb for value1gb
DS_WEBSOCKET_SERVERWhether to enable listening over ws:. values: on,offon
DWN_BASE_URLBase external URL of this DWN. Used to construct URL paths such as the Request URI for the Web5 Connect flow.http://localhost
DWN_EVENT_STREAM_PLUGIN_PATHPath to DWN Event Stream plugin to use. Default single-node implementation will be used if left empty.unset
DWN_REGISTRATION_STORE_URLURL to use for storage of registered DIDs. Leave unset to if DWN does not require registration (ie. open for all)unset
DWN_REGISTRATION_PROOF_OF_WORK_SEEDOptional seed to generate the challenge nonce from, this allows all DWN instances in a cluster to generate the same challenge.unset
DWN_REGISTRATION_PROOF_OF_WORK_ENABLEDRequire new users to complete a proof-of-work challengefalse
DWN_REGISTRATION_PROOF_OF_WORK_INITIAL_MAX_HASHInitial maximum allowed hash in 64 char HEX string. The more leading zeros (smaller number) the higher the difficulty.000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
DWN_STORAGEURL to use for storage by default. See Storage Options for detailslevel://data
DWN_STORAGE_MESSAGESConnection URL or file path to custom plugin to use for the message store.value of DWN_STORAGE
DWN_STORAGE_DATAConnection URL or file path to custom plugin to use for the data store.value of DWN_STORAGE
DWN_STORAGE_RESUMABLE_TASKSConnection URL or file path to custom plugin to use for the resumable task store.value of DWN_STORAGE
DWN_STORAGE_EVENTSConnection URL or file path to custom plugin to use for the event store.value of DWN_STORAGE
DWN_TERMS_OF_SERVICE_FILE_PATHRequired terms of service agreement if set. Value is path to the terms of service file.unset
DWN_TTL_CACHE_URLURL of the TTL cache used by the DWN. Currently only supports SQL databases.sqlite://

Storage Options

Several built storage options are supported, and may be configured with the DWN_STORAGE_* environment variables:

DatabaseExampleNotes
LevelDBlevel://datause three slashes for absolute paths, two for relative. Example shown uses directory data in the current working directory
Sqlitesqlite://dwn.dbuse three slashes for absolute paths, two for relative. Example shown creates a file dwn.db in the current working directory
MySQLmysql://user:pass@host/db?debug=true&timezone=-0700all URL options documented here
PostgreSQLpostgres:///dwnany options other than the URL scheme (postgres://) may also be specified via standard environment variables

Plugins

In some scenarios, you may want to provide a custom implementation of a pluggable module for the DWN Server. The following interfaces defined in dwn-sdk-js package are supported:

To load your custom plugin, specify the absolute path to the .js file of your custom implementation using the corresponding environment variable. For instance, use DWN_STORAGE_DATA for a custom DWN Data Store.

Refer to the tests/plugins/*.ts files for examples of plugin implementations. In summary, you need to:

Registration Requirements

There are multiple optional registration gates, each of which can be enabled (all are disabled by default). Tenants (DIDs) must comply with whatever requirements are enabled before they are allowed to use the server. Tenants that have not completed the registration requirements will be met with a 401. Note that registration is tracked in a database, and only SQL-based databases are supported (LevelDB is not supported). Current registration requirements are available at the /info endpoint.

Server info

the server exposes information about itself via the /info endpoint, which returns data in the following format:

{
  "server": "@web5/dwn-server",
  "maxFileSize": 1073741824,
  "registrationRequirements": ["proof-of-work-sha256-v0", "terms-of-service"],
  "version": "0.1.5",
  "sdkVersion": "0.2.6",
  "webSocketSupport": "true"
}