From c5e9f1c3a44480c8734ef2b61e232d179ef78889 Mon Sep 17 00:00:00 2001 From: Nam Hoang Date: Wed, 9 Aug 2023 10:45:08 +0700 Subject: [PATCH] feat: credential router (#139) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [x] 🍕 Feature - [ ] 🐛 Bug Fix - [ ] 📝 Documentation Update - [ ] 🎨 Style - [ ] 🧑‍💻 Code Refactor - [ ] 🔥 Performance Improvements - [ ] ✅ Test - [ ] 🤖 Build - [ ] 🔁 CI - [ ] 📦 Chore (Release) - [ ] ⏩ Revert ## Description Implement the credential router which is used to navigate the issuing and verifying request rely on the proof format of the credential ## Related Tickets & Documents ## Mobile & Desktop Screenshots/Recordings ## Added tests? - [ ] 👍 yes - [ ] 🙅 no, because they aren't needed - [ ] 🙋 no, because I need help ## Added to documentation? - [x] 📜 README.md - [ ] 📓 [vc-kit doc site](https://uncefact.github.io/vckit/) - [ ] 📕 storybook - [ ] 🙅 no documentation needed ## [optional] Are there any post-deployment tasks we need to perform? --------- Signed-off-by: Nam Hoang --- packages/cli/package.json | 5 +- packages/cli/src/credentialOA.ts | 2 +- packages/core-types/package.json | 3 +- packages/core-types/src/index.ts | 1 + packages/core-types/src/plugin.schema.json | 532 ++++++++++++++++++ .../core-types/src/types/ICredentialRouter.ts | 49 ++ .../__tests__/action-handler.test.ts | 12 +- packages/credential-oa/src/action-handler.ts | 21 +- packages/credential-oa/src/index.ts | 2 +- packages/credential-router/LICENSE | 201 +++++++ packages/credential-router/README.md | 24 + packages/credential-router/api-extractor.json | 18 + packages/credential-router/package.json | 42 ++ .../credential-router/src/action-handler.ts | 126 +++++ packages/credential-router/src/index.ts | 1 + packages/credential-router/tsconfig.json | 11 + packages/demo-explorer/package.json | 6 +- .../src/components/CredentialInfo.tsx | 68 ++- .../components/IssueCredentialFromSchema.tsx | 152 ++++- packages/demo-explorer/src/layout/Layout.tsx | 10 - .../src/pages/CredentialVerifier.tsx | 4 +- .../DevTools/CreateProfileCredential.tsx | 126 ----- .../src/pages/DevTools/IssueCredential.tsx | 261 --------- packages/demo-explorer/src/utils/helpers.ts | 16 + packages/demo-explorer/src/utils/signing.ts | 116 +++- packages/encrypted-storage/README.md | 6 +- packages/encrypted-storage/package.json | 2 +- packages/revocation-list-2020/README.md | 13 +- packages/revocation-list-2020/package.json | 2 +- packages/revocation-list-2020/src/index.ts | 2 +- .../src/revocation-list-2020-middleware.ts | 12 +- 31 files changed, 1328 insertions(+), 518 deletions(-) create mode 100644 packages/core-types/src/types/ICredentialRouter.ts create mode 100644 packages/credential-router/LICENSE create mode 100644 packages/credential-router/README.md create mode 100644 packages/credential-router/api-extractor.json create mode 100644 packages/credential-router/package.json create mode 100644 packages/credential-router/src/action-handler.ts create mode 100644 packages/credential-router/src/index.ts create mode 100644 packages/credential-router/tsconfig.json delete mode 100644 packages/demo-explorer/src/pages/DevTools/CreateProfileCredential.tsx delete mode 100644 packages/demo-explorer/src/pages/DevTools/IssueCredential.tsx diff --git a/packages/cli/package.json b/packages/cli/package.json index d76c6d56..96e4060b 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -45,8 +45,9 @@ "@vckit/remote-server": "^1.0.0-beta.5", "@vckit/renderer": "^1.0.0-beta.5", "@vckit/vc-api": "workspace:1.0.0-beta.5", - "@vckit/revocationlist": "workspace:*", - "@vckit/encrypted-storage": "workspace:*", + "@vckit/revocationlist": "workspace:^", + "@vckit/encrypted-storage": "workspace:^", + "@vckit/credential-router": "workspace:^", "@veramo/core": "5.2.0", "@veramo/credential-status": "5.2.0", "@veramo/credential-eip712": "5.2.0", diff --git a/packages/cli/src/credentialOA.ts b/packages/cli/src/credentialOA.ts index b38c8627..fb2eb612 100644 --- a/packages/cli/src/credentialOA.ts +++ b/packages/cli/src/credentialOA.ts @@ -32,7 +32,7 @@ credentialOA const proofFormat = 'OpenAttestationMerkleProofSignature2018'; if (identifiers.length === 0) { - console.error('No dids'); + console.error('No did ethrs'); process.exit(); } const answers = await inquirer.prompt([ diff --git a/packages/core-types/package.json b/packages/core-types/package.json index 9ddf65bc..13e5b58d 100644 --- a/packages/core-types/package.json +++ b/packages/core-types/package.json @@ -30,7 +30,8 @@ "ICredentialStatusManager": "./src/types/ICredentialStatusManager.ts", "IRenderer": "./src/types/IRender.ts", "IEncryptedStorage": "./src/types/IEncryptedStorage.ts", - "IRevocationList2020": "./src/types/IRevocationList2020.ts" + "IRevocationList2020": "./src/types/IRevocationList2020.ts", + "ICredentialRouter": "./src/types/ICredentialRouter.ts" } }, "dependencies": { diff --git a/packages/core-types/src/index.ts b/packages/core-types/src/index.ts index a39934c6..7368ce6e 100644 --- a/packages/core-types/src/index.ts +++ b/packages/core-types/src/index.ts @@ -31,3 +31,4 @@ export * from './types/IRender.js'; export * from './types/IRendererProvider.js'; export * from './types/IEncryptedStorage.js'; export * from './types/IRevocationList2020.js'; +export * from './types/ICredentialRouter.js'; diff --git a/packages/core-types/src/plugin.schema.json b/packages/core-types/src/plugin.schema.json index 7eb598f6..6a327161 100644 --- a/packages/core-types/src/plugin.schema.json +++ b/packages/core-types/src/plugin.schema.json @@ -188,6 +188,54 @@ }, "ethereumAddress": { "type": "string" + }, + "conditionOr": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionAnd": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "threshold": { + "type": "number" + }, + "conditionThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionWeightedThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConditionWeightedThreshold" + } + }, + "conditionDelegated": { + "type": "string" + }, + "relationshipParent": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipChild": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipSibling": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ @@ -242,6 +290,21 @@ ], "description": "Encapsulates a JSON web key type that includes only the public properties that can be used in DID documents.\n\nThe private properties are intentionally omitted to discourage the use (and accidental disclosure) of private keys in DID documents." }, + "ConditionWeightedThreshold": { + "type": "object", + "properties": { + "condition": { + "$ref": "#/components/schemas/VerificationMethod" + }, + "weight": { + "type": "number" + } + }, + "required": [ + "condition", + "weight" + ] + }, "Service": { "type": "object", "properties": { @@ -1687,6 +1750,54 @@ }, "ethereumAddress": { "type": "string" + }, + "conditionOr": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionAnd": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "threshold": { + "type": "number" + }, + "conditionThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionWeightedThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConditionWeightedThreshold" + } + }, + "conditionDelegated": { + "type": "string" + }, + "relationshipParent": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipChild": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipSibling": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ @@ -1741,6 +1852,21 @@ ], "description": "Encapsulates a JSON web key type that includes only the public properties that can be used in DID documents.\n\nThe private properties are intentionally omitted to discourage the use (and accidental disclosure) of private keys in DID documents." }, + "ConditionWeightedThreshold": { + "type": "object", + "properties": { + "condition": { + "$ref": "#/components/schemas/VerificationMethod" + }, + "weight": { + "type": "number" + } + }, + "required": [ + "condition", + "weight" + ] + }, "Service": { "type": "object", "properties": { @@ -5472,6 +5598,54 @@ }, "ethereumAddress": { "type": "string" + }, + "conditionOr": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionAnd": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "threshold": { + "type": "number" + }, + "conditionThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VerificationMethod" + } + }, + "conditionWeightedThreshold": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConditionWeightedThreshold" + } + }, + "conditionDelegated": { + "type": "string" + }, + "relationshipParent": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipChild": { + "type": "array", + "items": { + "type": "string" + } + }, + "relationshipSibling": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ @@ -5526,6 +5700,21 @@ ], "description": "Encapsulates a JSON web key type that includes only the public properties that can be used in DID documents.\n\nThe private properties are intentionally omitted to discourage the use (and accidental disclosure) of private keys in DID documents." }, + "ConditionWeightedThreshold": { + "type": "object", + "properties": { + "condition": { + "$ref": "#/components/schemas/VerificationMethod" + }, + "weight": { + "type": "number" + } + }, + "required": [ + "condition", + "weight" + ] + }, "Service": { "type": "object", "properties": { @@ -6204,5 +6393,348 @@ } } } + }, + "ICredentialRouter": { + "components": { + "schemas": { + "ICreateVerifiableCredentialArgs": { + "type": "object", + "properties": { + "credential": { + "$ref": "#/components/schemas/CredentialPayload", + "description": "The JSON payload of the Credential according to the\n {@link https://www.w3.org/TR/vc-data-model/#credentials | canonical model } \n\nThe signer of the Credential is chosen based on the `issuer.id` property of the `credential`\n\n`@context`, `type` and `issuanceDate` will be added automatically if omitted" + }, + "save": { + "type": "boolean", + "description": "If this parameter is true, the resulting VerifiablePresentation is sent to the\n {@link @veramo/core-types#IDataStore | storage plugin } to be saved.", + "deprecated": "Please call\n{@link @veramo/core-types#IDataStore.dataStoreSaveVerifiableCredential | dataStoreSaveVerifiableCredential()} to save\nthe credential after creating it." + }, + "proofFormat": { + "$ref": "#/components/schemas/ProofFormat", + "description": "The desired format for the VerifiablePresentation to be created." + }, + "removeOriginalFields": { + "type": "boolean", + "description": "Remove payload members during JWT-JSON transformation. Defaults to `true`. See https://www.w3.org/TR/vc-data-model/#jwt-encoding" + }, + "keyRef": { + "type": "string", + "description": "[Optional] The ID of the key that should sign this credential. If this is not specified, the first matching key will be used." + }, + "fetchRemoteContexts": { + "type": "boolean", + "description": "When dealing with JSON-LD you also MUST provide the proper contexts. Set this to `true` ONLY if you want the `@context` URLs to be fetched in case they are not preloaded. The context definitions SHOULD rather be provided at startup instead of being fetched.\n\nDefaults to `false`" + } + }, + "required": [ + "credential", + "proofFormat" + ], + "additionalProperties": { + "description": "Any other options that can be forwarded to the lower level libraries" + }, + "description": "Encapsulates the parameters required to create a\n {@link https://www.w3.org/TR/vc-data-model/#credentials | W3C Verifiable Credential }" + }, + "CredentialPayload": { + "type": "object", + "properties": { + "issuer": { + "$ref": "#/components/schemas/IssuerType" + }, + "credentialSubject": { + "$ref": "#/components/schemas/CredentialSubject" + }, + "type": { + "type": "array", + "items": { + "type": "string" + } + }, + "@context": { + "$ref": "#/components/schemas/ContextType" + }, + "issuanceDate": { + "$ref": "#/components/schemas/DateType" + }, + "expirationDate": { + "$ref": "#/components/schemas/DateType" + }, + "credentialStatus": { + "$ref": "#/components/schemas/CredentialStatusReference" + }, + "id": { + "type": "string" + } + }, + "required": [ + "issuer" + ], + "description": "Used as input when creating Verifiable Credentials" + }, + "IssuerType": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": [ + "id" + ] + }, + { + "type": "string" + } + ], + "description": "The issuer of a {@link VerifiableCredential } or the holder of a {@link VerifiablePresentation } .\n\nThe value of the issuer property MUST be either a URI or an object containing an id property. It is RECOMMENDED that the URI in the issuer or its id be one which, if de-referenced, results in a document containing machine-readable information about the issuer that can be used to verify the information expressed in the credential.\n\nSee {@link https://www.w3.org/TR/vc-data-model/#issuer | Issuer data model }" + }, + "CredentialSubject": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "description": "The value of the credentialSubject property is defined as a set of objects that contain one or more properties that are each related to a subject of the verifiable credential. Each object MAY contain an id.\n\nSee {@link https://www.w3.org/TR/vc-data-model/#credential-subject | Credential Subject }" + }, + "ContextType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object" + }, + { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object" + } + ] + } + } + ], + "description": "The data type for `@context` properties of credentials, presentations, etc." + }, + "DateType": { + "type": "string", + "description": "Represents an issuance or expiration date for Credentials / Presentations. This is used as input when creating them." + }, + "CredentialStatusReference": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "description": "Used for the discovery of information about the current status of a verifiable credential, such as whether it is suspended or revoked. The precise contents of the credential status information is determined by the specific `credentialStatus` type definition, and varies depending on factors such as whether it is simple to implement or if it is privacy-enhancing.\n\nSee {@link https://www.w3.org/TR/vc-data-model/#status | Credential Status }" + }, + "ProofFormat": { + "type": "string", + "enum": [ + "jwt", + "lds", + "EthereumEip712Signature2021", + "OpenAttestationMerkleProofSignature2018" + ], + "description": "The type of encoding to be used for the Verifiable Credential or Presentation to be generated.\n\nOnly `jwt` , `lds` and `OpenAttestationMerkleProofSignature2018` are supported at the moment." + }, + "VerifiableCredential": { + "type": "object", + "properties": { + "proof": { + "$ref": "#/components/schemas/ProofType" + }, + "issuer": { + "$ref": "#/components/schemas/IssuerType" + }, + "credentialSubject": { + "$ref": "#/components/schemas/CredentialSubject" + }, + "type": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "@context": { + "$ref": "#/components/schemas/ContextType" + }, + "issuanceDate": { + "type": "string" + }, + "expirationDate": { + "type": "string" + }, + "credentialStatus": { + "$ref": "#/components/schemas/CredentialStatusReference" + }, + "id": { + "type": "string" + } + }, + "required": [ + "@context", + "credentialSubject", + "issuanceDate", + "issuer", + "proof" + ], + "description": "Represents a signed Verifiable Credential payload (includes proof), using a JSON representation. See {@link https://www.w3.org/TR/vc-data-model/#credentials | VC data model }" + }, + "ProofType": { + "type": "object", + "properties": { + "type": { + "type": "string" + } + }, + "description": "A proof property of a {@link VerifiableCredential } or {@link VerifiablePresentation }" + }, + "IVerifyCredentialArgs": { + "type": "object", + "properties": { + "credential": { + "$ref": "#/components/schemas/W3CVerifiableCredential", + "description": "The Verifiable Credential object according to the\n {@link https://www.w3.org/TR/vc-data-model/#credentials | canonical model } or the JWT representation.\n\nThe signer of the Credential is verified based on the `issuer.id` property of the `credential` or the `iss` property of the JWT payload respectively" + }, + "fetchRemoteContexts": { + "type": "boolean", + "description": "When dealing with JSON-LD you also MUST provide the proper contexts. Set this to `true` ONLY if you want the `@context` URLs to be fetched in case they are not preloaded. The context definitions SHOULD rather be provided at startup instead of being fetched.\n\nDefaults to `false`" + }, + "policies": { + "$ref": "#/components/schemas/VerificationPolicies", + "description": "Overrides specific aspects of credential verification, where possible." + } + }, + "required": [ + "credential" + ], + "additionalProperties": { + "description": "Other options can be specified for verification. They will be forwarded to the lower level modules. that perform the checks" + }, + "description": "Encapsulates the parameters required to verify a\n {@link https://www.w3.org/TR/vc-data-model/#credentials | W3C Verifiable Credential }" + }, + "W3CVerifiableCredential": { + "anyOf": [ + { + "$ref": "#/components/schemas/VerifiableCredential" + }, + { + "$ref": "#/components/schemas/CompactJWT" + } + ], + "description": "Represents a signed Verifiable Credential (includes proof), in either JSON or compact JWT format. See {@link https://www.w3.org/TR/vc-data-model/#credentials | VC data model } \nSee {@link https://www.w3.org/TR/vc-data-model/#proof-formats | proof formats }" + }, + "CompactJWT": { + "type": "string", + "description": "Represents a Json Web Token in compact form. \"header.payload.signature\"" + }, + "VerificationPolicies": { + "type": "object", + "properties": { + "now": { + "type": "number", + "description": "policy to over the now (current time) during the verification check (UNIX time in seconds)" + }, + "issuanceDate": { + "type": "boolean", + "description": "policy to skip the issuanceDate (nbf) timestamp check when set to `false`" + }, + "expirationDate": { + "type": "boolean", + "description": "policy to skip the expirationDate (exp) timestamp check when set to `false`" + }, + "audience": { + "type": "boolean", + "description": "policy to skip the audience check when set to `false`" + }, + "credentialStatus": { + "type": "boolean", + "description": "policy to skip the revocation check (credentialStatus) when set to `false`" + } + }, + "additionalProperties": { + "description": "Other options can be specified for verification. They will be forwarded to the lower level modules that perform the checks" + }, + "description": "These optional settings can be used to override some default checks that are performed on Presentations during verification." + }, + "IVerifyResult": { + "type": "object", + "properties": { + "verified": { + "type": "boolean", + "description": "This value is used to transmit the result of verification." + }, + "error": { + "$ref": "#/components/schemas/IError", + "description": "Optional Error object for the but currently the machine readable errors are not expored from DID-JWT package to be imported here" + } + }, + "required": [ + "verified" + ], + "additionalProperties": { + "description": "Other options can be specified for verification. They will be forwarded to the lower level modules. that performt the checks" + }, + "description": "Encapsulates the response object to verifyPresentation method after verifying a\n {@link https://www.w3.org/TR/vc-data-model/#presentations | W3C Verifiable Presentation }" + }, + "IError": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "The details of the error being throw or forwarded" + }, + "errorCode": { + "type": "string", + "description": "The code for the error being throw" + } + }, + "description": "An error object, which can contain a code." + } + }, + "methods": { + "routeCreationVerifiableCredential": { + "description": "Creates a Verifiable Credential. The payload, signer and format are chosen based on the ", + "arguments": { + "$ref": "#/components/schemas/ICreateVerifiableCredentialArgs" + }, + "returnType": { + "$ref": "#/components/schemas/VerifiableCredential" + } + }, + "routeVerificationCredential": { + "description": "Verifies a Verifiable Credential JWT, LDS Format, EIP712 or OA.", + "arguments": { + "$ref": "#/components/schemas/IVerifyCredentialArgs" + }, + "returnType": { + "$ref": "#/components/schemas/IVerifyResult" + } + } + } + } } } \ No newline at end of file diff --git a/packages/core-types/src/types/ICredentialRouter.ts b/packages/core-types/src/types/ICredentialRouter.ts new file mode 100644 index 00000000..bb162622 --- /dev/null +++ b/packages/core-types/src/types/ICredentialRouter.ts @@ -0,0 +1,49 @@ +import { VerifiableCredential } from './vc-data-model.js'; +import { IPluginMethodMap } from './IAgent.js'; +import { + IssuerAgentContext, + ICreateVerifiableCredentialArgs, +} from './ICredentialIssuer.js'; +import { + IVerifyCredentialArgs, + VerifierAgentContext, +} from './ICredentialVerifier.js'; +import { IVerifyResult } from './IVerifyResult.js'; + +/** + * @public + */ +export interface ICredentialRouter extends IPluginMethodMap { + /** + * Creates a Verifiable Credential. + * The payload, signer and format are chosen based on the `args` parameter. + * + * @param args - Arguments necessary to create the Credential. + * @param context - This reserved param is automatically added and handled by the framework, *do not override* + * + * @returns - a promise that resolves to the {@link @veramo/core-types#VerifiableCredential} that was requested or rejects + * with an error if there was a problem with the input or while getting the key to sign + * + * @remarks Please see {@link https://www.w3.org/TR/vc-data-model/#credentials | Verifiable Credential data model} + */ + routeCreationVerifiableCredential( + args: ICreateVerifiableCredentialArgs, + context: IssuerAgentContext + ): Promise; + + /** + * Verifies a Verifiable Credential JWT, LDS Format, EIP712 or OA. + * + * @param args - Arguments necessary to verify a VerifiableCredential + * @param context - This reserved param is automatically added and handled by the framework, *do not override* + * + * @returns - a promise that resolves to an object containing a `verified` boolean property and an optional `error` + * for details + * + * @remarks Please see {@link https://www.w3.org/TR/vc-data-model/#credentials | Verifiable Credential data model} + */ + routeVerificationCredential( + args: IVerifyCredentialArgs, + context: VerifierAgentContext + ): Promise; +} diff --git a/packages/credential-oa/__tests__/action-handler.test.ts b/packages/credential-oa/__tests__/action-handler.test.ts index 08fef4d4..1dcab19a 100644 --- a/packages/credential-oa/__tests__/action-handler.test.ts +++ b/packages/credential-oa/__tests__/action-handler.test.ts @@ -5,19 +5,19 @@ import { IssuerAgentContext, } from '@vckit/core-types'; -import { CredentialIssuerOA } from '../src/action-handler'; +import { CredentialOA } from '../src/action-handler'; import { INVALID_RAW_OA_CREDENTIAL, RAW_OA_CREDENTIAL, } from './mocks/constants'; -describe('CredentialIssuerOA', () => { +describe('CredentialOA', () => { beforeEach(() => { jest.clearAllMocks(); }); describe('createVerifiableCredentialOA', () => { it('should create a verifiable credential with valid inputs', async () => { - const credentialPlugin = new CredentialIssuerOA(); + const credentialPlugin = new CredentialOA(); const args: ICreateVerifiableCredentialArgs = { credential: RAW_OA_CREDENTIAL, proofFormat: 'OpenAttestationMerkleProofSignature2018', @@ -54,7 +54,7 @@ describe('CredentialIssuerOA', () => { expect(result.proof.key).toEqual(`${did}#controller`); }); it('should throw an error if DID not managed by KMS', async () => { - const credentialPlugin = new CredentialIssuerOA(); + const credentialPlugin = new CredentialOA(); const args: ICreateVerifiableCredentialArgs = { credential: RAW_OA_CREDENTIAL, proofFormat: 'OpenAttestationMerkleProofSignature2018', @@ -80,7 +80,7 @@ describe('CredentialIssuerOA', () => { ).rejects.toThrow('No signing key for ' + did); }); it('should throw an error if payload is not in OpenAttestation format', async () => { - const credentialPlugin = new CredentialIssuerOA(); + const credentialPlugin = new CredentialOA(); const args: ICreateVerifiableCredentialArgs = { credential: INVALID_RAW_OA_CREDENTIAL, proofFormat: 'OpenAttestationMerkleProofSignature2018', @@ -95,7 +95,7 @@ describe('CredentialIssuerOA', () => { ); }); it('should throw an error if key type is not Secp256k1', async () => { - const credentialPlugin = new CredentialIssuerOA(); + const credentialPlugin = new CredentialOA(); const args: ICreateVerifiableCredentialArgs = { credential: RAW_OA_CREDENTIAL, proofFormat: 'OpenAttestationMerkleProofSignature2018', diff --git a/packages/credential-oa/src/action-handler.ts b/packages/credential-oa/src/action-handler.ts index beae848c..b282cc82 100644 --- a/packages/credential-oa/src/action-handler.ts +++ b/packages/credential-oa/src/action-handler.ts @@ -47,7 +47,7 @@ const OA_MANDATORY_CREDENTIAL_TYPES = 'VerifiableCredential'; * @public */ -export class CredentialIssuerOA implements IAgentPlugin { +export class CredentialOA implements IAgentPlugin { readonly methods: IOACredentialPlugin; readonly schema = { components: { @@ -73,7 +73,7 @@ export class CredentialIssuerOA implements IAgentPlugin { args: ICreateVerifiableCredentialArgs, context: IssuerAgentContext ): Promise { - const { credential: credentialInput } = args; + const { credential: credentialInput, save } = args; const credentialContext = processEntryToArray( credentialInput['@context'], @@ -87,7 +87,9 @@ export class CredentialIssuerOA implements IAgentPlugin { const credential = { ...credentialInput, - '@context': [...credentialContext, OA_MANDATORY_CREDENTIAL_CONTEXT], + '@context': [ + ...new Set([...credentialContext, OA_MANDATORY_CREDENTIAL_CONTEXT]), + ], type: credentialType, }; @@ -129,6 +131,12 @@ export class CredentialIssuerOA implements IAgentPlugin { }, }; + if (save) { + await context.agent.dataStoreSaveVerifiableCredential({ + verifiableCredential, + }); + } + return verifiableCredential; } @@ -164,14 +172,13 @@ export class CredentialIssuerOA implements IAgentPlugin { }); const fragments = await builtVerifier(credential); - const verified = isValid(fragments) + const verified = isValid(fragments); const verificationResult = { verified, - ...(verified && {verifiableCredential: credential}) - } + ...(verified && { verifiableCredential: credential }), + }; return verificationResult; - } catch (error) { return { verified: false, diff --git a/packages/credential-oa/src/index.ts b/packages/credential-oa/src/index.ts index 64e989e2..de48bbf2 100644 --- a/packages/credential-oa/src/index.ts +++ b/packages/credential-oa/src/index.ts @@ -1 +1 @@ -export { CredentialIssuerOA } from './action-handler.js'; +export { CredentialOA } from './action-handler.js'; diff --git a/packages/credential-router/LICENSE b/packages/credential-router/LICENSE new file mode 100644 index 00000000..fd815d7f --- /dev/null +++ b/packages/credential-router/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 2019 Consensys AG + + 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/credential-router/README.md b/packages/credential-router/README.md new file mode 100644 index 00000000..e9e950f0 --- /dev/null +++ b/packages/credential-router/README.md @@ -0,0 +1,24 @@ +# `credential-router` + +This plugin is used to route for issuing and verifying verifiable credential that will navigate to the correct plugin based on the proof format of the credential. + +## Usage + +- Add this declaration to `agent.yml` config file + +```yaml +# Agent +agent: + $require: '@veramo/core#Agent' + $args: + - schemaValidation: false + plugins: + - $require: '@vckit/credential-router#CredentialRouter' +``` + +- And export the functions of the plugin to be used in the application + +```yaml +- routeCreationVerifiableCredential +- routeVerificationCredential +``` diff --git a/packages/credential-router/api-extractor.json b/packages/credential-router/api-extractor.json new file mode 100644 index 00000000..409d7f16 --- /dev/null +++ b/packages/credential-router/api-extractor.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "apiReport": { + "enabled": true, + "reportFolder": "./api", + "reportTempFolder": "./api" + }, + + "docModel": { + "enabled": true, + "apiJsonFilePath": "./api/.api.json" + }, + + "dtsRollup": { + "enabled": false + }, + "mainEntryPointFilePath": "/build/index.d.ts" +} diff --git a/packages/credential-router/package.json b/packages/credential-router/package.json new file mode 100644 index 00000000..4e57f5a1 --- /dev/null +++ b/packages/credential-router/package.json @@ -0,0 +1,42 @@ +{ + "name": "@vckit/credential-router", + "version": "1.0.0-beta.5", + "description": "Credential router for VCKit to handle issue and verify with different proof types", + "author": "Nam Hoang ", + "homepage": "https://github.com/uncefact/project-vckit#readme", + "license": "Apache-2.0", + "main": "build/index.js", + "types": "build/index.d.ts", + "exports": { + ".": "./build/index.js", + "./build/plugin.schema.json": "./build/plugin.schema.json" + }, + "type": "module", + "moduleDirectories": [ + "node_modules", + "src" + ], + "files": [ + "build/**/*", + "src/**/*", + "README.md", + "LICENSE" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/uncefact/project-vckit.git" + }, + "scripts": { + "build": "tsc", + "watch": "tsc -b --watch", + "extract-api": "node ../cli/bin/vckit.js dev extract-api" + }, + "bugs": { + "url": "https://github.com/uncefact/project-vckit/issues" + }, + "dependencies": { + "@veramo/credential-w3c": "5.2.0", + "@vckit/core-types": "workspace:^", + "@vckit/credential-oa": "workspace:^" + } +} diff --git a/packages/credential-router/src/action-handler.ts b/packages/credential-router/src/action-handler.ts new file mode 100644 index 00000000..3fdebe58 --- /dev/null +++ b/packages/credential-router/src/action-handler.ts @@ -0,0 +1,126 @@ +import { + IAgentPlugin, + ICreateVerifiableCredentialArgs, + ICredentialRouter, + IVerifyCredentialArgs, + IVerifyResult, + IssuerAgentContext, + VerifiableCredential, + VerifierAgentContext, + W3CVerifiableCredential, + W3CVerifiablePresentation, +} from '@vckit/core-types'; +import schema from '@vckit/core-types/build/plugin.schema.json' assert { type: 'json' }; + +const enum DocumentFormat { + JWT, + JSONLD, + EIP712, + OA, +} + +/** + * @public + */ +export class CredentialRouter implements IAgentPlugin { + readonly methods: ICredentialRouter; + readonly schema = schema.ICredentialRouter; + + constructor() { + this.methods = { + routeCreationVerifiableCredential: + this.routeCreationVerifiableCredential.bind(this), + routeVerificationCredential: this.routeVerificationCredential.bind(this), + }; + } + + async routeCreationVerifiableCredential( + args: ICreateVerifiableCredentialArgs, + context: IssuerAgentContext + ): Promise { + const { proofFormat, credential } = args; + try { + let verifiableCredential: VerifiableCredential; + if (proofFormat === 'OpenAttestationMerkleProofSignature2018') { + if (typeof context.agent.createVerifiableCredentialOA === 'function') { + verifiableCredential = + await context.agent.createVerifiableCredentialOA({ + ...args, + credential, + }); + } else { + throw new Error( + 'invalid_setup: your agent does not seem to have CredentialOA plugin installed' + ); + } + } else { + if (typeof context.agent.createVerifiableCredential === 'function') { + verifiableCredential = await context.agent.createVerifiableCredential( + { + ...args, + credential, + } + ); + } else { + throw new Error( + 'invalid_setup: your agent does not seem to have CredentialW3c plugin installed' + ); + } + } + return verifiableCredential; + } catch (error) { + throw new Error(error); + } + } + + async routeVerificationCredential( + args: IVerifyCredentialArgs, + context: VerifierAgentContext + ): Promise { + const { credential } = args; + + const type: DocumentFormat = detectDocumentType(credential); + try { + if (type === DocumentFormat.OA) { + if (typeof context.agent.verifyCredentialOA === 'function') { + return await context.agent.verifyCredentialOA(args); + } else { + throw new Error( + 'invalid_setup: your agent does not seem to have CredentialOA plugin installed' + ); + } + } else { + if (typeof context.agent.verifyCredential === 'function') { + return await context.agent.verifyCredential(args); + } else { + throw new Error( + 'invalid_setup: your agent does not seem to have CredentialW3c plugin installed' + ); + } + } + } catch (error) { + throw new Error(error); + } + } +} + +function detectDocumentType( + document: W3CVerifiableCredential | W3CVerifiablePresentation +): DocumentFormat { + if ( + typeof document === 'string' || + (document)?.proof?.jwt + ) + return DocumentFormat.JWT; + if ( + (document)?.proof?.type === + 'EthereumEip712Signature2021' + ) + return DocumentFormat.EIP712; + if ( + (document)?.proof?.type === + 'OpenAttestationMerkleProofSignature2018' + ) + return DocumentFormat.OA; + return DocumentFormat.JSONLD; +} diff --git a/packages/credential-router/src/index.ts b/packages/credential-router/src/index.ts new file mode 100644 index 00000000..48c28356 --- /dev/null +++ b/packages/credential-router/src/index.ts @@ -0,0 +1 @@ +export { CredentialRouter } from './action-handler.js'; diff --git a/packages/credential-router/tsconfig.json b/packages/credential-router/tsconfig.json new file mode 100644 index 00000000..dde6c65b --- /dev/null +++ b/packages/credential-router/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.settings.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "build", + "declarationDir": "build" + }, + "references": [ + { "path": "../core-types" } + ] +} diff --git a/packages/demo-explorer/package.json b/packages/demo-explorer/package.json index 66ab7a6b..ee189c28 100644 --- a/packages/demo-explorer/package.json +++ b/packages/demo-explorer/package.json @@ -65,12 +65,14 @@ }, "dependencies": { "@govtechsg/oa-encryption": "^1.3.5", + "@jsonforms/core": "^3.1.0", "@jsonforms/material-renderers": "^3.1.0", "@jsonforms/react": "^3.1.0", "@vckit/example-documents": "workspace:^1.0.0-beta.4", + "@vckit/react-components": "workspace:^1.0.0-beta.5", + "@vckit/renderer": "workspace:^1.0.0-beta.5", "@veramo/remote-client": "5.2.1-next.5", - "@vckit/react-components": "workspace:^*", - "@vckit/renderer": "workspace:^*", + "ajv": "^8.12.0", "commander": "^10.0.1", "express": "^4.18.2", "express-favicon": "^2.0.4", diff --git a/packages/demo-explorer/src/components/CredentialInfo.tsx b/packages/demo-explorer/src/components/CredentialInfo.tsx index 3330cd5e..a7435907 100644 --- a/packages/demo-explorer/src/components/CredentialInfo.tsx +++ b/packages/demo-explorer/src/components/CredentialInfo.tsx @@ -3,6 +3,7 @@ import { Alert, Button, Descriptions, Spin } from 'antd' import { VerifiableCredential } from '@veramo/core' import { format } from 'date-fns' import { useVeramo } from '@veramo-community/veramo-react' +import { DocumentFormat, detectDocumentType } from '../utils/helpers' interface CredentialInfoProps { credential: VerifiableCredential @@ -24,6 +25,7 @@ const CredentialInfo: React.FC = ({ const [loading, setLoading] = useState(false) const [revoked, setRevoked] = useState(false) const [errorMessage, setErrorMessage] = useState() + const [proofFormat, setProofFormat] = useState(null) const fetchVCStatus = useCallback(async () => { setLoading(true) @@ -39,7 +41,14 @@ const CredentialInfo: React.FC = ({ value = typeof value === 'string' ? value : JSON.stringify(value) setData((d) => [...d, { key, value }]) } - fetchVCStatus() + const documentType = detectDocumentType(credentialData) + setProofFormat(documentType) + if ( + documentType === DocumentFormat.JWT || + documentType === DocumentFormat.JSONLD + ) { + fetchVCStatus() + } // eslint-disable-next-line react-hooks/exhaustive-deps }, [credentialData]) @@ -111,34 +120,39 @@ const CredentialInfo: React.FC = ({ {i.value} ))} - - {revoked ? 'Revoked' : 'Active'} - + {proofFormat === DocumentFormat.JWT || + proofFormat === DocumentFormat.JSONLD ? ( + + {revoked ? 'Revoked' : 'Active'} + + ) : null}
- - {revoked ? ( - - ) : ( - - )} + {proofFormat === DocumentFormat.JWT || + proofFormat === DocumentFormat.JSONLD ? ( + revoked ? ( + + ) : ( + + ) + ) : null} {errorMessage && ( <>
diff --git a/packages/demo-explorer/src/components/IssueCredentialFromSchema.tsx b/packages/demo-explorer/src/components/IssueCredentialFromSchema.tsx index b664a004..9118dc62 100644 --- a/packages/demo-explorer/src/components/IssueCredentialFromSchema.tsx +++ b/packages/demo-explorer/src/components/IssueCredentialFromSchema.tsx @@ -9,6 +9,8 @@ import { materialCells, materialRenderers } from '@jsonforms/material-renderers' import { VCJSONSchema } from '../types' import { convertToSchema } from '../utils/dataGenerator' import { dropFields } from '../utils/helpers' +import { Generate } from '@jsonforms/core' +import { ErrorObject } from 'ajv' const renderers = [ ...materialRenderers, @@ -33,6 +35,8 @@ const IssueCredentialFromSchema: React.FC = ({ const [formData, setFormData] = useState({}) const [errors, setErrors] = useState([]) const [schemaData, setSchemaData] = useState({}) + const [uischema, setUiSchema] = useState({}) + const [additionalErrors, setAdditionalErrors] = useState([]) const { data: identifiers, isLoading: identifiersLoading } = useQuery( ['identifiers', { agentId: agent?.context.id }], @@ -54,22 +58,42 @@ const IssueCredentialFromSchema: React.FC = ({ oneOf: [ { const: 'jwt', - title: 'jwt', + title: 'JWT', }, { const: 'lds', - title: 'lds', + title: 'JSON-LD Signature', }, // { // const: 'EthereumEip712Signature2021', // title: 'EthereumEip712Signature2021', // }, - // { - // const: 'OpenAttestationMerkleProofSignature2018', - // title: 'OpenAttestationMerkleProofSignature2018', - // }, + { + const: 'OpenAttestationMerkleProofSignature2018', + title: 'OpenAttestationMerkleProofSignature2018', + }, ], }, + identityProofType: { + type: 'string', + oneOf: [ + { + const: 'DID', + title: 'DID', + }, + { + const: 'DNS-DID', + title: 'DNS-DID', + }, + { + const: 'DNS-TXT', + title: 'DNS-TXT', + }, + ], + }, + identityProofIdentifier: { + type: 'string', + }, issuer: { type: 'string', oneOf: identitierOptions, @@ -88,6 +112,30 @@ const IssueCredentialFromSchema: React.FC = ({ } convertedSchema.required = required + const uiSchema = Generate.uiSchema(convertedSchema) as any + const proofTypeUiSchema = uiSchema.elements.find( + (e: any) => e.scope === '#/properties/identityProofType', + ) + proofTypeUiSchema.rule = { + effect: 'SHOW', + condition: { + scope: '#/properties/proofFormat', + schema: { const: 'OpenAttestationMerkleProofSignature2018' }, + }, + } + + const identityProofIdentifierUiSchema = uiSchema.elements.find( + (e: any) => e.scope === '#/properties/identityProofIdentifier', + ) + identityProofIdentifierUiSchema.rule = { + effect: 'SHOW', + condition: { + scope: '#/properties/identityProofType', + schema: { enum: ['DNS-DID', 'DNS-TXT'] }, + }, + } + + setUiSchema(uiSchema) setSchemaData(convertedSchema) setFormData({ credentialSubject: schema.credentialSubject, @@ -98,6 +146,59 @@ const IssueCredentialFromSchema: React.FC = ({ const onChange = ({ errors, data }: { errors: any[]; data: any }) => { setFormData(data) setErrors([...errors]) + + if (data.proofFormat !== 'OpenAttestationMerkleProofSignature2018') { + setFormData((d: any) => + dropFields(d, ['identityProofType', 'identityProofIdentifier']), + ) + } + + if (data.proofFormat === 'OpenAttestationMerkleProofSignature2018') { + if (data.identityProofType) { + const newErrors = errors.filter( + (e) => e.instancePath !== '/identityProofType', + ) + setAdditionalErrors(newErrors) + setErrors(newErrors) + } else { + const newError: ErrorObject = { + // AJV style path to the property in the schema + instancePath: '/identityProofType', + // message to display + message: 'is a required property', + schemaPath: '', + keyword: '', + params: {}, + } + setAdditionalErrors((errors) => [...errors, newError]) + setErrors([...errors, newError]) + } + + if ( + data.identityProofType === 'DNS-DID' || + data.identityProofType === 'DNS-TXT' + ) { + if (data.identityProofIdentifier) { + const newErrors = errors.filter( + (e) => e.instancePath !== '/identityProofIdentifier', + ) + setAdditionalErrors(newErrors) + setErrors(newErrors) + } else { + const newError: ErrorObject = { + // AJV style path to the property in the schema + instancePath: '/identityProofIdentifier', + // message to display + message: 'is a required property', + schemaPath: '', + keyword: '', + params: {}, + } + setAdditionalErrors((errors) => [...errors, newError]) + setErrors([...errors, newError]) + } + } + } } const signVc = async (fields: Field[]) => { @@ -105,27 +206,23 @@ const IssueCredentialFromSchema: React.FC = ({ console.log(schema['@context']) try { setSending(true) - await issueCredential( + + await issueCredential({ agent, - formData.issuer, - '', - fields, - formData.proofFormat, - // @ts-ignore - schema['@context'], - // @ts-ignore - schema.type, - '', // id - // @ts-ignore - dropFields(schema, [ - '@context', - 'type', - 'credentialSubject', - 'id', - 'issuer', - 'issuanceDate', - ]), - ) + issuer: formData.issuer, + credentialSubject: formData.credentialSubject, + proofFormat: formData.proofFormat, + customContext: schema['@context'], + type: schema.type, + identityProofType: formData.identityProofType, + identityProofIdentifier: formData.identityProofIdentifier, + openAttestationMetadata: schema.openAttestationMetadata, + version: schema.version, + issuerProfile: { + name: schema.issuer.name, + type: schema.issuer.type, + }, + }) setFormData({}) } catch (err) { setErrorMessage( @@ -140,11 +237,12 @@ const IssueCredentialFromSchema: React.FC = ({
diff --git a/packages/demo-explorer/src/layout/Layout.tsx b/packages/demo-explorer/src/layout/Layout.tsx index 8896435f..01b27c1d 100644 --- a/packages/demo-explorer/src/layout/Layout.tsx +++ b/packages/demo-explorer/src/layout/Layout.tsx @@ -27,8 +27,6 @@ import CreateResponse from '../components/CreateResponse' import Statistics from '../pages/Statistics' import DataGenerator from '../pages/DevTools/DataGenerator' import SelectSchemaAndIssue from '../pages/DevTools/SelectSchemaAndIssue' -import CreateProfileCredential from '../pages/DevTools/CreateProfileCredential' -import IssueCredential from '../pages/DevTools/IssueCredential' import CreatePresentation from '../pages/DevTools/CreatePresentation' import md5 from 'md5' import AgentDropdown from '../components/AgentDropdown' @@ -229,14 +227,6 @@ const Layout = () => { path="/developer/credential-from-schema" element={} /> - } - /> - } - /> } diff --git a/packages/demo-explorer/src/pages/CredentialVerifier.tsx b/packages/demo-explorer/src/pages/CredentialVerifier.tsx index 9f0be8d8..502b725b 100644 --- a/packages/demo-explorer/src/pages/CredentialVerifier.tsx +++ b/packages/demo-explorer/src/pages/CredentialVerifier.tsx @@ -39,7 +39,7 @@ const CredentialVerifier = () => { const vc = JSON.parse(stringifyVC) try { - const result = await agent?.verifyCredential({ + const result = await agent?.routeVerificationCredential({ credential: vc, fetchRemoteContexts: true, }) @@ -71,7 +71,7 @@ const CredentialVerifier = () => { setIsVerifying(true) setVerificationResult(undefined) try { - const result = await agent?.verifyCredential({ + const result = await agent?.routeVerificationCredential({ credential: JSON.parse(text), fetchRemoteContexts: true, }) diff --git a/packages/demo-explorer/src/pages/DevTools/CreateProfileCredential.tsx b/packages/demo-explorer/src/pages/DevTools/CreateProfileCredential.tsx deleted file mode 100644 index 7d506106..00000000 --- a/packages/demo-explorer/src/pages/DevTools/CreateProfileCredential.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import React, { useState } from 'react' -import { Button, Card, Input, Select } from 'antd' -import { useVeramo } from '@veramo-community/veramo-react' -import { useQuery } from 'react-query' -import { IIdentifier } from '@veramo/core' -import { issueCredential } from '../../utils/signing' -import { v4 } from 'uuid' -import { PageContainer } from '@ant-design/pro-components' -const { TextArea } = Input -const { Option } = Select - -const CreateProfileCredential: React.FC = () => { - const { agent } = useVeramo() - - const { data: identifiers, isLoading: identifiersLoading } = useQuery( - ['identifiers', { agentId: agent?.context.id }], - () => agent?.didManagerFind(), - ) - const [issuer, setIssuer] = useState('') - const [proofFormat, setProofFormat] = useState('') - const [name, setName] = useState('') - const [bio, setBio] = useState('') - const [recipient, setRecipient] = useState('') - const [inFlight, setInFlight] = useState(false) - - return ( - - - - setName(e.target.value)} /> -