Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding vc create #148

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8,577 changes: 6,704 additions & 1,873 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion packages/credentials/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@
"engines": {
"node": ">=18.0.0"
},
"dependencies": {},
"dependencies": {
"@sphereon/pex": "^2.1.0",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/chai": "4.3.0",
"@types/eslint": "8.37.0",
Expand Down
58 changes: 9 additions & 49 deletions packages/credentials/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,10 @@
import { ICredential, IIssuer, ICredentialStatus, ICredentialSubject} from '@sphereon/ssi-types';

Check warning on line 2 in packages/credentials/src/types.ts

View check run for this annotation

Codecov / codecov/patch

packages/credentials/src/types.ts#L2

Added line #L2 was not covered by tests

/**
* @see {@link https://www.w3.org/TR/vc-data-model/#credentials | VC data model}
*/
export type VerifiableCredential = {
/** see {@link https://www.w3.org/TR/vc-data-model/#contexts | Contexts} */
'@context': ['https://www.w3.org/2018/credentials/v1', ...string[]];
credentialSubject: CredentialSubject | CredentialSubject[];
/** @see {@link https://www.w3.org/TR/vc-data-model/#identifiers | Identifiers} */
id?: string;
/** @see {@link IssuerType} */
issuer: Issuer;
/** @see {@link https://www.w3.org/TR/vc-data-model/#types | Types} */
type?: string[] | string;
/** @see {@link https://www.w3.org/TR/vc-data-model/#issuance-date | Issuance Date} */
issuanceDate: string;
/** @see {@link https://www.w3.org/TR/vc-data-model/#expiration | Expiration} */
expirationDate?: string;
/** @see {@link CredentialStatusReference} */
credentialStatus?: CredentialStatusReference;
[key: string]: any;
}
export type { ICredential as VerifiableCredential };

Check warning on line 7 in packages/credentials/src/types.ts

View check run for this annotation

Codecov / codecov/patch

packages/credentials/src/types.ts#L7

Added line #L7 was not covered by tests

/**
* The issuer of a {@link VerifiableCredential}.
Expand All @@ -30,23 +15,18 @@
*
* See {@link https://www.w3.org/TR/vc-data-model/#issuer | Issuer data model}
*/
export type Issuer = {
/** @see {@link https://www.w3.org/TR/vc-data-model/#identifiers | Identifiers} */
id: string;
[key: string]: any;
} | string
export type {IIssuer as Issuer};

Check warning on line 19 in packages/credentials/src/types.ts

View check run for this annotation

Codecov / codecov/patch

packages/credentials/src/types.ts#L18-L19

Added lines #L18 - L19 were not covered by tests

/**
* 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.
*
* See {@link https://www.w3.org/TR/vc-data-model/#credential-subject | Credential Subject}
*/
export type CredentialSubject = {
/** @see {@link https://www.w3.org/TR/vc-data-model/#identifiers | Identifiers} */
id?: string;
[key: string]: any;
}

export type {ICredentialSubject as CredentialSubject};

Check warning on line 29 in packages/credentials/src/types.ts

View check run for this annotation

Codecov / codecov/patch

packages/credentials/src/types.ts#L27-L29

Added lines #L27 - L29 were not covered by tests

/**
* Used for the discovery of information about the current status of a verifiable credential, such as whether it is
Expand All @@ -56,24 +36,4 @@
*
* See {@link https://www.w3.org/TR/vc-data-model/#status | Credential Status}
*/
export type CredentialStatusReference = {
/** @see {@link https://www.w3.org/TR/vc-data-model/#identifiers | Identifiers} */
id: string;
/** expresses the credential status type (also referred to as the credential status method).
* It is expected that the value will provide enough information to determine the current status
* of the credential and that machine readable information needs to be retrievable from the URI.
* For example, the object could contain a link to an external document noting whether or not the credential
* is suspended or revoked.
*/
type: string;
[key: string]: any;
}

/**
* proof property of a {@link VerifiableCredential}
*/
export type ProofType = {
/** @see {@link https://www.w3.org/TR/vc-data-model/#types | Types} */
type?: string;
[key: string]: any;
}
export type {ICredentialStatus as CredentialStatus};

Check warning on line 39 in packages/credentials/src/types.ts

View check run for this annotation

Codecov / codecov/patch

packages/credentials/src/types.ts#L39

Added line #L39 was not covered by tests
12 changes: 12 additions & 0 deletions packages/credentials/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export function getCurrentXmlSchema112Timestamp() : string {
// Omit the milliseconds part from toISOString() output
return new Date().toISOString().replace(/\.\d+Z$/, 'Z');
}

export function getFutureXmlSchema112Timestamp(secondsInFuture: number): string {
// Create a new Date object for the current time plus the specified number of seconds
const futureDate = new Date(Date.now() + secondsInFuture * 1000); // convert seconds to milliseconds

// Omit the milliseconds part from toISOString() output
return futureDate.toISOString().replace(/\.\d+Z$/, 'Z');
}
7 changes: 0 additions & 7 deletions packages/credentials/tests/example.spec.ts

This file was deleted.

67 changes: 67 additions & 0 deletions packages/credentials/tests/types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { expect } from 'chai';
import {getCurrentXmlSchema112Timestamp, getFutureXmlSchema112Timestamp} from '../src/utils.js';
import {VerifiableCredential, CredentialSubject, Issuer, CredentialStatus } from '../src/types.js';

describe('credential types', () => {
it('creates a vc', () => {
const credentialSubject: CredentialSubject = {
id: 'did:example:ebfeb1f712ebc6f1c276e12ec21',
};

const issuer: Issuer = {
id : 'did:example:123456',
otherProp : 'value',
};

const credentialStatus: CredentialStatus = {
id : 'http://example.com/status/123',
type : 'CredentialStatusType1',
};

// Create the credential
const credential: VerifiableCredential = {
'@context' : ['https://www.w3.org/2018/credentials/v1'],
type : ['VerifiableCredential'],
issuer : issuer,
issuanceDate : getCurrentXmlSchema112Timestamp(),
credentialSubject : credentialSubject,
credentialStatus : credentialStatus,
credentialSchema : {
id : 'http://example.com/schema/123',
type : 'SchemaType1',
},
id : 'http://example.edu/credentials/3732',
expirationDate : getFutureXmlSchema112Timestamp(60 * 60 * 24 * 365), // expires in 1 year
name : 'Credential Name',
description : 'Credential Description',
};

expect(credential).to.have.property('@context');
expect(credential).to.have.property('type');
expect(credential).to.have.property('issuer');
expect(credential).to.have.property('issuanceDate');
expect(credential).to.have.property('credentialSubject');
expect(credential).to.have.property('credentialStatus');
expect(credential).to.have.property('credentialSchema');
expect(credential).to.have.property('id');
expect(credential).to.have.property('expirationDate');
expect(credential).to.have.property('name');
expect(credential).to.have.property('description');
});

it('creates a minimum viable vc', () => {
const credential: VerifiableCredential = {
'@context' : ['https://www.w3.org/2018/credentials/v1'],
type : ['VerifiableCredential'],
issuer : { id: 'did:example:123456' },
issuanceDate : getCurrentXmlSchema112Timestamp(),
credentialSubject : { id: 'did:example:ebfeb1f712ebc6f1c276e12ec21' },
};

expect(credential).to.have.property('@context');
expect(credential).to.have.property('type');
expect(credential).to.have.property('issuer');
expect(credential).to.have.property('issuanceDate');
expect(credential).to.have.property('credentialSubject');
});
});
17 changes: 17 additions & 0 deletions packages/credentials/tests/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { expect } from 'chai';
import {getCurrentXmlSchema112Timestamp, getFutureXmlSchema112Timestamp} from '../src/utils.js';

describe('credentials utils', () => {
it('gets correct time', () => {
const timestamp = getCurrentXmlSchema112Timestamp();
expect(timestamp).to.not.be.undefined;
expect(timestamp).to.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);

});

it('gets correct time', () => {
const timestamp = getFutureXmlSchema112Timestamp(123);
expect(timestamp).to.not.be.undefined;
expect(timestamp).to.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
});
});
75 changes: 69 additions & 6 deletions packages/web5/src/vc-api.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,79 @@
import type { Web5Agent } from '@tbd54566975/web5-agent';
import { Web5Agent } from '@tbd54566975/web5-agent';
import type { VerifiableCredential } from '../../credentials/src/types.js';

import { getCurrentXmlSchema112Timestamp } from '../../credentials/src/utils.js';
import { v4 as uuidv4 } from 'uuid';
import { dataToBlob } from './utils.js';
import { Record } from './record.js';

import { DwnInterfaceName, DwnMethodName, RecordsWriteMessage, RecordsWriteOptions } from '@tbd54566975/dwn-sdk-js';
import { RecordsWriteResponse } from './dwn-api.js';

export type VcCreateResponse = RecordsWriteResponse & {
vc: VerifiableCredential;
};

export class VcApi {
#agent: Web5Agent;
#web5Agent: Web5Agent;
#connectedDid: string;

constructor(agent: Web5Agent, connectedDid: string) {
this.#agent = agent;
this.#web5Agent = agent;
this.#connectedDid = connectedDid;
}

async create() {
// TODO: implement
throw new Error('Not implemented.');
// TODO: Add CreateOptions for more robust VC creation
async create(credentialSubject: any): Promise<VcCreateResponse> {
if (!credentialSubject || typeof credentialSubject !== 'object') {
throw new Error('credentialSubject not valid');
}

const vc: VerifiableCredential = {
id : uuidv4(),
'@context' : ['https://www.w3.org/2018/credentials/v1'],
credentialSubject : credentialSubject,
type : ['VerifiableCredential'],
issuer : { id: this.#connectedDid },
issuanceDate : getCurrentXmlSchema112Timestamp(),
};

// TODO: Sign VC
// const signedVc = this.#web5Agent.sign(vc);

const { record, status } = await this._writeRecord(vc);
return { record, status, vc };
}

private async _writeRecord(vc: VerifiableCredential) {
const messageOptions: Partial<RecordsWriteOptions> = { ...{ schema: 'vc/vc', dataFormat: 'application/json' } };
nitro-neal marked this conversation as resolved.
Show resolved Hide resolved

nitro-neal marked this conversation as resolved.
Show resolved Hide resolved
const { dataBlob, dataFormat } = dataToBlob(vc, 'application/json');
messageOptions.dataFormat = dataFormat;

const agentResponse = await this.#web5Agent.processDwnRequest({
author : this.#connectedDid,
dataStream : dataBlob,
messageOptions,
messageType : DwnInterfaceName.Records + DwnMethodName.Write,
store : true,
target : this.#connectedDid
});

const { message, reply: { status } } = agentResponse;
const responseMessage = message as RecordsWriteMessage;

let record: Record;
if (200 <= status.code && status.code <= 299) {
const recordOptions = {
author : this.#connectedDid,
encodedData : dataBlob,
target : this.#connectedDid,
...responseMessage,
};

record = new Record(this.#web5Agent, recordOptions);

return {record, status};
}
}
}
29 changes: 21 additions & 8 deletions packages/web5/tests/web5-vc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,27 @@ describe('web5.vc', () => {
await testAgent.closeStorage();
});

describe('create', () => {
it('is not implemented', async () => {
try {
await vc.create();
expect.fail();
} catch(e) {
expect(e.message).to.include('Not implemented.');
}
describe('verifiable credentials', () => {
describe('create', () => {
it('valid vc', async () => {
const credentialSubject = {firstName: 'alice'};
const result = await vc.create(credentialSubject);

expect(result.status.code).to.equal(202);
expect(result.status.detail).to.equal('Accepted');
expect(result.record).to.exist;
expect(await result.record?.data.json()).to.deep.equal(result.vc);
});

it('invalid credential subject', async () => {
const credentialSubject = 'badcredsubject';
try {
await vc.create(credentialSubject);
expect.fail();
} catch(e) {
expect(e.message).to.include('credentialSubject not valid');
}
});
});
});
});
Loading