### Install mDL Library Source: https://github.com/auth0-lab/mdl/blob/main/README.md Install the mDL Node.js library using npm. ```bash npm i @auth0/mdl ``` -------------------------------- ### Install @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/QUICK-START.md Install the @auth0/mdl package using npm. ```bash npm install @auth0/mdl ``` -------------------------------- ### Complete Credential Verification Example Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/issuer-signed-document.md A full example demonstrating how to initialize a Verifier, verify an encoded document, and extract various pieces of information including document type, issuer details, validity periods, and specific attributes like driving privileges. This snippet shows end-to-end usage for examining a credential. ```typescript import { Verifier, IssuerSignedDocument } from '@auth0/mdl'; import fs from 'fs'; async function examineCredential() { const verifier = new Verifier([ fs.readFileSync('./ca-root.pem', 'utf-8'), ]); const mdoc = await verifier.verify(encodedBytes, { encodedSessionTranscript: sessionBytes, }); const doc = mdoc.documents[0] as IssuerSignedDocument; // Document information console.log('Document Type:', doc.docType); console.log('Namespaces:', doc.issuerSignedNameSpaces); // Issuer information const { issuerAuth } = doc.issuerSigned; console.log('Algorithm:', issuerAuth.algName); console.log('Issuer:', issuerAuth.certificate?.issuerName.toString()); // Validity const { validityInfo } = issuerAuth.decodedPayload; console.log(`Valid: ${validityInfo.validFrom} - ${validityInfo.validUntil}`); // Attributes const attrs = doc.getIssuerNameSpace('org.iso.18013.5.1'); console.log('Full Name:', `${attrs.given_name} ${attrs.family_name}`); console.log('Birth Date:', attrs.birth_date); console.log('Driving Privileges:'); for (const priv of attrs.driving_privileges) { console.log(` - Category: ${priv.vehicle_category_code}`); console.log(` Valid: ${priv.issue_date} - ${priv.expiry_date}`); } // Digest verification const digests = issuerAuth.decodedPayload.valueDigests; const mDLDigests = digests.get('org.iso.18013.5.1'); console.log('Attributes verified:', mDLDigests.size); } examineCredential().catch(console.error); ``` -------------------------------- ### Example Input Descriptor for mDL Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Provides a concrete example of an InputDescriptor for an mDL. It specifies the document ID, supported signing algorithms, and the fields to be disclosed. ```typescript const descriptor: InputDescriptor = { id: 'org.iso.18013.5.1.mDL', format: { mso_mdoc: { alg: ['ES256', 'EdDSA'] } }, constraints: { limit_disclosure: 'required', fields: [ { path: ["$['org.iso.18013.5.1']['family_name']"], intent_to_retain: false, }, ], }, }; ``` -------------------------------- ### VerificationAssessment Example Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Example of how to create a VerificationAssessment object. Ensure the status, check description, category, and id fields are correctly populated. ```typescript const assessment: VerificationAssessment = { status: 'PASSED', check: 'Issuer signature must be valid', category: 'ISSUER_AUTH', id: 'ISSUER_SIGNATURE_VALIDITY', }; ``` -------------------------------- ### Example Usage of ValidityInfo Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Demonstrates how to instantiate and populate the ValidityInfo type with sample date values. ```typescript const validity: ValidityInfo = { signed: new Date('2024-01-01'), validFrom: new Date('2024-01-01'), validUntil: new Date('2025-01-01'), expectedUpdate: new Date('2024-07-01'), }; ``` -------------------------------- ### Example IssuerNameSpaces Usage Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Illustrates how to create an `IssuerNameSpaces` object with a sample namespace and an empty array for issuer-signed items. ```typescript const namespaces: IssuerNameSpaces = { 'org.iso.18013.5.1': [ // IssuerSignedItem[] ], }; ``` -------------------------------- ### DateOnly Example Usage Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Shows how to create a DateOnly instance and log its ISO string representation. This is useful for mDL fields like birth_date. ```typescript const birthDate = new DateOnly('1990-01-15'); console.log(birthDate.toISOString()); // '1990-01-15' ``` -------------------------------- ### DataItem Example Usage Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Demonstrates creating a DataItem from an object, accessing its encoded buffer, and decoding its data. ```typescript const item = DataItem.fromData({ family_name: 'Smith' }); const encoded: Uint8Array = item.buffer; const decoded: any = item.data; ``` -------------------------------- ### Verifier - Strict Verification (Production) Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Example of setting up a Verifier for strict certificate validation, suitable for production environments. ```APIDOC ## Verifier - Strict Verification (Production) ### Description This example demonstrates how to instantiate and use the `Verifier` class with strict certificate chain validation enabled, which is recommended for production environments. ### Method ```typescript new Verifier(trustedCertificates: string[]) await verifier.verify(encodedDocument: Uint8Array, options: VerifyOptions) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body (for `verify` method) - **encodedDocument** (Uint8Array) - Required - The encoded document to verify. - **options** (VerifyOptions) - Required - Options for verification: - **encodedSessionTranscript** (Uint8Array) - Required - The session transcript. - **ephemeralReaderKey** (Uint8Array) - Required - The ephemeral reader key. - **disableCertificateChainValidation** (boolean) - Optional - Set to `false` for strict validation. ### Request Example ```typescript import { Verifier } from '@auth0/mdl'; import fs from 'fs'; const verifier = new Verifier([ fs.readFileSync('./iaca-root.pem', 'utf-8'), fs.readFileSync('./iaca-intermediate.pem', 'utf-8'), ]); const mdoc = await verifier.verify(encoded, { encodedSessionTranscript: sessionBytes, ephemeralReaderKey: ephemeralKeyBytes, disableCertificateChainValidation: false, }); ``` ``` -------------------------------- ### UserDefinedVerificationCallback Example Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Example of implementing a UserDefinedVerificationCallback. This demonstrates how to check the assessment status and log errors, with an option to call the original callback for default behavior. ```typescript const onCheck: UserDefinedVerificationCallback = (assessment, original) => { if (assessment.status === 'FAILED') { console.error(`${assessment.id}: ${assessment.reason}`); } // Can still call original for default behavior }; ``` -------------------------------- ### Example DiagnosticInformation Output Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/types.md Illustrates a sample output structure for DiagnosticInformation, showing key fields like general status, issuer signature, and attribute details. ```typescript { general: { type: 'DeviceResponse', version: '1.0', status: 0, documents: 1, }, issuerSignature: { alg: 'ES256', isValid: true, digests: { 'org.iso.18013.5.1': 15, }, }, attributes: [ { ns: 'org.iso.18013.5.1', id: 'family_name', value: 'Smith', isValid: true, matchCertificate: true, }, ], } ``` -------------------------------- ### Verifier - Diagnostic Mode (Development) Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Example of using the Verifier in diagnostic mode to get detailed information about verification failures. ```APIDOC ## Verifier - Diagnostic Mode (Development) ### Description This example shows how to use the `getDiagnosticInformation` method of the `Verifier` class to obtain detailed insights into verification results, useful for debugging in development. ### Method ```typescript await verifier.getDiagnosticInformation(encodedDocument: Uint8Array, options: DiagnosticOptions) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body (for `getDiagnosticInformation` method) - **encodedDocument** (Uint8Array) - Required - The encoded document for which to get diagnostic information. - **options** (DiagnosticOptions) - Required - Options for retrieving diagnostics: - **encodedSessionTranscript** (Uint8Array) - Required - The session transcript. - **ephemeralReaderKey** (Uint8Array) - Required - The ephemeral reader key. ### Response (from `getDiagnosticInformation`) - **issuerSignature** (object) - Information about the issuer signature validation. - **isValid** (boolean) - Indicates if the issuer signature is valid. - **reasons** (array) - Array of reasons for failure if `isValid` is false. - **deviceSignature** (object | undefined) - Information about the device signature validation, if present. - **isValid** (boolean) - Indicates if the device signature is valid. - **reasons** (array) - Array of reasons for failure if `isValid` is false. - **attributes** (object) - Disclosed attributes. ### Request Example ```typescript const diagnostics = await verifier.getDiagnosticInformation(encoded, { encodedSessionTranscript: sessionBytes, ephemeralReaderKey: ephemeralKeyBytes, }); if (!diagnostics.issuerSignature.isValid) { console.error('Issuer signature failures:', diagnostics.issuerSignature.reasons); } if (diagnostics.deviceSignature && !diagnostics.deviceSignature.isValid) { console.error('Device signature failures:', diagnostics.deviceSignature.reasons); } console.log('Disclosed attributes:', diagnostics.attributes); ``` ``` -------------------------------- ### Verifier - Callback-Based Error Handling Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Example demonstrating how to use a callback function with the `verify` method to capture specific verification failures. ```APIDOC ## Verifier - Callback-Based Error Handling ### Description This example illustrates how to implement custom error handling during the verification process by providing an `onCheck` callback function to the `verify` method. This callback is invoked for each assessment, allowing you to capture and process specific failures. ### Method ```typescript await verifier.verify(encodedDocument: Uint8Array, options: VerifyOptionsWithCallback) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body (for `verify` method) - **encodedDocument** (Uint8Array) - Required - The encoded document to verify. - **options** (VerifyOptionsWithCallback) - Required - Options for verification, including a callback: - **encodedSessionTranscript** (Uint8Array) - Required - The session transcript. - **ephemeralReaderKey** (Uint8Array) - Required - The ephemeral reader key. - **onCheck** (function) - Optional - Callback function executed for each assessment. - **assessment** (object) - The current assessment result. - **status** (string) - The status of the assessment ('FAILED', 'PASSED', etc.). - **id** (string) - The ID of the assessment. - **check** (string) - The name of the check performed. - **reason** (string) - The reason for failure, if applicable. - **original** (object) - The original assessment object. ### Request Example ```typescript const failures = []; await verifier.verify(encoded, { encodedSessionTranscript: sessionBytes, onCheck: (assessment, original) => { if (assessment.status === 'FAILED') { failures.push({ id: assessment.id, check: assessment.check, reason: assessment.reason, }); } }, }); if (failures.length > 0) { console.log('Verification failures:', failures); } ``` ``` -------------------------------- ### Get Diagnostic Information with Options Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Retrieve diagnostic information for an encoded device response using optional parameters for session transcript and ephemeral reader key. This is useful for debugging verification issues. ```typescript const diagnostics = await verifier.getDiagnosticInformation(encoded, { encodedSessionTranscript: sessionBytes, ephemeralReaderKey: ephemeralKeyBytes, }); console.log('Issuer sig valid:', diagnostics.issuerSignature.isValid); console.log('Attributes:', diagnostics.attributes); ``` -------------------------------- ### Parse mDL document with error handling Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md This example demonstrates how to parse a CBOR-encoded mDL document and handle potential `MDLParseError` exceptions. It logs the number of documents, version, and status upon successful parsing. ```typescript import { parse, MDLParseError } from '@auth0/mdl'; try { const mdoc = parse(encodedBytes); console.log('Documents:', mdoc.documents.length); console.log('Version:', mdoc.version); console.log('Status:', mdoc.status); } catch (err) { if (err instanceof MDLParseError) { console.error('Parse error:', err.message); } } ``` -------------------------------- ### Get Issuer Namespace Attributes Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Retrieves attributes from a specific namespace within an IssuerSignedDocument as a JavaScript object. For example, accessing 'family_name' from the 'org.iso.18013.5.1' namespace. ```typescript const attrs = doc.getIssuerNameSpace('org.iso.18013.5.1'); console.log(attrs.family_name); // 'Smith' ``` -------------------------------- ### Create a Document Instance Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Instantiate a Document object, optionally specifying the document type. Defaults to 'org.iso.18013.5.1.mDL' if no type is provided. ```typescript import { Document } from '@auth0/mdl'; const doc = new Document('org.iso.18013.5.1.mDL'); // or use default const doc2 = new Document(); ``` -------------------------------- ### Build a Device Response with @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/QUICK-START.md Construct a device response for a Verifiable Presentation Request (VP). This involves using a presentation definition, session transcript, and authenticating with a device private key. ```typescript import { DeviceResponse } from '@auth0/mdl'; const mdoc = await DeviceResponse.from(issuerCredential) .usingPresentationDefinition({ id: 'disclosure', input_descriptors: [ { id: 'org.iso.18013.5.1.mDL', format: { mso_mdoc: { alg: ['ES256'] } }, constraints: { limit_disclosure: 'required', fields: [ { path: ["$['org.iso.18013.5.1']['family_name']"], intent_to_retain: false, }, ], }, }, ], }) .usingSessionTranscriptForOID4VP( 'nonce_from_device', 'client_id', 'https://verifier.example.com/response', 'nonce_from_verifier' ) .authenticateWithSignature(devicePrivateKeyJWK, 'ES256') .sign(); const encoded = mdoc.encode(); ``` -------------------------------- ### Document Constructor Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Creates a Document instance, optionally specifying the document type. Defaults to 'org.iso.18013.5.1.mDL' if no type is provided. ```APIDOC ## Document Constructor ### Description Creates a Document instance, optionally specifying the document type. Defaults to 'org.iso.18013.5.1.mDL' if no type is provided. ### Method ```typescript constructor(doc?: DocType) ``` ### Parameters #### Path Parameters - **docType** (DocType) - Optional - Document type identifier (defaults to 'org.iso.18013.5.1.mDL') ### Request Example ```typescript import { Document } from '@auth0/mdl'; const doc = new Document('org.iso.18013.5.1.mDL'); // or use default const doc2 = new Document(); ``` ``` -------------------------------- ### MDL Library Import Quick Reference Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/QUICK-START.md Lists essential imports for main classes, utilities, errors, configuration, and verification types from the '@auth0/mdl' library. ```typescript // Main classes import { Verifier, Document, DeviceResponse, MDoc, IssuerSignedDocument, DeviceSignedDocument, } from '@auth0/mdl' // Utilities import { parse, DataItem, DateOnly } from '@auth0/mdl' // Errors import { MDLError, MDLParseError } from '@auth0/mdl' // Configuration import { getCborEncodeDecodeOptions, setCborEncodeDecodeOptions, } from '@auth0/mdl' // Verification types import { VerificationAssessmentId } from '@auth0/mdl' ``` -------------------------------- ### Get Device Namespace Attributes Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Retrieves device-authenticated attributes from a specific namespace within a DeviceSignedDocument. ```typescript const deviceAttrs = doc.getDeviceNameSpace('org.iso.18013.5.1'); ``` -------------------------------- ### addValidityInfo Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Sets the validity period for the document, including signing date, validity start, and end dates. ```APIDOC ## addValidityInfo(info) ### Description Sets the validity period for the document. ### Parameters #### Path Parameters - **info.signed** (Date) - Optional - When the document was signed by issuer. Defaults to now. - **info.validFrom** (Date) - Optional - When validity begins. Defaults to signed date. - **info.validUntil** (Date) - Optional - When validity ends. Defaults to signed date + 1 year. - **info.expectedUpdate** (Date) - Optional - Expected re-signature date. ### Returns Document (fluent interface) ``` -------------------------------- ### Document Constructor Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Initializes a new Document builder. Optionally specifies the document type. ```APIDOC ## Document Constructor ### Description Initializes a new Document builder. Optionally specifies the document type. ### Parameters #### Path Parameters - **docType** (DocType) - Optional - Document type identifier. Defaults to 'org.iso.18013.5.1.mDL'. ``` -------------------------------- ### prepare Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/device-signed-document.md Prepares the document for CBOR encoding, including device authentication. The device authentication signature payload is detached. ```APIDOC ## prepare() ### Description Prepares the document for CBOR encoding, including device authentication. ### Returns Map - Map with: - **docType** — Document type - **issuerSigned** — Issuer authentication and all attributes - **deviceSigned** — Device authentication and disclosed attributes ### Note Device authentication signature payload is detached (set to null) per ISO 18013-5. ### Example ```typescript const prepared = doc.prepare(); const deviceSigned = prepared.get('deviceSigned'); console.log(deviceSigned.deviceAuth); // Contains signature or MAC ``` ``` -------------------------------- ### Handle MDLParseError in TypeScript Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/errors.md Example of catching an MDLParseError. Use this when you suspect the input data is malformed or not a valid mDL. ```typescript try { const mdoc = parse(invalidBytes); } catch (err) { if (err instanceof MDLParseError) { console.log('Failed to parse mDL'); } } ``` -------------------------------- ### Get Current CBOR Options Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Retrieves the current CBOR encoder/decoder options. Useful for inspecting or modifying existing settings. ```typescript import { getCborEncodeDecodeOptions } from '@auth0/mdl'; const options = getCborEncodeDecodeOptions(); console.log(options); // { tagUint8Array: false, useRecords: false, mapsAsObjects: false, ... } ``` -------------------------------- ### prepare() Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/issuer-signed-document.md Creates the structure for encoding the document to CBOR format. This method is used internally by the MDoc encoder to prepare the document's data for serialization. ```APIDOC ## prepare() ### Description Creates the structure for encoding the document to CBOR format. This is used internally by the MDoc encoder. ### Method ```typescript prepare(): Map ``` ### Returns Map with: - **docType** — Document type identifier - **issuerSigned** — Map containing: - **nameSpaces** — Map of namespace IDs to DataItem arrays - **issuerAuth** — Issuer authentication structure for encoding ### Example ```typescript const prepared = doc.prepare(); // Extract issuer auth for inspection const issuerAuth = prepared.get('issuerSigned').issuerAuth; // This is called internally by MDoc.encode() const mdoc = new MDoc([doc]); const encoded = mdoc.encode(); // Uses prepare() internally ``` ``` -------------------------------- ### addValidityInfo Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Adds validity information to the document, including signed date, validity start and end dates, and an expected update date. ```APIDOC ## addValidityInfo ### Description Adds validity information to the document, specifying when it was signed, its validity period, and an expected re-signature date. ### Method `addValidityInfo(info?: Partial): Document` ### Parameters #### Path Parameters - **info.signed** (Date) - Optional - When the document was signed. Defaults to the current date. - **info.validFrom** (Date) - Optional - The start date of the document's validity. Defaults to `info.signed`. - **info.validUntil** (Date) - Optional - The end date of the document's validity. Defaults to `info.signed` + 1 year. - **info.expectedUpdate** (Date) - Optional - The expected date for re-signing the document. ### Request Example ```typescript const doc = new Document() .addValidityInfo({ signed: new Date('2024-01-01'), validFrom: new Date('2024-01-01'), validUntil: new Date('2035-01-01'), expectedUpdate: new Date('2024-07-01'), }); ``` ``` -------------------------------- ### Initialize Verifier with Root Certificates Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Instantiate the Verifier by providing an array of trusted IACA root certificates in PEM format. The library handles building the certificate chain. ```typescript import fs from 'fs'; import { Verifier } from '@auth0/mdl'; const rootCerts = [ fs.readFileSync('./root-ca.pem', 'utf-8'), fs.readFileSync('./intermediate-ca.pem', 'utf-8'), ]; const verifier = new Verifier(rootCerts); ``` -------------------------------- ### Module Hierarchy Overview Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md This tree structure illustrates the internal organization of the @auth0/mdl library, showing the relationship between different modules and their primary components. ```tree @auth0/mdl (index.ts) ├── mdoc/ │ ├── Verifier.ts → Verifier class │ ├── parser.ts → parse() function │ ├── errors.ts → MDLError, MDLParseError │ ├── checkCallback.ts → VerificationAssessmentId │ ├── IssuerSignedItem.ts → IssuerSignedItem (internal) │ ├── utils.ts → calculateEphemeralMacKey(), etc. │ └── model/ │ ├── MDoc.ts → MDoc class │ ├── Document.ts → Document class │ ├── DeviceResponse.ts → DeviceResponse class │ ├── IssuerAuth.ts → IssuerAuth (extends Sign1) │ ├── IssuerSignedDocument.ts → IssuerSignedDocument │ ├── DeviceSignedDocument.ts → DeviceSignedDocument │ ├── PresentationDefinition.ts → Type definitions │ └── types.ts → All public type definitions └── cbor/ ├── index.ts → cborEncode, cborDecode, DateOnly └── DataItem.ts → DataItem class ``` -------------------------------- ### Handle MDLError in TypeScript Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/errors.md Example of catching and inspecting an MDLError. Use this when you need to differentiate between general errors and specific mDL library errors. ```typescript try { const mdoc = await verifier.verify(encoded); } catch (err) { if (err instanceof MDLError) { console.log(`Code: ${err.code}`); console.log(`Message: ${err.message}`); } } ``` -------------------------------- ### Get Issuer Namespace Attributes Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/device-signed-document.md Retrieves all issuer-signed attributes for a given namespace, including those not selectively disclosed by the device. This method is inherited from IssuerSignedDocument. ```typescript // All issuer-signed attributes const issuerAttrs = doc.getIssuerNameSpace('org.iso.18013.5.1'); // Contains all attributes, not just disclosed console.log(issuerAttrs.family_name); // 'Smith' console.log(issuerAttrs.birth_date); // DateOnly('1990-01-15') ``` -------------------------------- ### Get Device Namespace Attributes Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/device-signed-document.md Retrieves attributes that were selectively disclosed and authenticated by the device for a given namespace. Attributes not disclosed by the device will be undefined. ```typescript const deviceAttrs = doc.getDeviceNameSpace('org.iso.18013.5.1'); // Only attributes disclosed by the device are present console.log(deviceAttrs.family_name); // 'Smith' console.log(deviceAttrs.given_name); // 'John' // Attributes not disclosed are undefined console.log(deviceAttrs.birth_date); // undefined (not disclosed) ``` -------------------------------- ### MDL Document Lifecycle Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Illustrates the sequential steps from document creation by the issuer to its final encoded form for the verifier. ```text 1. Issuer creates → Document class ↓ 2. Issuer signs → IssuerSignedDocument ↓ 3. Device builds response → DeviceResponse builder ↓ 4. Device signs/MACs → DeviceSignedDocument ↓ 5. Transmit to verifier → Encoded bytes (CBOR) ↓ 6. Verifier parses & validates → MDoc with documents ``` -------------------------------- ### getCborEncodeDecodeOptions() / setCborEncodeDecodeOptions(options) Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Provides functionality to get and set global CBOR encoder/decoder options. This allows for customization of how CBOR data is handled by the library. ```APIDOC ## getCborEncodeDecodeOptions() / setCborEncodeDecodeOptions(options) ### Description Gets or sets global CBOR encoder/decoder options. ### Parameters #### Path Parameters - options (object) - Optional - CBOR encoder/decoder options to set. ``` -------------------------------- ### usingPresentationDefinition Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Configures the DeviceResponse using a provided PresentationDefinition. This method allows specifying document types, supported algorithms, and disclosure constraints. ```APIDOC ## usingPresentationDefinition ### Description Configures the DeviceResponse using a provided PresentationDefinition. This method allows specifying document types, supported algorithms, and disclosure constraints. ### Method ```typescript usingPresentationDefinition(pd: PresentationDefinition): DeviceResponse ``` ### Parameters #### Request Body - **pd** (PresentationDefinition) - Required - The presentation definition object. - **id** (string) - Required - The ID of the presentation definition. - **input_descriptors** (Array) - Required - An array of input descriptors. - **id** (string) - Required - Document type. - **format** (Object) - Required - Format constraints. - **mso_mdoc** (Object) - Required - mdoc specific format. - **alg** (Array) - Required - Supported algorithms. - **constraints** (Object) - Required - Disclosure constraints. - **limit_disclosure** (string) - Required - 'required' for selective disclosure. - **fields** (Array) - Required - Fields to disclose. - **path** (Array) - Required - JSON path to the field. - **intent_to_retain** (boolean) - Required - User retention permission request. ### Request Example ```typescript const pd = { id: 'mDL_disclosure', input_descriptors: [ { id: 'org.iso.18013.5.1.mDL', format: { mso_mdoc: { alg: ['ES256', 'EdDSA'] } }, constraints: { limit_disclosure: 'required', fields: [ { path: ["$['org.iso.18013.5.1']['family_name']"], intent_to_retain: false, }, { path: ["$['org.iso.18013.5.1']['given_name']"], intent_to_retain: false, }, ], }, }, ], }; await deviceResponse.usingPresentationDefinition(pd); ``` ``` -------------------------------- ### Create a Credential with @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/QUICK-START.md Create a new verifiable credential (mDL) using the Document class. This involves adding namespaces, device key information, and signing the document. ```typescript import { Document, MDoc } from '@auth0/mdl'; const doc = await new Document('org.iso.18013.5.1.mDL') .addIssuerNameSpace('org.iso.18013.5.1', { family_name: 'Smith', given_name: 'John', birth_date: '1990-01-15', issue_date: '2024-01-01', expiry_date: '2034-01-01', }) .addDeviceKeyInfo({ deviceKey: devicePublicKeyJWK }) .useDigestAlgorithm('SHA-256') .addValidityInfo({ signed: new Date(), validUntil: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), }) .sign({ issuerPrivateKey: issuerPrivateKeyJWK, issuerCertificate: issuerCertificatePem, alg: 'ES256', }); const mdoc = new MDoc([doc]); const encoded = mdoc.encode(); ``` -------------------------------- ### Get Current CBOR Encode/Decode Options Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md Retrieves the current global CBOR encoder/decoder options. This is useful for inspecting the current configuration before making changes or for logging. ```typescript import { getCborEncodeDecodeOptions } from '@auth0/mdl'; const options = getCborEncodeDecodeOptions(); ``` ```typescript const opts = getCborEncodeDecodeOptions(); console.log('Current options:', opts); // Check if using records if (opts.useRecords) { console.log('Using records for encoding'); } ``` -------------------------------- ### DeviceResponse.sign() Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Asynchronously signs the device response, returning the resulting MDoc. ```APIDOC ## DeviceResponse.sign() ### Description Asynchronously signs the device response. ### Method instance ### Returns Promise ``` -------------------------------- ### Import DeviceResponse from @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Import the DeviceResponse class for handling responses from a device. ```typescript // Device responses import { DeviceResponse } from '@auth0/mdl' ``` -------------------------------- ### Add Validity Information to Document Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Use to set the signed date, validity start and end dates, and expected update date for a document. Defaults are applied if not specified. ```typescript const doc = new Document() .addValidityInfo({ signed: new Date('2024-01-01'), validFrom: new Date('2024-01-01'), validUntil: new Date('2035-01-01'), expectedUpdate: new Date('2024-07-01'), }); ``` -------------------------------- ### Work with DataItem Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md Demonstrates creating a `DataItem` from data, accessing its encoded buffer, creating another `DataItem` from the buffer, and accessing its decoded data. Note that accessing `data` or `buffer` on different `DataItem` instances will result in new instances, not shared references. ```typescript import { DataItem, cborEncode } from '@auth0/mdl'; // Create from object const item1 = DataItem.fromData({ name: 'John', age: 30 }); // Access buffer (triggers encoding) const encoded: Uint8Array = item1.buffer; // Create from buffer const item2 = new DataItem({ buffer: encoded }); // Access data (triggers decoding) const decoded = item2.data; console.log(decoded.name); // 'John' // Both reference same underlying data console.log(item1.data === item2.data); // false (different instances) console.log(item1.buffer === item2.buffer); // false (different instances) ``` -------------------------------- ### Get Diagnostic Information from Device Response Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Extracts detailed diagnostic information from a DeviceResponse without throwing errors on verification failure. Useful for debugging and detailed analysis of verification results. ```typescript const diagnostics = await verifier.getDiagnosticInformation(encodedDeviceResponse, { encodedSessionTranscript: sessionTranscriptBytes, ephemeralReaderKey: ephemeralKeyBytes, }); console.log(diagnostics.issuerSignature.isValid); console.log(diagnostics.attributes); ``` -------------------------------- ### MDL Project File Structure Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Provides an overview of the directory layout and the purpose of each file within the MDL project. ```text /workspace/home/output/ ├── README.md (this file) ├── QUICK-START.md (quick reference, common tasks) ├── index.md (complete API reference) ├── types.md (all type definitions) ├── errors.md (error codes and conditions) ├── configuration.md (all constructor/options) ├── utilities.md (utility functions and CBOR) ├── issuer-signed-document.md (IssuerSignedDocument API) └── device-signed-document.md (DeviceSignedDocument API) ``` -------------------------------- ### Get mDL Diagnostic Information Source: https://github.com/auth0-lab/mdl/blob/main/README.md Retrieve diagnostic information for an mDL credential. This function requires the device response, session transcript, and ephemeral reader key, similar to the verification process. ```javascript import { Verifier } from "@auth0/mdl"; import { inspect } from "node:util"; import fs from "node:fs"; (async () => { const encodedDeviceResponse = Buffer.from(encodedDeviceResponseHex, 'hex'); const encodedSessionTranscript = Buffer.from(encodedSessionTranscriptHex, 'hex'); const ephemeralReaderKey = Buffer.from(ephemeralReaderKeyHex, 'hex'); const trustedCerts = [fs.readFileSync('./caCert1.pem')]/*, ... */; const verifier = new Verifier(trustedCerts); const diagnosticInfo = await verifier.getDiagnosticInformation(encodedDeviceResponse, { ephemeralReaderKey, encodedSessionTranscript, }); inspect(diagnosticInfo); })(); ``` -------------------------------- ### Set Document Validity Period Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Sets the validity period for the document, including signing date, start date, and end date. The default validity is one year from the signing date. ```typescript const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); doc.addValidityInfo({ signed: new Date(), validFrom: new Date(), validUntil: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), }); ``` -------------------------------- ### MDL Signature Algorithms Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Lists supported signature algorithms, their types, associated curves, and recommendation status for use in MDL. ```text | Algorithm | Type | Curves | Recommended | |-----------|------|--------|-------------| | ES256 | ECDSA | P-256 | ✓ Yes | | ES384 | ECDSA | P-384 | ✓ Yes | | ES512 | ECDSA | P-521 | ✓ Yes | | EdDSA | EdDSA | Ed25519, Ed448 | ✓ Yes | | HS256 | HMAC | N/A (MAC only) | ✓ Yes | ``` -------------------------------- ### DataItem Initialization Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/errors.md Use DataItem.fromData, new DataItem({ data: ... }), or new DataItem({ buffer: ... }) to correctly initialize a DataItem. Avoid calling the constructor without data or a buffer. ```typescript const item = DataItem.fromData(myData); // or const item = new DataItem({ data: myData }); // or const item = new DataItem({ buffer: myBuffer }); ``` -------------------------------- ### Get Diagnostic Information Without Throwing Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/errors.md Utilize the getDiagnosticInformation method to retrieve detailed verification results without causing the process to throw an error. This is useful for inspecting the validity and reasons for failure. ```typescript const diagnostics = await verifier.getDiagnosticInformation(encoded, options); console.log('Issuer signature valid?', diagnostics.issuerSignature.isValid); console.log('Device signature valid?', diagnostics.deviceSignature?.isValid); console.log('Failure reasons:', diagnostics.issuerSignature.reasons); ``` -------------------------------- ### Create an MDoc Instance Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Instantiate an MDoc object with optional signed documents, version, status, and document errors. Defaults are provided for version, status, and errors. ```typescript import { MDoc, MDocStatus } from '@auth0/mdl'; const mdoc = new MDoc( [signedDoc], '1.0', MDocStatus.OK, [] ); ``` -------------------------------- ### Complete Verification Flow Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md Demonstrates the complete verification flow using the Verifier class. Ensure root certificates are provided for verification. ```typescript import { Verifier, MDoc, IssuerSignedDocument, DeviceSignedDocument, } from '@auth0/mdl'; const verifier = new Verifier([rootCertPem]); const mdoc = await verifier.verify(encoded, options); const doc = mdoc.documents[0]; if (doc instanceof DeviceSignedDocument) { const attrs = doc.getDeviceNameSpace('org.iso.18013.5.1'); } ``` -------------------------------- ### Get Diagnostic Information with MDL Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/QUICK-START.md Retrieve diagnostic information from a verified MDL document. This includes issuer and device signature validity, and attribute validation status. Requires an initialized verifier and encoded session data. ```typescript const diagnostics = await verifier.getDiagnosticInformation(encoded, { encodedSessionTranscript: sessionBytes, ephemeralReaderKey: ephemeralKeyBytes, }); console.log('Issuer signature valid:', diagnostics.issuerSignature.isValid); console.log('Device signature valid:', diagnostics.deviceSignature?.isValid); console.log('Attributes:'); for (const attr of diagnostics.attributes) { console.log(` ${attr.ns}/${attr.id}: ${attr.isValid ? '✓' : '✗'}`); } ``` -------------------------------- ### Instantiate and Use Verifier Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Instantiates the Verifier with trusted IACA root certificates and uses it to verify a DeviceResponse credential. Ensure session transcript and ephemeral reader key are provided for full verification. ```typescript const verifier = new Verifier([fs.readFileSync('./caCert.pem', 'utf-8')]); const mdoc = await verifier.verify(encodedDeviceResponse, { encodedSessionTranscript: sessionTranscriptBytes, ephemeralReaderKey: ephemeralKeyBytes, }); ``` -------------------------------- ### CBOR Encode/Decode Round-Trip Example Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/utilities.md Demonstrates a full round-trip process: encoding a JavaScript object to CBOR bytes using `cborEncode` and then decoding those bytes back to a JavaScript object using `cborDecode`. This verifies data integrity. ```typescript import { cborEncode, cborDecode, DataItem } from '@auth0/mdl'; // Encode const original = { name: 'John', active: true }; const item = DataItem.fromData(original); const encoded = cborEncode(item); // Decode const decoded = cborDecode(encoded); console.log(decoded); // { name: 'John', active: true } ``` -------------------------------- ### MDoc Constructor Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Initializes an MDoc object with an array of signed documents, version, status, and document errors. Default values are provided for each parameter. ```APIDOC ## MDoc Constructor ### Description Initializes an MDoc object with an array of signed documents, version, status, and document errors. Default values are provided for each parameter. ### Method ```typescript constructor( documents?: IssuerSignedDocument[], version?: string, status?: MDocStatus, documentErrors?: DocumentError[] ) ``` ### Parameters #### Path Parameters - **documents** (IssuerSignedDocument[]) - Optional - Array of signed documents (defaults to []) - **version** (string) - Optional - MDoc format version (defaults to '1.0') - **status** (MDocStatus) - Optional - Status code (defaults to MDocStatus.OK) - **documentErrors** (DocumentError[]) - Optional - Document-level errors (defaults to []) ### Request Example ```typescript import { MDoc, MDocStatus } from '@auth0/mdl'; const mdoc = new MDoc( [signedDoc], '1.0', MDocStatus.OK, [] ); ``` ``` -------------------------------- ### Create DeviceResponse Builder Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Instantiate a DeviceResponse builder from an MDoc credential or its CBOR encoded bytes. ```typescript const deviceResponse = DeviceResponse.from(issuerMDoc); // or from CBOR bytes: const deviceResponse = DeviceResponse.from(encodedMDocBytes); ``` -------------------------------- ### Verify MDOC with Options Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Use this snippet to verify an encoded device response with optional parameters like session transcript, ephemeral reader key, and certificate chain validation settings. The `onCheck` callback can be used to monitor verification progress. ```typescript import { Verifier } from '@auth0/mdl'; import fs from 'fs'; const verifier = new Verifier([fs.readFileSync('./ca.pem', 'utf-8')]); const mdoc = await verifier.verify(encodedResponse, { encodedSessionTranscript: sessionBytes, ephemeralReaderKey: ephemeralKeyBytes, disableCertificateChainValidation: false, onCheck: (assessment, original) => { if (assessment.status === 'FAILED') { console.error(`${assessment.id}: ${assessment.reason}`); } }, }); ``` -------------------------------- ### DeviceResponse.from(mdoc) Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Creates a DeviceResponse builder instance from an mdoc credential or its CBOR-encoded bytes. ```APIDOC ## DeviceResponse.from(mdoc) ### Description Creates a DeviceResponse builder from an mdoc credential. ### Method static ### Parameters #### Path Parameters - **mdoc** (MDoc \| Uint8Array) - Required - Parsed MDoc or CBOR-encoded bytes ### Returns DeviceResponse (builder instance) ``` -------------------------------- ### MDoc Constructor and Add Document Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Initializes an MDoc object and adds a signed document to it. The document must be signed before adding. ```typescript export class MDoc { constructor( documents?: IssuerSignedDocument[], version?: string, status?: MDocStatus, documentErrors?: DocumentError[] ) addDocument(document: IssuerSignedDocument): void encode(): Buffer } const mdoc = new MDoc(); mdoc.addDocument(signedDoc); ``` -------------------------------- ### addDeviceKeyInfo Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Adds the device's public key to the document, which will be included in the issuer signature. ```APIDOC ## addDeviceKeyInfo({ deviceKey }) ### Description Adds the device's public key to the document. This will be included in the issuer signature. ### Parameters #### Path Parameters - **deviceKey** (JWK | Uint8Array) - Required - Device public key in JWK or COSE_Key format ### Returns Document (fluent interface) ``` -------------------------------- ### sign Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/index.md Finalizes the device response and returns the complete, encoded mDL. ```APIDOC ## async sign() ### Description Finalizes the device response and returns the encoded mDL. ### Request Example ```typescript const mdoc = await deviceResponse.sign(); const encoded = mdoc.encode(); ``` ### Returns `Promise` — Complete device response as MDoc ### Throws - Error: Presentation definition not set - Error: Session transcript not set ``` -------------------------------- ### Import Document and MDoc from @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Import the Document and MDoc classes for creating and managing mDL documents. ```typescript // Creating documents import { Document, MDoc } from '@auth0/mdl' ``` -------------------------------- ### Import CBOR Options Functions from @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Import functions getCborEncodeDecodeOptions and setCborEncodeDecodeOptions for configuring CBOR encoding and decoding. ```typescript // Configuration import { getCborEncodeDecodeOptions, setCborEncodeDecodeOptions } from '@auth0/mdl' ``` -------------------------------- ### Build Device Response with Selective Disclosure Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/issuer-signed-document.md Parse an issuer-signed mDL and use it as a base to build a device response. This involves specifying a presentation definition and authenticating the response with a device key. ```typescript import { DeviceResponse, parse } from '@auth0/mdl'; // Parse issuer-signed mDL const issuerMdoc = parse(issuerEncodedBytes); const doc = issuerMdoc.documents[0] as IssuerSignedDocument; // Build device response with selective disclosure const deviceResponse = DeviceResponse.from(issuerMdoc) .usingPresentationDefinition(pd) .usingSessionTranscriptForOID4VP(/* ... */) .authenticateWithSignature(deviceKey, 'ES256'); const deviceMdoc = await deviceResponse.sign(); ``` -------------------------------- ### Build and Sign Device Response Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/device-signed-document.md Create a DeviceResponse from an issuer-signed credential, configure selective disclosure and session transcript, and sign it with a device private key to generate a DeviceSignedDocument. This is used when a device needs to present credentials to a verifier. ```typescript import { DeviceResponse, parse, DataItem, cborEncode } from '@auth0/mdl'; // Start with issuer-signed credential const issuerMdoc = parse(issuerEncodedBytes); // Build device response with selective disclosure const deviceResponse = DeviceResponse.from(issuerMdoc) .usingPresentationDefinition({ id: 'disclosure', input_descriptors: [ { id: 'org.iso.18013.5.1.mDL', format: { mso_mdoc: { alg: ['ES256'] } }, constraints: { limit_disclosure: 'required', fields: [ { path: ["$['org.iso.18013.5.1']['family_name']"], intent_to_retain: false, }, { path: ["$['org.iso.18013.5.1']['given_name']"], intent_to_retain: false, }, ], }, }, ], }) .usingSessionTranscriptForOID4VP( 'device_nonce', 'client_id', 'https://verifier.example.com/response', 'verifier_nonce' ) .authenticateWithSignature(devicePrivateKey, 'ES256'); // Sign creates DeviceSignedDocument instances const mdoc = await deviceResponse.sign(); const doc = mdoc.documents[0] as DeviceSignedDocument; // Document now has device signature console.log('Device authenticated:', !!doc.deviceSigned.deviceAuth.deviceSignature); // Encode for transmission const encoded = mdoc.encode(); ``` -------------------------------- ### DateOnly Constructor Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/configuration.md Initializes a DateOnly instance from an ISO 8601 full-date string. If no string is provided, it defaults to the current date. ```APIDOC ## DateOnly Constructor ### Description Initializes a DateOnly instance from an ISO 8601 full-date string. If no string is provided, it defaults to the current date. ### Method ```typescript constructor(strDate?: string) ``` ### Parameters #### Path Parameters - **strDate** (string) - Optional - ISO 8601 full-date string (YYYY-MM-DD) (defaults to undefined) ### Request Example ```typescript import { DateOnly } from '@auth0/mdl'; const date1 = new DateOnly('1990-01-15'); const date2 = new DateOnly(); ``` ``` -------------------------------- ### Import IssuerSignedDocument and DeviceSignedDocument from @auth0/mdl Source: https://github.com/auth0-lab/mdl/blob/main/_autodocs/README.md Import types for IssuerSignedDocument and DeviceSignedDocument to work with signed document structures. ```typescript // Types import { IssuerSignedDocument, DeviceSignedDocument } from '@auth0/mdl' ```