├── src ├── third.party.types.d.ts ├── index.ts ├── helpers.ts ├── configuration.ts ├── __tests__ │ └── resolver.test.ts └── resolver.ts ├── babel.config.js ├── .prettierrc ├── babel-preset.js ├── .eslintrc.js ├── .releaserc ├── .github ├── workflows │ ├── test.yml │ └── release.yml ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── stale.yml ├── tsconfig.json ├── renovate.json ├── README.md ├── CHANGELOG.md ├── .vscode └── launch.json ├── Contributing.md ├── package.json ├── .gitignore └── LICENSE /src/third.party.types.d.ts: -------------------------------------------------------------------------------- 1 | declare module '@ensdomains/ensjs' 2 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'] 3 | } 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "jsxBracketSameLine": false, 3 | "tabWidth": 2, 4 | "printWidth": 120, 5 | "singleQuote": true, 6 | "trailingComma": "es5", 7 | "semi": false, 8 | "endOfLine":"auto" 9 | } 10 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { getResolver } from './resolver' 2 | export { 3 | ConfigurationOptions, 4 | InfuraConfiguration, 5 | MultiProviderConfiguration, 6 | ProviderConfiguration, 7 | } from './configuration' 8 | -------------------------------------------------------------------------------- /babel-preset.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | sourceMaps: true, 3 | plugins: [ 4 | [ 5 | 'module-resolver', 6 | { 7 | alias: { 8 | crypto: 'crypto-browserify' 9 | } 10 | } 11 | ] 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | 'jest/globals': true 5 | }, 6 | extends: [ 7 | 'eslint:recommended', 8 | 'plugin:@typescript-eslint/recommended', 9 | 'plugin:prettier/recommended' 10 | ], 11 | parser: '@typescript-eslint/parser', 12 | parserOptions: { 13 | ecmaVersion: 2018, 14 | sourceType: 'module' 15 | }, 16 | plugins: ['@typescript-eslint', 'jest'], 17 | rules: {} 18 | } 19 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "tagFormat": "${version}", 3 | "plugins": [ 4 | "@semantic-release/commit-analyzer", 5 | "@semantic-release/release-notes-generator", 6 | ["@semantic-release/changelog", { 7 | "changelogFile": "CHANGELOG.md" 8 | }], 9 | "@semantic-release/npm", 10 | ["@semantic-release/git", { 11 | "assets": ["CHANGELOG.md", "docs", "package.json", "yarn.lock"], 12 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" 13 | }], 14 | "@semantic-release/github" 15 | ], 16 | "branches": ["main"] 17 | } 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test NODE 2 | on: [push, pull_request, workflow_dispatch] 3 | jobs: 4 | build-test: 5 | runs-on: ubuntu-22.04 6 | steps: 7 | - uses: actions/checkout@v4 8 | with: 9 | fetch-depth: 0 10 | - name: "Setup node with cache" 11 | uses: actions/setup-node@v4 12 | with: 13 | node-version: 18 14 | cache: 'yarn' 15 | 16 | - run: yarn install --frozen-lockfile 17 | - run: yarn run build 18 | - run: yarn run lint 19 | - run: yarn run test:ci 20 | 21 | - name: "Upload coverage reports" 22 | uses: codecov/codecov-action@v4 23 | with: 24 | fail_ci_if_error: false 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '[proposal]' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2018", 4 | "module": "esnext", 5 | "lib": [ 6 | "dom", 7 | "es6", 8 | "es2015.promise" 9 | ], 10 | "declaration": true, 11 | "declarationMap": true, 12 | "sourceMap": true, 13 | "outDir": "lib", 14 | "strict": true, 15 | "noImplicitThis": false, 16 | "moduleResolution": "node", 17 | "types": [ 18 | "jest" 19 | ], 20 | "allowSyntheticDefaultImports": true, 21 | "resolveJsonModule": true, 22 | "esModuleInterop": true, 23 | // "skipDefaultLibCheck": true, 24 | "noImplicitAny": false 25 | }, 26 | "exclude": [ 27 | "**/__tests__/*", 28 | "node_modules", 29 | "lib" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base", 4 | "group:allNonMajor" 5 | ], 6 | "labels": [ 7 | "maintenance" 8 | ], 9 | "automergeType": "branch", 10 | "automerge": true, 11 | "packageRules": [ 12 | { 13 | "matchPackagePatterns": [ 14 | "did" 15 | ], 16 | "matchUpdateTypes": [ 17 | "bump", 18 | "patch", 19 | "minor", 20 | "major" 21 | ], 22 | "groupName": "did-dependencies", 23 | "commitMessagePrefix": "fix(deps):" 24 | }, 25 | { 26 | "matchDepTypes": [ 27 | "devDependencies" 28 | ], 29 | "groupName": "devDeps", 30 | "schedule": [ 31 | "before 5am on Monday" 32 | ] 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 70 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 14 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | - in-progress 10 | - planned-feature 11 | - good-first-issue 12 | - triage 13 | # Label to use when marking an issue as stale 14 | staleLabel: stale 15 | # Comment to post when marking an issue as stale. Set to `false` to disable 16 | markComment: > 17 | This issue has been automatically marked as stale because it has not had 18 | recent activity. It will be closed if no further activity occurs. Thank you 19 | for your contributions. 20 | # Comment to post when closing a stale issue. Set to `false` to disable 21 | closeComment: false 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build, Test and Publish 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - 'main' 7 | jobs: 8 | build-test-publish: 9 | runs-on: ubuntu-22.04 10 | steps: 11 | - uses: actions/checkout@v4 12 | with: 13 | fetch-depth: 0 14 | token: ${{ secrets.GH_TOKEN }} 15 | - name: "Setup node with cache" 16 | uses: actions/setup-node@v4 17 | with: 18 | node-version: 18 19 | cache: 'yarn' 20 | 21 | - run: yarn install --frozen-lockfile 22 | - run: yarn run build 23 | 24 | - name: setup git coordinates 25 | run: | 26 | git config user.name ${{secrets.GH_USER}} 27 | git config user.email ${{secrets.GH_EMAIL}} 28 | 29 | - name: Run semantic-release 30 | env: 31 | GH_TOKEN: ${{secrets.GH_TOKEN}} 32 | NPM_TOKEN: ${{secrets.NPM_TOKEN}} 33 | if: github.ref == 'refs/heads/main' 34 | run: yarn run release 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm](https://img.shields.io/npm/dt/ens-did-resolver.svg)](https://www.npmjs.com/package/ens-did-resolver) 2 | [![npm](https://img.shields.io/npm/v/ens-did-resolver.svg)](https://www.npmjs.com/package/ens-did-resolver) 3 | 4 | # ens DID Resolver 5 | 6 | This is the reference implementation for the [did:ens resolver](https://github.com/veramolabs/did-ens-spec). 7 | 8 | The Ethereum community has established ENS names as their identifiers (see Etherscan) for web3 projects. This DID method 9 | specification has two purposes: 10 | 11 | * to wrap existing ENS names as DIDs to be interoperable with applications relying on Decentralized Identifiers 12 | * to define a canonical way to augment ENS names with DID capabilities such as services and verification methods. 13 | 14 | ## Usage 15 | 16 | This library should be used with [`did-resolver`](https://github.com/decentralized-identity/did-resolver). 17 | 18 | ```bash 19 | npm i ens-did-resolver did-resolver 20 | ``` 21 | 22 | ```typescript 23 | import { getResolver } from 'ens-did-resolver' 24 | import { Resolver } from 'did-resolver' 25 | 26 | const infuraProjectId = '' 27 | 28 | const resolver = new Resolver({ 29 | ...getResolver({ infuraProjectId }) 30 | }) 31 | 32 | const result = await resolver.resolve('did:ens:vitalik.eth') 33 | console.dir(result.didDocument, { depth: 4 }) 34 | ``` 35 | -------------------------------------------------------------------------------- /src/helpers.ts: -------------------------------------------------------------------------------- 1 | export const identifierMatcher = /^(.*:)?(.*\.eth)$/ 2 | export const nullAddress = '0x0000000000000000000000000000000000000000' 3 | export const DEFAULT_JSON_RPC = 'http://127.0.0.1:8545/' 4 | 5 | export const knownInfuraNetworks: Record = { 6 | mainnet: '0x1', 7 | goerli: '0x5', 8 | } 9 | 10 | export const knownNetworks: Record = { 11 | ...knownInfuraNetworks, 12 | rsk: '0x1e', 13 | 'rsk:testnet': '0x1f', 14 | artis_t1: '0x03c401', 15 | artis_s1: '0x03c301', 16 | matic: '0x89', 17 | maticmum: '0x13881', 18 | } 19 | 20 | export enum Errors { 21 | /** 22 | * The resolver has failed to construct the DID document. 23 | * This can be caused by a network issue, a wrong registry address or malformed logs while parsing the registry 24 | * history. Please inspect the `DIDResolutionMetadata.message` to debug further. 25 | */ 26 | notFound = 'notFound', 27 | 28 | /** 29 | * The resolver does not know how to resolve the given DID. Most likely it is not a `did:ens`. 30 | */ 31 | invalidDid = 'invalidDid', 32 | 33 | /** 34 | * The resolver is misconfigured or is being asked to resolve a DID anchored on an unknown network 35 | */ 36 | unknownNetwork = 'unknownNetwork', 37 | 38 | /** 39 | * The resolver is being asked to resolve a DID anchored on a network without a known ENS resolver. 40 | */ 41 | unknownEnsResolver = 'unknownEnsResolver', 42 | } 43 | 44 | export function isDefined(arg: T): arg is Exclude { 45 | return arg && typeof arg !== 'undefined' 46 | } 47 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Prerequisites 11 | 12 | Please answer the following questions for yourself before submitting an issue. 13 | 14 | - [ ] I am running the latest version 15 | - [ ] I checked the documentation and found no answer 16 | - [ ] I checked to make sure that this issue has not already been filed 17 | 18 | **YOU MAY DELETE THE PREREQUISITES SECTION** if you're sure you checked all the boxes. 19 | 20 | ### Current Behavior 21 | 22 | What is the current behavior? 23 | 24 | ### Expected Behavior 25 | 26 | Please describe the behavior you are expecting 27 | 28 | ### Failure Information 29 | 30 | Please help provide information about the failure. 31 | 32 | #### Steps to Reproduce 33 | 34 | Please provide detailed steps for reproducing the issue. 35 | 36 | 1. step 1 37 | 2. step 2 38 | 3. you get it... 39 | 40 | #### Environment Details 41 | 42 | Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions. 43 | 44 | * node/browser version: 45 | * OS Version: 46 | * Device details: 47 | 48 | #### Failure Logs/Screenshots 49 | 50 | Please include any relevant log snippets or files here. 51 | Create a [GIST](https://gist.github.com) which is a paste of your _full or sanitized_ logs, and link them here. 52 | Please do _NOT_ paste your full logs here, as it will make this issue very long and hard to read! 53 | 54 | #### Alternatives you considered 55 | 56 | Please provide details about an environment where this bug does not occur. 57 | 58 | --- 59 | 60 | > **Don't paste private keys anywhere public!** 61 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [1.0.4](https://github.com/veramolabs/ens-did-resolver/compare/1.0.3...1.0.4) (2023-03-23) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * **deps:** update all non-major dependencies to v5.7.0 ([d2f94fd](https://github.com/veramolabs/ens-did-resolver/commit/d2f94fd4382bb4a18a8fda91bb0cc248ead7e476)) 7 | 8 | ## [1.0.3](https://github.com/veramolabs/ens-did-resolver/compare/1.0.2...1.0.3) (2023-03-22) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * **deps:** Update dependency did-resolver to v4.1.0 ([ef637fb](https://github.com/veramolabs/ens-did-resolver/commit/ef637fb2e3db1ffde82a905b9d6d8046a0de27ac)) 14 | 15 | ## [1.0.2](https://github.com/veramolabs/ens-did-resolver/compare/1.0.1...1.0.2) (2023-02-02) 16 | 17 | 18 | ### Bug Fixes 19 | 20 | * fix corner case when ENS resolver is unknown ([c1f8d6f](https://github.com/veramolabs/ens-did-resolver/commit/c1f8d6fd5b21c57e17bfc06fe063f02962404d70)) 21 | * **deps:** fix breaking changes from did-resolver v4 ([eed4441](https://github.com/veramolabs/ens-did-resolver/commit/eed4441565b131e7ea6cd7aec7e20b72c69e8bbd)) 22 | * **deps:** Update dependency did-resolver to v4 ([a0a5488](https://github.com/veramolabs/ens-did-resolver/commit/a0a5488d95b06c2450d7b168f4275338d72beffd)) 23 | 24 | ## [1.0.1](https://github.com/veramolabs/ens-did-resolver/compare/1.0.0...1.0.1) (2022-11-03) 25 | 26 | 27 | ### Bug Fixes 28 | 29 | * remove deprecated testnets ([#12](https://github.com/veramolabs/ens-did-resolver/issues/12)) ([d197b30](https://github.com/veramolabs/ens-did-resolver/commit/d197b307d30be1fe6a89ff7e807bf96ed76c1833)) 30 | 31 | # 1.0.0 (2022-07-10) 32 | 33 | 34 | * initial implementation ([#1](https://github.com/veramolabs/ens-did-resolver/issues/1)) ([889b3ff](https://github.com/veramolabs/ens-did-resolver/commit/889b3ff6a77fe127d2d58a9d5d99b5628667b583)) 35 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Jest All", 11 | "program": "${workspaceFolder}/node_modules/.bin/jest", 12 | "args": ["--runInBand"], 13 | "console": "integratedTerminal", 14 | "internalConsoleOptions": "neverOpen", 15 | "windows": { 16 | "program": "${workspaceFolder}/node_modules/jest/bin/jest" 17 | } 18 | }, 19 | { 20 | "type": "node", 21 | "request": "launch", 22 | "name": "Jest Current File", 23 | "program": "${workspaceFolder}/node_modules/.bin/jest", 24 | "args": ["${relativeFile}", "--detectOpenHandles"], 25 | "console": "integratedTerminal", 26 | "internalConsoleOptions": "neverOpen", 27 | "windows": { 28 | "program": "${workspaceFolder}/node_modules/jest/bin/jest" 29 | } 30 | }, 31 | { 32 | "type": "node", 33 | "request": "launch", 34 | "name": "Launch Program", 35 | "skipFiles": ["/**"], 36 | "program": "${workspaceFolder}/lib/index.js", 37 | "preLaunchTask": "tsc: build - tsconfig.json", 38 | "outFiles": ["${workspaceFolder}/lib/**/*.js"] 39 | }, 40 | { 41 | "type": "node", 42 | "request": "launch", 43 | "name": "test revoker", 44 | "skipFiles": ["/**"], 45 | "program": "${workspaceFolder}/node_modules/.bin/jest", 46 | "args": ["revokerTests"] 47 | }, 48 | { 49 | "type": "node", 50 | "request": "launch", 51 | "name": "test basic", 52 | "skipFiles": ["/**"], 53 | "program": "${workspaceFolder}/node_modules/.bin/jest", 54 | "args": ["basic"] 55 | } 56 | ] 57 | } 58 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # How to contribute to ens-did-resolver 2 | 3 | We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | 10 | ## Report a bug with detail, background and sample code 11 | 12 | **Great Bug Reports** tend to have: 13 | 14 | - A quick summary and/or background 15 | - Steps to reproduce 16 | - Be specific! 17 | - Give sample code if you can. 18 | - What you expected would happen 19 | - What actually happens 20 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 21 | - You get extra kudos if you attach a failing test demonstrating that bug 22 | 23 | ## Submitting improvements 24 | 25 | ### Commit messages 26 | 27 | We use GitHub to host code, to track issues and feature requests, as well as accept pull requests. 28 | We Use [semantic-release](https://github.com/semantic-release/semantic-release) and 29 | [commitlint](https://github.com/conventional-changelog/commitlint) to automate our release process. 30 | Versioning, changelogs and publication is all covered by this automation. 31 | Please see some [commit message examples](https://github.com/semantic-release/semantic-release#commit-message-format) 32 | 33 | Commit messages are really important in this process, and the build might fail if your commits don't adhere to this. 34 | 35 | ### Code style 36 | 37 | Use the built-in code formatter (`npm run format`) before committing code. It makes lives much easier. 38 | 39 | ### Submitting a fix 40 | 41 | - Branch off of `main` 42 | - Wherever possible, commit at least one test to demonstrate the bug 43 | - Commit your code to fix that bug 44 | - Create a PR for it 45 | - Mention the issue you're fixing in the PR (Example: __Closes #17__) 46 | 47 | ### Submitting a proposal 48 | 49 | We prefer to discuss proposals before accepting them into the codebase. 50 | Open an issue with as much detail and background as possible to make your case. 51 | Small proposals can come in directly as PRs, but it's generally better to discuss before starting work. 52 | 53 | Any contributions you make will be under the Apache-2.0 License 54 | 55 | ### Posting PRs 56 | 57 | - Describe your changes in the PR description. 58 | - Mention issues that should be fixed or closed when the PR is merged. 59 | - Make sure any new code has tests associated! 60 | - Make sure the documentation is still valid if your changes get included. 61 | 62 | Thank you for your contribution! 63 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ens-did-resolver", 3 | "version": "1.0.4", 4 | "description": "Resolve DID documents for ENS", 5 | "source": "src/index.ts", 6 | "main": "lib/index.js", 7 | "module": "lib/index.module.js", 8 | "unpkg": "lib/index.umd.js", 9 | "types": "lib/index.d.ts", 10 | "umd:main": "lib/index.umd.js", 11 | "repository": { 12 | "type": "git", 13 | "url": "git@github.com:veramolabs/ens-did-resolver.git" 14 | }, 15 | "files": [ 16 | "lib", 17 | "src", 18 | "LICENSE" 19 | ], 20 | "author": "Oliver Terbu", 21 | "contributors": [ 22 | "Mircea Nistor " 23 | ], 24 | "license": "Apache-2.0", 25 | "keywords": [ 26 | "did:ens", 27 | "DID", 28 | "DID document", 29 | "PKI", 30 | "resolver", 31 | "Verifiable Credential", 32 | "W3C", 33 | "ethereum", 34 | "ethereumAddress", 35 | "blockchainAccountId", 36 | "ENS" 37 | ], 38 | "scripts": { 39 | "test": "jest", 40 | "test:ci": "jest --coverage", 41 | "build:js": "microbundle --compress=false", 42 | "build": "yarn lint && yarn build:js && yarn test", 43 | "format": "prettier --write \"src/**/*.[jt]s\"", 44 | "lint": "eslint --ignore-pattern \"src/**/*.test.[jt]s\" \"src/**/*.[jt]s\"", 45 | "prepublishOnly": "yarn test:ci && yarn format && yarn lint", 46 | "release": "semantic-release --debug" 47 | }, 48 | "jest": { 49 | "clearMocks": true, 50 | "collectCoverageFrom": [ 51 | "src/**/*.{ts,tsx}", 52 | "!src/**/*.d.ts", 53 | "!**/node_modules/**", 54 | "!**/__tests__/**" 55 | ], 56 | "testEnvironment": "node", 57 | "testMatch": [ 58 | "**/__tests__/**/*.test.[jt]s" 59 | ] 60 | }, 61 | "devDependencies": { 62 | "@babel/core": "7.24.4", 63 | "@babel/preset-env": "7.24.4", 64 | "@babel/preset-typescript": "7.24.1", 65 | "@semantic-release/changelog": "6.0.3", 66 | "@semantic-release/git": "10.0.1", 67 | "@types/jest": "29.5.12", 68 | "@typescript-eslint/eslint-plugin": "6.21.0", 69 | "@typescript-eslint/parser": "6.21.0", 70 | "babel-jest": "29.7.0", 71 | "eslint": "8.57.0", 72 | "eslint-config-prettier": "9.1.0", 73 | "eslint-plugin-jest": "27.9.0", 74 | "eslint-plugin-prettier": "5.1.3", 75 | "ganache-cli": "6.12.2", 76 | "jest": "29.7.0", 77 | "microbundle": "0.15.1", 78 | "prettier": "3.2.5", 79 | "semantic-release": "21.1.2", 80 | "typescript": "5.4.4" 81 | }, 82 | "dependencies": { 83 | "@ethersproject/bignumber": "^5.1.0", 84 | "@ethersproject/providers": "^5.1.0", 85 | "did-resolver": "^4.0.0" 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | lib/ 2 | 3 | # Created by https://www.gitignore.io/api/node,linux,macos,windows,intellij 4 | # Edit at https://www.gitignore.io/?templates=node,linux,macos,windows,intellij 5 | 6 | ### Intellij ### 7 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 8 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 9 | 10 | # User-specific stuff 11 | **/.idea/ 12 | .vscode/ 13 | 14 | # CMake 15 | cmake-build-*/ 16 | 17 | # Mongo Explorer plugin 18 | .idea/**/mongoSettings.xml 19 | 20 | # File-based project format 21 | *.iws 22 | 23 | # IntelliJ 24 | out/ 25 | 26 | # mpeltonen/sbt-idea plugin 27 | .idea_modules/ 28 | 29 | # JIRA plugin 30 | atlassian-ide-plugin.xml 31 | 32 | # Cursive Clojure plugin 33 | .idea/replstate.xml 34 | 35 | # Crashlytics plugin (for Android Studio and IntelliJ) 36 | com_crashlytics_export_strings.xml 37 | crashlytics.properties 38 | crashlytics-build.properties 39 | fabric.properties 40 | 41 | # Editor-based Rest Client 42 | .idea/httpRequests 43 | 44 | # Android studio 3.1+ serialized cache file 45 | .idea/caches/build_file_checksums.ser 46 | 47 | ### Intellij Patch ### 48 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 49 | 50 | *.iml 51 | # modules.xml 52 | # .idea/misc.xml 53 | # *.ipr 54 | 55 | # Sonarlint plugin 56 | .idea/**/sonarlint/ 57 | 58 | # SonarQube Plugin 59 | .idea/**/sonarIssues.xml 60 | 61 | # Markdown Navigator plugin 62 | .idea/**/markdown-navigator.xml 63 | .idea/**/markdown-navigator/ 64 | 65 | ### Linux ### 66 | *~ 67 | 68 | # temporary files which can be created if a process still has a handle open of a deleted file 69 | .fuse_hidden* 70 | 71 | # KDE directory preferences 72 | .directory 73 | 74 | # Linux trash folder which might appear on any partition or disk 75 | .Trash-* 76 | 77 | # .nfs files are created when an open file is removed but is still being accessed 78 | .nfs* 79 | 80 | ### macOS ### 81 | # General 82 | .DS_Store 83 | .AppleDouble 84 | .LSOverride 85 | 86 | # Icon must end with two \r 87 | Icon 88 | 89 | # Thumbnails 90 | ._* 91 | 92 | # Files that might appear in the root of a volume 93 | .DocumentRevisions-V100 94 | .fseventsd 95 | .Spotlight-V100 96 | .TemporaryItems 97 | .Trashes 98 | .VolumeIcon.icns 99 | .com.apple.timemachine.donotpresent 100 | 101 | # Directories potentially created on remote AFP share 102 | .AppleDB 103 | .AppleDesktop 104 | Network Trash Folder 105 | Temporary Items 106 | .apdisk 107 | 108 | ### Node ### 109 | # Logs 110 | logs 111 | *.log 112 | npm-debug.log* 113 | yarn-debug.log* 114 | yarn-error.log* 115 | lerna-debug.log* 116 | 117 | # Diagnostic reports (https://nodejs.org/api/report.html) 118 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 119 | 120 | # Runtime data 121 | pids 122 | *.pid 123 | *.seed 124 | *.pid.lock 125 | 126 | # Directory for instrumented libs generated by jscoverage/JSCover 127 | lib-cov 128 | 129 | # Coverage directory used by tools like istanbul 130 | coverage 131 | *.lcov 132 | 133 | # nyc test coverage 134 | .nyc_output 135 | 136 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 137 | .grunt 138 | 139 | # Bower dependency directory (https://bower.io/) 140 | bower_components 141 | 142 | # node-waf configuration 143 | .lock-wscript 144 | 145 | # Compiled binary addons (https://nodejs.org/api/addons.html) 146 | build/Release 147 | 148 | # Dependency directories 149 | node_modules/ 150 | jspm_packages/ 151 | 152 | # TypeScript v1 declaration files 153 | typings/ 154 | 155 | # TypeScript cache 156 | *.tsbuildinfo 157 | 158 | # Optional npm cache directory 159 | .npm 160 | 161 | # Optional eslint cache 162 | .eslintcache 163 | 164 | # Optional REPL history 165 | .node_repl_history 166 | 167 | # Output of 'npm pack' 168 | *.tgz 169 | 170 | # Yarn Integrity file 171 | .yarn-integrity 172 | 173 | # dotenv environment variables file 174 | .env 175 | .env.test 176 | 177 | # parcel-bundler cache (https://parceljs.org/) 178 | .cache 179 | 180 | # next.js build output 181 | .next 182 | 183 | # nuxt.js build output 184 | .nuxt 185 | 186 | # react / gatsby 187 | public/ 188 | 189 | # vuepress build output 190 | .vuepress/dist 191 | 192 | # Serverless directories 193 | .serverless/ 194 | 195 | # FuseBox cache 196 | .fusebox/ 197 | 198 | # DynamoDB Local files 199 | .dynamodb/ 200 | 201 | ### Windows ### 202 | # Windows thumbnail cache files 203 | Thumbs.db 204 | Thumbs.db:encryptable 205 | ehthumbs.db 206 | ehthumbs_vista.db 207 | 208 | # Dump file 209 | *.stackdump 210 | 211 | # Folder config file 212 | [Dd]esktop.ini 213 | 214 | # Recycle Bin used on file shares 215 | $RECYCLE.BIN/ 216 | 217 | # Windows Installer files 218 | *.cab 219 | *.msi 220 | *.msix 221 | *.msm 222 | *.msp 223 | 224 | # Windows shortcuts 225 | *.lnk 226 | 227 | # End of https://www.gitignore.io/api/node,linux,macos,windows,intellij -------------------------------------------------------------------------------- /src/configuration.ts: -------------------------------------------------------------------------------- 1 | import { BigNumber } from '@ethersproject/bignumber' 2 | import { InfuraProvider, JsonRpcProvider, Provider } from '@ethersproject/providers' 3 | import { knownInfuraNetworks, knownNetworks } from './helpers' 4 | 5 | /** 6 | * A configuration entry for an ethereum network 7 | * It should contain at least one of `name` or `chainId` AND one of `provider`, `web3`, or `rpcUrl` 8 | * 9 | * @example ```js 10 | * { name: 'development', rpcUrl: 'http://127.0.0.1:8545/' } 11 | * { name: 'goerli', chainId: 5, provider: new InfuraProvider('goerli') } 12 | * { name: 'rinkeby', provider: new AlchemyProvider('rinkeby') } 13 | * { name: 'rsk:testnet', chainId: '0x1f', rpcUrl: 'https://public-node.testnet.rsk.co' } 14 | * ``` 15 | */ 16 | export interface ProviderConfiguration { 17 | name?: string 18 | provider?: Provider 19 | rpcUrl?: string 20 | chainId?: string | number 21 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 22 | web3?: any 23 | 24 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 25 | [index: string]: any 26 | } 27 | 28 | export interface MultiProviderConfiguration extends ProviderConfiguration { 29 | networks?: ProviderConfiguration[] 30 | } 31 | 32 | export interface InfuraConfiguration { 33 | infuraProjectId: string 34 | } 35 | 36 | export type ConfigurationOptions = MultiProviderConfiguration | InfuraConfiguration 37 | 38 | export type ConfiguredNetworks = Record 39 | 40 | function configureNetworksWithInfura(projectId?: string): ConfiguredNetworks { 41 | if (!projectId) { 42 | return {} 43 | } 44 | const networks: ProviderConfiguration[] = [ 45 | { name: 'mainnet', chainId: '0x1', provider: new InfuraProvider('homestead', projectId) }, 46 | { name: 'goerli', chainId: '0x5', provider: new InfuraProvider('goerli', projectId) }, 47 | ] 48 | return configureNetworks({ networks }) 49 | } 50 | 51 | export function getProviderForNetwork(conf: ProviderConfiguration): Provider { 52 | let provider: Provider = conf.provider || conf.web3?.currentProvider 53 | if (!provider) { 54 | if (conf.rpcUrl) { 55 | const chainIdRaw = conf.chainId ? conf.chainId : knownNetworks[conf.name || ''] 56 | const chainId = chainIdRaw ? BigNumber.from(chainIdRaw).toNumber() : chainIdRaw 57 | const networkName = knownInfuraNetworks[conf.name || ''] ? conf.name?.replace('mainnet', 'homestead') : 'any' 58 | provider = new JsonRpcProvider(conf.rpcUrl, chainId || networkName) 59 | } else { 60 | throw new Error(`invalid_config: No web3 provider could be determined for network ${conf.name || conf.chainId}`) 61 | } 62 | } 63 | return provider 64 | } 65 | 66 | function configureNetwork(net: ProviderConfiguration): ConfiguredNetworks { 67 | const networks: ConfiguredNetworks = {} 68 | const chainId = net.chainId || knownNetworks[net.name || ''] 69 | if (chainId) { 70 | if (net.name) { 71 | networks[net.name] = getProviderForNetwork(net) 72 | } 73 | const id = typeof chainId === 'number' ? `0x${chainId.toString(16)}` : chainId 74 | networks[id] = getProviderForNetwork(net) 75 | } else if (net.provider || net.web3 || net.rpcUrl) { 76 | networks[net.name || ''] = getProviderForNetwork(net) 77 | } 78 | return networks 79 | } 80 | 81 | function configureNetworks(conf: MultiProviderConfiguration): ConfiguredNetworks { 82 | return { 83 | ...configureNetwork(conf), 84 | ...conf.networks?.reduce((networks, net) => { 85 | return { ...networks, ...configureNetwork(net) } 86 | }, {}), 87 | } 88 | } 89 | 90 | /** 91 | * Generates a configuration that maps ethereum network names and chainIDs to the respective web3 providers. 92 | * @returns a record of providers 93 | * @param conf configuration options for the resolver. An array of network details. 94 | * Each network entry should contain at least one of `name` or `chainId` AND one of `provider`, `web3`, or `rpcUrl` 95 | * For convenience, you can also specify an `infuraProjectId` which will create a mapping for all the networks 96 | * supported by https://infura.io. 97 | * @example ```js 98 | * [ 99 | * { name: 'development', rpcUrl: 'http://127.0.0.1:8545/' }, 100 | * { name: 'goerli', chainId: 5, provider: new InfuraProvider('goerli') }, 101 | * { name: 'rinkeby', provider: new AlchemyProvider('rinkeby') }, 102 | * { name: 'rsk:testnet', chainId: '0x1f', rpcUrl: 'https://public-node.testnet.rsk.co' }, 103 | * ] 104 | * ``` 105 | */ 106 | export function configureResolverWithNetworks(conf: ConfigurationOptions = {}): ConfiguredNetworks { 107 | const networks = { 108 | ...configureNetworksWithInfura((conf).infuraProjectId), 109 | ...configureNetworks(conf), 110 | } 111 | if (Object.keys(networks).length === 0) { 112 | throw new Error('invalid_config: Please make sure to have at least one network') 113 | } 114 | return networks 115 | } 116 | -------------------------------------------------------------------------------- /src/__tests__/resolver.test.ts: -------------------------------------------------------------------------------- 1 | import { DIDDocument, DIDResolutionResult, Resolvable, Resolver } from 'did-resolver' 2 | import { getResolver } from '../resolver' 3 | 4 | jest.setTimeout(60000) 5 | 6 | describe('ensResolver', () => { 7 | beforeAll(async () => {}) 8 | 9 | it('works with single, unnamed network', async () => { 10 | expect.assertions(1) 11 | let didResolver: Resolvable = new Resolver( 12 | getResolver({ rpcUrl: 'https://mainnet.infura.io/v3/e471b8639c314004ae67ec0078f70102' }) 13 | ) 14 | const did = 'did:ens:vitalik.eth' 15 | const ethrAddr = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' 16 | const resolutionResult = await didResolver.resolve(did) 17 | expect(resolutionResult).toEqual({ 18 | didDocument: { 19 | id: did, 20 | service: [ 21 | { 22 | id: `${did}#Web3PublicProfile-${ethrAddr}`, 23 | type: 'Web3PublicProfile', 24 | serviceEndpoint: 'vitalik.eth', 25 | }, 26 | ], 27 | verificationMethod: [ 28 | { 29 | id: `${did}#${ethrAddr}`, 30 | type: 'EcdsaSecp256k1RecoveryMethod2020', 31 | controller: did, 32 | blockchainAccountId: `${ethrAddr}@eip155:1`, 33 | }, 34 | ], 35 | authentication: [`${did}#${ethrAddr}`], 36 | capabilityDelegation: [`${did}#${ethrAddr}`], 37 | capabilityInvocation: [`${did}#${ethrAddr}`], 38 | assertionMethod: [`${did}#${ethrAddr}`], 39 | keyAgreement: [], 40 | }, 41 | didDocumentMetadata: {}, 42 | didResolutionMetadata: { contentType: 'application/did+json' }, 43 | }) 44 | }) 45 | 46 | it('works with single, named network', async () => { 47 | expect.assertions(1) 48 | let didResolver: Resolvable = new Resolver( 49 | getResolver({ name: 'goerli', rpcUrl: 'https://goerli.infura.io/v3/e471b8639c314004ae67ec0078f70102' }) 50 | ) 51 | const did = 'did:ens:goerli:whatever.eth' 52 | const ethrAddr = '0x4af859d61d07A8c515FE0E3Cc1Ea5e49A260bBa3' 53 | const resolutionResult = await didResolver.resolve(did) 54 | expect(resolutionResult).toEqual({ 55 | didDocument: { 56 | id: did, 57 | service: [ 58 | { 59 | id: `${did}#Web3PublicProfile-${ethrAddr}`, 60 | type: 'Web3PublicProfile', 61 | serviceEndpoint: 'whatever.eth', 62 | }, 63 | ], 64 | verificationMethod: [ 65 | { 66 | id: `${did}#${ethrAddr}`, 67 | type: 'EcdsaSecp256k1RecoveryMethod2020', 68 | controller: did, 69 | blockchainAccountId: `${ethrAddr}@eip155:5`, 70 | }, 71 | { 72 | id: `${did}#my-key`, 73 | type: 'X25519KeyAgreementKey2019', 74 | controller: did, 75 | publicKeyMultibase: 'z9hFgmPVfmBZwRvFEyniQDBkz9LmV7gDEqytWyGZLmDXE', 76 | }, 77 | ], 78 | authentication: [`${did}#${ethrAddr}`], 79 | capabilityDelegation: [`${did}#${ethrAddr}`], 80 | capabilityInvocation: [`${did}#${ethrAddr}`], 81 | assertionMethod: [`${did}#${ethrAddr}`], 82 | keyAgreement: [`${did}#my-key`], 83 | }, 84 | didDocumentMetadata: {}, 85 | didResolutionMetadata: { contentType: 'application/did+json' }, 86 | }) 87 | }) 88 | 89 | it('works with infura', async () => { 90 | expect.assertions(1) 91 | let didResolver: Resolvable = new Resolver(getResolver({ infuraProjectId: 'e471b8639c314004ae67ec0078f70102' })) 92 | const did = 'did:ens:goerli:whatever.eth' 93 | const ethrAddr = '0x4af859d61d07A8c515FE0E3Cc1Ea5e49A260bBa3' 94 | const resolutionResult = await didResolver.resolve(did) 95 | expect(resolutionResult).toEqual({ 96 | didDocument: { 97 | id: did, 98 | service: [ 99 | { 100 | id: `${did}#Web3PublicProfile-${ethrAddr}`, 101 | type: 'Web3PublicProfile', 102 | serviceEndpoint: 'whatever.eth', 103 | }, 104 | ], 105 | verificationMethod: [ 106 | { 107 | id: `${did}#${ethrAddr}`, 108 | type: 'EcdsaSecp256k1RecoveryMethod2020', 109 | controller: did, 110 | blockchainAccountId: `${ethrAddr}@eip155:5`, 111 | }, 112 | { 113 | id: `${did}#my-key`, 114 | type: 'X25519KeyAgreementKey2019', 115 | controller: did, 116 | publicKeyMultibase: 'z9hFgmPVfmBZwRvFEyniQDBkz9LmV7gDEqytWyGZLmDXE', 117 | }, 118 | ], 119 | authentication: [`${did}#${ethrAddr}`], 120 | capabilityDelegation: [`${did}#${ethrAddr}`], 121 | capabilityInvocation: [`${did}#${ethrAddr}`], 122 | assertionMethod: [`${did}#${ethrAddr}`], 123 | keyAgreement: [`${did}#my-key`], 124 | }, 125 | didDocumentMetadata: {}, 126 | didResolutionMetadata: { contentType: 'application/did+json' }, 127 | }) 128 | }) 129 | 130 | it('works fails trying to goerli name on mainnet', async () => { 131 | expect.assertions(1) 132 | let didResolver: Resolvable = new Resolver( 133 | getResolver({ rpcUrl: 'https://mainnet.infura.io/v3/e471b8639c314004ae67ec0078f70102' }) 134 | ) 135 | const did = 'did:ens:goerli:whatever.eth' 136 | const resolutionResult = await didResolver.resolve(did) 137 | expect(resolutionResult.didResolutionMetadata.error).toEqual('unknownNetwork') 138 | }) 139 | 140 | it('multi provider config', async () => { 141 | expect.assertions(2) 142 | let didResolver: Resolvable = new Resolver( 143 | getResolver({ 144 | networks: [ 145 | { name: 'goerli', rpcUrl: 'https://goerli.infura.io/v3/e471b8639c314004ae67ec0078f70102' }, 146 | { rpcUrl: 'https://mainnet.infura.io/v3/e471b8639c314004ae67ec0078f70102' }, 147 | ], 148 | }) 149 | ) 150 | const did = 'did:ens:goerli:whatever.eth' 151 | const resolutionResult = await didResolver.resolve(did) 152 | expect(resolutionResult.didDocument?.id).toEqual('did:ens:goerli:whatever.eth') 153 | 154 | const resolutionResult2 = await didResolver.resolve('did:ens:vitalik.eth') 155 | expect(resolutionResult2.didDocument?.id).toEqual('did:ens:vitalik.eth') 156 | }) 157 | }) 158 | -------------------------------------------------------------------------------- /src/resolver.ts: -------------------------------------------------------------------------------- 1 | import { EnsResolver, Provider, Web3Provider } from '@ethersproject/providers' 2 | import { DIDDocument, DIDResolutionResult, DIDResolver, ParsedDID, Service, VerificationMethod } from 'did-resolver' 3 | import { ConfigurationOptions, configureResolverWithNetworks } from './configuration' 4 | import { Errors, identifierMatcher, isDefined } from './helpers' 5 | 6 | export function getResolver(config?: ConfigurationOptions): Record { 7 | async function resolve(did: string, parsed: ParsedDID): Promise { 8 | const networks = configureResolverWithNetworks(config) 9 | // check if identifier(parsed.id) contains a network code 10 | const fullId = parsed.id.match(identifierMatcher) 11 | if (!fullId) { 12 | return { 13 | didResolutionMetadata: { 14 | error: Errors.invalidDid, 15 | message: `Not a valid did:ens: ${parsed.id}`, 16 | }, 17 | didDocumentMetadata: {}, 18 | didDocument: null, 19 | } 20 | } 21 | const ensName = fullId[2] 22 | const networkCode = typeof fullId[1] === 'string' ? fullId[1].slice(0, -1) : '' 23 | 24 | // get provider for that network or the mainnet provider if none other is given 25 | const provider: Provider = networks[networkCode] 26 | if (!provider || typeof provider === 'undefined') { 27 | return { 28 | didResolutionMetadata: { 29 | error: Errors.unknownNetwork, 30 | message: `This resolver is not configured for the ${networkCode} network required by ${ 31 | parsed.id 32 | }. Networks: ${JSON.stringify(Object.keys(networks))}`, 33 | }, 34 | didDocumentMetadata: {}, 35 | didDocument: null, 36 | } 37 | } 38 | const ensResolver: EnsResolver | null = await (provider as Web3Provider).getResolver(ensName) 39 | if (!ensResolver) { 40 | return { 41 | didResolutionMetadata: { 42 | error: Errors.unknownEnsResolver, 43 | message: `This network (${networkCode}), required by ${parsed.id}, does not have a known ENS resolver`, 44 | }, 45 | didDocumentMetadata: {}, 46 | didDocument: null, 47 | } 48 | } 49 | let err: string | null = null 50 | let address: string | null = null 51 | try { 52 | address = await ensResolver.getAddress() 53 | } catch (error) { 54 | err = `resolver_error: Cannot resolve ENS name: ${error}` 55 | } 56 | 57 | const didDocumentMetadata = {} 58 | let didDocument: DIDDocument | null = null 59 | 60 | if (address) { 61 | const chainId = (await provider.getNetwork()).chainId 62 | const blockchainAccountId = `${address}@eip155:${chainId}` 63 | const postfix = address 64 | 65 | // setup default did doc 66 | didDocument = { 67 | id: did, 68 | service: [ 69 | { 70 | id: `${did}#Web3PublicProfile-${postfix}`, 71 | type: 'Web3PublicProfile', 72 | serviceEndpoint: ensName, 73 | }, 74 | ], 75 | verificationMethod: [ 76 | { 77 | id: `${did}#${postfix}`, 78 | type: 'EcdsaSecp256k1RecoveryMethod2020', 79 | controller: did, 80 | blockchainAccountId, 81 | }, 82 | ], 83 | authentication: [`${did}#${postfix}`], 84 | capabilityDelegation: [`${did}#${postfix}`], 85 | capabilityInvocation: [`${did}#${postfix}`], 86 | assertionMethod: [`${did}#${postfix}`], 87 | } 88 | } 89 | 90 | const getEnsRecord = async (ensResolver: EnsResolver, name: string): Promise => { 91 | let parsedEntry: T | null = null 92 | const entry = await ensResolver.getText(name) 93 | if (entry) { 94 | try { 95 | parsedEntry = JSON.parse(unescape(entry)) 96 | } catch (e) { 97 | return null 98 | } 99 | } 100 | return parsedEntry 101 | } 102 | 103 | const filterValidVerificationMethods = ( 104 | did: string, 105 | current: (string | VerificationMethod)[], 106 | all: VerificationMethod[] 107 | ): (string | VerificationMethod)[] => { 108 | const methodLinks = (current.filter((entry) => typeof entry === 'string') as string[]) 109 | .map((entry) => (entry.startsWith('#') ? `${did}${entry}` : entry)) 110 | .filter((entry) => all?.some((b) => b.id === entry)) 111 | 112 | const fullMethods = ( 113 | current.filter( 114 | (entry) => 115 | entry != null && 116 | typeof entry === 'object' && 117 | Object.keys(entry).includes('id') && 118 | Object.keys(entry).includes('type') && 119 | Object.keys(entry).some((k) => k.startsWith('publicKey')) 120 | ) as VerificationMethod[] 121 | ).map((entry: VerificationMethod) => { 122 | entry.controller = entry.controller || did 123 | if (entry.id.startsWith('#')) { 124 | entry.id = `${did}${entry}` 125 | } 126 | return entry 127 | }) 128 | return [...methodLinks, ...fullMethods] 129 | } 130 | 131 | const services = (await getEnsRecord(ensResolver, 'org.w3c.did.service')) || [] 132 | if (services) { 133 | if (didDocument) { 134 | didDocument.service = [...(didDocument.service || []), ...services].filter(isDefined) 135 | } 136 | } 137 | 138 | const verificationMethods = 139 | (await getEnsRecord(ensResolver, 'org.w3c.did.verificationMethod')) || [] 140 | 141 | if (verificationMethods) { 142 | verificationMethods.map((method) => { 143 | if (method.id.startsWith('#')) { 144 | method.id = `${did}${method.id}` 145 | } 146 | method.controller = method.controller || did 147 | return method 148 | }) 149 | if (didDocument) { 150 | didDocument.verificationMethod = [...(didDocument.verificationMethod || []), ...verificationMethods].filter( 151 | isDefined 152 | ) 153 | } 154 | } 155 | 156 | const relationships = [ 157 | 'keyAgreement', 158 | 'assertionMethod', 159 | 'authentication', 160 | 'capabilityInvocation', 161 | 'capabilityDelegation', 162 | ] 163 | await relationships.reduce(async (memo, relationship) => { 164 | await memo 165 | try { 166 | const verificationMethod = 167 | (await getEnsRecord<(string | VerificationMethod)[]>(ensResolver, `org.w3c.did.${relationship}`)) || [] 168 | if (verificationMethod) { 169 | if (didDocument) { 170 | didDocument[relationship] = [ 171 | ...(didDocument[relationship] || []), 172 | ...filterValidVerificationMethods(did, verificationMethod, verificationMethods), 173 | ] 174 | } 175 | } 176 | } catch (e) { 177 | // nop 178 | } 179 | }, Promise.resolve()) 180 | 181 | const contentType = 182 | typeof didDocument?.['@context'] !== 'undefined' ? 'application/did+ld+json' : 'application/did+json' 183 | 184 | if (err) { 185 | return { 186 | didDocument, 187 | didDocumentMetadata, 188 | didResolutionMetadata: { 189 | error: Errors.notFound, 190 | message: err, 191 | }, 192 | } 193 | } else { 194 | return { 195 | didDocument, 196 | didDocumentMetadata, 197 | didResolutionMetadata: { contentType }, 198 | } 199 | } 200 | } 201 | 202 | return { ens: resolve } 203 | } 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Consensys AG 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------