diff --git a/package.json b/package.json index 820b0b8d0..e72e5c373 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,7 @@ "ts-jest": "^27.1.3", "ts-json-schema-generator": "^0.97.0", "ts-node": "^10.4.0", - "typescript": "^4.5.4", + "typescript": "4.6.4", "eslint": "^8.7.0", "eslint-plugin-eslint-comments": "^3.2.0", "@typescript-eslint/eslint-plugin": "^5.9.1", diff --git a/packages/tsconfig.json b/packages/tsconfig.json index 98f25d4a3..87d1ed881 100644 --- a/packages/tsconfig.json +++ b/packages/tsconfig.json @@ -18,6 +18,7 @@ { "path": "data-store-common" }, { "path": "connection-manager" }, { "path": "data-store" }, - { "path": "ion-did-provider" } + { "path": "ion-did-provider" }, + { "path": "wellknown-did-verifier" }, ] } diff --git a/packages/wellknown-did-verifier/CHANGELOG.md b/packages/wellknown-did-verifier/CHANGELOG.md new file mode 100644 index 000000000..420e6f23d --- /dev/null +++ b/packages/wellknown-did-verifier/CHANGELOG.md @@ -0,0 +1 @@ +# Change Log diff --git a/packages/wellknown-did-verifier/LICENSE b/packages/wellknown-did-verifier/LICENSE new file mode 100644 index 000000000..a51495fe7 --- /dev/null +++ b/packages/wellknown-did-verifier/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2022] [Sphereon BV, info@sphereon.com] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/wellknown-did-verifier/README.md b/packages/wellknown-did-verifier/README.md new file mode 100644 index 000000000..ec455f867 --- /dev/null +++ b/packages/wellknown-did-verifier/README.md @@ -0,0 +1,108 @@ + +

+
+ Sphereon +
Well-Known DID Verifier (Typescript) +
+

+ +--- + +**Warning: This package still is in very early development. Breaking changes without notice will happen at this point!** + +--- + +A `Sphereon SSI-SDK` plugin to verify relationships between the controller of an origin and a DID conforming to the DIF [spec for well-known DID Configurations](https://identity.foundation/.well-known/resources/did-configuration/) It is written in Typescript and can be compiled to any target JavaScript version. + +## Available functions + +- registerSignatureValidation +- removeSignatureValidation +- verifyDomainLinkage +- verifyDidConfigurationResource + +## Usage + +### Adding the plugin to an agent: + +```typescript +import { IWellKnownDidVerifier, WellKnownDidVerifier } from '@sphereon/ssi-sdk-wellknown-did-verifier' + +const agent = createAgent({ + plugins: [ + new WellKnownDidVerifier({ + signatureVerifications: { verified: () => Promise.resolve({ verified: true }) }, + onlyVerifyServiceDids: true, + }), + ], +}) +``` + +### Register signature verification callback: + +Registers a callback function to be called within the verification process, to verify the signature of the credentials within the DID configuration resource. + +```typescript +agent + .registerSignatureVerification({ + callbackName: 'example_key', + signatureVerification: () => Promise.resolve({ verified: true }), + }) + .then(() => console.log('success')) + .catch(() => console.log('failed')) +``` + +### Remove signature verification callback: + +Removes a registered callback function. + +```typescript +agent + .removeSignatureVerification({ callbackName: 'example_key' }) + .then(() => console.log('success')) + .catch(() => console.log('failed')) +``` + +### Verify domain linkage: + +Verifies the relationship between the controller of an origin and a given DID. +Option available to only verify the service DID. + +```typescript +agent + .verifyDomainLinkage({ + did: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', + signatureVerification: 'verified', + onlyVerifyServiceDids: false, + }) + .then((result: IDomainLinkageValidation) => console.log(result.status)) +``` + +### Verify DID configuration resource: + +Verifies a DID configuration resource and domain linkage credentials it holds. + +You can either pass in a DID configuration resource or fetch it remotely by setting a secure well-known location (origin). +Option available to only verify a given DID. + +```typescript +agent + .verifyDidConfigurationResource({ + signatureVerification: () => Promise.resolve({ verified: true }), + origin: 'https://example.com', + did: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM#foo', + }) + .then((result: IResourceValidation) => console.log(result.status)) +``` + +## Installation + +```shell +yarn add @sphereon/ssi-sdk-wellknown-did-verifier +``` + +## Build + +```shell +yarn build +``` diff --git a/packages/wellknown-did-verifier/__tests__/localAgent.test.ts b/packages/wellknown-did-verifier/__tests__/localAgent.test.ts new file mode 100644 index 000000000..77411b25b --- /dev/null +++ b/packages/wellknown-did-verifier/__tests__/localAgent.test.ts @@ -0,0 +1,76 @@ +import { getConfig } from '@veramo/cli/build/setup' +import { createObjects } from '@veramo/cli/build/lib/objectCreator' +import { ServiceTypesEnum } from '@sphereon/wellknown-dids-client/dist/types' +import wellKnownDidVerifierAgentLogic from './shared/wellKnownDidVerifierAgentLogic' + +jest.setTimeout(30000) + +let agent: any + +const setup = async (): Promise => { + const config = getConfig('packages/wellknown-did-verifier/agent.yml') + const { localAgent } = createObjects(config, { localAgent: '/agent' }) + + await localAgent.registerSignatureVerification( + { + callbackName: 'verified', + signatureVerification: () => Promise.resolve({ verified: true }), + }, + null + ) + + const DID = 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM' + const ORIGIN = 'https://example.com' + const DOCUMENT = { + '@context': ['https://www.w3.org/ns/did/v1', 'https://identity.foundation/.well-known/did-configuration/v1'], + id: DID, + verificationMethod: [ + { + id: `${DID}#_Qq0UL2Fq651Q0Fjd6TvnYE-faHiOpRlPVQcY_-tA4A`, + type: 'JsonWebKey2020', + controller: DID, + publicKeyJwk: { + kty: 'OKP', + crv: 'Ed25519', + x: 'VCpo2LMLhn6iWku8MKvSLg2ZAoC-nlOyPVQaO3FxVeQ', + }, + }, + ], + service: [ + { + id: `${DID}#foo`, + type: ServiceTypesEnum.LINKED_DOMAINS, + serviceEndpoint: { + origins: [ORIGIN, ORIGIN], + }, + }, + { + id: `${DID}#bar`, + type: ServiceTypesEnum.LINKED_DOMAINS, + serviceEndpoint: ORIGIN, + }, + ], + } + + localAgent.resolveDid = jest.fn().mockReturnValue(Promise.resolve({ didDocument: DOCUMENT })) + + agent = localAgent + + return true +} + +const tearDown = async (): Promise => { + return true +} + +const getAgent = () => agent +const testContext = { + getAgent, + setup, + tearDown, + isRestTest: false, +} + +describe('Local integration tests', () => { + wellKnownDidVerifierAgentLogic(testContext) +}) diff --git a/packages/wellknown-did-verifier/__tests__/restAgent.test.ts b/packages/wellknown-did-verifier/__tests__/restAgent.test.ts new file mode 100644 index 000000000..fe54fd482 --- /dev/null +++ b/packages/wellknown-did-verifier/__tests__/restAgent.test.ts @@ -0,0 +1,114 @@ +import 'cross-fetch/polyfill' +// @ts-ignore +import express from 'express' +import { Server } from 'http' +import { IAgent, createAgent, IAgentOptions } from '@veramo/core' +import { AgentRestClient } from '@veramo/remote-client' +import { AgentRouter, RequestWithAgentRouter } from '@veramo/remote-server' +import { getConfig } from '@veramo/cli/build/setup' +import { createObjects } from '@veramo/cli/build/lib/objectCreator' +import { IWellKnownDidVerifier } from '../src/types/IWellKnownDidVerifier' +import { ServiceTypesEnum } from '@sphereon/wellknown-dids-client/dist/types' +import wellKnownDidVerifierAgentLogic from './shared/wellKnownDidVerifierAgentLogic' + +jest.setTimeout(30000) + +const port = 3002 +const basePath = '/agent' + +let serverAgent: IAgent +let restServer: Server + +const getAgent = (options?: IAgentOptions) => + createAgent({ + ...options, + plugins: [ + new AgentRestClient({ + url: 'http://localhost:' + port + basePath, + enabledMethods: serverAgent.availableMethods(), + schema: serverAgent.getSchema(), + }), + ], + }) + +const setup = async (): Promise => { + const config = getConfig('packages/wellknown-did-verifier/agent.yml') + const { agent } = createObjects(config, { agent: '/agent' }) + + await agent.registerSignatureVerification( + { + callbackName: 'verified', + signatureVerification: () => Promise.resolve({ verified: true }), + }, + null + ) + + const DID = 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM' + const ORIGIN = 'https://example.com' + const DOCUMENT = { + '@context': ['https://www.w3.org/ns/did/v1', 'https://identity.foundation/.well-known/did-configuration/v1'], + id: DID, + verificationMethod: [ + { + id: `${DID}#_Qq0UL2Fq651Q0Fjd6TvnYE-faHiOpRlPVQcY_-tA4A`, + type: 'JsonWebKey2020', + controller: DID, + publicKeyJwk: { + kty: 'OKP', + crv: 'Ed25519', + x: 'VCpo2LMLhn6iWku8MKvSLg2ZAoC-nlOyPVQaO3FxVeQ', + }, + }, + ], + service: [ + { + id: `${DID}#foo`, + type: ServiceTypesEnum.LINKED_DOMAINS, + serviceEndpoint: { + origins: [ORIGIN, ORIGIN], + }, + }, + { + id: `${DID}#bar`, + type: ServiceTypesEnum.LINKED_DOMAINS, + serviceEndpoint: ORIGIN, + }, + ], + } + + agent.resolveDid = jest.fn().mockReturnValue(Promise.resolve({ didDocument: DOCUMENT })) + + serverAgent = agent + + const agentRouter = AgentRouter({ + exposedMethods: serverAgent.availableMethods(), + }) + + const requestWithAgent = RequestWithAgentRouter({ + agent: serverAgent, + }) + + return new Promise((resolve) => { + const app = express() + app.use(basePath, requestWithAgent, agentRouter) + restServer = app.listen(port, () => { + resolve(true) + }) + }) +} + +const tearDown = async (): Promise => { + restServer.close() + return true +} + +const testContext = { + getAgent, + setup, + tearDown, + isRestTest: true, +} + +describe('REST integration tests', () => { + wellKnownDidVerifierAgentLogic(testContext) +}) diff --git a/packages/wellknown-did-verifier/__tests__/shared/wellKnownDidVerifierAgentLogic.ts b/packages/wellknown-did-verifier/__tests__/shared/wellKnownDidVerifierAgentLogic.ts new file mode 100644 index 000000000..a57133bbb --- /dev/null +++ b/packages/wellknown-did-verifier/__tests__/shared/wellKnownDidVerifierAgentLogic.ts @@ -0,0 +1,170 @@ +import { ValidationStatusEnum } from '@sphereon/wellknown-dids-client/dist/types' +import { TAgent, IResolver } from '@veramo/core' +import { IWellKnownDidVerifier } from '../../src/types/IWellKnownDidVerifier' + +const nock = require('nock') + +type ConfiguredAgent = TAgent + +export default (testContext: { + getAgent: () => ConfiguredAgent + setup: () => Promise + tearDown: () => Promise + isRestTest: boolean +}) => { + describe('Well-Known DID Verifier Agent Plugin', () => { + const DID = 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM' + const DID_CONFIGURATION = { + '@context': 'https://identity.foundation/.well-known/did-configuration/v1', + linked_dids: [ + 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNI3o2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSJ9.eyJleHAiOjE3NjQ4NzkxMzksImlzcyI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNIiwibmJmIjoxNjA3MTEyNzM5LCJzdWIiOiJkaWQ6a2V5Ono2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSIsInZjIjp7IkBjb250ZXh0IjpbImh0dHBzOi8vd3d3LnczLm9yZy8yMDE4L2NyZWRlbnRpYWxzL3YxIiwiaHR0cHM6Ly9pZGVudGl0eS5mb3VuZGF0aW9uLy53ZWxsLWtub3duL2RpZC1jb25maWd1cmF0aW9uL3YxIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImlkIjoiZGlkOmtleTp6Nk1rb1RIc2dOTnJieThKekNOUTFpUkx5VzVRUTZSOFh1dTZBQThpZ0dyTVZQVU0iLCJvcmlnaW4iOiJodHRwczovL2lkZW50aXR5LmZvdW5kYXRpb24ifSwiZXhwaXJhdGlvbkRhdGUiOiIyMDI1LTEyLTA0VDE0OjEyOjE5LTA2OjAwIiwiaXNzdWFuY2VEYXRlIjoiMjAyMC0xMi0wNFQxNDoxMjoxOS0wNjowMCIsImlzc3VlciI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNIiwidHlwZSI6WyJWZXJpZmlhYmxlQ3JlZGVudGlhbCIsIkRvbWFpbkxpbmthZ2VDcmVkZW50aWFsIl19fQ.YZnpPMAW3GdaPXC2YKoJ7Igt1OaVZKq09XZBkptyhxTAyHTkX2Ewtew-JKHKQjyDyabY3HAy1LUPoIQX0jrU0J82pIYT3k2o7nNTdLbxlgb49FcDn4czntt5SbY0m1XwrMaKEvV0bHQsYPxNTqjYsyySccgPfmvN9IT8gRS-M9a6MZQxuB3oEMrVOQ5Vco0bvTODXAdCTHibAk1FlvKz0r1vO5QMhtW4OlRrVTI7ibquf9Nim_ch0KeMMThFjsBDKetuDF71nUcL5sf7PCFErvl8ZVw3UK4NkZ6iM-XIRsLL6rXP2SnDUVovcldhxd_pyKEYviMHBOgBdoNP6fOgRQ', + 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNI3o2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSJ9.eyJleHAiOjE3NjQ4NzkxMzksImlzcyI6ImRpZDprZXk6b3RoZXIiLCJuYmYiOjE2MDcxMTI3MzksInN1YiI6ImRpZDprZXk6b3RoZXIiLCJ2YyI6eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImh0dHBzOi8vaWRlbnRpdHkuZm91bmRhdGlvbi8ud2VsbC1rbm93bi9kaWQtY29uZmlndXJhdGlvbi92MSJdLCJjcmVkZW50aWFsU3ViamVjdCI6eyJpZCI6ImRpZDprZXk6b3RoZXIiLCJvcmlnaW4iOiJodHRwczovL2lkZW50aXR5LmZvdW5kYXRpb24ifSwiZXhwaXJhdGlvbkRhdGUiOiIyMDI1LTEyLTA0VDE0OjEyOjE5LTA2OjAwIiwiaXNzdWFuY2VEYXRlIjoiMjAyMC0xMi0wNFQxNDoxMjoxOS0wNjowMCIsImlzc3VlciI6ImRpZDprZXk6b3RoZXIiLCJ0eXBlIjpbIlZlcmlmaWFibGVDcmVkZW50aWFsIiwiRG9tYWluTGlua2FnZUNyZWRlbnRpYWwiXX19.rRuc-ojuEgyq8p_tBYK7BayuiNTBeXNyAnC14Rnjs-jsnhae4_E1Q12W99K2NGCGBi5KjNsBcZmdNJPxejiKPrjjcB99poFCgTY8tuRzDjVo0lIeBwfx9qqjKHTRTUR8FGM_imlOpVfBF4AHYxjkHvZn6c9lYvatYcDpB2UfH4BNXkdSVrUXy_kYjpMpAdRtyCAnD_isN1YpEHBqBmnfuVUbYcQK5kk6eiokRFDtWruL1OEeJMYPqjuBSd2m-H54tSM84Oic_pg2zXDjjBlXNelat6MPNT2QxmkwJg7oyewQWX2Ot2yyhSp9WyAQWMlQIe2x84R0lADUmZ1TPQchNw', + ], + } + + let agent: ConfiguredAgent + + beforeAll(async () => { + await testContext.setup() + agent = testContext.getAgent() + }) + + afterAll(testContext.tearDown) + + it('should verify domain linkage with signature verification key', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(3).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDomainLinkage({ + did: DID, + signatureVerification: 'verified', + }) + + expect(result.status).toEqual(ValidationStatusEnum.VALID) + }) + + it('should only verify service DIDs when onlyVerifyServiceDids set to true', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(3).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDomainLinkage({ + did: DID, + signatureVerification: 'verified', + onlyVerifyServiceDids: true, + }) + + expect(result.endpointDescriptors[0].resources[0].credentials.length).toEqual(1) + }) + + it('should throw error if signature verification key is not found when verifying a domain linkage', async () => { + const signatureVerificationKey = 'unknown' + await expect( + agent.verifyDomainLinkage({ + did: DID, + signatureVerification: signatureVerificationKey, + }) + ).rejects.toThrow(`Signature validation not found for key: ${signatureVerificationKey}`) + }) + + it('should throw error if signature verification key is not found when verifying a DID configuration resource', async () => { + const signatureVerificationKey = 'unknown' + + await expect( + agent.verifyDidConfigurationResource({ + signatureVerification: signatureVerificationKey, + origin: 'https://example.com', + }) + ).rejects.toThrow(`Signature validation not found for key: ${signatureVerificationKey}`) + }) + + it('should throw error if no configuration or origin is supplied', async () => { + await expect( + agent.verifyDidConfigurationResource({ + signatureVerification: 'verified', + }) + ).rejects.toThrow('No DID configuration resource or origin supplied.') + }) + + it('should throw error if both configuration and origin are supplied', async () => { + await expect( + agent.verifyDidConfigurationResource({ + signatureVerification: 'verified', + configuration: DID_CONFIGURATION, + origin: 'https://example.com', + }) + ).rejects.toThrow('Cannot supply both a DID configuration resource and an origin.') + }) + + it('should verify DID configuration resource with signature verification key', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(1).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDidConfigurationResource({ + signatureVerification: 'verified', + origin: 'https://example.com', + }) + + expect(result.status).toEqual(ValidationStatusEnum.VALID) + }) + + it('should only verify specific DID when given', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(1).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDidConfigurationResource({ + did: DID, + signatureVerification: 'verified', + origin: 'https://example.com', + }) + + expect(result.credentials.length).toEqual(1) + }) + + if (!testContext.isRestTest) { + it('should verify domain linkage with signature verification callback', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(3).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDomainLinkage({ + did: DID, + signatureVerification: () => Promise.resolve({ verified: true }), + }) + + expect(result.status).toEqual(ValidationStatusEnum.VALID) + }) + + it('should register signature verification', async () => { + const callbackName = 'new' + await agent.registerSignatureVerification({ + callbackName, + signatureVerification: () => Promise.resolve({ verified: true }), + }) + + await expect( + agent.registerSignatureVerification({ + callbackName, + signatureVerification: () => Promise.resolve({ verified: true }), + }) + ).rejects.toThrow(`Signature validation with key: ${callbackName} already present`) + }) + + it('should remove signature verification', async () => { + const callbackName = 'remove' + await agent.registerSignatureVerification({ + callbackName, + signatureVerification: () => Promise.resolve({ verified: true }), + }) + + const result = await agent.removeSignatureVerification({ callbackName }) + + expect(result).toEqual(true) + }) + + it('should verify DID configuration resource with signature verification callback', async () => { + nock('https://example.com').get('/.well-known/did-configuration.json').times(1).reply(200, DID_CONFIGURATION) + + const result = await agent.verifyDidConfigurationResource({ + signatureVerification: () => Promise.resolve({ verified: true }), + origin: 'https://example.com', + }) + + expect(result.status).toEqual(ValidationStatusEnum.VALID) + }) + } + }) +} diff --git a/packages/wellknown-did-verifier/agent.yml b/packages/wellknown-did-verifier/agent.yml new file mode 100644 index 000000000..92424989f --- /dev/null +++ b/packages/wellknown-did-verifier/agent.yml @@ -0,0 +1,105 @@ +version: 3.0 + +constants: + baseUrl: http://localhost:3335 + port: 3335 + methods: + - registerSignatureValidation + - removeSignatureValidation + - verifyDomainLinkage + - verifyDidConfigurationResource + +server: + baseUrl: + $ref: /constants/baseUrl + port: + $ref: /constants/port + use: + # CORS + - - $require: 'cors' + + # Add agent to the request object + - - $require: '@veramo/remote-server?t=function#RequestWithAgentRouter' + $args: + - agent: + $ref: /agent + + # API base path + - - /agent + - $require: '@veramo/remote-server?t=function#apiKeyAuth' + $args: + # Please configure your own API key. This is used when executing agent methods through ${baseUrl}/agent or ${baseUrl}/api-docs + - apiKey: test123 + - $require: '@veramo/remote-server?t=function#AgentRouter' + $args: + - exposedMethods: + $ref: /constants/methods + + # Open API schema + - - /open-api.json + - $require: '@veramo/remote-server?t=function#ApiSchemaRouter' + $args: + - basePath: :3335/agent + securityScheme: bearer + apiName: Agent + apiVersion: '1.0.0' + exposedMethods: + $ref: /constants/methods + + # Swagger docs + - - /api-docs + - $require: swagger-ui-express?t=object#serve + - $require: swagger-ui-express?t=function#setup + $args: + - null + - swaggerOptions: + url: '/open-api.json' + + # Execute during server initialization + init: + - $require: '@veramo/remote-server?t=function#createDefaultDid' + $args: + - agent: + $ref: /agent + baseUrl: + $ref: /constants/baseUrl + messagingServiceEndpoint: /messaging + +didResolver: + $require: '@veramo/did-resolver#DIDResolverPlugin' + $args: + - resolver: + $require: did-resolver#Resolver + $args: + - web: + $ref: /web-did-resolver + key: + $ref: /did-key-resolver + elem: + $ref: /universal-resolver + io: + $ref: /universal-resolver + ion: + $ref: /universal-resolver + sov: + $ref: /universal-resolver + +universal-resolver: + $require: '@veramo/did-resolver#UniversalResolver' + $args: + - url: https://dev.uniresolver.io/1.0/identifiers/ + +did-key-resolver: + $require: '@veramo/did-provider-key?t=function&p=/key#getDidKeyResolver' + +web-did-resolver: + $require: web-did-resolver?t=function&p=/web#getResolver + +# Agent +agent: + $require: '@veramo/core#Agent' + $args: + - schemaValidation: false + plugins: + - $ref: /didResolver + - $require: ./packages/wellknown-did-verifier/dist#WellKnownDidVerifier diff --git a/packages/wellknown-did-verifier/api-extractor.json b/packages/wellknown-did-verifier/api-extractor.json new file mode 100644 index 000000000..94c2c6a9f --- /dev/null +++ b/packages/wellknown-did-verifier/api-extractor.json @@ -0,0 +1,3 @@ +{ + "extends": "../include/api-extractor-base.json" +} diff --git a/packages/wellknown-did-verifier/package.json b/packages/wellknown-did-verifier/package.json new file mode 100644 index 000000000..049dc579d --- /dev/null +++ b/packages/wellknown-did-verifier/package.json @@ -0,0 +1,43 @@ +{ + "name": "@sphereon/ssi-sdk-wellknown-did-verifier", + "version": "0.7.0", + "source": "src/index.ts", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "veramo": { + "pluginInterfaces": { + "IWellknownDidVerifier": "./src/types/IWellKnownDidVerifier.ts" + } + }, + "scripts": { + "build": "tsc --build" + }, + "dependencies": { + "@sphereon/wellknown-dids-client": "^0.1.0" + }, + "devDependencies": { + "@veramo/cli": "3.1.2-next.84", + "nock": "^13.2.9", + "typescript": "4.6.4" + }, + "files": [ + "dist/**/*", + "src/**/*", + "README.md", + "plugin.schema.json", + "LICENSE" + ], + "publishConfig": { + "access": "public" + }, + "repository": "git@github.com:Sphereon-Opensource/SSI-SDK.git", + "author": "Sphereon ", + "license": "Apache-2.0", + "keywords": [ + "DID", + "Domain Linkage", + "DID Configuration Resource", + "Verifier", + "Well-Known DIDs" + ] +} diff --git a/packages/wellknown-did-verifier/plugin.schema.json b/packages/wellknown-did-verifier/plugin.schema.json new file mode 100644 index 000000000..8050db33d --- /dev/null +++ b/packages/wellknown-did-verifier/plugin.schema.json @@ -0,0 +1,34 @@ +{ + "IWellKnownDidVerifier": { + "components": { + "schemas": { + "IVerifyDomainLinkageArgs": { + "type": "object", + "properties": { + "didUrl": { + "type": "string" + }, + "signatureVerification": { + "type": "string" + }, + "onlyVerifyServiceDids": { + "type": "boolean" + }, + "additionalProperties": false + }, + "required": ["didUrl", "signatureVerification"], + "description": "Arguments needed for {@link IWellKnownDidVerifier.verifyDomainLinkage } " + } + }, + "methods": { + "verifyDomainLinkage": { + "description": "Verifies the relationship between the controller of an origin and a DID", + "arguments": { + "$ref": "#/components/schemas/IVerifyDomainLinkageArgs" + }, + "returnType": "object" + } + } + } + } +} diff --git a/packages/wellknown-did-verifier/src/agent/WellKnownDidVerifier.ts b/packages/wellknown-did-verifier/src/agent/WellKnownDidVerifier.ts new file mode 100644 index 000000000..61a35715d --- /dev/null +++ b/packages/wellknown-did-verifier/src/agent/WellKnownDidVerifier.ts @@ -0,0 +1,104 @@ +import { IAgentPlugin, DIDResolutionResult } from '@veramo/core' +import { WellKnownDidVerifier as Verifier } from '@sphereon/wellknown-dids-client' +import { + IDomainLinkageValidation, + IResourceValidation, + IVerifyCallbackArgs, + IVerifyCredentialResult, +} from '@sphereon/wellknown-dids-client/dist/types' +import { schema } from '../index' +import { + IWellKnownDidVerifier, + IWellKnownDidVerifierOptionsArgs, + IRegisterSignatureVerificationArgs, + IRemoveSignatureVerificationArgs, + IRequiredContext, + IVerifyDidConfigurationResourceArgs, + IVerifyDomainLinkageArgs, +} from '../types/IWellKnownDidVerifier' + +/** + * {@inheritDoc IWellKnownDidVerifier} + */ +export class WellKnownDidVerifier implements IAgentPlugin { + readonly schema = schema.IWellKnownDidVerifier + readonly methods: IWellKnownDidVerifier = { + registerSignatureVerification: this.registerSignatureVerification.bind(this), + removeSignatureVerification: this.removeSignatureVerification.bind(this), + verifyDomainLinkage: this.verifyDomainLinkage.bind(this), + verifyDidConfigurationResource: this.verifyDidConfigurationResource.bind(this), + } + + private readonly signatureVerifications: Record Promise> + private readonly onlyVerifyServiceDids: boolean + + constructor(args?: IWellKnownDidVerifierOptionsArgs) { + this.signatureVerifications = (args && args.signatureVerifications) || {} + this.onlyVerifyServiceDids = (args && args.onlyVerifyServiceDids) || false + } + + /** {@inheritDoc IWellKnownDidVerifier.registerSignatureVerification} */ + private async registerSignatureVerification(args: IRegisterSignatureVerificationArgs, context: IRequiredContext): Promise { + if (this.signatureVerifications[args.callbackName] !== undefined) { + return Promise.reject(new Error(`Signature validation with key: ${args.callbackName} already present`)) + } + + this.signatureVerifications[args.callbackName] = args.signatureVerification + } + + /** {@inheritDoc IWellKnownDidVerifier.removeSignatureVerification} */ + private async removeSignatureVerification(args: IRemoveSignatureVerificationArgs, context: IRequiredContext): Promise { + return delete this.signatureVerifications[args.callbackName] + } + + /** {@inheritDoc IWellKnownDidVerifier.verifyDomainLinkage} */ + private async verifyDomainLinkage(args: IVerifyDomainLinkageArgs, context: IRequiredContext): Promise { + const signatureVerification: (args: IVerifyCallbackArgs) => Promise = + typeof args.signatureVerification === 'string' + ? await this.getSignatureVerification(args.signatureVerification) + : (args.signatureVerification as (args: IVerifyCallbackArgs) => Promise) + + return context.agent.resolveDid({ didUrl: args.did }).then((didResolutionResult: DIDResolutionResult) => { + if (!didResolutionResult.didDocument) { + return Promise.reject(Error(`Unable to resolve did: ${args.did}`)) + } + + return new Verifier().verifyDomainLinkage({ + didDocument: didResolutionResult.didDocument, + verifySignatureCallback: signatureVerification, + onlyVerifyServiceDid: args.onlyVerifyServiceDids || this.onlyVerifyServiceDids, + }) + }) + } + + /** {@inheritDoc IWellKnownDidVerifier.verifyDidConfigurationResource} */ + private async verifyDidConfigurationResource(args: IVerifyDidConfigurationResourceArgs, context: IRequiredContext): Promise { + if (args.configuration && args.origin) { + return Promise.reject(Error('Cannot supply both a DID configuration resource and an origin.')) + } + + if (!args.configuration && !args.origin) { + return Promise.reject(Error('No DID configuration resource or origin supplied.')) + } + + const signatureVerification: (args: IVerifyCallbackArgs) => Promise = + typeof args.signatureVerification === 'string' + ? await this.getSignatureVerification(args.signatureVerification) + : (args.signatureVerification as (args: IVerifyCallbackArgs) => Promise) + + return new Verifier().verifyResource({ + verifySignatureCallback: signatureVerification, + configuration: args.configuration, + origin: args.origin, + did: args.did, + }) + } + + private async getSignatureVerification(key: string): Promise<(args: IVerifyCallbackArgs) => Promise> { + if (this.signatureVerifications[key] === undefined) { + return Promise.reject(new Error(`Signature validation not found for key: ${key}`)) + } + + return this.signatureVerifications[key] + } +} diff --git a/packages/wellknown-did-verifier/src/index.ts b/packages/wellknown-did-verifier/src/index.ts new file mode 100644 index 000000000..c4d83f300 --- /dev/null +++ b/packages/wellknown-did-verifier/src/index.ts @@ -0,0 +1,7 @@ +/** + * @public + */ +const schema = require('../plugin.schema.json') +export { schema } +export { WellKnownDidVerifier } from './agent/WellKnownDidVerifier' +export * from './types/IWellKnownDidVerifier' diff --git a/packages/wellknown-did-verifier/src/types/IWellKnownDidVerifier.ts b/packages/wellknown-did-verifier/src/types/IWellKnownDidVerifier.ts new file mode 100644 index 000000000..26bf17d40 --- /dev/null +++ b/packages/wellknown-did-verifier/src/types/IWellKnownDidVerifier.ts @@ -0,0 +1,44 @@ +import { + IDidConfigurationResource, + IDomainLinkageValidation, + IVerifyCallbackArgs, + IVerifyCredentialResult, + IResourceValidation, +} from '@sphereon/wellknown-dids-client/dist/types' +import { IAgentContext, IPluginMethodMap, IResolver } from '@veramo/core' + +export interface IWellKnownDidVerifier extends IPluginMethodMap { + registerSignatureVerification(args: IRegisterSignatureVerificationArgs, context: IRequiredContext): Promise + removeSignatureVerification(args: IRemoveSignatureVerificationArgs, context: IRequiredContext): Promise + verifyDomainLinkage(args: IVerifyDomainLinkageArgs, context: IRequiredContext): Promise + verifyDidConfigurationResource(args: IVerifyDidConfigurationResourceArgs, context: IRequiredContext): Promise +} + +export interface IWellKnownDidVerifierOptionsArgs { + signatureVerifications?: Record Promise> + onlyVerifyServiceDids?: boolean +} + +export interface IRegisterSignatureVerificationArgs { + callbackName: string + signatureVerification: (args: IVerifyCallbackArgs) => Promise +} + +export interface IRemoveSignatureVerificationArgs { + callbackName: string +} + +export interface IVerifyDomainLinkageArgs { + did: string + signatureVerification: ((args: IVerifyCallbackArgs) => Promise) | string + onlyVerifyServiceDids?: boolean +} + +export interface IVerifyDidConfigurationResourceArgs { + signatureVerification: ((args: IVerifyCallbackArgs) => Promise) | string + configuration?: IDidConfigurationResource + origin?: string + did?: string +} + +export type IRequiredContext = IAgentContext diff --git a/packages/wellknown-did-verifier/tsconfig.json b/packages/wellknown-did-verifier/tsconfig.json new file mode 100644 index 000000000..d3e5c24d2 --- /dev/null +++ b/packages/wellknown-did-verifier/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig-base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "declarationDir": "dist", + "strictPropertyInitialization": false + }, + "references": [] +} diff --git a/yarn.lock b/yarn.lock index 37dd52f87..8c1ee4567 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3306,6 +3306,15 @@ resolved "https://registry.yarnpkg.com/@sphereon/react-native-argon2/-/react-native-argon2-2.0.6.tgz#602abb96d6d41a7f0778a3323940fca0b4fa13ed" integrity sha512-5RkIzhfeDw12p1t2BcQQJyYmgtPE3CQDPLwPfwpnVGamG5R8tY4FhJRNScGzRzttHw6tbBWC1acZ2IM0swEmUQ== +"@sphereon/wellknown-dids-client@^0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@sphereon/wellknown-dids-client/-/wellknown-dids-client-0.1.0.tgz#b682cfad2086513564dbde3df1388a2fd865f3be" + integrity sha512-JpXTVCZQCGvKPhJ4KJ2bkklo/MnAoUrsfMN6C65FgLu9VznLM3pEMB/IbqHk4yJ8OWIg8zeOc5s2G2YiGxaQ1A== + dependencies: + "@sphereon/ssi-sdk-core" "^0.7.0" + cross-fetch "^3.1.5" + jwt-decode "^3.1.2" + "@sqltools/formatter@^1.2.2": version "1.2.3" resolved "https://registry.yarnpkg.com/@sqltools/formatter/-/formatter-1.2.3.tgz#1185726610acc37317ddab11c3c7f9066966bd20" @@ -11459,7 +11468,7 @@ nerf-dart@^1.0.0: resolved "https://registry.yarnpkg.com/nerf-dart/-/nerf-dart-1.0.0.tgz#e6dab7febf5ad816ea81cf5c629c5a0ebde72c1a" integrity sha512-EZSPZB70jiVsivaBLYDCyntd5eH8NTSMOn3rB+HxwdmKThGELLdYv8qVIMWvZEFy9w8ZZpW9h9OB32l1rGtj7g== -nock@*, nock@^13.2.1: +nock@*, nock@^13.2.1, nock@^13.2.9: version "13.2.9" resolved "https://registry.yarnpkg.com/nock/-/nock-13.2.9.tgz#4faf6c28175d36044da4cfa68e33e5a15086ad4c" integrity sha512-1+XfJNYF1cjGB+TKMWi29eZ0b82QOvQs2YoLNzbpWGqFMtRQHTa57osqdGj4FrFPgkO4D4AZinzUJR9VvW3QUA== @@ -14705,6 +14714,11 @@ typescript@4.4.3: resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.3.tgz#bdc5407caa2b109efd4f82fe130656f977a29324" integrity sha512-4xfscpisVgqqDfPaJo5vkd+Qd/ItkoagnHpufr+i2QCHBsNYp+G7UAoyFl8aPtx879u38wPV65rZ8qbGZijalA== +typescript@4.6.4, typescript@~4.6.2, typescript@~4.6.3: + version "4.6.4" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.4.tgz#caa78bbc3a59e6a5c510d35703f6a09877ce45e9" + integrity sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg== + typescript@^4.4.3, typescript@^4.5.2, typescript@^4.5.4, typescript@^4.7.4: version "4.7.4" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235" @@ -14715,11 +14729,6 @@ typescript@~4.4.3: resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.4.tgz#2cd01a1a1f160704d3101fd5a58ff0f9fcb8030c" integrity sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA== -typescript@~4.6.2, typescript@~4.6.3: - version "4.6.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.4.tgz#caa78bbc3a59e6a5c510d35703f6a09877ce45e9" - integrity sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg== - typical@^2.6.0, typical@^2.6.1: version "2.6.1" resolved "https://registry.yarnpkg.com/typical/-/typical-2.6.1.tgz#5c080e5d661cbbe38259d2e70a3c7253e873881d"