diff --git a/guides/getting-started/set-up/cheqd/index.md b/guides/getting-started/set-up/cheqd/index.md index c0bc9135..10ed94c3 100644 --- a/guides/getting-started/set-up/cheqd/index.md +++ b/guides/getting-started/set-up/cheqd/index.md @@ -91,4 +91,4 @@ The cosmosPayerSeed can be a 32-bit seed value or a mnemonic, which can be manag - [Cheqd DID Module](../../../tutorials/cheqd/index.md) - [Register Schema and Credential Definition](../../../tutorials/registering-schema-and-credential-definition.md) -- [Issue a Credential](../../../tutorials/issue-a-credential.md) +- [Issue an AnonCreds Credential over DIDComm](../../../tutorials/issue-an-anoncreds-credential-over-didcomm.md) diff --git a/guides/getting-started/set-up/openid4vc.md b/guides/getting-started/set-up/openid4vc.md new file mode 100644 index 00000000..013a3d10 --- /dev/null +++ b/guides/getting-started/set-up/openid4vc.md @@ -0,0 +1,37 @@ +# OpenID for Verifiable Credentials + +The OpenID4VC module provides support for the [OpenID for Verifiable Credentials group of protocols](https://openid.net/sg/openid4vc/) defined under the OpenID Foundation. Currently this includes the [OpenID for Verifiable Credential Issuance](https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html), [Self-Issued OpenID Provider v2](https://openid.net/specs/openid-connect-self-issued-v2-1_0.html), and [OpenID for Verifiable Presentations](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html). + +For the current supported versions for any of the OpenID4VC protocols, please refer to the [OpenID4VC Feature](../../features/openid4vc.md) page. + +The OpenID4VC Module in Credo currently exposes three modules, one for each role in the triangle trust: `OpenId4VcIssuerModule`, `OpenId4VcHolderModule`, and `OpenId4VcVerifierModule`. The issuer and verifier modules are expected to run in a cloud environment, as they require several endpoints to be exposed to the public internet. The holder module can run in a cloud environment or on a mobile device. + +### Installing OpenID4VC Module + +When using Credo with OpenID4VC you need to install the `@credo-ts/openid4vc` module: + +```console +yarn add @credo-ts/openid4vc@^0.5.3 +``` + +### Adding OpenID4VC Modules to the Agent + +After installing the dependencies, we can register the the different modules on the agent. + +#### Issuer and Verifier + +If you want to issue or verify credentials using OpenID for Verifiable Credentials, you can add the `OpenId4VcIssuerModule` and the `OpenId4VcVerifierModule`. These modules can only run on the server, in Node.JS and don't work in a React Native environment. These modules can be added separately, it's not required to use both modules. The set up for the issuer and verifier module can be combined with the set up for the holder module below to support issuance, holding, and verification OpenID4VC flows within the same agent. + +In the example we haven't implemented the `credentialRequestToCredentialMapper` method for the issuer module yet, this is covered in the [OpenID4VC Guides](/guides/tutorials/openid4vc). + +```typescript showLineNumbers set-up-openid4vc-issuer-verifier.ts section-1 + +``` + +### Holder + +If you want to receive and present credentials using OpenID for Verifiable Credentials, you can add the `OpenId4VcHolderModule`. This module can run in both Node.JS and React Native. + +```typescript showLineNumbers set-up-openid4vc-holder.ts section-1 + +``` diff --git a/guides/tutorials/issue-a-credential.md b/guides/tutorials/issue-an-anoncreds-credential-over-didcomm.md similarity index 82% rename from guides/tutorials/issue-a-credential.md rename to guides/tutorials/issue-an-anoncreds-credential-over-didcomm.md index d99f6e1c..f1bd7f98 100644 --- a/guides/tutorials/issue-a-credential.md +++ b/guides/tutorials/issue-an-anoncreds-credential-over-didcomm.md @@ -1,6 +1,6 @@ -# Issue a credential +# Issue an AnonCreds credential over DIDComm -In this tutorial we will issue a credential from the _Issuer_ to a _Holder_. We will start with setting up both their agents with the minimal configuration required to follow this tutorial. It is assumed that there is a connection between the _Issuer_ and the _Holder_ and the _Issuer_ also has a registered schema and credential definition. After initializing the _Issuer_ will send a credential to the _holder_, and will then accept this credential and automatically store it in their wallet. +In this tutorial we will issue an AnonCreds credential from the _Issuer_ to a _Holder_ over DIDComm. We will start with setting up both their agents with the minimal configuration required to follow this tutorial. It is assumed that there is a connection between the _Issuer_ and the _Holder_ and the _Issuer_ also has a registered schema and credential definition. After initializing the _Issuer_ will send a credential to the _holder_, and will then accept this credential and automatically store it in their wallet. _Using [AnonCreds](https://anoncreds-wg.github.io/anoncreds-spec/) and the [Issue Credential V2 Protocol](https://github.com/hyperledger/aries-rfcs/blob/main/features/0453-issue-credential-v2/README.md) or the [Issue Credential V1 Protocol](https://github.com/hyperledger/aries-rfcs/blob/main/features/0036-issue-credential/README.md)._ @@ -8,7 +8,7 @@ _Using [AnonCreds](https://anoncreds-wg.github.io/anoncreds-spec/) and the [Issu This section assumes that -1. You have [set-up your develoment environment](../getting-started). +1. You have [set-up your development environment](../getting-started). 1. You have basic knowledge of the required fields in the [Agent Config](./agent-config) 1. You have completed the [Create a Connection tutorial](./create-a-connection) 1. You have a registered schema and credential definition. This can be done by following the [Registering on a AnonCreds Registry](./registering-schema-and-credential-definition) @@ -53,7 +53,7 @@ ngrok http :::issuer -```typescript showLineNumbers issue-a-credential.ts section-1 +```typescript showLineNumbers issue-anoncreds-credential-didcomm.ts section-1 ``` @@ -70,7 +70,7 @@ For the _Holder_ we need to setup a basic agent with a wallet, mediator, outboun :::holder -```typescript showLineNumbers issue-a-credential.ts section-2 +```typescript showLineNumbers issue-anoncreds-credential-didcomm.ts section-2 ``` @@ -82,7 +82,7 @@ When we want to accept a credential, we have to listen to incoming credentials a :::holder -```typescript showLineNumbers issue-a-credential.ts section-3 +```typescript showLineNumbers issue-anoncreds-credential-didcomm.ts section-3 ``` @@ -100,7 +100,7 @@ Now that everything is setup on both sides, the _Issuer_ can now offer a credent :::issuer -```typescript showLineNumbers issue-a-credential.ts section-4 +```typescript showLineNumbers issue-anoncreds-credential-didcomm.ts section-4 ``` @@ -110,7 +110,7 @@ Now that everything is setup on both sides, the _Issuer_ can now offer a credent :::issuer -```typescript showLineNumbers issue-a-credential.ts section-5 +```typescript showLineNumbers issue-anoncreds-credential-didcomm.ts section-5 ``` diff --git a/guides/tutorials/openid4vc/index.md b/guides/tutorials/openid4vc/index.md new file mode 100644 index 00000000..33008784 --- /dev/null +++ b/guides/tutorials/openid4vc/index.md @@ -0,0 +1,7 @@ +import DocCardList from '@theme/DocCardList'; + +# OpenID for Verifiable Credentials Tutorials + +This section covers all tutorials related to the OpenID for Verifiable Credentials module in Credo. Before you start, make sure you have configured the required OpenID4VC modules on your agent according to the [OpenID4VC Setup Guide](/guides/getting-started/set-up/openid4vc.md) + + diff --git a/guides/tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module.md b/guides/tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module.md new file mode 100644 index 00000000..87dacc44 --- /dev/null +++ b/guides/tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module.md @@ -0,0 +1,39 @@ +# Issuing Credentials using the OpenID4VC Issuer Module + +This tutorial will guide you through the process of issuing credentials using the OpenID4VC Issuer Module. Before starting this tutorial, make sure you have completed the [OpenID4VC Issuer Module Setup](/guides/getting-started/set-up/openid4vc.md). + +This guides only covers the issuance of credentials using the OpenID4VC Issuer Module. Follow the [Receiving and Proving Credentials using the OpenID4VC Holder Module](/guides/tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module.md) guide to learn how to receive and prove credentials using the OpenID4VC Holder Module. + +## Creating the issuer + +Once you have set-up your agent (under `issuer` variable), we first need to configure your issuer and the credentials you want to issue. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-2 + +``` + +If you want to update the display metadata or the credentials supported by the issuer, you can use the `issuer.modules.openId4VcIssuer.updateIssuer` method. + +## Creating a credential offer + +Once you have configured the issuer, you can create a credential offer. The credential offer method will generate a credential offer URI that you can share with a holder. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-3 + +``` + +We have also added an event listener that listens for state changed events, this allows us to know when the issuance session is done. + +## Implementing the credential mapper + +The OpenID4VC Issuer Module setup didn't cover the implementation of the `credentialRequestToCredentialMapper` yet. When you create a credential offer with the OpenID4VC Issuer Module in Credo, you don't have to provide the credential data directly. + +Instead, you provide a `credentialRequestToCredentialMapper` function in the agent configuration, that will be called when the holder requests the credential. + +This allows you to dynamically generate the credential data based on the holder's request, and means you also don't have to store any credential data in the agent. + +Below is an example `credentialRequestToCredentialMapper` function that generates a credential based on the holder's request. Make sure to register this function in the agent configuration `modules.openId4VcIssuer.endpoints.credential.credentialsRequestToCredentialMapper`. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-4 + +``` diff --git a/guides/tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module.md b/guides/tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module.md new file mode 100644 index 00000000..264c251c --- /dev/null +++ b/guides/tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module.md @@ -0,0 +1,25 @@ +# Receiving and Proving Credentials using the OpenID4VC Holder Module + +This tutorial will guide you through the process of receiving and proving credentials using the OpenID4VC Holder Module. Before starting this tutorial, make sure you have completed the [OpenID4VC Holder Module Setup](/guides/getting-started/set-up/openid4vc.md). + +This guides only covers the receiving and proving of credentials using the OpenID4VC Holder Module. Follow the [Issuing Credentials using the OpenID4VC Issuer Module](/guides/tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module.md) and [Verifying Credentials using the OpenID4VC Verifier Module](/guides/tutorials/openid4vc/verifying-credentials-using-openid4vc-verifier-module.md) guides to learn how to issue and verify credentials using the OpenID4VC Issuer and Verifier Modules. + +## Resolving and accepting a credential offer + +Once you have set-up your agent (under `holder` variable), and have a credential offer (either created using the issuer module, or an external OpenID4VC issuer), we can resolve and accept the credential offer. + +The `credentialBindingResolver` is a method you need to provide that configures how the credential should be bound to the wallet. The implemented binding resolver in this tutorial first checks if the issuer supports `did:key` and will use that. Otherwise it will check if jwk is supported. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-6 + +``` + +Finally the credentials are stored using the SD JWT VC and W3C modules. In a wallet application you could choose to first show the credential to the user before storing it in the wallet. + +## Resolving and accepting an authorization request (presentation request) + +Once you have a credential in your wallet, you can start presenting it based on a receive authorization request including an OpenID4VP presentation request (either created using the verifier module, or an external OpenID4VC verifier). First we resolve the authorization request, and then we accept it and present the credential in our wallet. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-9 + +``` diff --git a/guides/tutorials/openid4vc/verifying-credentials-using-openid4vc-verifier-module.md b/guides/tutorials/openid4vc/verifying-credentials-using-openid4vc-verifier-module.md new file mode 100644 index 00000000..0958b2e4 --- /dev/null +++ b/guides/tutorials/openid4vc/verifying-credentials-using-openid4vc-verifier-module.md @@ -0,0 +1,23 @@ +# Verifying Credentials using the OpenID4VC Verifier Module + +This tutorial will guide you through the process of verifying credentials using the OpenID4VC Verifier Module. Before starting this tutorial, make sure you have completed the [OpenID4VC Verifier Module Setup](/guides/getting-started/set-up/openid4vc.md). + +This guides only covers the verification of credentials using the OpenID4VC Verifier Module. Follow the [Issuing Credentials using the OpenID4VC Issuer Module](/guides/tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module.md) and [Receiving and Proving Credentials using the OpenID4VC Holder Module](/guides/tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module.md) guide to learn how to issuer, receive and prove credentials using the OpenID4VC Issuer and Holder Modules. + +## Creating the verifier + +Once you have set-up your agent (under `verifier` variable), we first need to configure your verifier. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-7 + +``` + +## Creating an authorization request + +Once you have configured the verifier, you can create an authorization request including an OpenID4VP presentation request based on [DIF Presentation Exchange V2](https://identity.foundation/presentation-exchange/spec/v2.0.0/). The authorization request method will generate an authorization request URI that you can share with a holder. + +```typescript showLineNumbers sd-jwt-vc-openid4vc.ts section-8 + +``` + +We have also added an event listener that listens for state changed events, this allows us to know when the verification session is done. diff --git a/guides/updating/versions/0.2-to-0.3.md b/guides/updating/versions/0.2-to-0.3.md index f1a47066..6d24d1c1 100644 --- a/guides/updating/versions/0.2-to-0.3.md +++ b/guides/updating/versions/0.2-to-0.3.md @@ -190,7 +190,7 @@ This procedure can be done in module's `register(dependencyManager, featureRegis ### Ledger Module -Apart from the aforementioned indyLedgers configuration, you should also [note a slight change](../../tutorials/issue-a-credential.md#side-notes) in behaviour when attempting to register credential definitions that already exists on the ledger but not in the wallet. +Apart from the aforementioned indyLedgers configuration, you should also [note a slight change](../../tutorials/issue-an-anoncreds-credential-over-didcomm.md#side-notes) in behaviour when attempting to register credential definitions that already exists on the ledger but not in the wallet. ### Proofs Module diff --git a/guides/updating/versions/0.4-to-0.5.md b/guides/updating/versions/0.4-to-0.5.md index 3806c2a6..6a769848 100644 --- a/guides/updating/versions/0.4-to-0.5.md +++ b/guides/updating/versions/0.4-to-0.5.md @@ -310,7 +310,7 @@ await agent.modules.openId4VcHolder.acceptCredentialOfferUsingPreAuthorizedCode( // NOTE: example implementation. Adjust based on your needs // Return the binding to the credential that should be used. Either did or jwk is supported - if (supportsAllDidMethods || supportedDidMethods?.include('did:key')) { + if (supportsAllDidMethods || supportedDidMethods?.includes('did:key')) { const didResult = await agent.dids.create({ method: 'key', options: { diff --git a/package.json b/package.json index c9a0170a..d033259d 100644 --- a/package.json +++ b/package.json @@ -36,10 +36,10 @@ "devDependencies": { "@docusaurus/module-type-aliases": "^2.3.1", "@tsconfig/docusaurus": "^1.0.5", - "prettier": "^2.7.1", - "typescript": "^4.6.4", "@types/node": "18", - "ts-node": "^10.8.1" + "prettier": "^2.7.1", + "ts-node": "^10.8.1", + "typescript": "^4.6.4" }, "browserslist": { "production": [ diff --git a/sidebars.js b/sidebars.js index cd20c172..3e360777 100644 --- a/sidebars.js +++ b/sidebars.js @@ -35,6 +35,7 @@ const sidebars = { 'getting-started/set-up/anoncreds', 'getting-started/set-up/indy-vdr', 'getting-started/set-up/cheqd/index', + 'getting-started/set-up/openid4vc', ], }, ], @@ -65,8 +66,18 @@ const sidebars = { 'tutorials/create-a-connection', 'tutorials/cheqd/index', 'tutorials/registering-schema-and-credential-definition', - 'tutorials/issue-a-credential', + 'tutorials/issue-an-anoncreds-credential-over-didcomm', 'tutorials/mediation', + { + type: 'category', + label: 'OpenID for Verifiable Credentials', + link: { type: 'doc', id: 'tutorials/openid4vc/index' }, + items: [ + 'tutorials/openid4vc/issuing-credentials-using-openid4vc-issuer-module', + 'tutorials/openid4vc/receiving-and-proving-credentials-using-openid4vc-holder-module', + 'tutorials/openid4vc/verifying-credentials-using-openid4vc-verifier-module', + ], + }, ], }, { @@ -79,6 +90,7 @@ const sidebars = { 'updating/versions/0.1-to-0.2', 'updating/versions/0.2-to-0.3', 'updating/versions/0.3-to-0.4', + 'updating/versions/0.4-to-0.5', ], }, 'ecosystem/index', diff --git a/snippets/current/package.json b/snippets/current/package.json index 3bb9acc3..23cd3623 100644 --- a/snippets/current/package.json +++ b/snippets/current/package.json @@ -8,7 +8,8 @@ "dev:mediator-setup": "ts-node --esm src/mediator-setup.ts", "dev:mediation-recipient": "ts-node --esm src/mediation-recipient.ts", "dev:connection": "ts-node --esm src/create-a-connection.ts", - "dev:credential": "ts-node --esm src/issue-a-credential.ts", + "dev:issue-anoncreds-credential-didcomm": "ts-node --esm src/issue-anoncreds-credential-didcomm.ts", + "dev:openid4vc": "ts-node --esm src/sd-jwt-vc-openid4vc.ts", "dev:register-with-indy": "ts-node --esm src/register-schema-and-cred-def.ts", "dev:set-up": "ts-node --esm src/set-up.ts" }, diff --git a/snippets/current/src/issue-a-credential.ts b/snippets/current/src/issue-anoncreds-credential-didcomm.ts similarity index 99% rename from snippets/current/src/issue-a-credential.ts rename to snippets/current/src/issue-anoncreds-credential-didcomm.ts index b3d9ca4d..40522465 100644 --- a/snippets/current/src/issue-a-credential.ts +++ b/snippets/current/src/issue-anoncreds-credential-didcomm.ts @@ -143,6 +143,7 @@ holder.events.on(CredentialEventTypes.CredentialSta console.log('received a credential') // custom logic here await holder.credentials.acceptOffer({ credentialRecordId: payload.credentialRecord.id }) + break case CredentialState.Done: console.log(`Credential for credential id ${payload.credentialRecord.id} is accepted`) // For demo purposes we exit the program here. diff --git a/snippets/current/src/sd-jwt-vc-openid4vc.ts b/snippets/current/src/sd-jwt-vc-openid4vc.ts new file mode 100644 index 00000000..5f320e9d --- /dev/null +++ b/snippets/current/src/sd-jwt-vc-openid4vc.ts @@ -0,0 +1,435 @@ +import type { InitConfig, SdJwtVcRecord, W3cCredentialRecord } from '@credo-ts/core' +import { AskarModule } from '@credo-ts/askar' + +const issuerConfig: InitConfig = { + label: 'openid4vc-issuer', + walletConfig: { + id: 'openid4vc-issuer', + key: 'testkey0000000000000000000000000', + }, +} + +const holderConfig: InitConfig = { + label: 'openid4vc-holder', + walletConfig: { + id: 'openid4vc-holder', + key: 'testkey0000000000000000000000000', + }, +} + +// start-section-4 +import { + OpenId4VcIssuanceSessionStateChangedEvent, + OpenId4VcIssuerEvents, + OpenId4VcVerificationSessionState, + OpenId4VcVerificationSessionStateChangedEvent, + OpenId4VcVerifierEvents, + OpenId4VciCredentialFormatProfile, + OpenId4VciCredentialRequestToCredentialMapper, +} from '@credo-ts/openid4vc' + +const credentialRequestToCredentialMapper: OpenId4VciCredentialRequestToCredentialMapper = async ({ + // agent context for the current wallet / tenant + agentContext, + // the credential offer related to the credential request + credentialOffer, + // the received credential request + credentialRequest, + // the list of credentialsSupported entries + credentialsSupported, + // the cryptographic binding provided by the holder in the credential request proof + holderBinding, + // the issuance session associated with the credential request and offer + issuanceSession, +}) => { + const firstSupported = credentialsSupported[0] + + // We only support vc+sd-jwt in this example, but you can add more formats + if (firstSupported.format !== OpenId4VciCredentialFormatProfile.SdJwtVc) { + throw new Error('Only vc+sd-jwt is supported') + } + + // We only support AcmeCorpEmployee in this example, but you can support any type + if (firstSupported.vct !== 'AcmeCorpEmployee') { + throw new Error('Only AcmeCorpEmployee is supported') + } + + // find the first did:key did in our wallet. You can modify this based on your needs + const didsApi = agentContext.dependencyManager.resolve(DidsApi) + const [didKeyDidRecord] = await didsApi.getCreatedDids({ + method: 'key', + }) + + const didKey = DidKey.fromDid(didKeyDidRecord.did) + const didUrl = `${didKey.did}#${didKey.key.fingerprint}` + + return { + credentialSupportedId: firstSupported.id, + format: 'vc+sd-jwt', + // We can provide the holderBinding as is, if we don't want to make changes + holder: holderBinding, + payload: { + vct: firstSupported.vct, + firstName: 'John', + lastName: 'Doe', + }, + disclosureFrame: { + _sd: ['lastName'], + }, + issuer: { + method: 'did', + didUrl, + }, + } +} + +// end-section-4 + +// start-section-1 +import { Agent, DidsApi, DifPresentationExchangeService, KeyType } from '@credo-ts/core' +import { agentDependencies } from '@credo-ts/node' +import { ariesAskar } from '@hyperledger/aries-askar-nodejs' + +import express, { Router } from 'express' +import { OpenId4VcIssuerModule, OpenId4VcVerifierModule } from '@credo-ts/openid4vc' + +// Create two express routers, all endpoints for the +// issuer and verifier will be added to these routers +const verifierRouter = Router() +const issuerRouter = Router() + +// Register the routers on the express server. The path should match +// with the baseUrl you configure in the modules below. +const app = express() +app.use('/oid4vci', issuerRouter) +app.use('/siop', verifierRouter) + +const issuer = new Agent({ + config: issuerConfig, + dependencies: agentDependencies, + modules: { + askar: new AskarModule({ + ariesAskar, + }), + openId4VcIssuer: new OpenId4VcIssuerModule({ + baseUrl: 'http://127.0.0.1:3000/oid4vci', + + // If no router is passed, one will be created. + // you still have to register the router on your express server + // but you can access it on agent.modules.openId4VcIssuer.config.router + // It works the same for verifier: agent.modules.openId4VcVerifier.config.router + router: issuerRouter, + + // Each of the endpoints can have configuration associated with it, such as the + // path (under the baseUrl) to use for the endpoints. + endpoints: { + // The credentialRequestToCredentialMapper is the only required endpoint + // configuration that must be provided. This method is called whenever a + // credential request has been received for an offer we created. The callback should + // return the issued credential to return in the credential response to the holder. + credential: { + credentialRequestToCredentialMapper, + }, + }, + }), + + // the base URL of the verifier, the router + openId4VcVerifier: new OpenId4VcVerifierModule({ + baseUrl: 'http://127.0.0.1:3000/siop', + + router: verifierRouter, + }), + }, +}) + +// listen on port 3000 for the openid4vc app +app.listen(3000) +// end-section-1 + +await issuer + .initialize() + .then(() => { + console.log('Issuer agent initialized!') + }) + .catch((e) => { + console.error(`Something went wrong while setting up the issuer agent! Message: ${e}`) + }) + +// we use the same agent for the verifier, but the tutorial uses verifier.xxx +const verifier = issuer + +// start-section-2 +import { JwaSignatureAlgorithm } from '@credo-ts/core' + +// Create an issuer with one supported credential: AcmeCorpEmployee +const openid4vcIssuer = await issuer.modules.openId4VcIssuer.createIssuer({ + display: [ + { + name: 'ACME Corp.', + description: 'ACME Corp. is a company that provides the best services.', + text_color: '#000000', + background_color: '#FFFFFF', + logo: { + url: 'https://acme.com/logo.png', + alt_text: 'ACME Corp. logo', + }, + }, + ], + credentialsSupported: [ + { + format: 'vc+sd-jwt', + vct: 'AcmeCorpEmployee', + id: 'AcmeCorpEmployee', + cryptographic_binding_methods_supported: ['did:key'], + cryptographic_suites_supported: [JwaSignatureAlgorithm.ES256], + }, + ], +}) + +// Create a did:key that we will use for issuance +const issuerDidResult = await issuer.dids.create({ + method: 'key', + options: { + keyType: KeyType.Ed25519, + }, +}) + +if (issuerDidResult.didState.state !== 'finished') { + throw new Error('DID creation failed.') +} +// end-section-2 + +// start-section-3 +const { credentialOffer, issuanceSession } = await issuer.modules.openId4VcIssuer.createCredentialOffer({ + issuerId: openid4vcIssuer.issuerId, + // values must match the `id` of the credential supported by the issuer + offeredCredentials: ['AcmeCorpEmployee'], + + // Only pre-authorized code flow is supported + preAuthorizedCodeFlowConfig: { + userPinRequired: false, + }, + + // You can store any metadata about the issuance here + issuanceMetadata: { + someKey: 'someValue', + }, +}) + +// Listen and react to changes in the issuance session +issuer.events.on( + OpenId4VcIssuerEvents.IssuanceSessionStateChanged, + (event) => { + if (event.payload.issuanceSession.id === issuanceSession.id) { + console.log('Issuance session state changed to ', event.payload.issuanceSession.state) + } + } +) +// end-section-3 + +// start-section-5 +import { OpenId4VcHolderModule } from '@credo-ts/openid4vc' + +const holder = new Agent({ + config: holderConfig, + dependencies: agentDependencies, + modules: { + askar: new AskarModule({ + ariesAskar, + }), + + // no configuration required for holder module + openId4VcHolderModule: new OpenId4VcHolderModule(), + }, +}) +// end-section-5 + +await holder + .initialize() + .then(() => { + console.log('Holder agent initialized!') + }) + .catch((e) => { + console.error(`Something went wrong while setting up the holder agent! Message: ${e}`) + }) + +// start-section-6 +import { KeyDidCreateOptions, getJwkFromKey, DidKey } from '@credo-ts/core' + +// resolved credential offer contains the offer, metadata, etc.. +const resolvedCredentialOffer = await holder.modules.openId4VcHolderModule.resolveCredentialOffer(credentialOffer) +console.log('Resolved credential offer', JSON.stringify(resolvedCredentialOffer.credentialOfferPayload, null, 2)) + +// issuer only supports pre-authorized flow for now +const credentials = await holder.modules.openId4VcHolderModule.acceptCredentialOfferUsingPreAuthorizedCode( + resolvedCredentialOffer, + { + credentialBindingResolver: async ({ + supportedDidMethods, + keyType, + supportsAllDidMethods, + // supportsJwk now also passed + supportsJwk, + credentialFormat, + }) => { + // NOTE: example implementation. Adjust based on your needs + // Return the binding to the credential that should be used. Either did or jwk is supported + + if (supportsAllDidMethods || supportedDidMethods?.includes('did:key')) { + const didResult = await holder.dids.create({ + method: 'key', + options: { + keyType, + }, + }) + + if (didResult.didState.state !== 'finished') { + throw new Error('DID creation failed.') + } + + const didKey = DidKey.fromDid(didResult.didState.did) + + return { + method: 'did', + didUrl: `${didKey.did}#${didKey.key.fingerprint}`, + } + } + + // we also support plain jwk for sd-jwt only + if (supportsJwk && credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtVc) { + const key = await holder.wallet.createKey({ + keyType, + }) + + // you now need to return an object instead of VerificationMethod instance + // and method 'did' or 'jwk' + return { + method: 'jwk', + jwk: getJwkFromKey(key), + } + } + + throw new Error('Unable to create a key binding') + }, + } +) + +console.log('Received credentials', JSON.stringify(credentials, null, 2)) + +// Store the received credentials +const records: Array = [] +for (const credential of credentials) { + if ('compact' in credential) { + const record = await holder.sdJwtVc.store(credential.compact) + records.push(record) + } else { + const record = await holder.w3cCredentials.storeCredential({ + credential, + }) + records.push(record) + } +} +// end-section-6 + +// start-section-7 +// Create a verifier +const openId4VcVerifier = await verifier.modules.openId4VcVerifier.createVerifier({}) + +// Create a did:key that we will use for signing OpenID4VP authorization requests +const verifierDidResult = await issuer.dids.create({ + method: 'key', + options: { + keyType: KeyType.Ed25519, + }, +}) + +if (verifierDidResult.didState.state !== 'finished') { + throw new Error('DID creation failed.') +} + +const verifierDidKey = DidKey.fromDid(verifierDidResult.didState.did) +// end-section-7 + +// start-section-8 +const { authorizationRequest, verificationSession } = + await verifier.modules.openId4VcVerifier.createAuthorizationRequest({ + verifierId: openId4VcVerifier.verifierId, + requestSigner: { + didUrl: `${verifierDidKey.did}#${verifierDidKey.key.fingerprint}`, + method: 'did', + }, + // Add DIF presentation exchange data + presentationExchange: { + definition: { + id: '9ed05140-b33b-445e-a0f0-9a23aa501868', + name: 'Employee Verification', + purpose: 'We need to verify your employee status to grant access to the employee portal', + input_descriptors: [ + { + id: '9c98fb43-6fd5-49b1-8dcc-69bd2a378f23', + constraints: { + // Require limit disclosure + limit_disclosure: 'required', + fields: [ + { + filter: { + type: 'string', + const: 'AcmeCorpEmployee', + }, + path: ['$.vct'], + }, + ], + }, + }, + ], + }, + }, + }) + +// Listen and react to changes in the verification session +verifier.events.on( + OpenId4VcVerifierEvents.VerificationSessionStateChanged, + async (event) => { + if (event.payload.verificationSession.id === verificationSession.id) { + console.log('Verification session state changed to ', event.payload.verificationSession.state) + } + + if (event.payload.verificationSession.state === OpenId4VcVerificationSessionState.ResponseVerified) { + const verifiedAuthorizationResponse = await verifier.modules.openId4VcVerifier.getVerifiedAuthorizationResponse( + verificationSession.id + ) + console.log('Successfully verified presentation.', JSON.stringify(verifiedAuthorizationResponse, null, 2)) + + console.log('Exiting...') + process.exit() + } + } +) +// end-section-8 + +// start-section-9 + +// resolved credential offer contains the offer, metadata, etc.. +const resolvedAuthorizationRequest = await holder.modules.openId4VcHolderModule.resolveSiopAuthorizationRequest( + authorizationRequest +) +console.log( + 'Resolved credentials for request', + JSON.stringify(resolvedAuthorizationRequest.presentationExchange.credentialsForRequest, null, 2) +) + +const presentationExchangeService = holder.dependencyManager.resolve(DifPresentationExchangeService) +// Automatically select credentials. In a wallet you could manually choose which credentials to return based on the "resolvedAuthorizationRequest.presentationExchange.credentialsForRequest" value +const selectedCredentials = presentationExchangeService.selectCredentialsForRequest( + resolvedAuthorizationRequest.presentationExchange.credentialsForRequest +) + +// issuer only supports pre-authorized flow for now +const authorizationResponse = await holder.modules.openId4VcHolderModule.acceptSiopAuthorizationRequest({ + authorizationRequest: resolvedAuthorizationRequest.authorizationRequest, + presentationExchange: { + credentials: selectedCredentials, + }, +}) +console.log('Submitted authorization response', JSON.stringify(authorizationResponse.submittedResponse, null, 2)) +// end-section-9 diff --git a/snippets/current/src/set-up-openid4vc-holder.ts b/snippets/current/src/set-up-openid4vc-holder.ts new file mode 100644 index 00000000..ccd5d21d --- /dev/null +++ b/snippets/current/src/set-up-openid4vc-holder.ts @@ -0,0 +1,35 @@ +import type { InitConfig } from '@credo-ts/core' + +const config: InitConfig = { + label: 'docs-agent-nodejs', + walletConfig: { + id: 'wallet-id', + key: 'testkey0000000000000000000000000', + }, +} + +// start-section-1 +import { Agent } from '@credo-ts/core' +// or import from '@credo-ts/react-native' for React Native +import { agentDependencies } from '@credo-ts/node' + +import { OpenId4VcHolderModule } from '@credo-ts/openid4vc' + +const agent = new Agent({ + config, + dependencies: agentDependencies, + modules: { + // no configuration required for holder module + openId4VcHolderModule: new OpenId4VcHolderModule(), + }, +}) +// end-section-1 + +agent + .initialize() + .then(() => { + console.log('Agent initialized!') + }) + .catch((e) => { + console.error(`Something went wrong while setting up the agent! Message: ${e}`) + }) diff --git a/snippets/current/src/set-up-openid4vc-issuer-verifier.ts b/snippets/current/src/set-up-openid4vc-issuer-verifier.ts new file mode 100644 index 00000000..93125970 --- /dev/null +++ b/snippets/current/src/set-up-openid4vc-issuer-verifier.ts @@ -0,0 +1,79 @@ +import type { InitConfig } from '@credo-ts/core' + +const config: InitConfig = { + label: 'docs-agent-nodejs', + walletConfig: { + id: 'wallet-id', + key: 'testkey0000000000000000000000000', + }, +} + +// start-section-1 +import { Agent } from '@credo-ts/core' +// OpenID4VC issuer and verifier modules only work in Node.JS +import { agentDependencies } from '@credo-ts/node' + +import express, { Router } from 'express' +import { OpenId4VcIssuerModule, OpenId4VcVerifierModule } from '@credo-ts/openid4vc' + +// Create two express routers, all endpoints for the +// issuer and verifier will be added to these routers +const verifierRouter = Router() +const issuerRouter = Router() + +// Register the routers on the express server. The path should match +// with the baseUrl you configure in the modules below. +const app = express() +app.use('/oid4vci', issuerRouter) +app.use('/siop', verifierRouter) + +const agent = new Agent({ + config, + dependencies: agentDependencies, + modules: { + openId4VcIssuer: new OpenId4VcIssuerModule({ + baseUrl: 'http://127.0.0.1:3000/oid4vci', + + // If no router is passed, one will be created. + // you still have to register the router on your express server + // but you can access it on agent.modules.openId4VcIssuer.config.router + // It works the same for verifier: agent.modules.openId4VcVerifier.config.router + router: issuerRouter, + + // Each of the endpoints can have configuration associated with it, such as the + // path (under the baseUrl) to use for the endpoints. + endpoints: { + // The credentialRequestToCredentialMapper is the only required endpoint + // configuration that must be provided. This method is called whenever a + // credential request has been received for an offer we created. The callback should + // return the issued credential to return in the credential response to the holder. + credential: { + credentialRequestToCredentialMapper: async () => { + throw new Error('Not implemented') + }, + }, + }, + }), + + // openId4VcVerifier module can only be used in Node.JS + openId4VcVerifier: new OpenId4VcVerifierModule({ + baseUrl: 'http://127.0.0.1:3000/siop', + + router: verifierRouter, + }), + }, +}) + +// listen on port 3000 for the openid4vc app. +app.listen(3000) + +// end-section-1 + +agent + .initialize() + .then(() => { + console.log('Agent initialized!') + }) + .catch((e) => { + console.error(`Something went wrong while setting up the agent! Message: ${e}`) + })